Web UI for ARGUS server
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.

18208 lines
772 KiB

6 years ago
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. typeof window !== "undefined" &&
  2. (function webpackUniversalModuleDefinition(root, factory) {
  3. if(typeof exports === 'object' && typeof module === 'object')
  4. module.exports = factory();
  5. else if(typeof define === 'function' && define.amd)
  6. define([], factory);
  7. else if(typeof exports === 'object')
  8. exports["Hls"] = factory();
  9. else
  10. root["Hls"] = factory();
  11. })(this, function() {
  12. return /******/ (function(modules) { // webpackBootstrap
  13. /******/ // The module cache
  14. /******/ var installedModules = {};
  15. /******/
  16. /******/ // The require function
  17. /******/ function __webpack_require__(moduleId) {
  18. /******/
  19. /******/ // Check if module is in cache
  20. /******/ if(installedModules[moduleId]) {
  21. /******/ return installedModules[moduleId].exports;
  22. /******/ }
  23. /******/ // Create a new module (and put it into the cache)
  24. /******/ var module = installedModules[moduleId] = {
  25. /******/ i: moduleId,
  26. /******/ l: false,
  27. /******/ exports: {}
  28. /******/ };
  29. /******/
  30. /******/ // Execute the module function
  31. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  32. /******/
  33. /******/ // Flag the module as loaded
  34. /******/ module.l = true;
  35. /******/
  36. /******/ // Return the exports of the module
  37. /******/ return module.exports;
  38. /******/ }
  39. /******/
  40. /******/
  41. /******/ // expose the modules object (__webpack_modules__)
  42. /******/ __webpack_require__.m = modules;
  43. /******/
  44. /******/ // expose the module cache
  45. /******/ __webpack_require__.c = installedModules;
  46. /******/
  47. /******/ // define getter function for harmony exports
  48. /******/ __webpack_require__.d = function(exports, name, getter) {
  49. /******/ if(!__webpack_require__.o(exports, name)) {
  50. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  51. /******/ }
  52. /******/ };
  53. /******/
  54. /******/ // define __esModule on exports
  55. /******/ __webpack_require__.r = function(exports) {
  56. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  57. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  58. /******/ }
  59. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  60. /******/ };
  61. /******/
  62. /******/ // create a fake namespace object
  63. /******/ // mode & 1: value is a module id, require it
  64. /******/ // mode & 2: merge all properties of value into the ns
  65. /******/ // mode & 4: return value when already ns object
  66. /******/ // mode & 8|1: behave like require
  67. /******/ __webpack_require__.t = function(value, mode) {
  68. /******/ if(mode & 1) value = __webpack_require__(value);
  69. /******/ if(mode & 8) return value;
  70. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  71. /******/ var ns = Object.create(null);
  72. /******/ __webpack_require__.r(ns);
  73. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  74. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  75. /******/ return ns;
  76. /******/ };
  77. /******/
  78. /******/ // getDefaultExport function for compatibility with non-harmony modules
  79. /******/ __webpack_require__.n = function(module) {
  80. /******/ var getter = module && module.__esModule ?
  81. /******/ function getDefault() { return module['default']; } :
  82. /******/ function getModuleExports() { return module; };
  83. /******/ __webpack_require__.d(getter, 'a', getter);
  84. /******/ return getter;
  85. /******/ };
  86. /******/
  87. /******/ // Object.prototype.hasOwnProperty.call
  88. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  89. /******/
  90. /******/ // __webpack_public_path__
  91. /******/ __webpack_require__.p = "/dist/";
  92. /******/
  93. /******/
  94. /******/ // Load entry module and return exports
  95. /******/ return __webpack_require__(__webpack_require__.s = "./src/hls.js");
  96. /******/ })
  97. /************************************************************************/
  98. /******/ ({
  99. /***/ "./node_modules/eventemitter3/index.js":
  100. /*!*********************************************!*\
  101. !*** ./node_modules/eventemitter3/index.js ***!
  102. \*********************************************/
  103. /*! no static exports found */
  104. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  105. /***/ (function(module, exports, __webpack_require__) {
  106. "use strict";
  107. var has = Object.prototype.hasOwnProperty
  108. , prefix = '~';
  109. /**
  110. * Constructor to create a storage for our `EE` objects.
  111. * An `Events` instance is a plain object whose properties are event names.
  112. *
  113. * @constructor
  114. * @private
  115. */
  116. function Events() {}
  117. //
  118. // We try to not inherit from `Object.prototype`. In some engines creating an
  119. // instance in this way is faster than calling `Object.create(null)` directly.
  120. // If `Object.create(null)` is not supported we prefix the event names with a
  121. // character to make sure that the built-in object properties are not
  122. // overridden or used as an attack vector.
  123. //
  124. if (Object.create) {
  125. Events.prototype = Object.create(null);
  126. //
  127. // This hack is needed because the `__proto__` property is still inherited in
  128. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  129. //
  130. if (!new Events().__proto__) prefix = false;
  131. }
  132. /**
  133. * Representation of a single event listener.
  134. *
  135. * @param {Function} fn The listener function.
  136. * @param {*} context The context to invoke the listener with.
  137. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  138. * @constructor
  139. * @private
  140. */
  141. function EE(fn, context, once) {
  142. this.fn = fn;
  143. this.context = context;
  144. this.once = once || false;
  145. }
  146. /**
  147. * Add a listener for a given event.
  148. *
  149. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  150. * @param {(String|Symbol)} event The event name.
  151. * @param {Function} fn The listener function.
  152. * @param {*} context The context to invoke the listener with.
  153. * @param {Boolean} once Specify if the listener is a one-time listener.
  154. * @returns {EventEmitter}
  155. * @private
  156. */
  157. function addListener(emitter, event, fn, context, once) {
  158. if (typeof fn !== 'function') {
  159. throw new TypeError('The listener must be a function');
  160. }
  161. var listener = new EE(fn, context || emitter, once)
  162. , evt = prefix ? prefix + event : event;
  163. if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;
  164. else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);
  165. else emitter._events[evt] = [emitter._events[evt], listener];
  166. return emitter;
  167. }
  168. /**
  169. * Clear event by name.
  170. *
  171. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  172. * @param {(String|Symbol)} evt The Event name.
  173. * @private
  174. */
  175. function clearEvent(emitter, evt) {
  176. if (--emitter._eventsCount === 0) emitter._events = new Events();
  177. else delete emitter._events[evt];
  178. }
  179. /**
  180. * Minimal `EventEmitter` interface that is molded against the Node.js
  181. * `EventEmitter` interface.
  182. *
  183. * @constructor
  184. * @public
  185. */
  186. function EventEmitter() {
  187. this._events = new Events();
  188. this._eventsCount = 0;
  189. }
  190. /**
  191. * Return an array listing the events for which the emitter has registered
  192. * listeners.
  193. *
  194. * @returns {Array}
  195. * @public
  196. */
  197. EventEmitter.prototype.eventNames = function eventNames() {
  198. var names = []
  199. , events
  200. , name;
  201. if (this._eventsCount === 0) return names;
  202. for (name in (events = this._events)) {
  203. if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);
  204. }
  205. if (Object.getOwnPropertySymbols) {
  206. return names.concat(Object.getOwnPropertySymbols(events));
  207. }
  208. return names;
  209. };
  210. /**
  211. * Return the listeners registered for a given event.
  212. *
  213. * @param {(String|Symbol)} event The event name.
  214. * @returns {Array} The registered listeners.
  215. * @public
  216. */
  217. EventEmitter.prototype.listeners = function listeners(event) {
  218. var evt = prefix ? prefix + event : event
  219. , handlers = this._events[evt];
  220. if (!handlers) return [];
  221. if (handlers.fn) return [handlers.fn];
  222. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  223. ee[i] = handlers[i].fn;
  224. }
  225. return ee;
  226. };
  227. /**
  228. * Return the number of listeners listening to a given event.
  229. *
  230. * @param {(String|Symbol)} event The event name.
  231. * @returns {Number} The number of listeners.
  232. * @public
  233. */
  234. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  235. var evt = prefix ? prefix + event : event
  236. , listeners = this._events[evt];
  237. if (!listeners) return 0;
  238. if (listeners.fn) return 1;
  239. return listeners.length;
  240. };
  241. /**
  242. * Calls each of the listeners registered for a given event.
  243. *
  244. * @param {(String|Symbol)} event The event name.
  245. * @returns {Boolean} `true` if the event had listeners, else `false`.
  246. * @public
  247. */
  248. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  249. var evt = prefix ? prefix + event : event;
  250. if (!this._events[evt]) return false;
  251. var listeners = this._events[evt]
  252. , len = arguments.length
  253. , args
  254. , i;
  255. if (listeners.fn) {
  256. if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);
  257. switch (len) {
  258. case 1: return listeners.fn.call(listeners.context), true;
  259. case 2: return listeners.fn.call(listeners.context, a1), true;
  260. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  261. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  262. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  263. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  264. }
  265. for (i = 1, args = new Array(len -1); i < len; i++) {
  266. args[i - 1] = arguments[i];
  267. }
  268. listeners.fn.apply(listeners.context, args);
  269. } else {
  270. var length = listeners.length
  271. , j;
  272. for (i = 0; i < length; i++) {
  273. if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);
  274. switch (len) {
  275. case 1: listeners[i].fn.call(listeners[i].context); break;
  276. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  277. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  278. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  279. default:
  280. if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {
  281. args[j - 1] = arguments[j];
  282. }
  283. listeners[i].fn.apply(listeners[i].context, args);
  284. }
  285. }
  286. }
  287. return true;
  288. };
  289. /**
  290. * Add a listener for a given event.
  291. *
  292. * @param {(String|Symbol)} event The event name.
  293. * @param {Function} fn The listener function.
  294. * @param {*} [context=this] The context to invoke the listener with.
  295. * @returns {EventEmitter} `this`.
  296. * @public
  297. */
  298. EventEmitter.prototype.on = function on(event, fn, context) {
  299. return addListener(this, event, fn, context, false);
  300. };
  301. /**
  302. * Add a one-time listener for a given event.
  303. *
  304. * @param {(String|Symbol)} event The event name.
  305. * @param {Function} fn The listener function.
  306. * @param {*} [context=this] The context to invoke the listener with.
  307. * @returns {EventEmitter} `this`.
  308. * @public
  309. */
  310. EventEmitter.prototype.once = function once(event, fn, context) {
  311. return addListener(this, event, fn, context, true);
  312. };
  313. /**
  314. * Remove the listeners of a given event.
  315. *
  316. * @param {(String|Symbol)} event The event name.
  317. * @param {Function} fn Only remove the listeners that match this function.
  318. * @param {*} context Only remove the listeners that have this context.
  319. * @param {Boolean} once Only remove one-time listeners.
  320. * @returns {EventEmitter} `this`.
  321. * @public
  322. */
  323. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  324. var evt = prefix ? prefix + event : event;
  325. if (!this._events[evt]) return this;
  326. if (!fn) {
  327. clearEvent(this, evt);
  328. return this;
  329. }
  330. var listeners = this._events[evt];
  331. if (listeners.fn) {
  332. if (
  333. listeners.fn === fn &&
  334. (!once || listeners.once) &&
  335. (!context || listeners.context === context)
  336. ) {
  337. clearEvent(this, evt);
  338. }
  339. } else {
  340. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  341. if (
  342. listeners[i].fn !== fn ||
  343. (once && !listeners[i].once) ||
  344. (context && listeners[i].context !== context)
  345. ) {
  346. events.push(listeners[i]);
  347. }
  348. }
  349. //
  350. // Reset the array, or remove it completely if we have no more listeners.
  351. //
  352. if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;
  353. else clearEvent(this, evt);
  354. }
  355. return this;
  356. };
  357. /**
  358. * Remove all listeners, or those of the specified event.
  359. *
  360. * @param {(String|Symbol)} [event] The event name.
  361. * @returns {EventEmitter} `this`.
  362. * @public
  363. */
  364. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  365. var evt;
  366. if (event) {
  367. evt = prefix ? prefix + event : event;
  368. if (this._events[evt]) clearEvent(this, evt);
  369. } else {
  370. this._events = new Events();
  371. this._eventsCount = 0;
  372. }
  373. return this;
  374. };
  375. //
  376. // Alias methods names because people roll like that.
  377. //
  378. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  379. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  380. //
  381. // Expose the prefix.
  382. //
  383. EventEmitter.prefixed = prefix;
  384. //
  385. // Allow `EventEmitter` to be imported as module namespace.
  386. //
  387. EventEmitter.EventEmitter = EventEmitter;
  388. //
  389. // Expose the module.
  390. //
  391. if (true) {
  392. module.exports = EventEmitter;
  393. }
  394. /***/ }),
  395. /***/ "./node_modules/node-libs-browser/node_modules/events/events.js":
  396. /*!**********************************************************************!*\
  397. !*** ./node_modules/node-libs-browser/node_modules/events/events.js ***!
  398. \**********************************************************************/
  399. /*! no static exports found */
  400. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  401. /***/ (function(module, exports) {
  402. // Copyright Joyent, Inc. and other Node contributors.
  403. //
  404. // Permission is hereby granted, free of charge, to any person obtaining a
  405. // copy of this software and associated documentation files (the
  406. // "Software"), to deal in the Software without restriction, including
  407. // without limitation the rights to use, copy, modify, merge, publish,
  408. // distribute, sublicense, and/or sell copies of the Software, and to permit
  409. // persons to whom the Software is furnished to do so, subject to the
  410. // following conditions:
  411. //
  412. // The above copyright notice and this permission notice shall be included
  413. // in all copies or substantial portions of the Software.
  414. //
  415. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  416. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  417. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  418. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  419. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  420. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  421. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  422. function EventEmitter() {
  423. this._events = this._events || {};
  424. this._maxListeners = this._maxListeners || undefined;
  425. }
  426. module.exports = EventEmitter;
  427. // Backwards-compat with node 0.10.x
  428. EventEmitter.EventEmitter = EventEmitter;
  429. EventEmitter.prototype._events = undefined;
  430. EventEmitter.prototype._maxListeners = undefined;
  431. // By default EventEmitters will print a warning if more than 10 listeners are
  432. // added to it. This is a useful default which helps finding memory leaks.
  433. EventEmitter.defaultMaxListeners = 10;
  434. // Obviously not all Emitters should be limited to 10. This function allows
  435. // that to be increased. Set to zero for unlimited.
  436. EventEmitter.prototype.setMaxListeners = function(n) {
  437. if (!isNumber(n) || n < 0 || isNaN(n))
  438. throw TypeError('n must be a positive number');
  439. this._maxListeners = n;
  440. return this;
  441. };
  442. EventEmitter.prototype.emit = function(type) {
  443. var er, handler, len, args, i, listeners;
  444. if (!this._events)
  445. this._events = {};
  446. // If there is no 'error' event listener then throw.
  447. if (type === 'error') {
  448. if (!this._events.error ||
  449. (isObject(this._events.error) && !this._events.error.length)) {
  450. er = arguments[1];
  451. if (er instanceof Error) {
  452. throw er; // Unhandled 'error' event
  453. } else {
  454. // At least give some kind of context to the user
  455. var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
  456. err.context = er;
  457. throw err;
  458. }
  459. }
  460. }
  461. handler = this._events[type];
  462. if (isUndefined(handler))
  463. return false;
  464. if (isFunction(handler)) {
  465. switch (arguments.length) {
  466. // fast cases
  467. case 1:
  468. handler.call(this);
  469. break;
  470. case 2:
  471. handler.call(this, arguments[1]);
  472. break;
  473. case 3:
  474. handler.call(this, arguments[1], arguments[2]);
  475. break;
  476. // slower
  477. default:
  478. args = Array.prototype.slice.call(arguments, 1);
  479. handler.apply(this, args);
  480. }
  481. } else if (isObject(handler)) {
  482. args = Array.prototype.slice.call(arguments, 1);
  483. listeners = handler.slice();
  484. len = listeners.length;
  485. for (i = 0; i < len; i++)
  486. listeners[i].apply(this, args);
  487. }
  488. return true;
  489. };
  490. EventEmitter.prototype.addListener = function(type, listener) {
  491. var m;
  492. if (!isFunction(listener))
  493. throw TypeError('listener must be a function');
  494. if (!this._events)
  495. this._events = {};
  496. // To avoid recursion in the case that type === "newListener"! Before
  497. // adding it to the listeners, first emit "newListener".
  498. if (this._events.newListener)
  499. this.emit('newListener', type,
  500. isFunction(listener.listener) ?
  501. listener.listener : listener);
  502. if (!this._events[type])
  503. // Optimize the case of one listener. Don't need the extra array object.
  504. this._events[type] = listener;
  505. else if (isObject(this._events[type]))
  506. // If we've already got an array, just append.
  507. this._events[type].push(listener);
  508. else
  509. // Adding the second element, need to change to array.
  510. this._events[type] = [this._events[type], listener];
  511. // Check for listener leak
  512. if (isObject(this._events[type]) && !this._events[type].warned) {
  513. if (!isUndefined(this._maxListeners)) {
  514. m = this._maxListeners;
  515. } else {
  516. m = EventEmitter.defaultMaxListeners;
  517. }
  518. if (m && m > 0 && this._events[type].length > m) {
  519. this._events[type].warned = true;
  520. console.error('(node) warning: possible EventEmitter memory ' +
  521. 'leak detected. %d listeners added. ' +
  522. 'Use emitter.setMaxListeners() to increase limit.',
  523. this._events[type].length);
  524. if (typeof console.trace === 'function') {
  525. // not supported in IE 10
  526. console.trace();
  527. }
  528. }
  529. }
  530. return this;
  531. };
  532. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  533. EventEmitter.prototype.once = function(type, listener) {
  534. if (!isFunction(listener))
  535. throw TypeError('listener must be a function');
  536. var fired = false;
  537. function g() {
  538. this.removeListener(type, g);
  539. if (!fired) {
  540. fired = true;
  541. listener.apply(this, arguments);
  542. }
  543. }
  544. g.listener = listener;
  545. this.on(type, g);
  546. return this;
  547. };
  548. // emits a 'removeListener' event iff the listener was removed
  549. EventEmitter.prototype.removeListener = function(type, listener) {
  550. var list, position, length, i;
  551. if (!isFunction(listener))
  552. throw TypeError('listener must be a function');
  553. if (!this._events || !this._events[type])
  554. return this;
  555. list = this._events[type];
  556. length = list.length;
  557. position = -1;
  558. if (list === listener ||
  559. (isFunction(list.listener) && list.listener === listener)) {
  560. delete this._events[type];
  561. if (this._events.removeListener)
  562. this.emit('removeListener', type, listener);
  563. } else if (isObject(list)) {
  564. for (i = length; i-- > 0;) {
  565. if (list[i] === listener ||
  566. (list[i].listener && list[i].listener === listener)) {
  567. position = i;
  568. break;
  569. }
  570. }
  571. if (position < 0)
  572. return this;
  573. if (list.length === 1) {
  574. list.length = 0;
  575. delete this._events[type];
  576. } else {
  577. list.splice(position, 1);
  578. }
  579. if (this._events.removeListener)
  580. this.emit('removeListener', type, listener);
  581. }
  582. return this;
  583. };
  584. EventEmitter.prototype.removeAllListeners = function(type) {
  585. var key, listeners;
  586. if (!this._events)
  587. return this;
  588. // not listening for removeListener, no need to emit
  589. if (!this._events.removeListener) {
  590. if (arguments.length === 0)
  591. this._events = {};
  592. else if (this._events[type])
  593. delete this._events[type];
  594. return this;
  595. }
  596. // emit removeListener for all listeners on all events
  597. if (arguments.length === 0) {
  598. for (key in this._events) {
  599. if (key === 'removeListener') continue;
  600. this.removeAllListeners(key);
  601. }
  602. this.removeAllListeners('removeListener');
  603. this._events = {};
  604. return this;
  605. }
  606. listeners = this._events[type];
  607. if (isFunction(listeners)) {
  608. this.removeListener(type, listeners);
  609. } else if (listeners) {
  610. // LIFO order
  611. while (listeners.length)
  612. this.removeListener(type, listeners[listeners.length - 1]);
  613. }
  614. delete this._events[type];
  615. return this;
  616. };
  617. EventEmitter.prototype.listeners = function(type) {
  618. var ret;
  619. if (!this._events || !this._events[type])
  620. ret = [];
  621. else if (isFunction(this._events[type]))
  622. ret = [this._events[type]];
  623. else
  624. ret = this._events[type].slice();
  625. return ret;
  626. };
  627. EventEmitter.prototype.listenerCount = function(type) {
  628. if (this._events) {
  629. var evlistener = this._events[type];
  630. if (isFunction(evlistener))
  631. return 1;
  632. else if (evlistener)
  633. return evlistener.length;
  634. }
  635. return 0;
  636. };
  637. EventEmitter.listenerCount = function(emitter, type) {
  638. return emitter.listenerCount(type);
  639. };
  640. function isFunction(arg) {
  641. return typeof arg === 'function';
  642. }
  643. function isNumber(arg) {
  644. return typeof arg === 'number';
  645. }
  646. function isObject(arg) {
  647. return typeof arg === 'object' && arg !== null;
  648. }
  649. function isUndefined(arg) {
  650. return arg === void 0;
  651. }
  652. /***/ }),
  653. /***/ "./node_modules/url-toolkit/src/url-toolkit.js":
  654. /*!*****************************************************!*\
  655. !*** ./node_modules/url-toolkit/src/url-toolkit.js ***!
  656. \*****************************************************/
  657. /*! no static exports found */
  658. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  659. /***/ (function(module, exports, __webpack_require__) {
  660. // see https://tools.ietf.org/html/rfc1808
  661. /* jshint ignore:start */
  662. (function(root) {
  663. /* jshint ignore:end */
  664. var URL_REGEX = /^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/\?#]*\/)*.*?)??(;.*?)?(\?.*?)?(#.*?)?$/;
  665. var FIRST_SEGMENT_REGEX = /^([^\/?#]*)(.*)$/;
  666. var SLASH_DOT_REGEX = /(?:\/|^)\.(?=\/)/g;
  667. var SLASH_DOT_DOT_REGEX = /(?:\/|^)\.\.\/(?!\.\.\/).*?(?=\/)/g;
  668. var URLToolkit = { // jshint ignore:line
  669. // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //
  670. // E.g
  671. // With opts.alwaysNormalize = false (default, spec compliant)
  672. // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g
  673. // With opts.alwaysNormalize = true (not spec compliant)
  674. // http://a.com/b/cd + /e/f/../g => http://a.com/e/g
  675. buildAbsoluteURL: function(baseURL, relativeURL, opts) {
  676. opts = opts || {};
  677. // remove any remaining space and CRLF
  678. baseURL = baseURL.trim();
  679. relativeURL = relativeURL.trim();
  680. if (!relativeURL) {
  681. // 2a) If the embedded URL is entirely empty, it inherits the
  682. // entire base URL (i.e., is set equal to the base URL)
  683. // and we are done.
  684. if (!opts.alwaysNormalize) {
  685. return baseURL;
  686. }
  687. var basePartsForNormalise = URLToolkit.parseURL(baseURL);
  688. if (!basePartsForNormalise) {
  689. throw new Error('Error trying to parse base URL.');
  690. }
  691. basePartsForNormalise.path = URLToolkit.normalizePath(basePartsForNormalise.path);
  692. return URLToolkit.buildURLFromParts(basePartsForNormalise);
  693. }
  694. var relativeParts = URLToolkit.parseURL(relativeURL);
  695. if (!relativeParts) {
  696. throw new Error('Error trying to parse relative URL.');
  697. }
  698. if (relativeParts.scheme) {
  699. // 2b) If the embedded URL starts with a scheme name, it is
  700. // interpreted as an absolute URL and we are done.
  701. if (!opts.alwaysNormalize) {
  702. return relativeURL;
  703. }
  704. relativeParts.path = URLToolkit.normalizePath(relativeParts.path);
  705. return URLToolkit.buildURLFromParts(relativeParts);
  706. }
  707. var baseParts = URLToolkit.parseURL(baseURL);
  708. if (!baseParts) {
  709. throw new Error('Error trying to parse base URL.');
  710. }
  711. if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {
  712. // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc
  713. // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'
  714. var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);
  715. baseParts.netLoc = pathParts[1];
  716. baseParts.path = pathParts[2];
  717. }
  718. if (baseParts.netLoc && !baseParts.path) {
  719. baseParts.path = '/';
  720. }
  721. var builtParts = {
  722. // 2c) Otherwise, the embedded URL inherits the scheme of
  723. // the base URL.
  724. scheme: baseParts.scheme,
  725. netLoc: relativeParts.netLoc,
  726. path: null,
  727. params: relativeParts.params,
  728. query: relativeParts.query,
  729. fragment: relativeParts.fragment
  730. };
  731. if (!relativeParts.netLoc) {
  732. // 3) If the embedded URL's <net_loc> is non-empty, we skip to
  733. // Step 7. Otherwise, the embedded URL inherits the <net_loc>
  734. // (if any) of the base URL.
  735. builtParts.netLoc = baseParts.netLoc;
  736. // 4) If the embedded URL path is preceded by a slash "/", the
  737. // path is not relative and we skip to Step 7.
  738. if (relativeParts.path[0] !== '/') {
  739. if (!relativeParts.path) {
  740. // 5) If the embedded URL path is empty (and not preceded by a
  741. // slash), then the embedded URL inherits the base URL path
  742. builtParts.path = baseParts.path;
  743. // 5a) if the embedded URL's <params> is non-empty, we skip to
  744. // step 7; otherwise, it inherits the <params> of the base
  745. // URL (if any) and
  746. if (!relativeParts.params) {
  747. builtParts.params = baseParts.params;
  748. // 5b) if the embedded URL's <query> is non-empty, we skip to
  749. // step 7; otherwise, it inherits the <query> of the base
  750. // URL (if any) and we skip to step 7.
  751. if (!relativeParts.query) {
  752. builtParts.query = baseParts.query;
  753. }
  754. }
  755. } else {
  756. // 6) The last segment of the base URL's path (anything
  757. // following the rightmost slash "/", or the entire path if no
  758. // slash is present) is removed and the embedded URL's path is
  759. // appended in its place.
  760. var baseURLPath = baseParts.path;
  761. var newPath = baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) + relativeParts.path;
  762. builtParts.path = URLToolkit.normalizePath(newPath);
  763. }
  764. }
  765. }
  766. if (builtParts.path === null) {
  767. builtParts.path = opts.alwaysNormalize ? URLToolkit.normalizePath(relativeParts.path) : relativeParts.path;
  768. }
  769. return URLToolkit.buildURLFromParts(builtParts);
  770. },
  771. parseURL: function(url) {
  772. var parts = URL_REGEX.exec(url);
  773. if (!parts) {
  774. return null;
  775. }
  776. return {
  777. scheme: parts[1] || '',
  778. netLoc: parts[2] || '',
  779. path: parts[3] || '',
  780. params: parts[4] || '',
  781. query: parts[5] || '',
  782. fragment: parts[6] || ''
  783. };
  784. },
  785. normalizePath: function(path) {
  786. // The following operations are
  787. // then applied, in order, to the new path:
  788. // 6a) All occurrences of "./", where "." is a complete path
  789. // segment, are removed.
  790. // 6b) If the path ends with "." as a complete path segment,
  791. // that "." is removed.
  792. path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');
  793. // 6c) All occurrences of "<segment>/../", where <segment> is a
  794. // complete path segment not equal to "..", are removed.
  795. // Removal of these path segments is performed iteratively,
  796. // removing the leftmost matching pattern on each iteration,
  797. // until no matching pattern remains.
  798. // 6d) If the path ends with "<segment>/..", where <segment> is a
  799. // complete path segment not equal to "..", that
  800. // "<segment>/.." is removed.
  801. while (path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length) {} // jshint ignore:line
  802. return path.split('').reverse().join('');
  803. },
  804. buildURLFromParts: function(parts) {
  805. return parts.scheme + parts.netLoc + parts.path + parts.params + parts.query + parts.fragment;
  806. }
  807. };
  808. /* jshint ignore:start */
  809. if(true)
  810. module.exports = URLToolkit;
  811. else {}
  812. })(this);
  813. /* jshint ignore:end */
  814. /***/ }),
  815. /***/ "./node_modules/webworkify-webpack/index.js":
  816. /*!**************************************************!*\
  817. !*** ./node_modules/webworkify-webpack/index.js ***!
  818. \**************************************************/
  819. /*! no static exports found */
  820. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  821. /***/ (function(module, exports, __webpack_require__) {
  822. function webpackBootstrapFunc (modules) {
  823. /******/ // The module cache
  824. /******/ var installedModules = {};
  825. /******/ // The require function
  826. /******/ function __webpack_require__(moduleId) {
  827. /******/ // Check if module is in cache
  828. /******/ if(installedModules[moduleId])
  829. /******/ return installedModules[moduleId].exports;
  830. /******/ // Create a new module (and put it into the cache)
  831. /******/ var module = installedModules[moduleId] = {
  832. /******/ i: moduleId,
  833. /******/ l: false,
  834. /******/ exports: {}
  835. /******/ };
  836. /******/ // Execute the module function
  837. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  838. /******/ // Flag the module as loaded
  839. /******/ module.l = true;
  840. /******/ // Return the exports of the module
  841. /******/ return module.exports;
  842. /******/ }
  843. /******/ // expose the modules object (__webpack_modules__)
  844. /******/ __webpack_require__.m = modules;
  845. /******/ // expose the module cache
  846. /******/ __webpack_require__.c = installedModules;
  847. /******/ // identity function for calling harmony imports with the correct context
  848. /******/ __webpack_require__.i = function(value) { return value; };
  849. /******/ // define getter function for harmony exports
  850. /******/ __webpack_require__.d = function(exports, name, getter) {
  851. /******/ if(!__webpack_require__.o(exports, name)) {
  852. /******/ Object.defineProperty(exports, name, {
  853. /******/ configurable: false,
  854. /******/ enumerable: true,
  855. /******/ get: getter
  856. /******/ });
  857. /******/ }
  858. /******/ };
  859. /******/ // define __esModule on exports
  860. /******/ __webpack_require__.r = function(exports) {
  861. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  862. /******/ };
  863. /******/ // getDefaultExport function for compatibility with non-harmony modules
  864. /******/ __webpack_require__.n = function(module) {
  865. /******/ var getter = module && module.__esModule ?
  866. /******/ function getDefault() { return module['default']; } :
  867. /******/ function getModuleExports() { return module; };
  868. /******/ __webpack_require__.d(getter, 'a', getter);
  869. /******/ return getter;
  870. /******/ };
  871. /******/ // Object.prototype.hasOwnProperty.call
  872. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  873. /******/ // __webpack_public_path__
  874. /******/ __webpack_require__.p = "/";
  875. /******/ // on error function for async loading
  876. /******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };
  877. var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)
  878. return f.default || f // try to call default if defined to also support babel esmodule exports
  879. }
  880. var moduleNameReqExp = '[\\.|\\-|\\+|\\w|\/|@]+'
  881. var dependencyRegExp = '\\((\/\\*.*?\\*\/)?\s?.*?(' + moduleNameReqExp + ').*?\\)' // additional chars when output.pathinfo is true
  882. // http://stackoverflow.com/a/2593661/130442
  883. function quoteRegExp (str) {
  884. return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, '\\$&')
  885. }
  886. function isNumeric(n) {
  887. return !isNaN(1 * n); // 1 * n converts integers, integers as string ("123"), 1e3 and "1e3" to integers and strings to NaN
  888. }
  889. function getModuleDependencies (sources, module, queueName) {
  890. var retval = {}
  891. retval[queueName] = []
  892. var fnString = module.toString()
  893. var wrapperSignature = fnString.match(/^function\s?\(\w+,\s*\w+,\s*(\w+)\)/)
  894. if (!wrapperSignature) return retval
  895. var webpackRequireName = wrapperSignature[1]
  896. // main bundle deps
  897. var re = new RegExp('(\\\\n|\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')
  898. var match
  899. while ((match = re.exec(fnString))) {
  900. if (match[3] === 'dll-reference') continue
  901. retval[queueName].push(match[3])
  902. }
  903. // dll deps
  904. re = new RegExp('\\(' + quoteRegExp(webpackRequireName) + '\\("(dll-reference\\s(' + moduleNameReqExp + '))"\\)\\)' + dependencyRegExp, 'g')
  905. while ((match = re.exec(fnString))) {
  906. if (!sources[match[2]]) {
  907. retval[queueName].push(match[1])
  908. sources[match[2]] = __webpack_require__(match[1]).m
  909. }
  910. retval[match[2]] = retval[match[2]] || []
  911. retval[match[2]].push(match[4])
  912. }
  913. // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3
  914. var keys = Object.keys(retval);
  915. for (var i = 0; i < keys.length; i++) {
  916. for (var j = 0; j < retval[keys[i]].length; j++) {
  917. if (isNumeric(retval[keys[i]][j])) {
  918. retval[keys[i]][j] = 1 * retval[keys[i]][j];
  919. }
  920. }
  921. }
  922. return retval
  923. }
  924. function hasValuesInQueues (queues) {
  925. var keys = Object.keys(queues)
  926. return keys.reduce(function (hasValues, key) {
  927. return hasValues || queues[key].length > 0
  928. }, false)
  929. }
  930. function getRequiredModules (sources, moduleId) {
  931. var modulesQueue = {
  932. main: [moduleId]
  933. }
  934. var requiredModules = {
  935. main: []
  936. }
  937. var seenModules = {
  938. main: {}
  939. }
  940. while (hasValuesInQueues(modulesQueue)) {
  941. var queues = Object.keys(modulesQueue)
  942. for (var i = 0; i < queues.length; i++) {
  943. var queueName = queues[i]
  944. var queue = modulesQueue[queueName]
  945. var moduleToCheck = queue.pop()
  946. seenModules[queueName] = seenModules[queueName] || {}
  947. if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue
  948. seenModules[queueName][moduleToCheck] = true
  949. requiredModules[queueName] = requiredModules[queueName] || []
  950. requiredModules[queueName].push(moduleToCheck)
  951. var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)
  952. var newModulesKeys = Object.keys(newModules)
  953. for (var j = 0; j < newModulesKeys.length; j++) {
  954. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []
  955. modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])
  956. }
  957. }
  958. }
  959. return requiredModules
  960. }
  961. module.exports = function (moduleId, options) {
  962. options = options || {}
  963. var sources = {
  964. main: __webpack_require__.m
  965. }
  966. var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)
  967. var src = ''
  968. Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {
  969. var entryModule = 0
  970. while (requiredModules[module][entryModule]) {
  971. entryModule++
  972. }
  973. requiredModules[module].push(entryModule)
  974. sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'
  975. src = src + 'var ' + module + ' = (' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(entryModule)) + ')({' + requiredModules[module].map(function (id) { return '' + JSON.stringify(id) + ': ' + sources[module][id].toString() }).join(',') + '});\n'
  976. })
  977. src = src + 'new ((' + webpackBootstrapFunc.toString().replace('ENTRY_MODULE', JSON.stringify(moduleId)) + ')({' + requiredModules.main.map(function (id) { return '' + JSON.stringify(id) + ': ' + sources.main[id].toString() }).join(',') + '}))(self);'
  978. var blob = new window.Blob([src], { type: 'text/javascript' })
  979. if (options.bare) { return blob }
  980. var URL = window.URL || window.webkitURL || window.mozURL || window.msURL
  981. var workerUrl = URL.createObjectURL(blob)
  982. var worker = new window.Worker(workerUrl)
  983. worker.objectURL = workerUrl
  984. return worker
  985. }
  986. /***/ }),
  987. /***/ "./src/config.js":
  988. /*!***********************!*\
  989. !*** ./src/config.js ***!
  990. \***********************/
  991. /*! no static exports found */
  992. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  993. /***/ (function(module, exports, __webpack_require__) {
  994. "use strict";
  995. /**
  996. * HLS config
  997. */
  998. Object.defineProperty(exports, "__esModule", { value: true });
  999. var abr_controller_1 = __webpack_require__(/*! ./controller/abr-controller */ "./src/controller/abr-controller.js");
  1000. var buffer_controller_1 = __webpack_require__(/*! ./controller/buffer-controller */ "./src/controller/buffer-controller.js");
  1001. var cap_level_controller_1 = __webpack_require__(/*! ./controller/cap-level-controller */ "./src/controller/cap-level-controller.js");
  1002. var fps_controller_1 = __webpack_require__(/*! ./controller/fps-controller */ "./src/controller/fps-controller.js");
  1003. var xhr_loader_1 = __webpack_require__(/*! ./utils/xhr-loader */ "./src/utils/xhr-loader.js");
  1004. // import FetchLoader from './utils/fetch-loader';
  1005. var audio_track_controller_1 = __webpack_require__(/*! ./controller/audio-track-controller */ "./src/controller/audio-track-controller.js");
  1006. var audio_stream_controller_1 = __webpack_require__(/*! ./controller/audio-stream-controller */ "./src/controller/audio-stream-controller.js");
  1007. var Cues = __webpack_require__(/*! ./utils/cues */ "./src/utils/cues.js");
  1008. var timeline_controller_1 = __webpack_require__(/*! ./controller/timeline-controller */ "./src/controller/timeline-controller.js");
  1009. var subtitle_track_controller_1 = __webpack_require__(/*! ./controller/subtitle-track-controller */ "./src/controller/subtitle-track-controller.js");
  1010. var subtitle_stream_controller_1 = __webpack_require__(/*! ./controller/subtitle-stream-controller */ "./src/controller/subtitle-stream-controller.js");
  1011. var eme_controller_1 = __webpack_require__(/*! ./controller/eme-controller */ "./src/controller/eme-controller.js");
  1012. var mediakeys_helper_1 = __webpack_require__(/*! ./utils/mediakeys-helper */ "./src/utils/mediakeys-helper.js");
  1013. exports.hlsDefaultConfig = {
  1014. autoStartLoad: true,
  1015. startPosition: -1,
  1016. defaultAudioCodec: undefined,
  1017. debug: false,
  1018. capLevelOnFPSDrop: false,
  1019. capLevelToPlayerSize: false,
  1020. initialLiveManifestSize: 1,
  1021. maxBufferLength: 30,
  1022. maxBufferSize: 60 * 1000 * 1000,
  1023. maxBufferHole: 0.5,
  1024. lowBufferWatchdogPeriod: 0.5,
  1025. highBufferWatchdogPeriod: 3,
  1026. nudgeOffset: 0.1,
  1027. nudgeMaxRetry: 3,
  1028. maxFragLookUpTolerance: 0.25,
  1029. liveSyncDurationCount: 3,
  1030. liveMaxLatencyDurationCount: Infinity,
  1031. liveSyncDuration: undefined,
  1032. liveMaxLatencyDuration: undefined,
  1033. liveDurationInfinity: false,
  1034. liveBackBufferLength: Infinity,
  1035. maxMaxBufferLength: 600,
  1036. enableWorker: true,
  1037. enableSoftwareAES: true,
  1038. manifestLoadingTimeOut: 10000,
  1039. manifestLoadingMaxRetry: 1,
  1040. manifestLoadingRetryDelay: 1000,
  1041. manifestLoadingMaxRetryTimeout: 64000,
  1042. startLevel: undefined,
  1043. levelLoadingTimeOut: 10000,
  1044. levelLoadingMaxRetry: 4,
  1045. levelLoadingRetryDelay: 1000,
  1046. levelLoadingMaxRetryTimeout: 64000,
  1047. fragLoadingTimeOut: 20000,
  1048. fragLoadingMaxRetry: 6,
  1049. fragLoadingRetryDelay: 1000,
  1050. fragLoadingMaxRetryTimeout: 64000,
  1051. startFragPrefetch: false,
  1052. fpsDroppedMonitoringPeriod: 5000,
  1053. fpsDroppedMonitoringThreshold: 0.2,
  1054. appendErrorMaxRetry: 3,
  1055. loader: xhr_loader_1.default,
  1056. // loader: FetchLoader,
  1057. fLoader: undefined,
  1058. pLoader: undefined,
  1059. xhrSetup: undefined,
  1060. licenseXhrSetup: undefined,
  1061. // fetchSetup: undefined,
  1062. abrController: abr_controller_1.default,
  1063. bufferController: buffer_controller_1.default,
  1064. capLevelController: cap_level_controller_1.default,
  1065. fpsController: fps_controller_1.default,
  1066. stretchShortVideoTrack: false,
  1067. maxAudioFramesDrift: 1,
  1068. forceKeyFrameOnDiscontinuity: true,
  1069. abrEwmaFastLive: 3,
  1070. abrEwmaSlowLive: 9,
  1071. abrEwmaFastVoD: 3,
  1072. abrEwmaSlowVoD: 9,
  1073. abrEwmaDefaultEstimate: 5e5,
  1074. abrBandWidthFactor: 0.95,
  1075. abrBandWidthUpFactor: 0.7,
  1076. abrMaxWithRealBitrate: false,
  1077. maxStarvationDelay: 4,
  1078. maxLoadingDelay: 4,
  1079. minAutoBitrate: 0,
  1080. emeEnabled: false,
  1081. widevineLicenseUrl: undefined,
  1082. requestMediaKeySystemAccessFunc: mediakeys_helper_1.requestMediaKeySystemAccess // used by eme-controller
  1083. };
  1084. if (true) {
  1085. exports.hlsDefaultConfig.subtitleStreamController = subtitle_stream_controller_1.SubtitleStreamController;
  1086. exports.hlsDefaultConfig.subtitleTrackController = subtitle_track_controller_1.default;
  1087. exports.hlsDefaultConfig.timelineController = timeline_controller_1.default;
  1088. exports.hlsDefaultConfig.cueHandler = Cues; // used by timeline-controller
  1089. exports.hlsDefaultConfig.enableCEA708Captions = true; // used by timeline-controller
  1090. exports.hlsDefaultConfig.enableWebVTT = true; // used by timeline-controller
  1091. exports.hlsDefaultConfig.captionsTextTrack1Label = 'English'; // used by timeline-controller
  1092. exports.hlsDefaultConfig.captionsTextTrack1LanguageCode = 'en'; // used by timeline-controller
  1093. exports.hlsDefaultConfig.captionsTextTrack2Label = 'Spanish'; // used by timeline-controller
  1094. exports.hlsDefaultConfig.captionsTextTrack2LanguageCode = 'es'; // used by timeline-controller
  1095. }
  1096. if (true) {
  1097. exports.hlsDefaultConfig.audioStreamController = audio_stream_controller_1.default;
  1098. exports.hlsDefaultConfig.audioTrackController = audio_track_controller_1.default;
  1099. }
  1100. if (true) {
  1101. exports.hlsDefaultConfig.emeController = eme_controller_1.default;
  1102. }
  1103. /***/ }),
  1104. /***/ "./src/controller/abr-controller.js":
  1105. /*!******************************************!*\
  1106. !*** ./src/controller/abr-controller.js ***!
  1107. \******************************************/
  1108. /*! no static exports found */
  1109. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  1110. /***/ (function(module, exports, __webpack_require__) {
  1111. "use strict";
  1112. /* WEBPACK VAR INJECTION */(function(Number) {
  1113. /*
  1114. * simple ABR Controller
  1115. * - compute next level based on last fragment bw heuristics
  1116. * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling
  1117. */
  1118. var __extends = (this && this.__extends) || (function () {
  1119. var extendStatics = Object.setPrototypeOf ||
  1120. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1121. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1122. return function (d, b) {
  1123. extendStatics(d, b);
  1124. function __() { this.constructor = d; }
  1125. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1126. };
  1127. })();
  1128. Object.defineProperty(exports, "__esModule", { value: true });
  1129. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  1130. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  1131. var buffer_helper_1 = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.js");
  1132. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  1133. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  1134. var ewma_bandwidth_estimator_1 = __webpack_require__(/*! ../utils/ewma-bandwidth-estimator */ "./src/utils/ewma-bandwidth-estimator.js");
  1135. var performance = window.performance;
  1136. var AbrController = /** @class */ (function (_super) {
  1137. __extends(AbrController, _super);
  1138. function AbrController(hls) {
  1139. var _this = _super.call(this, hls, events_1.default.FRAG_LOADING, events_1.default.FRAG_LOADED, events_1.default.FRAG_BUFFERED, events_1.default.ERROR) || this;
  1140. _this.lastLoadedFragLevel = 0;
  1141. _this._nextAutoLevel = -1;
  1142. _this.hls = hls;
  1143. _this.timer = null;
  1144. _this._bwEstimator = null;
  1145. _this.onCheck = _this._abandonRulesCheck.bind(_this);
  1146. return _this;
  1147. }
  1148. AbrController.prototype.destroy = function () {
  1149. this.clearTimer();
  1150. event_handler_1.default.prototype.destroy.call(this);
  1151. };
  1152. AbrController.prototype.onFragLoading = function (data) {
  1153. var frag = data.frag;
  1154. if (frag.type === 'main') {
  1155. if (!this.timer) {
  1156. this.fragCurrent = frag;
  1157. this.timer = setInterval(this.onCheck, 100);
  1158. }
  1159. // lazy init of BwEstimator, rationale is that we use different params for Live/VoD
  1160. // so we need to wait for stream manifest / playlist type to instantiate it.
  1161. if (!this._bwEstimator) {
  1162. var hls_1 = this.hls;
  1163. var config = hls_1.config;
  1164. var level = frag.level;
  1165. var isLive = hls_1.levels[level].details.live;
  1166. var ewmaFast = void 0, ewmaSlow = void 0;
  1167. if (isLive) {
  1168. ewmaFast = config.abrEwmaFastLive;
  1169. ewmaSlow = config.abrEwmaSlowLive;
  1170. }
  1171. else {
  1172. ewmaFast = config.abrEwmaFastVoD;
  1173. ewmaSlow = config.abrEwmaSlowVoD;
  1174. }
  1175. this._bwEstimator = new ewma_bandwidth_estimator_1.default(hls_1, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);
  1176. }
  1177. }
  1178. };
  1179. AbrController.prototype._abandonRulesCheck = function () {
  1180. /*
  1181. monitor fragment retrieval time...
  1182. we compute expected time of arrival of the complete fragment.
  1183. we compare it to expected time of buffer starvation
  1184. */
  1185. var hls = this.hls;
  1186. var video = hls.media;
  1187. var frag = this.fragCurrent;
  1188. if (!frag) {
  1189. return;
  1190. }
  1191. var loader = frag.loader;
  1192. var minAutoLevel = hls.minAutoLevel;
  1193. // if loader has been destroyed or loading has been aborted, stop timer and return
  1194. if (!loader || (loader.stats && loader.stats.aborted)) {
  1195. logger_1.logger.warn('frag loader destroy or aborted, disarm abandonRules');
  1196. this.clearTimer();
  1197. // reset forced auto level value so that next level will be selected
  1198. this._nextAutoLevel = -1;
  1199. return;
  1200. }
  1201. var stats = loader.stats;
  1202. /* only monitor frag retrieval time if
  1203. (video not paused OR first fragment being loaded(ready state === HAVE_NOTHING = 0)) AND autoswitching enabled AND not lowest level (=> means that we have several levels) */
  1204. if (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {
  1205. var requestDelay = performance.now() - stats.trequest, playbackRate = Math.abs(video.playbackRate);
  1206. // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate
  1207. if (requestDelay > (500 * frag.duration / playbackRate)) {
  1208. var levels = hls.levels, loadRate = Math.max(1, stats.bw ? stats.bw / 8 : stats.loaded * 1000 / requestDelay), // byte/s; at least 1 byte/s to avoid division by zero
  1209. // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size
  1210. level = levels[frag.level], levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate, expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8)), pos = video.currentTime, fragLoadedDelay = (expectedLen - stats.loaded) / loadRate, bufferStarvationDelay = (buffer_helper_1.BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;
  1211. // consider emergency switch down only if we have less than 2 frag buffered AND
  1212. // time to finish loading current fragment is bigger than buffer starvation delay
  1213. // ie if we risk buffer starvation if bw does not increase quickly
  1214. if ((bufferStarvationDelay < (2 * frag.duration / playbackRate)) && (fragLoadedDelay > bufferStarvationDelay)) {
  1215. var fragLevelNextLoadedDelay = void 0, nextLoadLevel = void 0;
  1216. // lets iterate through lower level and try to find the biggest one that could avoid rebuffering
  1217. // we start from current level - 1 and we step down , until we find a matching level
  1218. for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {
  1219. // compute time to load next fragment at lower level
  1220. // 0.8 : consider only 80% of current bw to be conservative
  1221. // 8 = bits per byte (bps/Bps)
  1222. var levelNextBitrate = levels[nextLoadLevel].realBitrate ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate) : levels[nextLoadLevel].bitrate;
  1223. fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);
  1224. if (fragLevelNextLoadedDelay < bufferStarvationDelay) {
  1225. // we found a lower level that be rebuffering free with current estimated bw !
  1226. break;
  1227. }
  1228. }
  1229. // only emergency switch down if it takes less time to load new fragment at lowest level instead
  1230. // of finishing loading current one ...
  1231. if (fragLevelNextLoadedDelay < fragLoadedDelay) {
  1232. logger_1.logger.warn("loading too slow, abort fragment loading and switch to level " + nextLoadLevel + ":fragLoadedDelay[" + nextLoadLevel + "]<fragLoadedDelay[" + (frag.level - 1) + "];bufferStarvationDelay:" + fragLevelNextLoadedDelay.toFixed(1) + "<" + fragLoadedDelay.toFixed(1) + ":" + bufferStarvationDelay.toFixed(1));
  1233. // force next load level in auto mode
  1234. hls.nextLoadLevel = nextLoadLevel;
  1235. // update bw estimate for this fragment before cancelling load (this will help reducing the bw)
  1236. this._bwEstimator.sample(requestDelay, stats.loaded);
  1237. // abort fragment loading
  1238. loader.abort();
  1239. // stop abandon rules timer
  1240. this.clearTimer();
  1241. hls.trigger(events_1.default.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });
  1242. }
  1243. }
  1244. }
  1245. }
  1246. };
  1247. AbrController.prototype.onFragLoaded = function (data) {
  1248. var frag = data.frag;
  1249. if (frag.type === 'main' && Number.isFinite(frag.sn)) {
  1250. // stop monitoring bw once frag loaded
  1251. this.clearTimer();
  1252. // store level id after successful fragment load
  1253. this.lastLoadedFragLevel = frag.level;
  1254. // reset forced auto level value so that next level will be selected
  1255. this._nextAutoLevel = -1;
  1256. // compute level average bitrate
  1257. if (this.hls.config.abrMaxWithRealBitrate) {
  1258. var level = this.hls.levels[frag.level];
  1259. var loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;
  1260. var loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;
  1261. level.loaded = { bytes: loadedBytes, duration: loadedDuration };
  1262. level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);
  1263. }
  1264. // if fragment has been loaded to perform a bitrate test,
  1265. if (data.frag.bitrateTest) {
  1266. var stats = data.stats;
  1267. stats.tparsed = stats.tbuffered = stats.tload;
  1268. this.onFragBuffered(data);
  1269. }
  1270. }
  1271. };
  1272. AbrController.prototype.onFragBuffered = function (data) {
  1273. var stats = data.stats;
  1274. var frag = data.frag;
  1275. // only update stats on first frag buffering
  1276. // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly
  1277. // and leading to wrong bw estimation
  1278. // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)
  1279. if (stats.aborted !== true && frag.type === 'main' && Number.isFinite(frag.sn) && ((!frag.bitrateTest || stats.tload === stats.tbuffered))) {
  1280. // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached
  1281. // in case we use config.startFragPrefetch while media is not attached yet, fragment might be parsed while media not attached yet, but it will only be buffered on media attached
  1282. // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation
  1283. var fragLoadingProcessingMs = stats.tparsed - stats.trequest;
  1284. logger_1.logger.log("latency/loading/parsing/append/kbps:" + Math.round(stats.tfirst - stats.trequest) + "/" + Math.round(stats.tload - stats.tfirst) + "/" + Math.round(stats.tparsed - stats.tload) + "/" + Math.round(stats.tbuffered - stats.tparsed) + "/" + Math.round(8 * stats.loaded / (stats.tbuffered - stats.trequest)));
  1285. this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);
  1286. stats.bwEstimate = this._bwEstimator.getEstimate();
  1287. // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration
  1288. if (frag.bitrateTest) {
  1289. this.bitrateTestDelay = fragLoadingProcessingMs / 1000;
  1290. }
  1291. else {
  1292. this.bitrateTestDelay = 0;
  1293. }
  1294. }
  1295. };
  1296. AbrController.prototype.onError = function (data) {
  1297. // stop timer in case of frag loading error
  1298. switch (data.details) {
  1299. case errors_1.ErrorDetails.FRAG_LOAD_ERROR:
  1300. case errors_1.ErrorDetails.FRAG_LOAD_TIMEOUT:
  1301. this.clearTimer();
  1302. break;
  1303. default:
  1304. break;
  1305. }
  1306. };
  1307. AbrController.prototype.clearTimer = function () {
  1308. clearInterval(this.timer);
  1309. this.timer = null;
  1310. };
  1311. Object.defineProperty(AbrController.prototype, "nextAutoLevel", {
  1312. // return next auto level
  1313. get: function () {
  1314. var forcedAutoLevel = this._nextAutoLevel;
  1315. var bwEstimator = this._bwEstimator;
  1316. // in case next auto level has been forced, and bw not available or not reliable, return forced value
  1317. if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {
  1318. return forcedAutoLevel;
  1319. }
  1320. // compute next level using ABR logic
  1321. var nextABRAutoLevel = this._nextABRAutoLevel;
  1322. // if forced auto level has been defined, use it to cap ABR computed quality level
  1323. if (forcedAutoLevel !== -1) {
  1324. nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);
  1325. }
  1326. return nextABRAutoLevel;
  1327. },
  1328. set: function (nextLevel) {
  1329. this._nextAutoLevel = nextLevel;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(AbrController.prototype, "_nextABRAutoLevel", {
  1335. get: function () {
  1336. var hls = this.hls, maxAutoLevel = hls.maxAutoLevel, levels = hls.levels, config = hls.config, minAutoLevel = hls.minAutoLevel;
  1337. var video = hls.media, currentLevel = this.lastLoadedFragLevel, currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0, pos = (video ? video.currentTime : 0),
  1338. // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as
  1339. // if we're playing back at the normal rate.
  1340. playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.playbackRate) : 1.0), avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate,
  1341. // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.
  1342. bufferStarvationDelay = (buffer_helper_1.BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate;
  1343. // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all
  1344. var bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);
  1345. if (bestLevel >= 0) {
  1346. return bestLevel;
  1347. }
  1348. else {
  1349. logger_1.logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');
  1350. // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering
  1351. // if no matching level found, logic will return 0
  1352. var maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay, bwFactor = config.abrBandWidthFactor, bwUpFactor = config.abrBandWidthUpFactor;
  1353. if (bufferStarvationDelay === 0) {
  1354. // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test
  1355. var bitrateTestDelay = this.bitrateTestDelay;
  1356. if (bitrateTestDelay) {
  1357. // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value
  1358. // max video loading delay used in automatic start level selection :
  1359. // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +
  1360. // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )
  1361. // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration
  1362. var maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;
  1363. maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;
  1364. logger_1.logger.trace("bitrate test took " + Math.round(1000 * bitrateTestDelay) + "ms, set first fragment max fetchDuration to " + Math.round(1000 * maxStarvationDelay) + " ms");
  1365. // don't use conservative factor on bitrate test
  1366. bwFactor = bwUpFactor = 1;
  1367. }
  1368. }
  1369. bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);
  1370. return Math.max(bestLevel, 0);
  1371. }
  1372. },
  1373. enumerable: true,
  1374. configurable: true
  1375. });
  1376. AbrController.prototype._findBestLevel = function (currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {
  1377. for (var i = maxAutoLevel; i >= minAutoLevel; i--) {
  1378. var levelInfo = levels[i];
  1379. if (!levelInfo) {
  1380. continue;
  1381. }
  1382. var levelDetails = levelInfo.details, avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration, live = levelDetails ? levelDetails.live : false, adjustedbw = void 0;
  1383. // follow algorithm captured from stagefright :
  1384. // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp
  1385. // Pick the highest bandwidth stream below or equal to estimated bandwidth.
  1386. // consider only 80% of the available bandwidth, but if we are switching up,
  1387. // be even more conservative (70%) to avoid overestimating and immediately
  1388. // switching back.
  1389. if (i <= currentLevel) {
  1390. adjustedbw = bwFactor * currentBw;
  1391. }
  1392. else {
  1393. adjustedbw = bwUpFactor * currentBw;
  1394. }
  1395. var bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate, fetchDuration = bitrate * avgDuration / adjustedbw;
  1396. logger_1.logger.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: " + i + "/" + Math.round(adjustedbw) + "/" + bitrate + "/" + avgDuration + "/" + maxFetchDuration + "/" + fetchDuration);
  1397. // if adjusted bw is greater than level bitrate AND
  1398. if (adjustedbw > bitrate &&
  1399. // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches
  1400. // we don't account for max Fetch Duration for live streams, this is to avoid switching down when near the edge of live sliding window ...
  1401. // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1
  1402. (!fetchDuration || (live && !this.bitrateTestDelay) || fetchDuration < maxFetchDuration)) {
  1403. // as we are looping from highest to lowest, this will return the best achievable quality level
  1404. return i;
  1405. }
  1406. }
  1407. // not enough time budget even with quality level 0 ... rebuffering might happen
  1408. return -1;
  1409. };
  1410. return AbrController;
  1411. }(event_handler_1.default));
  1412. exports.default = AbrController;
  1413. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  1414. /***/ }),
  1415. /***/ "./src/controller/audio-stream-controller.js":
  1416. /*!***************************************************!*\
  1417. !*** ./src/controller/audio-stream-controller.js ***!
  1418. \***************************************************/
  1419. /*! no static exports found */
  1420. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  1421. /***/ (function(module, exports, __webpack_require__) {
  1422. "use strict";
  1423. /* WEBPACK VAR INJECTION */(function(Number) {
  1424. /*
  1425. * Audio Stream Controller
  1426. */
  1427. var __extends = (this && this.__extends) || (function () {
  1428. var extendStatics = Object.setPrototypeOf ||
  1429. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  1430. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  1431. return function (d, b) {
  1432. extendStatics(d, b);
  1433. function __() { this.constructor = d; }
  1434. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  1435. };
  1436. })();
  1437. Object.defineProperty(exports, "__esModule", { value: true });
  1438. var binary_search_1 = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.js");
  1439. var buffer_helper_1 = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.js");
  1440. var demuxer_1 = __webpack_require__(/*! ../demux/demuxer */ "./src/demux/demuxer.js");
  1441. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  1442. var LevelHelper = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.js");
  1443. var time_ranges_1 = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.js");
  1444. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  1445. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  1446. var discontinuities_1 = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.js");
  1447. var fragment_tracker_1 = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.js");
  1448. var fragment_1 = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.js");
  1449. var base_stream_controller_1 = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.js");
  1450. var performance = window.performance;
  1451. var TICK_INTERVAL = 100; // how often to tick in ms
  1452. var AudioStreamController = /** @class */ (function (_super) {
  1453. __extends(AudioStreamController, _super);
  1454. function AudioStreamController(hls, fragmentTracker) {
  1455. var _this = _super.call(this, hls, events_1.default.MEDIA_ATTACHED, events_1.default.MEDIA_DETACHING, events_1.default.AUDIO_TRACKS_UPDATED, events_1.default.AUDIO_TRACK_SWITCHING, events_1.default.AUDIO_TRACK_LOADED, events_1.default.KEY_LOADED, events_1.default.FRAG_LOADED, events_1.default.FRAG_PARSING_INIT_SEGMENT, events_1.default.FRAG_PARSING_DATA, events_1.default.FRAG_PARSED, events_1.default.ERROR, events_1.default.BUFFER_RESET, events_1.default.BUFFER_CREATED, events_1.default.BUFFER_APPENDED, events_1.default.BUFFER_FLUSHED, events_1.default.INIT_PTS_FOUND) || this;
  1456. _this.fragmentTracker = fragmentTracker;
  1457. _this.config = hls.config;
  1458. _this.audioCodecSwap = false;
  1459. _this._state = base_stream_controller_1.State.STOPPED;
  1460. _this.initPTS = [];
  1461. _this.waitingFragment = null;
  1462. _this.videoTrackCC = null;
  1463. return _this;
  1464. }
  1465. // Signal that video PTS was found
  1466. AudioStreamController.prototype.onInitPtsFound = function (data) {
  1467. var demuxerId = data.id, cc = data.frag.cc, initPTS = data.initPTS;
  1468. if (demuxerId === 'main') {
  1469. // Always update the new INIT PTS
  1470. // Can change due level switch
  1471. this.initPTS[cc] = initPTS;
  1472. this.videoTrackCC = cc;
  1473. logger_1.logger.log("InitPTS for cc: " + cc + " found from video track: " + initPTS);
  1474. // If we are waiting we need to demux/remux the waiting frag
  1475. // With the new initPTS
  1476. if (this.state === base_stream_controller_1.State.WAITING_INIT_PTS) {
  1477. this.tick();
  1478. }
  1479. }
  1480. };
  1481. AudioStreamController.prototype.startLoad = function (startPosition) {
  1482. if (this.tracks) {
  1483. var lastCurrentTime = this.lastCurrentTime;
  1484. this.stopLoad();
  1485. this.setInterval(TICK_INTERVAL);
  1486. this.fragLoadError = 0;
  1487. if (lastCurrentTime > 0 && startPosition === -1) {
  1488. logger_1.logger.log("audio:override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  1489. this.state = base_stream_controller_1.State.IDLE;
  1490. }
  1491. else {
  1492. this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;
  1493. this.state = base_stream_controller_1.State.STARTING;
  1494. }
  1495. this.nextLoadPosition = this.startPosition = this.lastCurrentTime;
  1496. this.tick();
  1497. }
  1498. else {
  1499. this.startPosition = startPosition;
  1500. this.state = base_stream_controller_1.State.STOPPED;
  1501. }
  1502. };
  1503. Object.defineProperty(AudioStreamController.prototype, "state", {
  1504. get: function () {
  1505. return this._state;
  1506. },
  1507. set: function (nextState) {
  1508. if (this.state !== nextState) {
  1509. var previousState = this.state;
  1510. this._state = nextState;
  1511. logger_1.logger.log("audio stream:" + previousState + "->" + nextState);
  1512. }
  1513. },
  1514. enumerable: true,
  1515. configurable: true
  1516. });
  1517. AudioStreamController.prototype.doTick = function () {
  1518. var pos, track, trackDetails, hls = this.hls, config = hls.config;
  1519. // logger.log('audioStream:' + this.state);
  1520. switch (this.state) {
  1521. case base_stream_controller_1.State.ERROR:
  1522. // don't do anything in error state to avoid breaking further ...
  1523. case base_stream_controller_1.State.PAUSED:
  1524. // don't do anything in paused state either ...
  1525. case base_stream_controller_1.State.BUFFER_FLUSHING:
  1526. break;
  1527. case base_stream_controller_1.State.STARTING:
  1528. this.state = base_stream_controller_1.State.WAITING_TRACK;
  1529. this.loadedmetadata = false;
  1530. break;
  1531. case base_stream_controller_1.State.IDLE:
  1532. var tracks = this.tracks;
  1533. // audio tracks not received => exit loop
  1534. if (!tracks) {
  1535. break;
  1536. }
  1537. // if video not attached AND
  1538. // start fragment already requested OR start frag prefetch disable
  1539. // exit loop
  1540. // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop
  1541. if (!this.media &&
  1542. (this.startFragRequested || !config.startFragPrefetch)) {
  1543. break;
  1544. }
  1545. // determine next candidate fragment to be loaded, based on current position and
  1546. // end of buffer position
  1547. // if we have not yet loaded any fragment, start loading from start position
  1548. if (this.loadedmetadata) {
  1549. pos = this.media.currentTime;
  1550. }
  1551. else {
  1552. pos = this.nextLoadPosition;
  1553. if (pos === undefined) {
  1554. break;
  1555. }
  1556. }
  1557. var media = this.mediaBuffer ? this.mediaBuffer : this.media, videoBuffer = this.videoBuffer ? this.videoBuffer : this.media, bufferInfo = buffer_helper_1.BufferHelper.bufferInfo(media, pos, config.maxBufferHole), mainBufferInfo = buffer_helper_1.BufferHelper.bufferInfo(videoBuffer, pos, config.maxBufferHole), bufferLen = bufferInfo.len, bufferEnd_1 = bufferInfo.end, fragPrevious = this.fragPrevious,
  1558. // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)
  1559. // whichever is smaller.
  1560. // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)
  1561. maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength), maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len), audioSwitch = this.audioSwitch, trackId = this.trackId;
  1562. // if buffer length is less than maxBufLen try to load a new fragment
  1563. if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {
  1564. trackDetails = tracks[trackId].details;
  1565. // if track info not retrieved yet, switch state and wait for track retrieval
  1566. if (typeof trackDetails === 'undefined') {
  1567. this.state = base_stream_controller_1.State.WAITING_TRACK;
  1568. break;
  1569. }
  1570. if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {
  1571. this.hls.trigger(events_1.default.BUFFER_EOS, { type: 'audio' });
  1572. this.state = base_stream_controller_1.State.ENDED;
  1573. return;
  1574. }
  1575. // find fragment index, contiguous with end of buffer position
  1576. var fragments = trackDetails.fragments, fragLen = fragments.length, start = fragments[0].start, end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration, frag = void 0;
  1577. // When switching audio track, reload audio as close as possible to currentTime
  1578. if (audioSwitch) {
  1579. if (trackDetails.live && !trackDetails.PTSKnown) {
  1580. logger_1.logger.log('switching audiotrack, live stream, unknown PTS,load first fragment');
  1581. bufferEnd_1 = 0;
  1582. }
  1583. else {
  1584. bufferEnd_1 = pos;
  1585. // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime
  1586. if (trackDetails.PTSKnown && pos < start) {
  1587. // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start
  1588. if (bufferInfo.end > start || bufferInfo.nextStart) {
  1589. logger_1.logger.log('alt audio track ahead of main track, seek to start of alt audio track');
  1590. this.media.currentTime = start + 0.05;
  1591. }
  1592. else {
  1593. return;
  1594. }
  1595. }
  1596. }
  1597. }
  1598. if (trackDetails.initSegment && !trackDetails.initSegment.data) {
  1599. frag = trackDetails.initSegment;
  1600. } // eslint-disable-line brace-style
  1601. // if bufferEnd before start of playlist, load first fragment
  1602. else if (bufferEnd_1 <= start) {
  1603. frag = fragments[0];
  1604. if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {
  1605. // Ensure we find a fragment which matches the continuity of the video track
  1606. frag = discontinuities_1.findFragWithCC(fragments, this.videoTrackCC);
  1607. }
  1608. if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {
  1609. // we just loaded this first fragment, and we are still lagging behind the start of the live playlist
  1610. // let's force seek to start
  1611. var nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;
  1612. logger_1.logger.log("no alt audio available @currentTime:" + this.media.currentTime + ", seeking @" + (nextBuffered + 0.05));
  1613. this.media.currentTime = nextBuffered + 0.05;
  1614. return;
  1615. }
  1616. }
  1617. else {
  1618. var foundFrag = void 0;
  1619. var maxFragLookUpTolerance_1 = config.maxFragLookUpTolerance;
  1620. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;
  1621. var fragmentWithinToleranceTest = function (candidate) {
  1622. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  1623. // this is to cope with situations like
  1624. // bufferEnd = 9.991
  1625. // frag[Ø] : [0,10]
  1626. // frag[1] : [10,20]
  1627. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  1628. // frag start frag start+duration
  1629. // |-----------------------------|
  1630. // <---> <--->
  1631. // ...--------><-----------------------------><---------....
  1632. // previous frag matching fragment next frag
  1633. // return -1 return 0 return 1
  1634. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  1635. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  1636. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance_1, candidate.duration);
  1637. if ((candidate.start + candidate.duration - candidateLookupTolerance) <= bufferEnd_1) {
  1638. return 1;
  1639. }
  1640. else if (candidate.start - candidateLookupTolerance > bufferEnd_1 && candidate.start) {
  1641. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  1642. return -1;
  1643. }
  1644. return 0;
  1645. };
  1646. if (bufferEnd_1 < end) {
  1647. if (bufferEnd_1 > end - maxFragLookUpTolerance_1) {
  1648. maxFragLookUpTolerance_1 = 0;
  1649. }
  1650. // Prefer the next fragment if it's within tolerance
  1651. if (fragNext && !fragmentWithinToleranceTest(fragNext)) {
  1652. foundFrag = fragNext;
  1653. }
  1654. else {
  1655. foundFrag = binary_search_1.default.search(fragments, fragmentWithinToleranceTest);
  1656. }
  1657. }
  1658. else {
  1659. // reach end of playlist
  1660. foundFrag = fragments[fragLen - 1];
  1661. }
  1662. if (foundFrag) {
  1663. frag = foundFrag;
  1664. start = foundFrag.start;
  1665. // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  1666. if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {
  1667. if (frag.sn < trackDetails.endSN) {
  1668. frag = fragments[frag.sn + 1 - trackDetails.startSN];
  1669. logger_1.logger.log("SN just loaded, load next one: " + frag.sn);
  1670. }
  1671. else {
  1672. frag = null;
  1673. }
  1674. }
  1675. }
  1676. }
  1677. if (frag) {
  1678. // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));
  1679. if (frag.encrypted) {
  1680. logger_1.logger.log("Loading key for " + frag.sn + " of [" + trackDetails.startSN + " ," + trackDetails.endSN + "],track " + trackId);
  1681. this.state = base_stream_controller_1.State.KEY_LOADING;
  1682. hls.trigger(events_1.default.KEY_LOADING, { frag: frag });
  1683. }
  1684. else {
  1685. logger_1.logger.log("Loading " + frag.sn + ", cc: " + frag.cc + " of [" + trackDetails.startSN + " ," + trackDetails.endSN + "],track " + trackId + ", currentTime:" + pos + ",bufferEnd:" + bufferEnd_1.toFixed(3));
  1686. // only load if fragment is not loaded or if in audio switch
  1687. // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch
  1688. this.fragCurrent = frag;
  1689. if (audioSwitch || this.fragmentTracker.getState(frag) === fragment_tracker_1.FragmentState.NOT_LOADED) {
  1690. this.startFragRequested = true;
  1691. if (Number.isFinite(frag.sn)) {
  1692. this.nextLoadPosition = frag.start + frag.duration;
  1693. }
  1694. hls.trigger(events_1.default.FRAG_LOADING, { frag: frag });
  1695. this.state = base_stream_controller_1.State.FRAG_LOADING;
  1696. }
  1697. }
  1698. }
  1699. }
  1700. break;
  1701. case base_stream_controller_1.State.WAITING_TRACK:
  1702. track = this.tracks[this.trackId];
  1703. // check if playlist is already loaded
  1704. if (track && track.details) {
  1705. this.state = base_stream_controller_1.State.IDLE;
  1706. }
  1707. break;
  1708. case base_stream_controller_1.State.FRAG_LOADING_WAITING_RETRY:
  1709. var now = performance.now();
  1710. var retryDate = this.retryDate;
  1711. media = this.media;
  1712. var isSeeking = media && media.seeking;
  1713. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  1714. if (!retryDate || (now >= retryDate) || isSeeking) {
  1715. logger_1.logger.log('audioStreamController: retryDate reached, switch back to IDLE state');
  1716. this.state = base_stream_controller_1.State.IDLE;
  1717. }
  1718. break;
  1719. case base_stream_controller_1.State.WAITING_INIT_PTS:
  1720. var videoTrackCC = this.videoTrackCC;
  1721. if (this.initPTS[videoTrackCC] === undefined) {
  1722. break;
  1723. }
  1724. // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS
  1725. var waitingFrag = this.waitingFragment;
  1726. if (waitingFrag) {
  1727. var waitingFragCC = waitingFrag.frag.cc;
  1728. if (videoTrackCC !== waitingFragCC) {
  1729. track = this.tracks[this.trackId];
  1730. if (track.details && track.details.live) {
  1731. logger_1.logger.warn("Waiting fragment CC (" + waitingFragCC + ") does not match video track CC (" + videoTrackCC + ")");
  1732. this.waitingFragment = null;
  1733. this.state = base_stream_controller_1.State.IDLE;
  1734. }
  1735. }
  1736. else {
  1737. this.state = base_stream_controller_1.State.FRAG_LOADING;
  1738. this.onFragLoaded(this.waitingFragment);
  1739. this.waitingFragment = null;
  1740. }
  1741. }
  1742. else {
  1743. this.state = base_stream_controller_1.State.IDLE;
  1744. }
  1745. break;
  1746. case base_stream_controller_1.State.STOPPED:
  1747. case base_stream_controller_1.State.FRAG_LOADING:
  1748. case base_stream_controller_1.State.PARSING:
  1749. case base_stream_controller_1.State.PARSED:
  1750. case base_stream_controller_1.State.ENDED:
  1751. break;
  1752. default:
  1753. break;
  1754. }
  1755. };
  1756. AudioStreamController.prototype.onMediaAttached = function (data) {
  1757. var media = this.media = this.mediaBuffer = data.media;
  1758. this.onvseeking = this.onMediaSeeking.bind(this);
  1759. this.onvended = this.onMediaEnded.bind(this);
  1760. media.addEventListener('seeking', this.onvseeking);
  1761. media.addEventListener('ended', this.onvended);
  1762. var config = this.config;
  1763. if (this.tracks && config.autoStartLoad) {
  1764. this.startLoad(config.startPosition);
  1765. }
  1766. };
  1767. AudioStreamController.prototype.onMediaDetaching = function () {
  1768. var media = this.media;
  1769. if (media && media.ended) {
  1770. logger_1.logger.log('MSE detaching and video ended, reset startPosition');
  1771. this.startPosition = this.lastCurrentTime = 0;
  1772. }
  1773. // remove video listeners
  1774. if (media) {
  1775. media.removeEventListener('seeking', this.onvseeking);
  1776. media.removeEventListener('ended', this.onvended);
  1777. this.onvseeking = this.onvseeked = this.onvended = null;
  1778. }
  1779. this.media = this.mediaBuffer = this.videoBuffer = null;
  1780. this.loadedmetadata = false;
  1781. this.stopLoad();
  1782. };
  1783. AudioStreamController.prototype.onAudioTracksUpdated = function (data) {
  1784. logger_1.logger.log('audio tracks updated');
  1785. this.tracks = data.audioTracks;
  1786. };
  1787. AudioStreamController.prototype.onAudioTrackSwitching = function (data) {
  1788. // if any URL found on new audio track, it is an alternate audio track
  1789. var altAudio = !!data.url;
  1790. this.trackId = data.id;
  1791. this.fragCurrent = null;
  1792. this.state = base_stream_controller_1.State.PAUSED;
  1793. this.waitingFragment = null;
  1794. // destroy useless demuxer when switching audio to main
  1795. if (!altAudio) {
  1796. if (this.demuxer) {
  1797. this.demuxer.destroy();
  1798. this.demuxer = null;
  1799. }
  1800. }
  1801. else {
  1802. // switching to audio track, start timer if not already started
  1803. this.setInterval(TICK_INTERVAL);
  1804. }
  1805. // should we switch tracks ?
  1806. if (altAudio) {
  1807. this.audioSwitch = true;
  1808. // main audio track are handled by stream-controller, just do something if switching to alt audio track
  1809. this.state = base_stream_controller_1.State.IDLE;
  1810. }
  1811. this.tick();
  1812. };
  1813. AudioStreamController.prototype.onAudioTrackLoaded = function (data) {
  1814. var newDetails = data.details, trackId = data.id, track = this.tracks[trackId], duration = newDetails.totalduration, sliding = 0;
  1815. logger_1.logger.log("track " + trackId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + duration);
  1816. if (newDetails.live) {
  1817. var curDetails = track.details;
  1818. if (curDetails && newDetails.fragments.length > 0) {
  1819. // we already have details for that level, merge them
  1820. LevelHelper.mergeDetails(curDetails, newDetails);
  1821. sliding = newDetails.fragments[0].start;
  1822. // TODO
  1823. // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  1824. if (newDetails.PTSKnown) {
  1825. logger_1.logger.log("live audio playlist sliding:" + sliding.toFixed(3));
  1826. }
  1827. else {
  1828. logger_1.logger.log('live audio playlist - outdated PTS, unknown sliding');
  1829. }
  1830. }
  1831. else {
  1832. newDetails.PTSKnown = false;
  1833. logger_1.logger.log('live audio playlist - first load, unknown sliding');
  1834. }
  1835. }
  1836. else {
  1837. newDetails.PTSKnown = false;
  1838. }
  1839. track.details = newDetails;
  1840. // compute start position
  1841. if (!this.startFragRequested) {
  1842. // compute start position if set to -1. use it straight away if value is defined
  1843. if (this.startPosition === -1) {
  1844. // first, check if start time offset has been set in playlist, if yes, use this value
  1845. var startTimeOffset = newDetails.startTimeOffset;
  1846. if (Number.isFinite(startTimeOffset)) {
  1847. logger_1.logger.log("start time offset found in playlist, adjust startPosition to " + startTimeOffset);
  1848. this.startPosition = startTimeOffset;
  1849. }
  1850. else {
  1851. this.startPosition = 0;
  1852. }
  1853. }
  1854. this.nextLoadPosition = this.startPosition;
  1855. }
  1856. // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment
  1857. if (this.state === base_stream_controller_1.State.WAITING_TRACK) {
  1858. this.state = base_stream_controller_1.State.IDLE;
  1859. }
  1860. // trigger handler right now
  1861. this.tick();
  1862. };
  1863. AudioStreamController.prototype.onKeyLoaded = function () {
  1864. if (this.state === base_stream_controller_1.State.KEY_LOADING) {
  1865. this.state = base_stream_controller_1.State.IDLE;
  1866. this.tick();
  1867. }
  1868. };
  1869. AudioStreamController.prototype.onFragLoaded = function (data) {
  1870. var fragCurrent = this.fragCurrent, fragLoaded = data.frag;
  1871. if (this.state === base_stream_controller_1.State.FRAG_LOADING &&
  1872. fragCurrent &&
  1873. fragLoaded.type === 'audio' &&
  1874. fragLoaded.level === fragCurrent.level &&
  1875. fragLoaded.sn === fragCurrent.sn) {
  1876. var track = this.tracks[this.trackId], details = track.details, duration = details.totalduration, trackId = fragCurrent.level, sn = fragCurrent.sn, cc = fragCurrent.cc, audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2', stats = this.stats = data.stats;
  1877. if (sn === 'initSegment') {
  1878. this.state = base_stream_controller_1.State.IDLE;
  1879. stats.tparsed = stats.tbuffered = performance.now();
  1880. details.initSegment.data = data.payload;
  1881. this.hls.trigger(events_1.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });
  1882. this.tick();
  1883. }
  1884. else {
  1885. this.state = base_stream_controller_1.State.PARSING;
  1886. // transmux the MPEG-TS data to ISO-BMFF segments
  1887. this.appended = false;
  1888. if (!this.demuxer) {
  1889. this.demuxer = new demuxer_1.default(this.hls, 'audio');
  1890. }
  1891. // Check if we have video initPTS
  1892. // If not we need to wait for it
  1893. var initPTS = this.initPTS[cc];
  1894. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  1895. if (details.initSegment || initPTS !== undefined) {
  1896. this.pendingBuffering = true;
  1897. logger_1.logger.log("Demuxing " + sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
  1898. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)
  1899. var accurateTimeOffset = false; // details.PTSKnown || !details.live;
  1900. this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);
  1901. }
  1902. else {
  1903. logger_1.logger.log("unknown video PTS for continuity counter " + cc + ", waiting for video PTS before demuxing audio frag " + sn + " of [" + details.startSN + " ," + details.endSN + "],track " + trackId);
  1904. this.waitingFragment = data;
  1905. this.state = base_stream_controller_1.State.WAITING_INIT_PTS;
  1906. }
  1907. }
  1908. }
  1909. this.fragLoadError = 0;
  1910. };
  1911. AudioStreamController.prototype.onFragParsingInitSegment = function (data) {
  1912. var fragCurrent = this.fragCurrent;
  1913. var fragNew = data.frag;
  1914. if (fragCurrent &&
  1915. data.id === 'audio' &&
  1916. fragNew.sn === fragCurrent.sn &&
  1917. fragNew.level === fragCurrent.level &&
  1918. this.state === base_stream_controller_1.State.PARSING) {
  1919. var tracks = data.tracks, track = void 0;
  1920. // delete any video track found on audio demuxer
  1921. if (tracks.video) {
  1922. delete tracks.video;
  1923. }
  1924. // include levelCodec in audio and video tracks
  1925. track = tracks.audio;
  1926. if (track) {
  1927. track.levelCodec = track.codec;
  1928. track.id = data.id;
  1929. this.hls.trigger(events_1.default.BUFFER_CODECS, tracks);
  1930. logger_1.logger.log("audio track:audio,container:" + track.container + ",codecs[level/parsed]=[" + track.levelCodec + "/" + track.codec + "]");
  1931. var initSegment = track.initSegment;
  1932. if (initSegment) {
  1933. var appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };
  1934. if (this.audioSwitch) {
  1935. this.pendingData = [appendObj];
  1936. }
  1937. else {
  1938. this.appended = true;
  1939. // arm pending Buffering flag before appending a segment
  1940. this.pendingBuffering = true;
  1941. this.hls.trigger(events_1.default.BUFFER_APPENDING, appendObj);
  1942. }
  1943. }
  1944. // trigger handler right now
  1945. this.tick();
  1946. }
  1947. }
  1948. };
  1949. AudioStreamController.prototype.onFragParsingData = function (data) {
  1950. var _this = this;
  1951. var fragCurrent = this.fragCurrent;
  1952. var fragNew = data.frag;
  1953. if (fragCurrent &&
  1954. data.id === 'audio' &&
  1955. data.type === 'audio' &&
  1956. fragNew.sn === fragCurrent.sn &&
  1957. fragNew.level === fragCurrent.level &&
  1958. this.state === base_stream_controller_1.State.PARSING) {
  1959. var trackId = this.trackId, track = this.tracks[trackId], hls_1 = this.hls;
  1960. if (!Number.isFinite(data.endPTS)) {
  1961. data.endPTS = data.startPTS + fragCurrent.duration;
  1962. data.endDTS = data.startDTS + fragCurrent.duration;
  1963. }
  1964. fragCurrent.addElementaryStream(fragment_1.default.ElementaryStreamTypes.AUDIO);
  1965. logger_1.logger.log("parsed " + data.type + ",PTS:[" + data.startPTS.toFixed(3) + "," + data.endPTS.toFixed(3) + "],DTS:[" + data.startDTS.toFixed(3) + "/" + data.endDTS.toFixed(3) + "],nb:" + data.nb);
  1966. LevelHelper.updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);
  1967. var audioSwitch = this.audioSwitch, media = this.media, appendOnBufferFlush = false;
  1968. // Only flush audio from old audio tracks when PTS is known on new audio track
  1969. if (audioSwitch && media) {
  1970. if (media.readyState) {
  1971. var currentTime = media.currentTime;
  1972. logger_1.logger.log('switching audio track : currentTime:' + currentTime);
  1973. if (currentTime >= data.startPTS) {
  1974. logger_1.logger.log('switching audio track : flushing all audio');
  1975. this.state = base_stream_controller_1.State.BUFFER_FLUSHING;
  1976. hls_1.trigger(events_1.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  1977. appendOnBufferFlush = true;
  1978. // Lets announce that the initial audio track switch flush occur
  1979. this.audioSwitch = false;
  1980. hls_1.trigger(events_1.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  1981. }
  1982. }
  1983. else {
  1984. // Lets announce that the initial audio track switch flush occur
  1985. this.audioSwitch = false;
  1986. hls_1.trigger(events_1.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  1987. }
  1988. }
  1989. var pendingData_1 = this.pendingData;
  1990. if (!pendingData_1) {
  1991. logger_1.logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');
  1992. hls_1.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: null, fatal: true });
  1993. return;
  1994. }
  1995. if (!this.audioSwitch) {
  1996. [data.data1, data.data2].forEach(function (buffer) {
  1997. if (buffer && buffer.length) {
  1998. pendingData_1.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });
  1999. }
  2000. });
  2001. if (!appendOnBufferFlush && pendingData_1.length) {
  2002. pendingData_1.forEach(function (appendObj) {
  2003. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  2004. // in that case it is useless to append following segments
  2005. if (_this.state === base_stream_controller_1.State.PARSING) {
  2006. // arm pending Buffering flag before appending a segment
  2007. _this.pendingBuffering = true;
  2008. _this.hls.trigger(events_1.default.BUFFER_APPENDING, appendObj);
  2009. }
  2010. });
  2011. this.pendingData = [];
  2012. this.appended = true;
  2013. }
  2014. }
  2015. // trigger handler right now
  2016. this.tick();
  2017. }
  2018. };
  2019. AudioStreamController.prototype.onFragParsed = function (data) {
  2020. var fragCurrent = this.fragCurrent;
  2021. var fragNew = data.frag;
  2022. if (fragCurrent &&
  2023. data.id === 'audio' &&
  2024. fragNew.sn === fragCurrent.sn &&
  2025. fragNew.level === fragCurrent.level &&
  2026. this.state === base_stream_controller_1.State.PARSING) {
  2027. this.stats.tparsed = performance.now();
  2028. this.state = base_stream_controller_1.State.PARSED;
  2029. this._checkAppendedParsed();
  2030. }
  2031. };
  2032. AudioStreamController.prototype.onBufferReset = function () {
  2033. // reset reference to sourcebuffers
  2034. this.mediaBuffer = this.videoBuffer = null;
  2035. this.loadedmetadata = false;
  2036. };
  2037. AudioStreamController.prototype.onBufferCreated = function (data) {
  2038. var audioTrack = data.tracks.audio;
  2039. if (audioTrack) {
  2040. this.mediaBuffer = audioTrack.buffer;
  2041. this.loadedmetadata = true;
  2042. }
  2043. if (data.tracks.video) {
  2044. this.videoBuffer = data.tracks.video.buffer;
  2045. }
  2046. };
  2047. AudioStreamController.prototype.onBufferAppended = function (data) {
  2048. if (data.parent === 'audio') {
  2049. var state = this.state;
  2050. if (state === base_stream_controller_1.State.PARSING || state === base_stream_controller_1.State.PARSED) {
  2051. // check if all buffers have been appended
  2052. this.pendingBuffering = (data.pending > 0);
  2053. this._checkAppendedParsed();
  2054. }
  2055. }
  2056. };
  2057. AudioStreamController.prototype._checkAppendedParsed = function () {
  2058. // trigger handler right now
  2059. if (this.state === base_stream_controller_1.State.PARSED && (!this.appended || !this.pendingBuffering)) {
  2060. var frag = this.fragCurrent, stats = this.stats, hls_2 = this.hls;
  2061. if (frag) {
  2062. this.fragPrevious = frag;
  2063. stats.tbuffered = performance.now();
  2064. hls_2.trigger(events_1.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });
  2065. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  2066. logger_1.logger.log("audio buffered : " + time_ranges_1.default.toString(media.buffered));
  2067. if (this.audioSwitch && this.appended) {
  2068. this.audioSwitch = false;
  2069. hls_2.trigger(events_1.default.AUDIO_TRACK_SWITCHED, { id: this.trackId });
  2070. }
  2071. this.state = base_stream_controller_1.State.IDLE;
  2072. }
  2073. this.tick();
  2074. }
  2075. };
  2076. AudioStreamController.prototype.onError = function (data) {
  2077. var frag = data.frag;
  2078. // don't handle frag error not related to audio fragment
  2079. if (frag && frag.type !== 'audio') {
  2080. return;
  2081. }
  2082. switch (data.details) {
  2083. case errors_1.ErrorDetails.FRAG_LOAD_ERROR:
  2084. case errors_1.ErrorDetails.FRAG_LOAD_TIMEOUT:
  2085. var frag_1 = data.frag;
  2086. // don't handle frag error not related to audio fragment
  2087. if (frag_1 && frag_1.type !== 'audio') {
  2088. break;
  2089. }
  2090. if (!data.fatal) {
  2091. var loadError = this.fragLoadError;
  2092. if (loadError) {
  2093. loadError++;
  2094. }
  2095. else {
  2096. loadError = 1;
  2097. }
  2098. var config = this.config;
  2099. if (loadError <= config.fragLoadingMaxRetry) {
  2100. this.fragLoadError = loadError;
  2101. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  2102. var delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);
  2103. logger_1.logger.warn("AudioStreamController: frag loading failed, retry in " + delay + " ms");
  2104. this.retryDate = performance.now() + delay;
  2105. // retry loading state
  2106. this.state = base_stream_controller_1.State.FRAG_LOADING_WAITING_RETRY;
  2107. }
  2108. else {
  2109. logger_1.logger.error("AudioStreamController: " + data.details + " reaches max retry, redispatch as fatal ...");
  2110. // switch error to fatal
  2111. data.fatal = true;
  2112. this.state = base_stream_controller_1.State.ERROR;
  2113. }
  2114. }
  2115. break;
  2116. case errors_1.ErrorDetails.AUDIO_TRACK_LOAD_ERROR:
  2117. case errors_1.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:
  2118. case errors_1.ErrorDetails.KEY_LOAD_ERROR:
  2119. case errors_1.ErrorDetails.KEY_LOAD_TIMEOUT:
  2120. // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received
  2121. if (this.state !== base_stream_controller_1.State.ERROR) {
  2122. // if fatal error, stop processing, otherwise move to IDLE to retry loading
  2123. this.state = data.fatal ? base_stream_controller_1.State.ERROR : base_stream_controller_1.State.IDLE;
  2124. logger_1.logger.warn("AudioStreamController: " + data.details + " while loading frag, now switching to " + this.state + " state ...");
  2125. }
  2126. break;
  2127. case errors_1.ErrorDetails.BUFFER_FULL_ERROR:
  2128. // if in appending state
  2129. if (data.parent === 'audio' && (this.state === base_stream_controller_1.State.PARSING || this.state === base_stream_controller_1.State.PARSED)) {
  2130. var media = this.mediaBuffer, currentTime = this.media.currentTime, mediaBuffered = media && buffer_helper_1.BufferHelper.isBuffered(media, currentTime) && buffer_helper_1.BufferHelper.isBuffered(media, currentTime + 0.5);
  2131. // reduce max buf len if current position is buffered
  2132. if (mediaBuffered) {
  2133. var config = this.config;
  2134. if (config.maxMaxBufferLength >= config.maxBufferLength) {
  2135. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  2136. config.maxMaxBufferLength /= 2;
  2137. logger_1.logger.warn("AudioStreamController: reduce max buffer length to " + config.maxMaxBufferLength + "s");
  2138. }
  2139. this.state = base_stream_controller_1.State.IDLE;
  2140. }
  2141. else {
  2142. // current position is not buffered, but browser is still complaining about buffer full error
  2143. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  2144. // in that case flush the whole audio buffer to recover
  2145. logger_1.logger.warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');
  2146. this.fragCurrent = null;
  2147. // flush everything
  2148. this.state = base_stream_controller_1.State.BUFFER_FLUSHING;
  2149. this.hls.trigger(events_1.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  2150. }
  2151. }
  2152. break;
  2153. default:
  2154. break;
  2155. }
  2156. };
  2157. AudioStreamController.prototype.onBufferFlushed = function () {
  2158. var _this = this;
  2159. var pendingData = this.pendingData;
  2160. if (pendingData && pendingData.length) {
  2161. logger_1.logger.log('AudioStreamController: appending pending audio data after buffer flushed');
  2162. pendingData.forEach(function (appendObj) {
  2163. _this.hls.trigger(events_1.default.BUFFER_APPENDING, appendObj);
  2164. });
  2165. this.appended = true;
  2166. this.pendingData = [];
  2167. this.state = base_stream_controller_1.State.PARSED;
  2168. }
  2169. else {
  2170. // move to IDLE once flush complete. this should trigger new fragment loading
  2171. this.state = base_stream_controller_1.State.IDLE;
  2172. // reset reference to frag
  2173. this.fragPrevious = null;
  2174. this.tick();
  2175. }
  2176. };
  2177. return AudioStreamController;
  2178. }(base_stream_controller_1.default));
  2179. exports.default = AudioStreamController;
  2180. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  2181. /***/ }),
  2182. /***/ "./src/controller/audio-track-controller.js":
  2183. /*!**************************************************!*\
  2184. !*** ./src/controller/audio-track-controller.js ***!
  2185. \**************************************************/
  2186. /*! no static exports found */
  2187. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  2188. /***/ (function(module, exports, __webpack_require__) {
  2189. "use strict";
  2190. var __extends = (this && this.__extends) || (function () {
  2191. var extendStatics = Object.setPrototypeOf ||
  2192. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2193. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2194. return function (d, b) {
  2195. extendStatics(d, b);
  2196. function __() { this.constructor = d; }
  2197. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2198. };
  2199. })();
  2200. Object.defineProperty(exports, "__esModule", { value: true });
  2201. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  2202. var task_loop_1 = __webpack_require__(/*! ../task-loop */ "./src/task-loop.js");
  2203. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  2204. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  2205. /**
  2206. * @class AudioTrackController
  2207. * @implements {EventHandler}
  2208. *
  2209. * Handles main manifest and audio-track metadata loaded,
  2210. * owns and exposes the selectable audio-tracks data-models.
  2211. *
  2212. * Exposes internal interface to select available audio-tracks.
  2213. *
  2214. * Handles errors on loading audio-track playlists. Manages fallback mechanism
  2215. * with redundants tracks (group-IDs).
  2216. *
  2217. * Handles level-loading and group-ID switches for video (fallback on video levels),
  2218. * and eventually adapts the audio-track group-ID to match.
  2219. *
  2220. * @fires AUDIO_TRACK_LOADING
  2221. * @fires AUDIO_TRACK_SWITCHING
  2222. * @fires AUDIO_TRACKS_UPDATED
  2223. * @fires ERROR
  2224. *
  2225. */
  2226. var AudioTrackController = /** @class */ (function (_super) {
  2227. __extends(AudioTrackController, _super);
  2228. function AudioTrackController(hls) {
  2229. var _this = _super.call(this, hls, events_1.default.MANIFEST_LOADING, events_1.default.MANIFEST_PARSED, events_1.default.AUDIO_TRACK_LOADED, events_1.default.AUDIO_TRACK_SWITCHED, events_1.default.LEVEL_LOADED, events_1.default.ERROR) || this;
  2230. /**
  2231. * @private
  2232. * Currently selected index in `tracks`
  2233. * @member {number} trackId
  2234. */
  2235. _this._trackId = -1;
  2236. /**
  2237. * @private
  2238. * If should select tracks according to default track attribute
  2239. * @member {boolean} _selectDefaultTrack
  2240. */
  2241. _this._selectDefaultTrack = true;
  2242. /**
  2243. * @public
  2244. * All tracks available
  2245. * @member {AudioTrack[]}
  2246. */
  2247. _this.tracks = [];
  2248. /**
  2249. * @public
  2250. * List of blacklisted audio track IDs (that have caused failure)
  2251. * @member {number[]}
  2252. */
  2253. _this.trackIdBlacklist = Object.create(null);
  2254. /**
  2255. * @public
  2256. * The currently running group ID for audio
  2257. * (we grab this on manifest-parsed and new level-loaded)
  2258. * @member {string}
  2259. */
  2260. _this.audioGroupId = null;
  2261. return _this;
  2262. }
  2263. /**
  2264. * Reset audio tracks on new manifest loading.
  2265. */
  2266. AudioTrackController.prototype.onManifestLoading = function () {
  2267. this.tracks = [];
  2268. this._trackId = -1;
  2269. this._selectDefaultTrack = true;
  2270. };
  2271. /**
  2272. * Store tracks data from manifest parsed data.
  2273. *
  2274. * Trigger AUDIO_TRACKS_UPDATED event.
  2275. *
  2276. * @param {*} data
  2277. */
  2278. AudioTrackController.prototype.onManifestParsed = function (data) {
  2279. var tracks = this.tracks = data.audioTracks || [];
  2280. this.hls.trigger(events_1.default.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });
  2281. };
  2282. /**
  2283. * Store track details of loaded track in our data-model.
  2284. *
  2285. * Set-up metadata update interval task for live-mode streams.
  2286. *
  2287. * @param {} data
  2288. */
  2289. AudioTrackController.prototype.onAudioTrackLoaded = function (data) {
  2290. if (data.id >= this.tracks.length) {
  2291. logger_1.logger.warn('Invalid audio track id:', data.id);
  2292. return;
  2293. }
  2294. logger_1.logger.log("audioTrack " + data.id + " loaded");
  2295. this.tracks[data.id].details = data.details;
  2296. // check if current playlist is a live playlist
  2297. // and if we have already our reload interval setup
  2298. if (data.details.live && !this.hasInterval()) {
  2299. // if live playlist we will have to reload it periodically
  2300. // set reload period to playlist target duration
  2301. var updatePeriodMs = data.details.targetduration * 1000;
  2302. this.setInterval(updatePeriodMs);
  2303. }
  2304. if (!data.details.live && this.hasInterval()) {
  2305. // playlist is not live and timer is scheduled: cancel it
  2306. this.clearInterval();
  2307. }
  2308. };
  2309. /**
  2310. * Update the internal group ID to any audio-track we may have set manually
  2311. * or because of a failure-handling fallback.
  2312. *
  2313. * Quality-levels should update to that group ID in this case.
  2314. *
  2315. * @param {*} data
  2316. */
  2317. AudioTrackController.prototype.onAudioTrackSwitched = function (data) {
  2318. var audioGroupId = this.tracks[data.id].groupId;
  2319. if (audioGroupId && (this.audioGroupId !== audioGroupId)) {
  2320. this.audioGroupId = audioGroupId;
  2321. }
  2322. };
  2323. /**
  2324. * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)
  2325. * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.
  2326. *
  2327. * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently
  2328. * selected one (based on NAME property).
  2329. *
  2330. * @param {*} data
  2331. */
  2332. AudioTrackController.prototype.onLevelLoaded = function (data) {
  2333. // FIXME: crashes because currentLevel is undefined
  2334. // const levelInfo = this.hls.levels[this.hls.currentLevel];
  2335. var levelInfo = this.hls.levels[data.level];
  2336. if (!levelInfo.audioGroupIds) {
  2337. return;
  2338. }
  2339. var audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];
  2340. if (this.audioGroupId !== audioGroupId) {
  2341. this.audioGroupId = audioGroupId;
  2342. this._selectInitialAudioTrack();
  2343. }
  2344. };
  2345. /**
  2346. * Handle network errors loading audio track manifests
  2347. * and also pausing on any netwok errors.
  2348. *
  2349. * @param {ErrorEventData} data
  2350. */
  2351. AudioTrackController.prototype.onError = function (data) {
  2352. // Only handle network errors
  2353. if (data.type !== errors_1.ErrorTypes.NETWORK_ERROR) {
  2354. return;
  2355. }
  2356. // If fatal network error, cancel update task
  2357. if (data.fatal) {
  2358. this.clearInterval();
  2359. }
  2360. // If not an audio-track loading error don't handle further
  2361. if (data.details !== errors_1.ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {
  2362. return;
  2363. }
  2364. logger_1.logger.warn('Network failure on audio-track id:', data.context.id);
  2365. this._handleLoadError();
  2366. };
  2367. Object.defineProperty(AudioTrackController.prototype, "audioTracks", {
  2368. /**
  2369. * @type {AudioTrack[]} Audio-track list we own
  2370. */
  2371. get: function () {
  2372. return this.tracks;
  2373. },
  2374. enumerable: true,
  2375. configurable: true
  2376. });
  2377. Object.defineProperty(AudioTrackController.prototype, "audioTrack", {
  2378. /**
  2379. * @type {number} Index into audio-tracks list of currently selected track.
  2380. */
  2381. get: function () {
  2382. return this._trackId;
  2383. },
  2384. /**
  2385. * Select current track by index
  2386. */
  2387. set: function (newId) {
  2388. this._setAudioTrack(newId);
  2389. // If audio track is selected from API then don't choose from the manifest default track
  2390. this._selectDefaultTrack = false;
  2391. },
  2392. enumerable: true,
  2393. configurable: true
  2394. });
  2395. /**
  2396. * @private
  2397. * @param {number} newId
  2398. */
  2399. AudioTrackController.prototype._setAudioTrack = function (newId) {
  2400. // noop on same audio track id as already set
  2401. if (this._trackId === newId && this.tracks[this._trackId].details) {
  2402. logger_1.logger.debug('Same id as current audio-track passed, and track details available -> no-op');
  2403. return;
  2404. }
  2405. // check if level idx is valid
  2406. if (newId < 0 || newId >= this.tracks.length) {
  2407. logger_1.logger.warn('Invalid id passed to audio-track controller');
  2408. return;
  2409. }
  2410. var audioTrack = this.tracks[newId];
  2411. logger_1.logger.log("Now switching to audio-track index " + newId);
  2412. // stopping live reloading timer if any
  2413. this.clearInterval();
  2414. this._trackId = newId;
  2415. var url = audioTrack.url, type = audioTrack.type, id = audioTrack.id;
  2416. this.hls.trigger(events_1.default.AUDIO_TRACK_SWITCHING, { id: id, type: type, url: url });
  2417. this._loadTrackDetailsIfNeeded(audioTrack);
  2418. };
  2419. /**
  2420. * @override
  2421. */
  2422. AudioTrackController.prototype.doTick = function () {
  2423. this._updateTrack(this._trackId);
  2424. };
  2425. /**
  2426. * Select initial track
  2427. * @private
  2428. */
  2429. AudioTrackController.prototype._selectInitialAudioTrack = function () {
  2430. var _this = this;
  2431. var tracks = this.tracks;
  2432. if (!tracks.length) {
  2433. return;
  2434. }
  2435. var currentAudioTrack = this.tracks[this._trackId];
  2436. var name = null;
  2437. if (currentAudioTrack) {
  2438. name = currentAudioTrack.name;
  2439. }
  2440. // Pre-select default tracks if there are any
  2441. if (this._selectDefaultTrack) {
  2442. var defaultTracks = tracks.filter(function (track) { return track.default; });
  2443. if (defaultTracks.length) {
  2444. tracks = defaultTracks;
  2445. }
  2446. else {
  2447. logger_1.logger.warn('No default audio tracks defined');
  2448. }
  2449. }
  2450. var trackFound = false;
  2451. var traverseTracks = function () {
  2452. // Select track with right group ID
  2453. tracks.forEach(function (track) {
  2454. if (trackFound) {
  2455. return;
  2456. }
  2457. // We need to match the (pre-)selected group ID
  2458. // and the NAME of the current track.
  2459. if ((!_this.audioGroupId || track.groupId === _this.audioGroupId) &&
  2460. (!name || name === track.name)) {
  2461. // If there was a previous track try to stay with the same `NAME`.
  2462. // It should be unique across tracks of same group, and consistent through redundant track groups.
  2463. _this._setAudioTrack(track.id);
  2464. trackFound = true;
  2465. }
  2466. });
  2467. };
  2468. traverseTracks();
  2469. if (!trackFound) {
  2470. name = null;
  2471. traverseTracks();
  2472. }
  2473. if (!trackFound) {
  2474. logger_1.logger.error("No track found for running audio group-ID: " + this.audioGroupId);
  2475. this.hls.trigger(events_1.default.ERROR, {
  2476. type: errors_1.ErrorTypes.MEDIA_ERROR,
  2477. details: errors_1.ErrorDetails.AUDIO_TRACK_LOAD_ERROR,
  2478. fatal: true
  2479. });
  2480. }
  2481. };
  2482. /**
  2483. * @private
  2484. * @param {AudioTrack} audioTrack
  2485. * @returns {boolean}
  2486. */
  2487. AudioTrackController.prototype._needsTrackLoading = function (audioTrack) {
  2488. var details = audioTrack.details, url = audioTrack.url;
  2489. if (!details || details.live) {
  2490. // check if we face an audio track embedded in main playlist (audio track without URI attribute)
  2491. return !!url;
  2492. }
  2493. return false;
  2494. };
  2495. /**
  2496. * @private
  2497. * @param {AudioTrack} audioTrack
  2498. */
  2499. AudioTrackController.prototype._loadTrackDetailsIfNeeded = function (audioTrack) {
  2500. if (this._needsTrackLoading(audioTrack)) {
  2501. var url = audioTrack.url, id = audioTrack.id;
  2502. // track not retrieved yet, or live playlist we need to (re)load it
  2503. logger_1.logger.log("loading audio-track playlist for id: " + id);
  2504. this.hls.trigger(events_1.default.AUDIO_TRACK_LOADING, { url: url, id: id });
  2505. }
  2506. };
  2507. /**
  2508. * @private
  2509. * @param {number} newId
  2510. */
  2511. AudioTrackController.prototype._updateTrack = function (newId) {
  2512. // check if level idx is valid
  2513. if (newId < 0 || newId >= this.tracks.length) {
  2514. return;
  2515. }
  2516. // stopping live reloading timer if any
  2517. this.clearInterval();
  2518. this._trackId = newId;
  2519. logger_1.logger.log("trying to update audio-track " + newId);
  2520. var audioTrack = this.tracks[newId];
  2521. this._loadTrackDetailsIfNeeded(audioTrack);
  2522. };
  2523. /**
  2524. * @private
  2525. */
  2526. AudioTrackController.prototype._handleLoadError = function () {
  2527. // First, let's black list current track id
  2528. this.trackIdBlacklist[this._trackId] = true;
  2529. // Let's try to fall back on a functional audio-track with the same group ID
  2530. var previousId = this._trackId;
  2531. var _a = this.tracks[previousId], name = _a.name, language = _a.language, groupId = _a.groupId;
  2532. logger_1.logger.warn("Loading failed on audio track id: " + previousId + ", group-id: " + groupId + ", name/language: \"" + name + "\" / \"" + language + "\"");
  2533. // Find a non-blacklisted track ID with the same NAME
  2534. // At least a track that is not blacklisted, thus on another group-ID.
  2535. var newId = previousId;
  2536. for (var i = 0; i < this.tracks.length; i++) {
  2537. if (this.trackIdBlacklist[i]) {
  2538. continue;
  2539. }
  2540. var newTrack = this.tracks[i];
  2541. if (newTrack.name === name) {
  2542. newId = i;
  2543. break;
  2544. }
  2545. }
  2546. if (newId === previousId) {
  2547. logger_1.logger.warn("No fallback audio-track found for name/language: \"" + name + "\" / \"" + language + "\"");
  2548. return;
  2549. }
  2550. logger_1.logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);
  2551. this._setAudioTrack(newId);
  2552. };
  2553. return AudioTrackController;
  2554. }(task_loop_1.default));
  2555. exports.default = AudioTrackController;
  2556. /***/ }),
  2557. /***/ "./src/controller/base-stream-controller.js":
  2558. /*!**************************************************!*\
  2559. !*** ./src/controller/base-stream-controller.js ***!
  2560. \**************************************************/
  2561. /*! no static exports found */
  2562. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  2563. /***/ (function(module, exports, __webpack_require__) {
  2564. "use strict";
  2565. /* WEBPACK VAR INJECTION */(function(Number) {
  2566. var __extends = (this && this.__extends) || (function () {
  2567. var extendStatics = Object.setPrototypeOf ||
  2568. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2569. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2570. return function (d, b) {
  2571. extendStatics(d, b);
  2572. function __() { this.constructor = d; }
  2573. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2574. };
  2575. })();
  2576. Object.defineProperty(exports, "__esModule", { value: true });
  2577. var task_loop_1 = __webpack_require__(/*! ../task-loop */ "./src/task-loop.js");
  2578. var fragment_tracker_1 = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.js");
  2579. var buffer_helper_1 = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.js");
  2580. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  2581. exports.State = {
  2582. STOPPED: 'STOPPED',
  2583. STARTING: 'STARTING',
  2584. IDLE: 'IDLE',
  2585. PAUSED: 'PAUSED',
  2586. KEY_LOADING: 'KEY_LOADING',
  2587. FRAG_LOADING: 'FRAG_LOADING',
  2588. FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',
  2589. WAITING_TRACK: 'WAITING_TRACK',
  2590. PARSING: 'PARSING',
  2591. PARSED: 'PARSED',
  2592. BUFFER_FLUSHING: 'BUFFER_FLUSHING',
  2593. ENDED: 'ENDED',
  2594. ERROR: 'ERROR',
  2595. WAITING_INIT_PTS: 'WAITING_INIT_PTS',
  2596. WAITING_LEVEL: 'WAITING_LEVEL'
  2597. };
  2598. var BaseStreamController = /** @class */ (function (_super) {
  2599. __extends(BaseStreamController, _super);
  2600. function BaseStreamController() {
  2601. return _super !== null && _super.apply(this, arguments) || this;
  2602. }
  2603. BaseStreamController.prototype.doTick = function () { };
  2604. BaseStreamController.prototype.startLoad = function () { };
  2605. BaseStreamController.prototype.stopLoad = function () {
  2606. var frag = this.fragCurrent;
  2607. if (frag) {
  2608. if (frag.loader) {
  2609. frag.loader.abort();
  2610. }
  2611. this.fragmentTracker.removeFragment(frag);
  2612. }
  2613. if (this.demuxer) {
  2614. this.demuxer.destroy();
  2615. this.demuxer = null;
  2616. }
  2617. this.fragCurrent = null;
  2618. this.fragPrevious = null;
  2619. this.clearInterval();
  2620. this.clearNextTick();
  2621. this.state = exports.State.STOPPED;
  2622. };
  2623. BaseStreamController.prototype._streamEnded = function (bufferInfo, levelDetails) {
  2624. var _a = this, fragCurrent = _a.fragCurrent, fragmentTracker = _a.fragmentTracker;
  2625. // we just got done loading the final fragment and there is no other buffered range after ...
  2626. // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between
  2627. // so we should not switch to ENDED in that case, to be able to buffer them
  2628. // dont switch to ENDED if we need to backtrack last fragment
  2629. if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {
  2630. var fragState = fragmentTracker.getState(fragCurrent);
  2631. return fragState === fragment_tracker_1.FragmentState.PARTIAL || fragState === fragment_tracker_1.FragmentState.OK;
  2632. }
  2633. return false;
  2634. };
  2635. BaseStreamController.prototype.onMediaSeeking = function () {
  2636. var _a = this, config = _a.config, media = _a.media, mediaBuffer = _a.mediaBuffer, state = _a.state;
  2637. var currentTime = media ? media.currentTime : null;
  2638. var bufferInfo = buffer_helper_1.BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);
  2639. if (Number.isFinite(currentTime)) {
  2640. logger_1.logger.log("media seeking to " + currentTime.toFixed(3));
  2641. }
  2642. if (state === exports.State.FRAG_LOADING) {
  2643. var fragCurrent = this.fragCurrent;
  2644. // check if we are seeking to a unbuffered area AND if frag loading is in progress
  2645. if (bufferInfo.len === 0 && fragCurrent) {
  2646. var tolerance = config.maxFragLookUpTolerance;
  2647. var fragStartOffset = fragCurrent.start - tolerance;
  2648. var fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;
  2649. // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything
  2650. if (currentTime < fragStartOffset || currentTime > fragEndOffset) {
  2651. if (fragCurrent.loader) {
  2652. logger_1.logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');
  2653. fragCurrent.loader.abort();
  2654. }
  2655. this.fragCurrent = null;
  2656. this.fragPrevious = null;
  2657. // switch to IDLE state to load new fragment
  2658. this.state = exports.State.IDLE;
  2659. }
  2660. else {
  2661. logger_1.logger.log('seeking outside of buffer but within currently loaded fragment range');
  2662. }
  2663. }
  2664. }
  2665. else if (state === exports.State.ENDED) {
  2666. // if seeking to unbuffered area, clean up fragPrevious
  2667. if (bufferInfo.len === 0) {
  2668. this.fragPrevious = null;
  2669. this.fragCurrent = null;
  2670. }
  2671. // switch to IDLE state to check for potential new fragment
  2672. this.state = exports.State.IDLE;
  2673. }
  2674. if (media) {
  2675. this.lastCurrentTime = currentTime;
  2676. }
  2677. // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target
  2678. if (!this.loadedmetadata) {
  2679. this.nextLoadPosition = this.startPosition = currentTime;
  2680. }
  2681. // tick to speed up processing
  2682. this.tick();
  2683. };
  2684. BaseStreamController.prototype.onMediaEnded = function () {
  2685. // reset startPosition and lastCurrentTime to restart playback @ stream beginning
  2686. this.startPosition = this.lastCurrentTime = 0;
  2687. };
  2688. BaseStreamController.prototype.onHandlerDestroying = function () {
  2689. this.stopLoad();
  2690. _super.prototype.onHandlerDestroying.call(this);
  2691. };
  2692. BaseStreamController.prototype.onHandlerDestroyed = function () {
  2693. this.state = exports.State.STOPPED;
  2694. this.fragmentTracker = null;
  2695. };
  2696. return BaseStreamController;
  2697. }(task_loop_1.default));
  2698. exports.default = BaseStreamController;
  2699. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  2700. /***/ }),
  2701. /***/ "./src/controller/buffer-controller.js":
  2702. /*!*********************************************!*\
  2703. !*** ./src/controller/buffer-controller.js ***!
  2704. \*********************************************/
  2705. /*! no static exports found */
  2706. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  2707. /***/ (function(module, exports, __webpack_require__) {
  2708. "use strict";
  2709. /* WEBPACK VAR INJECTION */(function(Number) {
  2710. /*
  2711. * Buffer Controller
  2712. */
  2713. var __extends = (this && this.__extends) || (function () {
  2714. var extendStatics = Object.setPrototypeOf ||
  2715. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  2716. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  2717. return function (d, b) {
  2718. extendStatics(d, b);
  2719. function __() { this.constructor = d; }
  2720. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  2721. };
  2722. })();
  2723. Object.defineProperty(exports, "__esModule", { value: true });
  2724. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  2725. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  2726. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  2727. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  2728. var mediasource_helper_1 = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.js");
  2729. var MediaSource = mediasource_helper_1.getMediaSource();
  2730. var BufferController = /** @class */ (function (_super) {
  2731. __extends(BufferController, _super);
  2732. function BufferController(hls) {
  2733. var _this = _super.call(this, hls, events_1.default.MEDIA_ATTACHING, events_1.default.MEDIA_DETACHING, events_1.default.MANIFEST_PARSED, events_1.default.BUFFER_RESET, events_1.default.BUFFER_APPENDING, events_1.default.BUFFER_CODECS, events_1.default.BUFFER_EOS, events_1.default.BUFFER_FLUSHING, events_1.default.LEVEL_PTS_UPDATED, events_1.default.LEVEL_UPDATED) || this;
  2734. // the value that we have set mediasource.duration to
  2735. // (the actual duration may be tweaked slighly by the browser)
  2736. _this._msDuration = null;
  2737. // the value that we want to set mediaSource.duration to
  2738. _this._levelDuration = null;
  2739. // the target duration of the current media playlist
  2740. _this._levelTargetDuration = 10;
  2741. // current stream state: true - for live broadcast, false - for VoD content
  2742. _this._live = null;
  2743. // cache the self generated object url to detect hijack of video tag
  2744. _this._objectUrl = null;
  2745. // The number of BUFFER_CODEC events received before any sourceBuffers are created
  2746. _this.bufferCodecEventsExpected = 0;
  2747. // Source Buffer listeners
  2748. _this.onsbue = _this.onSBUpdateEnd.bind(_this);
  2749. _this.onsbe = _this.onSBUpdateError.bind(_this);
  2750. _this.pendingTracks = {};
  2751. _this.tracks = {};
  2752. return _this;
  2753. }
  2754. BufferController.prototype.destroy = function () {
  2755. event_handler_1.default.prototype.destroy.call(this);
  2756. };
  2757. BufferController.prototype.onLevelPtsUpdated = function (data) {
  2758. var type = data.type;
  2759. var audioTrack = this.tracks.audio;
  2760. // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)
  2761. // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`
  2762. // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos). At the time of change we issue
  2763. // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`
  2764. // event if SB is in updating state.
  2765. // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486
  2766. if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') { // Chrome audio mp3 track
  2767. var audioBuffer = this.sourceBuffer.audio;
  2768. var delta = Math.abs(audioBuffer.timestampOffset - data.start);
  2769. // adjust timestamp offset if time delta is greater than 100ms
  2770. if (delta > 0.1) {
  2771. var updating = audioBuffer.updating;
  2772. try {
  2773. audioBuffer.abort();
  2774. }
  2775. catch (err) {
  2776. logger_1.logger.warn('can not abort audio buffer: ' + err);
  2777. }
  2778. if (!updating) {
  2779. logger_1.logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);
  2780. audioBuffer.timestampOffset = data.start;
  2781. }
  2782. else {
  2783. this.audioTimestampOffset = data.start;
  2784. }
  2785. }
  2786. }
  2787. };
  2788. BufferController.prototype.onManifestParsed = function (data) {
  2789. // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller
  2790. // sourcebuffers will be created all at once when the expected nb of tracks will be reached
  2791. // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller
  2792. // it will contain the expected nb of source buffers, no need to compute it
  2793. this.bufferCodecEventsExpected = data.altAudio ? 2 : 1;
  2794. logger_1.logger.log(this.bufferCodecEventsExpected + " bufferCodec event(s) expected");
  2795. };
  2796. BufferController.prototype.onMediaAttaching = function (data) {
  2797. var media = this.media = data.media;
  2798. if (media) {
  2799. // setup the media source
  2800. var ms = this.mediaSource = new MediaSource();
  2801. // Media Source listeners
  2802. this.onmso = this.onMediaSourceOpen.bind(this);
  2803. this.onmse = this.onMediaSourceEnded.bind(this);
  2804. this.onmsc = this.onMediaSourceClose.bind(this);
  2805. ms.addEventListener('sourceopen', this.onmso);
  2806. ms.addEventListener('sourceended', this.onmse);
  2807. ms.addEventListener('sourceclose', this.onmsc);
  2808. // link video and media Source
  2809. media.src = window.URL.createObjectURL(ms);
  2810. // cache the locally generated object url
  2811. this._objectUrl = media.src;
  2812. }
  2813. };
  2814. BufferController.prototype.onMediaDetaching = function () {
  2815. logger_1.logger.log('media source detaching');
  2816. var ms = this.mediaSource;
  2817. if (ms) {
  2818. if (ms.readyState === 'open') {
  2819. try {
  2820. // endOfStream could trigger exception if any sourcebuffer is in updating state
  2821. // we don't really care about checking sourcebuffer state here,
  2822. // as we are anyway detaching the MediaSource
  2823. // let's just avoid this exception to propagate
  2824. ms.endOfStream();
  2825. }
  2826. catch (err) {
  2827. logger_1.logger.warn("onMediaDetaching:" + err.message + " while calling endOfStream");
  2828. }
  2829. }
  2830. ms.removeEventListener('sourceopen', this.onmso);
  2831. ms.removeEventListener('sourceended', this.onmse);
  2832. ms.removeEventListener('sourceclose', this.onmsc);
  2833. // Detach properly the MediaSource from the HTMLMediaElement as
  2834. // suggested in https://github.com/w3c/media-source/issues/53.
  2835. if (this.media) {
  2836. window.URL.revokeObjectURL(this._objectUrl);
  2837. // clean up video tag src only if it's our own url. some external libraries might
  2838. // hijack the video tag and change its 'src' without destroying the Hls instance first
  2839. if (this.media.src === this._objectUrl) {
  2840. this.media.removeAttribute('src');
  2841. this.media.load();
  2842. }
  2843. else {
  2844. logger_1.logger.warn('media.src was changed by a third party - skip cleanup');
  2845. }
  2846. }
  2847. this.mediaSource = null;
  2848. this.media = null;
  2849. this._objectUrl = null;
  2850. this.pendingTracks = {};
  2851. this.tracks = {};
  2852. this.sourceBuffer = {};
  2853. this.flushRange = [];
  2854. this.segments = [];
  2855. this.appended = 0;
  2856. }
  2857. this.onmso = this.onmse = this.onmsc = null;
  2858. this.hls.trigger(events_1.default.MEDIA_DETACHED);
  2859. };
  2860. BufferController.prototype.onMediaSourceOpen = function () {
  2861. logger_1.logger.log('media source opened');
  2862. this.hls.trigger(events_1.default.MEDIA_ATTACHED, { media: this.media });
  2863. var mediaSource = this.mediaSource;
  2864. if (mediaSource) {
  2865. // once received, don't listen anymore to sourceopen event
  2866. mediaSource.removeEventListener('sourceopen', this.onmso);
  2867. }
  2868. this.checkPendingTracks();
  2869. };
  2870. BufferController.prototype.checkPendingTracks = function () {
  2871. var _a = this, bufferCodecEventsExpected = _a.bufferCodecEventsExpected, pendingTracks = _a.pendingTracks;
  2872. // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.
  2873. // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after
  2874. // data has been appended to existing ones.
  2875. // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.
  2876. var pendingTracksCount = Object.keys(pendingTracks).length;
  2877. if ((pendingTracksCount && !bufferCodecEventsExpected) || pendingTracksCount === 2) {
  2878. // ok, let's create them now !
  2879. this.createSourceBuffers(pendingTracks);
  2880. this.pendingTracks = {};
  2881. // append any pending segments now !
  2882. this.doAppending();
  2883. }
  2884. };
  2885. BufferController.prototype.onMediaSourceClose = function () {
  2886. logger_1.logger.log('media source closed');
  2887. };
  2888. BufferController.prototype.onMediaSourceEnded = function () {
  2889. logger_1.logger.log('media source ended');
  2890. };
  2891. BufferController.prototype.onSBUpdateEnd = function () {
  2892. // update timestampOffset
  2893. if (this.audioTimestampOffset) {
  2894. var audioBuffer = this.sourceBuffer.audio;
  2895. logger_1.logger.warn("change mpeg audio timestamp offset from " + audioBuffer.timestampOffset + " to " + this.audioTimestampOffset);
  2896. audioBuffer.timestampOffset = this.audioTimestampOffset;
  2897. delete this.audioTimestampOffset;
  2898. }
  2899. if (this._needsFlush) {
  2900. this.doFlush();
  2901. }
  2902. if (this._needsEos) {
  2903. this.checkEos();
  2904. }
  2905. this.appending = false;
  2906. var parent = this.parent;
  2907. // count nb of pending segments waiting for appending on this sourcebuffer
  2908. var pending = this.segments.reduce(function (counter, segment) { return (segment.parent === parent) ? counter + 1 : counter; }, 0);
  2909. // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments
  2910. var timeRanges = {};
  2911. var sourceBuffer = this.sourceBuffer;
  2912. for (var streamType in sourceBuffer) {
  2913. timeRanges[streamType] = sourceBuffer[streamType].buffered;
  2914. }
  2915. this.hls.trigger(events_1.default.BUFFER_APPENDED, { parent: parent, pending: pending, timeRanges: timeRanges });
  2916. // don't append in flushing mode
  2917. if (!this._needsFlush) {
  2918. this.doAppending();
  2919. }
  2920. this.updateMediaElementDuration();
  2921. // appending goes first
  2922. if (pending === 0) {
  2923. this.flushLiveBackBuffer();
  2924. }
  2925. };
  2926. BufferController.prototype.onSBUpdateError = function (event) {
  2927. logger_1.logger.error('sourceBuffer error:', event);
  2928. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  2929. // this error might not always be fatal (it is fatal if decode error is set, in that case
  2930. // it will be followed by a mediaElement error ...)
  2931. this.hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  2932. // we don't need to do more than that, as accordin to the spec, updateend will be fired just after
  2933. };
  2934. BufferController.prototype.onBufferReset = function () {
  2935. var sourceBuffer = this.sourceBuffer;
  2936. for (var type in sourceBuffer) {
  2937. var sb = sourceBuffer[type];
  2938. try {
  2939. this.mediaSource.removeSourceBuffer(sb);
  2940. sb.removeEventListener('updateend', this.onsbue);
  2941. sb.removeEventListener('error', this.onsbe);
  2942. }
  2943. catch (err) {
  2944. }
  2945. }
  2946. this.sourceBuffer = {};
  2947. this.flushRange = [];
  2948. this.segments = [];
  2949. this.appended = 0;
  2950. };
  2951. BufferController.prototype.onBufferCodecs = function (tracks) {
  2952. var _this = this;
  2953. // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks
  2954. // if sourcebuffers already created, do nothing ...
  2955. if (Object.keys(this.sourceBuffer).length) {
  2956. return;
  2957. }
  2958. Object.keys(tracks).forEach(function (trackName) {
  2959. _this.pendingTracks[trackName] = tracks[trackName];
  2960. });
  2961. var mediaSource = this.mediaSource;
  2962. this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);
  2963. if (mediaSource && mediaSource.readyState === 'open') {
  2964. this.checkPendingTracks();
  2965. }
  2966. };
  2967. BufferController.prototype.createSourceBuffers = function (tracks) {
  2968. var sourceBuffer = this.sourceBuffer, mediaSource = this.mediaSource;
  2969. for (var trackName in tracks) {
  2970. if (!sourceBuffer[trackName]) {
  2971. var track = tracks[trackName];
  2972. // use levelCodec as first priority
  2973. var codec = track.levelCodec || track.codec;
  2974. var mimeType = track.container + ";codecs=" + codec;
  2975. logger_1.logger.log("creating sourceBuffer(" + mimeType + ")");
  2976. try {
  2977. var sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);
  2978. sb.addEventListener('updateend', this.onsbue);
  2979. sb.addEventListener('error', this.onsbe);
  2980. this.tracks[trackName] = { codec: codec, container: track.container };
  2981. track.buffer = sb;
  2982. }
  2983. catch (err) {
  2984. logger_1.logger.error("error while trying to add sourceBuffer:" + err.message);
  2985. this.hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });
  2986. }
  2987. }
  2988. }
  2989. this.hls.trigger(events_1.default.BUFFER_CREATED, { tracks: tracks });
  2990. };
  2991. BufferController.prototype.onBufferAppending = function (data) {
  2992. if (!this._needsFlush) {
  2993. if (!this.segments) {
  2994. this.segments = [data];
  2995. }
  2996. else {
  2997. this.segments.push(data);
  2998. }
  2999. this.doAppending();
  3000. }
  3001. };
  3002. BufferController.prototype.onBufferAppendFail = function (data) {
  3003. logger_1.logger.error('sourceBuffer error:', data.event);
  3004. // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error
  3005. // this error might not always be fatal (it is fatal if decode error is set, in that case
  3006. // it will be followed by a mediaElement error ...)
  3007. this.hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });
  3008. };
  3009. // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()
  3010. BufferController.prototype.onBufferEos = function (data) {
  3011. var sb = this.sourceBuffer;
  3012. var dataType = data.type;
  3013. for (var type in sb) {
  3014. if (!dataType || type === dataType) {
  3015. if (!sb[type].ended) {
  3016. sb[type].ended = true;
  3017. logger_1.logger.log(type + " sourceBuffer now EOS");
  3018. }
  3019. }
  3020. }
  3021. this.checkEos();
  3022. };
  3023. // if all source buffers are marked as ended, signal endOfStream() to MediaSource.
  3024. BufferController.prototype.checkEos = function () {
  3025. var sb = this.sourceBuffer, mediaSource = this.mediaSource;
  3026. if (!mediaSource || mediaSource.readyState !== 'open') {
  3027. this._needsEos = false;
  3028. return;
  3029. }
  3030. for (var type in sb) {
  3031. var sbobj = sb[type];
  3032. if (!sbobj.ended) {
  3033. return;
  3034. }
  3035. if (sbobj.updating) {
  3036. this._needsEos = true;
  3037. return;
  3038. }
  3039. }
  3040. logger_1.logger.log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment');
  3041. // Notify the media element that it now has all of the media data
  3042. try {
  3043. mediaSource.endOfStream();
  3044. }
  3045. catch (e) {
  3046. logger_1.logger.warn('exception while calling mediaSource.endOfStream()');
  3047. }
  3048. this._needsEos = false;
  3049. };
  3050. BufferController.prototype.onBufferFlushing = function (data) {
  3051. this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });
  3052. // attempt flush immediately
  3053. this.flushBufferCounter = 0;
  3054. this.doFlush();
  3055. };
  3056. BufferController.prototype.flushLiveBackBuffer = function () {
  3057. // clear back buffer for live only
  3058. if (!this._live) {
  3059. return;
  3060. }
  3061. var liveBackBufferLength = this.hls.config.liveBackBufferLength;
  3062. if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {
  3063. return;
  3064. }
  3065. var currentTime = this.media.currentTime;
  3066. var sourceBuffer = this.sourceBuffer;
  3067. var bufferTypes = Object.keys(sourceBuffer);
  3068. var targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);
  3069. for (var index = bufferTypes.length - 1; index >= 0; index--) {
  3070. var bufferType = bufferTypes[index], buffered = sourceBuffer[bufferType].buffered;
  3071. // when target buffer start exceeds actual buffer start
  3072. if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {
  3073. // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current
  3074. // time will lead to playback freezing)
  3075. // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91
  3076. this.removeBufferRange(bufferType, sourceBuffer[bufferType], 0, targetBackBufferPosition);
  3077. }
  3078. }
  3079. };
  3080. BufferController.prototype.onLevelUpdated = function (_a) {
  3081. var details = _a.details;
  3082. if (details.fragments.length > 0) {
  3083. this._levelDuration = details.totalduration + details.fragments[0].start;
  3084. this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;
  3085. this._live = details.live;
  3086. this.updateMediaElementDuration();
  3087. }
  3088. };
  3089. /**
  3090. * Update Media Source duration to current level duration or override to Infinity if configuration parameter
  3091. * 'liveDurationInfinity` is set to `true`
  3092. * More details: https://github.com/video-dev/hls.js/issues/355
  3093. */
  3094. BufferController.prototype.updateMediaElementDuration = function () {
  3095. var config = this.hls.config;
  3096. var duration;
  3097. if (this._levelDuration === null ||
  3098. !this.media ||
  3099. !this.mediaSource ||
  3100. !this.sourceBuffer ||
  3101. this.media.readyState === 0 ||
  3102. this.mediaSource.readyState !== 'open') {
  3103. return;
  3104. }
  3105. for (var type in this.sourceBuffer) {
  3106. if (this.sourceBuffer[type].updating === true) {
  3107. // can't set duration whilst a buffer is updating
  3108. return;
  3109. }
  3110. }
  3111. duration = this.media.duration;
  3112. // initialise to the value that the media source is reporting
  3113. if (this._msDuration === null) {
  3114. this._msDuration = this.mediaSource.duration;
  3115. }
  3116. if (this._live === true && config.liveDurationInfinity === true) {
  3117. // Override duration to Infinity
  3118. logger_1.logger.log('Media Source duration is set to Infinity');
  3119. this._msDuration = this.mediaSource.duration = Infinity;
  3120. }
  3121. else if ((this._levelDuration > this._msDuration && this._levelDuration > duration) || !Number.isFinite(duration)) {
  3122. // levelDuration was the last value we set.
  3123. // not using mediaSource.duration as the browser may tweak this value
  3124. // only update Media Source duration if its value increase, this is to avoid
  3125. // flushing already buffered portion when switching between quality level
  3126. logger_1.logger.log("Updating Media Source duration to " + this._levelDuration.toFixed(3));
  3127. this._msDuration = this.mediaSource.duration = this._levelDuration;
  3128. }
  3129. };
  3130. BufferController.prototype.doFlush = function () {
  3131. // loop through all buffer ranges to flush
  3132. while (this.flushRange.length) {
  3133. var range = this.flushRange[0];
  3134. // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer
  3135. if (this.flushBuffer(range.start, range.end, range.type)) {
  3136. // range flushed, remove from flush array
  3137. this.flushRange.shift();
  3138. this.flushBufferCounter = 0;
  3139. }
  3140. else {
  3141. this._needsFlush = true;
  3142. // avoid looping, wait for SB update end to retrigger a flush
  3143. return;
  3144. }
  3145. }
  3146. if (this.flushRange.length === 0) {
  3147. // everything flushed
  3148. this._needsFlush = false;
  3149. // let's recompute this.appended, which is used to avoid flush looping
  3150. var appended = 0;
  3151. var sourceBuffer = this.sourceBuffer;
  3152. try {
  3153. for (var type in sourceBuffer) {
  3154. appended += sourceBuffer[type].buffered.length;
  3155. }
  3156. }
  3157. catch (error) {
  3158. // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource
  3159. // this is harmess at this stage, catch this to avoid reporting an internal exception
  3160. logger_1.logger.error('error while accessing sourceBuffer.buffered');
  3161. }
  3162. this.appended = appended;
  3163. this.hls.trigger(events_1.default.BUFFER_FLUSHED);
  3164. }
  3165. };
  3166. BufferController.prototype.doAppending = function () {
  3167. var _a = this, hls = _a.hls, segments = _a.segments, sourceBuffer = _a.sourceBuffer;
  3168. if (Object.keys(sourceBuffer).length) {
  3169. if (this.media.error) {
  3170. this.segments = [];
  3171. logger_1.logger.error('trying to append although a media error occured, flush segment and abort');
  3172. return;
  3173. }
  3174. if (this.appending) {
  3175. // logger.log(`sb appending in progress`);
  3176. return;
  3177. }
  3178. if (segments && segments.length) {
  3179. var segment = segments.shift();
  3180. try {
  3181. var type = segment.type, sb = sourceBuffer[type];
  3182. if (sb) {
  3183. if (!sb.updating) {
  3184. // reset sourceBuffer ended flag before appending segment
  3185. sb.ended = false;
  3186. // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);
  3187. this.parent = segment.parent;
  3188. sb.appendBuffer(segment.data);
  3189. this.appendError = 0;
  3190. this.appended++;
  3191. this.appending = true;
  3192. }
  3193. else {
  3194. segments.unshift(segment);
  3195. }
  3196. }
  3197. else {
  3198. // in case we don't have any source buffer matching with this segment type,
  3199. // it means that Mediasource fails to create sourcebuffer
  3200. // discard this segment, and trigger update end
  3201. this.onSBUpdateEnd();
  3202. }
  3203. }
  3204. catch (err) {
  3205. // in case any error occured while appending, put back segment in segments table
  3206. logger_1.logger.error("error while trying to append buffer:" + err.message);
  3207. segments.unshift(segment);
  3208. var event_1 = { type: errors_1.ErrorTypes.MEDIA_ERROR, parent: segment.parent };
  3209. if (err.code !== 22) {
  3210. if (this.appendError) {
  3211. this.appendError++;
  3212. }
  3213. else {
  3214. this.appendError = 1;
  3215. }
  3216. event_1.details = errors_1.ErrorDetails.BUFFER_APPEND_ERROR;
  3217. /* with UHD content, we could get loop of quota exceeded error until
  3218. browser is able to evict some data from sourcebuffer. retrying help recovering this
  3219. */
  3220. if (this.appendError > hls.config.appendErrorMaxRetry) {
  3221. logger_1.logger.log("fail " + hls.config.appendErrorMaxRetry + " times to append segment in sourceBuffer");
  3222. this.segments = [];
  3223. event_1.fatal = true;
  3224. hls.trigger(events_1.default.ERROR, event_1);
  3225. }
  3226. else {
  3227. event_1.fatal = false;
  3228. hls.trigger(events_1.default.ERROR, event_1);
  3229. }
  3230. }
  3231. else {
  3232. // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror
  3233. // let's stop appending any segments, and report BUFFER_FULL_ERROR error
  3234. this.segments = [];
  3235. event_1.details = errors_1.ErrorDetails.BUFFER_FULL_ERROR;
  3236. event_1.fatal = false;
  3237. hls.trigger(events_1.default.ERROR, event_1);
  3238. }
  3239. }
  3240. }
  3241. }
  3242. };
  3243. /*
  3244. flush specified buffered range,
  3245. return true once range has been flushed.
  3246. as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end
  3247. */
  3248. BufferController.prototype.flushBuffer = function (startOffset, endOffset, typeIn) {
  3249. var sb;
  3250. var sourceBuffer = this.sourceBuffer;
  3251. if (Object.keys(sourceBuffer).length) {
  3252. logger_1.logger.log("flushBuffer,pos/start/end: " + this.media.currentTime.toFixed(3) + "/" + startOffset + "/" + endOffset);
  3253. // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments
  3254. if (this.flushBufferCounter < this.appended) {
  3255. for (var type in sourceBuffer) {
  3256. // check if sourcebuffer type is defined (typeIn): if yes, let's only flush this one
  3257. // if no, let's flush all sourcebuffers
  3258. if (typeIn && type !== typeIn) {
  3259. continue;
  3260. }
  3261. sb = sourceBuffer[type];
  3262. // we are going to flush buffer, mark source buffer as 'not ended'
  3263. sb.ended = false;
  3264. if (!sb.updating) {
  3265. if (this.removeBufferRange(type, sb, startOffset, endOffset)) {
  3266. this.flushBufferCounter++;
  3267. return false;
  3268. }
  3269. }
  3270. else {
  3271. logger_1.logger.warn('cannot flush, sb updating in progress');
  3272. return false;
  3273. }
  3274. }
  3275. }
  3276. else {
  3277. logger_1.logger.warn('abort flushing too many retries');
  3278. }
  3279. logger_1.logger.log('buffer flushed');
  3280. }
  3281. // everything flushed !
  3282. return true;
  3283. };
  3284. /**
  3285. * Removes first buffered range from provided source buffer that lies within given start and end offsets.
  3286. *
  3287. * @param type Type of the source buffer, logging purposes only.
  3288. * @param sb Target SourceBuffer instance.
  3289. * @param startOffset
  3290. * @param endOffset
  3291. *
  3292. * @returns {boolean} True when source buffer remove requested.
  3293. */
  3294. BufferController.prototype.removeBufferRange = function (type, sb, startOffset, endOffset) {
  3295. try {
  3296. for (var i = 0; i < sb.buffered.length; i++) {
  3297. var bufStart = sb.buffered.start(i);
  3298. var bufEnd = sb.buffered.end(i);
  3299. var removeStart = Math.max(bufStart, startOffset);
  3300. var removeEnd = Math.min(bufEnd, endOffset);
  3301. /* sometimes sourcebuffer.remove() does not flush
  3302. the exact expected time range.
  3303. to avoid rounding issues/infinite loop,
  3304. only flush buffer range of length greater than 500ms.
  3305. */
  3306. if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {
  3307. logger_1.logger.log("sb remove " + type + " [" + removeStart + "," + removeEnd + "], of [" + bufStart + "," + bufEnd + "], pos:" + this.media.currentTime);
  3308. sb.remove(removeStart, removeEnd);
  3309. return true;
  3310. }
  3311. }
  3312. }
  3313. catch (error) {
  3314. logger_1.logger.warn('removeBufferRange failed', error);
  3315. }
  3316. return false;
  3317. };
  3318. return BufferController;
  3319. }(event_handler_1.default));
  3320. exports.default = BufferController;
  3321. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  3322. /***/ }),
  3323. /***/ "./src/controller/cap-level-controller.js":
  3324. /*!************************************************!*\
  3325. !*** ./src/controller/cap-level-controller.js ***!
  3326. \************************************************/
  3327. /*! no static exports found */
  3328. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  3329. /***/ (function(module, exports, __webpack_require__) {
  3330. "use strict";
  3331. /* WEBPACK VAR INJECTION */(function(Number) {
  3332. /*
  3333. * cap stream level to media size dimension controller
  3334. */
  3335. var __extends = (this && this.__extends) || (function () {
  3336. var extendStatics = Object.setPrototypeOf ||
  3337. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3338. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3339. return function (d, b) {
  3340. extendStatics(d, b);
  3341. function __() { this.constructor = d; }
  3342. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3343. };
  3344. })();
  3345. Object.defineProperty(exports, "__esModule", { value: true });
  3346. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  3347. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  3348. var CapLevelController = /** @class */ (function (_super) {
  3349. __extends(CapLevelController, _super);
  3350. function CapLevelController(hls) {
  3351. var _this = _super.call(this, hls, events_1.default.FPS_DROP_LEVEL_CAPPING, events_1.default.MEDIA_ATTACHING, events_1.default.MANIFEST_PARSED, events_1.default.BUFFER_CODECS, events_1.default.MEDIA_DETACHING) || this;
  3352. _this.autoLevelCapping = Number.POSITIVE_INFINITY;
  3353. _this.firstLevel = null;
  3354. _this.levels = [];
  3355. _this.media = null;
  3356. _this.restrictedLevels = [];
  3357. _this.timer = null;
  3358. return _this;
  3359. }
  3360. CapLevelController.prototype.destroy = function () {
  3361. if (this.hls.config.capLevelToPlayerSize) {
  3362. this.media = null;
  3363. this._stopCapping();
  3364. }
  3365. };
  3366. CapLevelController.prototype.onFpsDropLevelCapping = function (data) {
  3367. // Don't add a restricted level more than once
  3368. if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {
  3369. this.restrictedLevels.push(data.droppedLevel);
  3370. }
  3371. };
  3372. CapLevelController.prototype.onMediaAttaching = function (data) {
  3373. this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;
  3374. };
  3375. CapLevelController.prototype.onManifestParsed = function (data) {
  3376. var hls = this.hls;
  3377. this.restrictedLevels = [];
  3378. this.levels = data.levels;
  3379. this.firstLevel = data.firstLevel;
  3380. if (hls.config.capLevelToPlayerSize && data.video) {
  3381. // Start capping immediately if the manifest has signaled video codecs
  3382. this._startCapping();
  3383. }
  3384. };
  3385. // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted
  3386. // to the first level
  3387. CapLevelController.prototype.onBufferCodecs = function (data) {
  3388. var hls = this.hls;
  3389. if (hls.config.capLevelToPlayerSize && data.video) {
  3390. // If the manifest did not signal a video codec capping has been deferred until we're certain video is present
  3391. this._startCapping();
  3392. }
  3393. };
  3394. CapLevelController.prototype.onLevelsUpdated = function (data) {
  3395. this.levels = data.levels;
  3396. };
  3397. CapLevelController.prototype.onMediaDetaching = function () {
  3398. this._stopCapping();
  3399. };
  3400. CapLevelController.prototype.detectPlayerSize = function () {
  3401. if (this.media) {
  3402. var levelsLength = this.levels ? this.levels.length : 0;
  3403. if (levelsLength) {
  3404. var hls_1 = this.hls;
  3405. hls_1.autoLevelCapping = this.getMaxLevel(levelsLength - 1);
  3406. if (hls_1.autoLevelCapping > this.autoLevelCapping) {
  3407. // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch
  3408. // usually happen when the user go to the fullscreen mode.
  3409. hls_1.streamController.nextLevelSwitch();
  3410. }
  3411. this.autoLevelCapping = hls_1.autoLevelCapping;
  3412. }
  3413. }
  3414. };
  3415. /*
  3416. * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)
  3417. */
  3418. CapLevelController.prototype.getMaxLevel = function (capLevelIndex) {
  3419. var _this = this;
  3420. if (!this.levels) {
  3421. return -1;
  3422. }
  3423. var validLevels = this.levels.filter(function (level, index) {
  3424. return CapLevelController.isLevelAllowed(index, _this.restrictedLevels) && index <= capLevelIndex;
  3425. });
  3426. return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);
  3427. };
  3428. CapLevelController.prototype._startCapping = function () {
  3429. if (this.timer) {
  3430. // Don't reset capping if started twice; this can happen if the manifest signals a video codec
  3431. return;
  3432. }
  3433. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  3434. this.hls.firstLevel = this.getMaxLevel(this.firstLevel);
  3435. clearInterval(this.timer);
  3436. this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);
  3437. this.detectPlayerSize();
  3438. };
  3439. CapLevelController.prototype._stopCapping = function () {
  3440. this.restrictedLevels = [];
  3441. this.firstLevel = null;
  3442. this.autoLevelCapping = Number.POSITIVE_INFINITY;
  3443. if (this.timer) {
  3444. this.timer = clearInterval(this.timer);
  3445. this.timer = null;
  3446. }
  3447. };
  3448. Object.defineProperty(CapLevelController.prototype, "mediaWidth", {
  3449. get: function () {
  3450. var width;
  3451. var media = this.media;
  3452. if (media) {
  3453. width = media.width || media.clientWidth || media.offsetWidth;
  3454. width *= CapLevelController.contentScaleFactor;
  3455. }
  3456. return width;
  3457. },
  3458. enumerable: true,
  3459. configurable: true
  3460. });
  3461. Object.defineProperty(CapLevelController.prototype, "mediaHeight", {
  3462. get: function () {
  3463. var height;
  3464. var media = this.media;
  3465. if (media) {
  3466. height = media.height || media.clientHeight || media.offsetHeight;
  3467. height *= CapLevelController.contentScaleFactor;
  3468. }
  3469. return height;
  3470. },
  3471. enumerable: true,
  3472. configurable: true
  3473. });
  3474. Object.defineProperty(CapLevelController, "contentScaleFactor", {
  3475. get: function () {
  3476. var pixelRatio = 1;
  3477. try {
  3478. pixelRatio = window.devicePixelRatio;
  3479. }
  3480. catch (e) { }
  3481. return pixelRatio;
  3482. },
  3483. enumerable: true,
  3484. configurable: true
  3485. });
  3486. CapLevelController.isLevelAllowed = function (level, restrictedLevels) {
  3487. if (restrictedLevels === void 0) { restrictedLevels = []; }
  3488. return restrictedLevels.indexOf(level) === -1;
  3489. };
  3490. CapLevelController.getMaxLevelByMediaSize = function (levels, width, height) {
  3491. if (!levels || (levels && !levels.length)) {
  3492. return -1;
  3493. }
  3494. // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next
  3495. // to determine whether we've chosen the greatest bandwidth for the media's dimensions
  3496. var atGreatestBandiwdth = function (curLevel, nextLevel) {
  3497. if (!nextLevel) {
  3498. return true;
  3499. }
  3500. return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;
  3501. };
  3502. // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to
  3503. // the max level
  3504. var maxLevelIndex = levels.length - 1;
  3505. for (var i = 0; i < levels.length; i += 1) {
  3506. var level = levels[i];
  3507. if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {
  3508. maxLevelIndex = i;
  3509. break;
  3510. }
  3511. }
  3512. return maxLevelIndex;
  3513. };
  3514. return CapLevelController;
  3515. }(event_handler_1.default));
  3516. exports.default = CapLevelController;
  3517. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  3518. /***/ }),
  3519. /***/ "./src/controller/eme-controller.js":
  3520. /*!******************************************!*\
  3521. !*** ./src/controller/eme-controller.js ***!
  3522. \******************************************/
  3523. /*! no static exports found */
  3524. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  3525. /***/ (function(module, exports, __webpack_require__) {
  3526. "use strict";
  3527. /**
  3528. * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>
  3529. *
  3530. * DRM support for Hls.js
  3531. */
  3532. var __extends = (this && this.__extends) || (function () {
  3533. var extendStatics = Object.setPrototypeOf ||
  3534. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3535. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3536. return function (d, b) {
  3537. extendStatics(d, b);
  3538. function __() { this.constructor = d; }
  3539. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3540. };
  3541. })();
  3542. Object.defineProperty(exports, "__esModule", { value: true });
  3543. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  3544. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  3545. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  3546. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  3547. var XMLHttpRequest = window.XMLHttpRequest;
  3548. var MAX_LICENSE_REQUEST_FAILURES = 3;
  3549. /**
  3550. * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess
  3551. */
  3552. var KeySystems = {
  3553. WIDEVINE: 'com.widevine.alpha',
  3554. PLAYREADY: 'com.microsoft.playready'
  3555. };
  3556. /**
  3557. * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration
  3558. * @param {Array<string>} audioCodecs List of required audio codecs to support
  3559. * @param {Array<string>} videoCodecs List of required video codecs to support
  3560. * @param {object} drmSystemOptions Optional parameters/requirements for the key-system
  3561. * @returns {Array<MediaSystemConfiguration>} An array of supported configurations
  3562. */
  3563. var createWidevineMediaKeySystemConfigurations = function (audioCodecs, videoCodecs, drmSystemOptions) {
  3564. var baseConfig = {
  3565. // initDataTypes: ['keyids', 'mp4'],
  3566. // label: "",
  3567. // persistentState: "not-allowed", // or "required" ?
  3568. // distinctiveIdentifier: "not-allowed", // or "required" ?
  3569. // sessionTypes: ['temporary'],
  3570. videoCapabilities: [
  3571. // { contentType: 'video/mp4; codecs="avc1.42E01E"' }
  3572. ]
  3573. };
  3574. videoCodecs.forEach(function (codec) {
  3575. baseConfig.videoCapabilities.push({
  3576. contentType: "video/mp4; codecs=\"" + codec + "\""
  3577. });
  3578. });
  3579. return [
  3580. baseConfig
  3581. ];
  3582. };
  3583. /**
  3584. * The idea here is to handle key-system (and their respective platforms) specific configuration differences
  3585. * in order to work with the local requestMediaKeySystemAccess method.
  3586. *
  3587. * We can also rule-out platform-related key-system support at this point by throwing an error or returning null.
  3588. *
  3589. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  3590. * @param {Array<string>} audioCodecs List of required audio codecs to support
  3591. * @param {Array<string>} videoCodecs List of required video codecs to support
  3592. * @returns {Array<MediaSystemConfiguration> | null} A non-empty Array of MediaKeySystemConfiguration objects or `null`
  3593. */
  3594. var getSupportedMediaKeySystemConfigurations = function (keySystem, audioCodecs, videoCodecs) {
  3595. switch (keySystem) {
  3596. case KeySystems.WIDEVINE:
  3597. return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs);
  3598. default:
  3599. throw Error('Unknown key-system: ' + keySystem);
  3600. }
  3601. };
  3602. /**
  3603. * Controller to deal with encrypted media extensions (EME)
  3604. * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API
  3605. *
  3606. * @class
  3607. * @constructor
  3608. */
  3609. var EMEController = /** @class */ (function (_super) {
  3610. __extends(EMEController, _super);
  3611. /**
  3612. * @constructs
  3613. * @param {Hls} hls Our Hls.js instance
  3614. */
  3615. function EMEController(hls) {
  3616. var _this = _super.call(this, hls, events_1.default.MEDIA_ATTACHED, events_1.default.MANIFEST_PARSED) || this;
  3617. _this._widevineLicenseUrl = hls.config.widevineLicenseUrl;
  3618. _this._licenseXhrSetup = hls.config.licenseXhrSetup;
  3619. _this._emeEnabled = hls.config.emeEnabled;
  3620. _this._requestMediaKeySystemAccess = hls.config.requestMediaKeySystemAccessFunc;
  3621. _this._mediaKeysList = [];
  3622. _this._media = null;
  3623. _this._hasSetMediaKeys = false;
  3624. _this._isMediaEncrypted = false;
  3625. _this._requestLicenseFailureCount = 0;
  3626. return _this;
  3627. }
  3628. /**
  3629. *
  3630. * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum
  3631. * @returns {string} License server URL for key-system (if any configured, otherwise causes error)
  3632. */
  3633. EMEController.prototype.getLicenseServerUrl = function (keySystem) {
  3634. var url;
  3635. switch (keySystem) {
  3636. case KeySystems.WIDEVINE:
  3637. url = this._widevineLicenseUrl;
  3638. break;
  3639. default:
  3640. url = null;
  3641. break;
  3642. }
  3643. if (!url) {
  3644. logger_1.logger.error("No license server URL configured for key-system \"" + keySystem + "\"");
  3645. this.hls.trigger(events_1.default.ERROR, {
  3646. type: errors_1.ErrorTypes.KEY_SYSTEM_ERROR,
  3647. details: errors_1.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  3648. fatal: true
  3649. });
  3650. }
  3651. return url;
  3652. };
  3653. /**
  3654. * Requests access object and adds it to our list upon success
  3655. * @private
  3656. * @param {string} keySystem System ID (see `KeySystems`)
  3657. * @param {Array<string>} audioCodecs List of required audio codecs to support
  3658. * @param {Array<string>} videoCodecs List of required video codecs to support
  3659. */
  3660. EMEController.prototype._attemptKeySystemAccess = function (keySystem, audioCodecs, videoCodecs) {
  3661. // TODO: add other DRM "options"
  3662. var _this = this;
  3663. var mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs);
  3664. if (!mediaKeySystemConfigs) {
  3665. logger_1.logger.warn('Can not create config for key-system (maybe because platform is not supported):', keySystem);
  3666. return;
  3667. }
  3668. logger_1.logger.log('Requesting encrypted media key-system access');
  3669. // expecting interface like window.navigator.requestMediaKeySystemAccess
  3670. this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs)
  3671. .then(function (mediaKeySystemAccess) {
  3672. _this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess);
  3673. })
  3674. .catch(function (err) {
  3675. logger_1.logger.error("Failed to obtain key-system \"" + keySystem + "\" access:", err);
  3676. });
  3677. };
  3678. Object.defineProperty(EMEController.prototype, "requestMediaKeySystemAccess", {
  3679. get: function () {
  3680. if (!this._requestMediaKeySystemAccess) {
  3681. throw new Error('No requestMediaKeySystemAccess function configured');
  3682. }
  3683. return this._requestMediaKeySystemAccess;
  3684. },
  3685. enumerable: true,
  3686. configurable: true
  3687. });
  3688. /**
  3689. * Handles obtaining access to a key-system
  3690. *
  3691. * @param {string} keySystem
  3692. * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess
  3693. */
  3694. EMEController.prototype._onMediaKeySystemAccessObtained = function (keySystem, mediaKeySystemAccess) {
  3695. var _this = this;
  3696. logger_1.logger.log("Access for key-system \"" + keySystem + "\" obtained");
  3697. var mediaKeysListItem = {
  3698. mediaKeys: null,
  3699. mediaKeysSession: null,
  3700. mediaKeysSessionInitialized: false,
  3701. mediaKeySystemAccess: mediaKeySystemAccess,
  3702. mediaKeySystemDomain: keySystem
  3703. };
  3704. this._mediaKeysList.push(mediaKeysListItem);
  3705. mediaKeySystemAccess.createMediaKeys()
  3706. .then(function (mediaKeys) {
  3707. mediaKeysListItem.mediaKeys = mediaKeys;
  3708. logger_1.logger.log("Media-keys created for key-system \"" + keySystem + "\"");
  3709. _this._onMediaKeysCreated();
  3710. })
  3711. .catch(function (err) {
  3712. logger_1.logger.error('Failed to create media-keys:', err);
  3713. });
  3714. };
  3715. /**
  3716. * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this
  3717. * for all existing keys where no session exists yet.
  3718. */
  3719. EMEController.prototype._onMediaKeysCreated = function () {
  3720. var _this = this;
  3721. // check for all key-list items if a session exists, otherwise, create one
  3722. this._mediaKeysList.forEach(function (mediaKeysListItem) {
  3723. if (!mediaKeysListItem.mediaKeysSession) {
  3724. mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys.createSession();
  3725. _this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);
  3726. }
  3727. });
  3728. };
  3729. /**
  3730. *
  3731. * @param {*} keySession
  3732. */
  3733. EMEController.prototype._onNewMediaKeySession = function (keySession) {
  3734. var _this = this;
  3735. logger_1.logger.log("New key-system session " + keySession.sessionId);
  3736. keySession.addEventListener('message', function (event) {
  3737. _this._onKeySessionMessage(keySession, event.message);
  3738. }, false);
  3739. };
  3740. EMEController.prototype._onKeySessionMessage = function (keySession, message) {
  3741. logger_1.logger.log('Got EME message event, creating license request');
  3742. this._requestLicense(message, function (data) {
  3743. logger_1.logger.log('Received license data, updating key-session');
  3744. keySession.update(data);
  3745. });
  3746. };
  3747. EMEController.prototype._onMediaEncrypted = function (initDataType, initData) {
  3748. logger_1.logger.log("Media is encrypted using \"" + initDataType + "\" init data type");
  3749. this._isMediaEncrypted = true;
  3750. this._mediaEncryptionInitDataType = initDataType;
  3751. this._mediaEncryptionInitData = initData;
  3752. this._attemptSetMediaKeys();
  3753. this._generateRequestWithPreferredKeySession();
  3754. };
  3755. EMEController.prototype._attemptSetMediaKeys = function () {
  3756. if (!this._hasSetMediaKeys) {
  3757. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  3758. var keysListItem = this._mediaKeysList[0];
  3759. if (!keysListItem || !keysListItem.mediaKeys) {
  3760. logger_1.logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');
  3761. this.hls.trigger(events_1.default.ERROR, {
  3762. type: errors_1.ErrorTypes.KEY_SYSTEM_ERROR,
  3763. details: errors_1.ErrorDetails.KEY_SYSTEM_NO_KEYS,
  3764. fatal: true
  3765. });
  3766. return;
  3767. }
  3768. logger_1.logger.log('Setting keys for encrypted media');
  3769. this._media.setMediaKeys(keysListItem.mediaKeys);
  3770. this._hasSetMediaKeys = true;
  3771. }
  3772. };
  3773. EMEController.prototype._generateRequestWithPreferredKeySession = function () {
  3774. var _this = this;
  3775. // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?
  3776. var keysListItem = this._mediaKeysList[0];
  3777. if (!keysListItem) {
  3778. logger_1.logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');
  3779. this.hls.trigger(events_1.default.ERROR, {
  3780. type: errors_1.ErrorTypes.KEY_SYSTEM_ERROR,
  3781. details: errors_1.ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  3782. fatal: true
  3783. });
  3784. return;
  3785. }
  3786. if (keysListItem.mediaKeysSessionInitialized) {
  3787. logger_1.logger.warn('Key-Session already initialized but requested again');
  3788. return;
  3789. }
  3790. var keySession = keysListItem.mediaKeysSession;
  3791. if (!keySession) {
  3792. logger_1.logger.error('Fatal: Media is encrypted but no key-session existing');
  3793. this.hls.trigger(events_1.default.ERROR, {
  3794. type: errors_1.ErrorTypes.KEY_SYSTEM_ERROR,
  3795. details: errors_1.ErrorDetails.KEY_SYSTEM_NO_SESSION,
  3796. fatal: true
  3797. });
  3798. }
  3799. var initDataType = this._mediaEncryptionInitDataType;
  3800. var initData = this._mediaEncryptionInitData;
  3801. logger_1.logger.log("Generating key-session request for \"" + initDataType + "\" init data type");
  3802. keysListItem.mediaKeysSessionInitialized = true;
  3803. keySession.generateRequest(initDataType, initData)
  3804. .then(function () {
  3805. logger_1.logger.debug('Key-session generation succeeded');
  3806. })
  3807. .catch(function (err) {
  3808. logger_1.logger.error('Error generating key-session request:', err);
  3809. _this.hls.trigger(events_1.default.ERROR, {
  3810. type: errors_1.ErrorTypes.KEY_SYSTEM_ERROR,
  3811. details: errors_1.ErrorDetails.KEY_SYSTEM_NO_SESSION,
  3812. fatal: false
  3813. });
  3814. });
  3815. };
  3816. /**
  3817. * @param {string} url License server URL
  3818. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  3819. * @param {function} callback Called when XHR has succeeded
  3820. * @returns {XMLHttpRequest} Unsent (but opened state) XHR object
  3821. */
  3822. EMEController.prototype._createLicenseXhr = function (url, keyMessage, callback) {
  3823. var xhr = new XMLHttpRequest();
  3824. var licenseXhrSetup = this._licenseXhrSetup;
  3825. try {
  3826. if (licenseXhrSetup) {
  3827. try {
  3828. licenseXhrSetup(xhr, url);
  3829. }
  3830. catch (e) {
  3831. // let's try to open before running setup
  3832. xhr.open('POST', url, true);
  3833. licenseXhrSetup(xhr, url);
  3834. }
  3835. }
  3836. // if licenseXhrSetup did not yet call open, let's do it now
  3837. if (!xhr.readyState) {
  3838. xhr.open('POST', url, true);
  3839. }
  3840. }
  3841. catch (e) {
  3842. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  3843. logger_1.logger.error('Error setting up key-system license XHR', e);
  3844. this.hls.trigger(events_1.default.ERROR, {
  3845. type: errors_1.ErrorTypes.KEY_SYSTEM_ERROR,
  3846. details: errors_1.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  3847. fatal: true
  3848. });
  3849. return;
  3850. }
  3851. xhr.responseType = 'arraybuffer';
  3852. xhr.onreadystatechange =
  3853. this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);
  3854. return xhr;
  3855. };
  3856. /**
  3857. * @param {XMLHttpRequest} xhr
  3858. * @param {string} url License server URL
  3859. * @param {ArrayBuffer} keyMessage Message data issued by key-system
  3860. * @param {function} callback Called when XHR has succeeded
  3861. *
  3862. */
  3863. EMEController.prototype._onLicenseRequestReadyStageChange = function (xhr, url, keyMessage, callback) {
  3864. switch (xhr.readyState) {
  3865. case 4:
  3866. if (xhr.status === 200) {
  3867. this._requestLicenseFailureCount = 0;
  3868. logger_1.logger.log('License request succeeded');
  3869. callback(xhr.response);
  3870. }
  3871. else {
  3872. logger_1.logger.error("License Request XHR failed (" + url + "). Status: " + xhr.status + " (" + xhr.statusText + ")");
  3873. this._requestLicenseFailureCount++;
  3874. if (this._requestLicenseFailureCount <= MAX_LICENSE_REQUEST_FAILURES) {
  3875. var attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;
  3876. logger_1.logger.warn("Retrying license request, " + attemptsLeft + " attempts left");
  3877. this._requestLicense(keyMessage, callback);
  3878. return;
  3879. }
  3880. this.hls.trigger(events_1.default.ERROR, {
  3881. type: errors_1.ErrorTypes.KEY_SYSTEM_ERROR,
  3882. details: errors_1.ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,
  3883. fatal: true
  3884. });
  3885. }
  3886. break;
  3887. }
  3888. };
  3889. /**
  3890. * @param {object} keysListItem
  3891. * @param {ArrayBuffer} keyMessage
  3892. * @returns {ArrayBuffer} Challenge data posted to license server
  3893. */
  3894. EMEController.prototype._generateLicenseRequestChallenge = function (keysListItem, keyMessage) {
  3895. var challenge;
  3896. if (keysListItem.mediaKeySystemDomain === KeySystems.PLAYREADY) {
  3897. logger_1.logger.error('PlayReady is not supported (yet)');
  3898. // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js
  3899. /*
  3900. if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {
  3901. // For PlayReady CDMs, we need to dig the Challenge out of the XML.
  3902. var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');
  3903. if (keyMessageXml.getElementsByTagName('Challenge')[0]) {
  3904. challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);
  3905. } else {
  3906. throw 'Cannot find <Challenge> in key message';
  3907. }
  3908. var headerNames = keyMessageXml.getElementsByTagName('name');
  3909. var headerValues = keyMessageXml.getElementsByTagName('value');
  3910. if (headerNames.length !== headerValues.length) {
  3911. throw 'Mismatched header <name>/<value> pair in key message';
  3912. }
  3913. for (var i = 0; i < headerNames.length; i++) {
  3914. xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);
  3915. }
  3916. }
  3917. */
  3918. }
  3919. else if (keysListItem.mediaKeySystemDomain === KeySystems.WIDEVINE) {
  3920. // For Widevine CDMs, the challenge is the keyMessage.
  3921. challenge = keyMessage;
  3922. }
  3923. else {
  3924. logger_1.logger.error('Unsupported key-system:', keysListItem.mediaKeySystemDomain);
  3925. }
  3926. return challenge;
  3927. };
  3928. EMEController.prototype._requestLicense = function (keyMessage, callback) {
  3929. logger_1.logger.log('Requesting content license for key-system');
  3930. var keysListItem = this._mediaKeysList[0];
  3931. if (!keysListItem) {
  3932. logger_1.logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');
  3933. this.hls.trigger(events_1.default.ERROR, {
  3934. type: errors_1.ErrorTypes.KEY_SYSTEM_ERROR,
  3935. details: errors_1.ErrorDetails.KEY_SYSTEM_NO_ACCESS,
  3936. fatal: true
  3937. });
  3938. return;
  3939. }
  3940. var url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);
  3941. var xhr = this._createLicenseXhr(url, keyMessage, callback);
  3942. logger_1.logger.log("Sending license request to URL: " + url);
  3943. xhr.send(this._generateLicenseRequestChallenge(keysListItem, keyMessage));
  3944. };
  3945. EMEController.prototype.onMediaAttached = function (data) {
  3946. var _this = this;
  3947. if (!this._emeEnabled) {
  3948. return;
  3949. }
  3950. var media = data.media;
  3951. // keep reference of media
  3952. this._media = media;
  3953. // FIXME: also handle detaching media !
  3954. media.addEventListener('encrypted', function (e) {
  3955. _this._onMediaEncrypted(e.initDataType, e.initData);
  3956. });
  3957. };
  3958. EMEController.prototype.onManifestParsed = function (data) {
  3959. if (!this._emeEnabled) {
  3960. return;
  3961. }
  3962. var audioCodecs = data.levels.map(function (level) { return level.audioCodec; });
  3963. var videoCodecs = data.levels.map(function (level) { return level.videoCodec; });
  3964. this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);
  3965. };
  3966. return EMEController;
  3967. }(event_handler_1.default));
  3968. exports.default = EMEController;
  3969. /***/ }),
  3970. /***/ "./src/controller/fps-controller.js":
  3971. /*!******************************************!*\
  3972. !*** ./src/controller/fps-controller.js ***!
  3973. \******************************************/
  3974. /*! no static exports found */
  3975. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  3976. /***/ (function(module, exports, __webpack_require__) {
  3977. "use strict";
  3978. /*
  3979. * FPS Controller
  3980. */
  3981. var __extends = (this && this.__extends) || (function () {
  3982. var extendStatics = Object.setPrototypeOf ||
  3983. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  3984. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  3985. return function (d, b) {
  3986. extendStatics(d, b);
  3987. function __() { this.constructor = d; }
  3988. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  3989. };
  3990. })();
  3991. Object.defineProperty(exports, "__esModule", { value: true });
  3992. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  3993. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  3994. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  3995. var performance = window.performance;
  3996. var FPSController = /** @class */ (function (_super) {
  3997. __extends(FPSController, _super);
  3998. function FPSController(hls) {
  3999. return _super.call(this, hls, events_1.default.MEDIA_ATTACHING) || this;
  4000. }
  4001. FPSController.prototype.destroy = function () {
  4002. if (this.timer) {
  4003. clearInterval(this.timer);
  4004. }
  4005. this.isVideoPlaybackQualityAvailable = false;
  4006. };
  4007. FPSController.prototype.onMediaAttaching = function (data) {
  4008. var config = this.hls.config;
  4009. if (config.capLevelOnFPSDrop) {
  4010. var video_1 = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;
  4011. if (typeof video_1.getVideoPlaybackQuality === 'function') {
  4012. this.isVideoPlaybackQualityAvailable = true;
  4013. }
  4014. clearInterval(this.timer);
  4015. this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);
  4016. }
  4017. };
  4018. FPSController.prototype.checkFPS = function (video, decodedFrames, droppedFrames) {
  4019. var currentTime = performance.now();
  4020. if (decodedFrames) {
  4021. if (this.lastTime) {
  4022. var currentPeriod = currentTime - this.lastTime, currentDropped = droppedFrames - this.lastDroppedFrames, currentDecoded = decodedFrames - this.lastDecodedFrames, droppedFPS = 1000 * currentDropped / currentPeriod, hls_1 = this.hls;
  4023. hls_1.trigger(events_1.default.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });
  4024. if (droppedFPS > 0) {
  4025. // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));
  4026. if (currentDropped > hls_1.config.fpsDroppedMonitoringThreshold * currentDecoded) {
  4027. var currentLevel = hls_1.currentLevel;
  4028. logger_1.logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);
  4029. if (currentLevel > 0 && (hls_1.autoLevelCapping === -1 || hls_1.autoLevelCapping >= currentLevel)) {
  4030. currentLevel = currentLevel - 1;
  4031. hls_1.trigger(events_1.default.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls_1.currentLevel });
  4032. hls_1.autoLevelCapping = currentLevel;
  4033. hls_1.streamController.nextLevelSwitch();
  4034. }
  4035. }
  4036. }
  4037. }
  4038. this.lastTime = currentTime;
  4039. this.lastDroppedFrames = droppedFrames;
  4040. this.lastDecodedFrames = decodedFrames;
  4041. }
  4042. };
  4043. FPSController.prototype.checkFPSInterval = function () {
  4044. var video = this.video;
  4045. if (video) {
  4046. if (this.isVideoPlaybackQualityAvailable) {
  4047. var videoPlaybackQuality = video.getVideoPlaybackQuality();
  4048. this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);
  4049. }
  4050. else {
  4051. this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);
  4052. }
  4053. }
  4054. };
  4055. return FPSController;
  4056. }(event_handler_1.default));
  4057. exports.default = FPSController;
  4058. /***/ }),
  4059. /***/ "./src/controller/fragment-finders.js":
  4060. /*!********************************************!*\
  4061. !*** ./src/controller/fragment-finders.js ***!
  4062. \********************************************/
  4063. /*! no static exports found */
  4064. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  4065. /***/ (function(module, exports, __webpack_require__) {
  4066. "use strict";
  4067. /* WEBPACK VAR INJECTION */(function(Number) {
  4068. Object.defineProperty(exports, "__esModule", { value: true });
  4069. var binary_search_1 = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.js");
  4070. /**
  4071. * Returns first fragment whose endPdt value exceeds the given PDT.
  4072. * @param {Array<Fragment>} fragments - The array of candidate fragments
  4073. * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded
  4074. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  4075. * @returns {*|null} fragment - The best matching fragment
  4076. */
  4077. function findFragmentByPDT(fragments, PDTValue, maxFragLookUpTolerance) {
  4078. if (!Array.isArray(fragments) || !fragments.length || !Number.isFinite(PDTValue)) {
  4079. return null;
  4080. }
  4081. // if less than start
  4082. if (PDTValue < fragments[0].programDateTime) {
  4083. return null;
  4084. }
  4085. if (PDTValue >= fragments[fragments.length - 1].endProgramDateTime) {
  4086. return null;
  4087. }
  4088. maxFragLookUpTolerance = maxFragLookUpTolerance || 0;
  4089. for (var seg = 0; seg < fragments.length; ++seg) {
  4090. var frag = fragments[seg];
  4091. if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {
  4092. return frag;
  4093. }
  4094. }
  4095. return null;
  4096. }
  4097. exports.findFragmentByPDT = findFragmentByPDT;
  4098. /**
  4099. * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.
  4100. * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus
  4101. * breaking any traps which would cause the same fragment to be continuously selected within a small range.
  4102. * @param {*} fragPrevious - The last frag successfully appended
  4103. * @param {Array<Fragment>} fragments - The array of candidate fragments
  4104. * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within
  4105. * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous
  4106. * @returns {*} foundFrag - The best matching fragment
  4107. */
  4108. function findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance) {
  4109. if (bufferEnd === void 0) { bufferEnd = 0; }
  4110. if (maxFragLookUpTolerance === void 0) { maxFragLookUpTolerance = 0; }
  4111. var fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : null;
  4112. // Prefer the next fragment if it's within tolerance
  4113. if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {
  4114. return fragNext;
  4115. }
  4116. return binary_search_1.default.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));
  4117. }
  4118. exports.findFragmentByPTS = findFragmentByPTS;
  4119. /**
  4120. * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.
  4121. * @param {*} candidate - The fragment to test
  4122. * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within
  4123. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  4124. * @returns {number} - 0 if it matches, 1 if too low, -1 if too high
  4125. */
  4126. function fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, candidate) {
  4127. if (bufferEnd === void 0) { bufferEnd = 0; }
  4128. if (maxFragLookUpTolerance === void 0) { maxFragLookUpTolerance = 0; }
  4129. // offset should be within fragment boundary - config.maxFragLookUpTolerance
  4130. // this is to cope with situations like
  4131. // bufferEnd = 9.991
  4132. // frag[Ø] : [0,10]
  4133. // frag[1] : [10,20]
  4134. // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here
  4135. // frag start frag start+duration
  4136. // |-----------------------------|
  4137. // <---> <--->
  4138. // ...--------><-----------------------------><---------....
  4139. // previous frag matching fragment next frag
  4140. // return -1 return 0 return 1
  4141. // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);
  4142. // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments
  4143. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));
  4144. if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {
  4145. return 1;
  4146. }
  4147. else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {
  4148. // if maxFragLookUpTolerance will have negative value then don't return -1 for first element
  4149. return -1;
  4150. }
  4151. return 0;
  4152. }
  4153. exports.fragmentWithinToleranceTest = fragmentWithinToleranceTest;
  4154. /**
  4155. * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.
  4156. * This function tests the candidate's program date time values, as represented in Unix time
  4157. * @param {*} candidate - The fragment to test
  4158. * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range
  4159. * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous
  4160. * @returns {boolean} True if contiguous, false otherwise
  4161. */
  4162. function pdtWithinToleranceTest(pdtBufferEnd, maxFragLookUpTolerance, candidate) {
  4163. var candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;
  4164. return candidate.endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;
  4165. }
  4166. exports.pdtWithinToleranceTest = pdtWithinToleranceTest;
  4167. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  4168. /***/ }),
  4169. /***/ "./src/controller/fragment-tracker.js":
  4170. /*!********************************************!*\
  4171. !*** ./src/controller/fragment-tracker.js ***!
  4172. \********************************************/
  4173. /*! no static exports found */
  4174. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  4175. /***/ (function(module, exports, __webpack_require__) {
  4176. "use strict";
  4177. /* WEBPACK VAR INJECTION */(function(Number) {
  4178. var __extends = (this && this.__extends) || (function () {
  4179. var extendStatics = Object.setPrototypeOf ||
  4180. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4181. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4182. return function (d, b) {
  4183. extendStatics(d, b);
  4184. function __() { this.constructor = d; }
  4185. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4186. };
  4187. })();
  4188. Object.defineProperty(exports, "__esModule", { value: true });
  4189. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  4190. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  4191. exports.FragmentState = {
  4192. NOT_LOADED: 'NOT_LOADED',
  4193. APPENDING: 'APPENDING',
  4194. PARTIAL: 'PARTIAL',
  4195. OK: 'OK'
  4196. };
  4197. var FragmentTracker = /** @class */ (function (_super) {
  4198. __extends(FragmentTracker, _super);
  4199. function FragmentTracker(hls) {
  4200. var _this = _super.call(this, hls, events_1.default.BUFFER_APPENDED, events_1.default.FRAG_BUFFERED, events_1.default.FRAG_LOADED) || this;
  4201. _this.bufferPadding = 0.2;
  4202. _this.fragments = Object.create(null);
  4203. _this.timeRanges = Object.create(null);
  4204. _this.config = hls.config;
  4205. return _this;
  4206. }
  4207. FragmentTracker.prototype.destroy = function () {
  4208. this.fragments = Object.create(null);
  4209. this.timeRanges = Object.create(null);
  4210. this.config = null;
  4211. event_handler_1.default.prototype.destroy.call(this);
  4212. _super.prototype.destroy.call(this);
  4213. };
  4214. /**
  4215. * Return a Fragment that match the position and levelType.
  4216. * If not found any Fragment, return null
  4217. * @param {number} position
  4218. * @param {LevelType} levelType
  4219. * @returns {Fragment|null}
  4220. */
  4221. FragmentTracker.prototype.getBufferedFrag = function (position, levelType) {
  4222. var fragments = this.fragments;
  4223. var bufferedFrags = Object.keys(fragments).filter(function (key) {
  4224. var fragmentEntity = fragments[key];
  4225. if (fragmentEntity.body.type !== levelType) {
  4226. return false;
  4227. }
  4228. if (!fragmentEntity.buffered) {
  4229. return false;
  4230. }
  4231. var frag = fragmentEntity.body;
  4232. return frag.startPTS <= position && position <= frag.endPTS;
  4233. });
  4234. if (bufferedFrags.length === 0) {
  4235. return null;
  4236. }
  4237. else {
  4238. // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566
  4239. var bufferedFragKey = bufferedFrags.pop();
  4240. return fragments[bufferedFragKey].body;
  4241. }
  4242. };
  4243. /**
  4244. * Partial fragments effected by coded frame eviction will be removed
  4245. * The browser will unload parts of the buffer to free up memory for new buffer data
  4246. * Fragments will need to be reloaded when the buffer is freed up, removing partial fragments will allow them to reload(since there might be parts that are still playable)
  4247. * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)
  4248. * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer
  4249. */
  4250. FragmentTracker.prototype.detectEvictedFragments = function (elementaryStream, timeRange) {
  4251. var _this = this;
  4252. var fragmentTimes, time;
  4253. // Check if any flagged fragments have been unloaded
  4254. Object.keys(this.fragments).forEach(function (key) {
  4255. var fragmentEntity = _this.fragments[key];
  4256. if (fragmentEntity.buffered === true) {
  4257. var esData = fragmentEntity.range[elementaryStream];
  4258. if (esData) {
  4259. fragmentTimes = esData.time;
  4260. for (var i = 0; i < fragmentTimes.length; i++) {
  4261. time = fragmentTimes[i];
  4262. if (_this.isTimeBuffered(time.startPTS, time.endPTS, timeRange) === false) {
  4263. // Unregister partial fragment as it needs to load again to be reused
  4264. _this.removeFragment(fragmentEntity.body);
  4265. break;
  4266. }
  4267. }
  4268. }
  4269. }
  4270. });
  4271. };
  4272. /**
  4273. * Checks if the fragment passed in is loaded in the buffer properly
  4274. * Partially loaded fragments will be registered as a partial fragment
  4275. * @param {Object} fragment Check the fragment against all sourceBuffers loaded
  4276. */
  4277. FragmentTracker.prototype.detectPartialFragments = function (fragment) {
  4278. var _this = this;
  4279. var fragKey = this.getFragmentKey(fragment);
  4280. var fragmentEntity = this.fragments[fragKey];
  4281. if (fragmentEntity) {
  4282. fragmentEntity.buffered = true;
  4283. Object.keys(this.timeRanges).forEach(function (elementaryStream) {
  4284. if (fragment.hasElementaryStream(elementaryStream)) {
  4285. var timeRange = _this.timeRanges[elementaryStream];
  4286. // Check for malformed fragments
  4287. // Gaps need to be calculated for each elementaryStream
  4288. fragmentEntity.range[elementaryStream] = _this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);
  4289. }
  4290. });
  4291. }
  4292. };
  4293. FragmentTracker.prototype.getBufferedTimes = function (startPTS, endPTS, timeRange) {
  4294. var fragmentTimes = [];
  4295. var startTime, endTime;
  4296. var fragmentPartial = false;
  4297. for (var i = 0; i < timeRange.length; i++) {
  4298. startTime = timeRange.start(i) - this.bufferPadding;
  4299. endTime = timeRange.end(i) + this.bufferPadding;
  4300. if (startPTS >= startTime && endPTS <= endTime) {
  4301. // Fragment is entirely contained in buffer
  4302. // No need to check the other timeRange times since it's completely playable
  4303. fragmentTimes.push({
  4304. startPTS: Math.max(startPTS, timeRange.start(i)),
  4305. endPTS: Math.min(endPTS, timeRange.end(i))
  4306. });
  4307. break;
  4308. }
  4309. else if (startPTS < endTime && endPTS > startTime) {
  4310. // Check for intersection with buffer
  4311. // Get playable sections of the fragment
  4312. fragmentTimes.push({
  4313. startPTS: Math.max(startPTS, timeRange.start(i)),
  4314. endPTS: Math.min(endPTS, timeRange.end(i))
  4315. });
  4316. fragmentPartial = true;
  4317. }
  4318. else if (endPTS <= startTime) {
  4319. // No need to check the rest of the timeRange as it is in order
  4320. break;
  4321. }
  4322. }
  4323. return {
  4324. time: fragmentTimes,
  4325. partial: fragmentPartial
  4326. };
  4327. };
  4328. FragmentTracker.prototype.getFragmentKey = function (fragment) {
  4329. return fragment.type + "_" + fragment.level + "_" + fragment.urlId + "_" + fragment.sn;
  4330. };
  4331. /**
  4332. * Gets the partial fragment for a certain time
  4333. * @param {Number} time
  4334. * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment
  4335. */
  4336. FragmentTracker.prototype.getPartialFragment = function (time) {
  4337. var _this = this;
  4338. var timePadding, startTime, endTime;
  4339. var bestFragment = null;
  4340. var bestOverlap = 0;
  4341. Object.keys(this.fragments).forEach(function (key) {
  4342. var fragmentEntity = _this.fragments[key];
  4343. if (_this.isPartial(fragmentEntity)) {
  4344. startTime = fragmentEntity.body.startPTS - _this.bufferPadding;
  4345. endTime = fragmentEntity.body.endPTS + _this.bufferPadding;
  4346. if (time >= startTime && time <= endTime) {
  4347. // Use the fragment that has the most padding from start and end time
  4348. timePadding = Math.min(time - startTime, endTime - time);
  4349. if (bestOverlap <= timePadding) {
  4350. bestFragment = fragmentEntity.body;
  4351. bestOverlap = timePadding;
  4352. }
  4353. }
  4354. }
  4355. });
  4356. return bestFragment;
  4357. };
  4358. /**
  4359. * @param {Object} fragment The fragment to check
  4360. * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded
  4361. */
  4362. FragmentTracker.prototype.getState = function (fragment) {
  4363. var fragKey = this.getFragmentKey(fragment);
  4364. var fragmentEntity = this.fragments[fragKey];
  4365. var state = exports.FragmentState.NOT_LOADED;
  4366. if (fragmentEntity !== undefined) {
  4367. if (!fragmentEntity.buffered) {
  4368. state = exports.FragmentState.APPENDING;
  4369. }
  4370. else if (this.isPartial(fragmentEntity) === true) {
  4371. state = exports.FragmentState.PARTIAL;
  4372. }
  4373. else {
  4374. state = exports.FragmentState.OK;
  4375. }
  4376. }
  4377. return state;
  4378. };
  4379. FragmentTracker.prototype.isPartial = function (fragmentEntity) {
  4380. return fragmentEntity.buffered === true &&
  4381. ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||
  4382. (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));
  4383. };
  4384. FragmentTracker.prototype.isTimeBuffered = function (startPTS, endPTS, timeRange) {
  4385. var startTime, endTime;
  4386. for (var i = 0; i < timeRange.length; i++) {
  4387. startTime = timeRange.start(i) - this.bufferPadding;
  4388. endTime = timeRange.end(i) + this.bufferPadding;
  4389. if (startPTS >= startTime && endPTS <= endTime) {
  4390. return true;
  4391. }
  4392. if (endPTS <= startTime) {
  4393. // No need to check the rest of the timeRange as it is in order
  4394. return false;
  4395. }
  4396. }
  4397. return false;
  4398. };
  4399. /**
  4400. * Fires when a fragment loading is completed
  4401. */
  4402. FragmentTracker.prototype.onFragLoaded = function (e) {
  4403. var fragment = e.frag;
  4404. // don't track initsegment (for which sn is not a number)
  4405. // don't track frags used for bitrateTest, they're irrelevant.
  4406. if (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {
  4407. return;
  4408. }
  4409. this.fragments[this.getFragmentKey(fragment)] = {
  4410. body: fragment,
  4411. range: Object.create(null),
  4412. buffered: false
  4413. };
  4414. };
  4415. /**
  4416. * Fires when the buffer is updated
  4417. */
  4418. FragmentTracker.prototype.onBufferAppended = function (e) {
  4419. var _this = this;
  4420. // Store the latest timeRanges loaded in the buffer
  4421. this.timeRanges = e.timeRanges;
  4422. Object.keys(this.timeRanges).forEach(function (elementaryStream) {
  4423. var timeRange = _this.timeRanges[elementaryStream];
  4424. _this.detectEvictedFragments(elementaryStream, timeRange);
  4425. });
  4426. };
  4427. /**
  4428. * Fires after a fragment has been loaded into the source buffer
  4429. */
  4430. FragmentTracker.prototype.onFragBuffered = function (e) {
  4431. this.detectPartialFragments(e.frag);
  4432. };
  4433. /**
  4434. * Return true if fragment tracker has the fragment.
  4435. * @param {Object} fragment
  4436. * @returns {boolean}
  4437. */
  4438. FragmentTracker.prototype.hasFragment = function (fragment) {
  4439. var fragKey = this.getFragmentKey(fragment);
  4440. return this.fragments[fragKey] !== undefined;
  4441. };
  4442. /**
  4443. * Remove a fragment from fragment tracker until it is loaded again
  4444. * @param {Object} fragment The fragment to remove
  4445. */
  4446. FragmentTracker.prototype.removeFragment = function (fragment) {
  4447. var fragKey = this.getFragmentKey(fragment);
  4448. delete this.fragments[fragKey];
  4449. };
  4450. /**
  4451. * Remove all fragments from fragment tracker.
  4452. */
  4453. FragmentTracker.prototype.removeAllFragments = function () {
  4454. this.fragments = Object.create(null);
  4455. };
  4456. return FragmentTracker;
  4457. }(event_handler_1.default));
  4458. exports.FragmentTracker = FragmentTracker;
  4459. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  4460. /***/ }),
  4461. /***/ "./src/controller/gap-controller.js":
  4462. /*!******************************************!*\
  4463. !*** ./src/controller/gap-controller.js ***!
  4464. \******************************************/
  4465. /*! no static exports found */
  4466. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  4467. /***/ (function(module, exports, __webpack_require__) {
  4468. "use strict";
  4469. Object.defineProperty(exports, "__esModule", { value: true });
  4470. var buffer_helper_1 = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.js");
  4471. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  4472. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  4473. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  4474. var stallDebounceInterval = 1000;
  4475. var jumpThreshold = 0.5; // tolerance needed as some browsers stalls playback before reaching buffered range end
  4476. var GapController = /** @class */ (function () {
  4477. function GapController(config, media, fragmentTracker, hls) {
  4478. this.config = config;
  4479. this.media = media;
  4480. this.fragmentTracker = fragmentTracker;
  4481. this.hls = hls;
  4482. this.stallReported = false;
  4483. }
  4484. /**
  4485. * Checks if the playhead is stuck within a gap, and if so, attempts to free it.
  4486. * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).
  4487. * @param lastCurrentTime
  4488. * @param buffered
  4489. */
  4490. GapController.prototype.poll = function (lastCurrentTime, buffered) {
  4491. var _a = this, config = _a.config, media = _a.media;
  4492. var currentTime = media.currentTime;
  4493. var tnow = window.performance.now();
  4494. if (currentTime !== lastCurrentTime) {
  4495. // The playhead is now moving, but was previously stalled
  4496. if (this.stallReported) {
  4497. logger_1.logger.warn("playback not stuck anymore @" + currentTime + ", after " + Math.round(tnow - this.stalled) + "ms");
  4498. this.stallReported = false;
  4499. }
  4500. this.stalled = null;
  4501. this.nudgeRetry = 0;
  4502. return;
  4503. }
  4504. if (media.ended || !media.buffered.length || media.readyState > 2) {
  4505. return;
  4506. }
  4507. if (media.seeking && buffer_helper_1.BufferHelper.isBuffered(media, currentTime)) {
  4508. return;
  4509. }
  4510. // The playhead isn't moving but it should be
  4511. // Allow some slack time to for small stalls to resolve themselves
  4512. var stalledDuration = tnow - this.stalled;
  4513. var bufferInfo = buffer_helper_1.BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);
  4514. if (!this.stalled) {
  4515. this.stalled = tnow;
  4516. return;
  4517. }
  4518. else if (stalledDuration >= stallDebounceInterval) {
  4519. // Report stalling after trying to fix
  4520. this._reportStall(bufferInfo.len);
  4521. }
  4522. this._tryFixBufferStall(bufferInfo, stalledDuration);
  4523. };
  4524. /**
  4525. * Detects and attempts to fix known buffer stalling issues.
  4526. * @param bufferInfo - The properties of the current buffer.
  4527. * @param stalledDuration - The amount of time Hls.js has been stalling for.
  4528. * @private
  4529. */
  4530. GapController.prototype._tryFixBufferStall = function (bufferInfo, stalledDuration) {
  4531. var _a = this, config = _a.config, fragmentTracker = _a.fragmentTracker, media = _a.media;
  4532. var currentTime = media.currentTime;
  4533. var partial = fragmentTracker.getPartialFragment(currentTime);
  4534. if (partial) {
  4535. // Try to skip over the buffer hole caused by a partial fragment
  4536. // This method isn't limited by the size of the gap between buffered ranges
  4537. this._trySkipBufferHole(partial);
  4538. }
  4539. if (bufferInfo.len > jumpThreshold && stalledDuration > config.highBufferWatchdogPeriod * 1000) {
  4540. // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds
  4541. // We only try to jump the hole if it's under the configured size
  4542. // Reset stalled so to rearm watchdog timer
  4543. this.stalled = null;
  4544. this._tryNudgeBuffer();
  4545. }
  4546. };
  4547. /**
  4548. * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.
  4549. * @param bufferLen - The playhead distance from the end of the current buffer segment.
  4550. * @private
  4551. */
  4552. GapController.prototype._reportStall = function (bufferLen) {
  4553. var _a = this, hls = _a.hls, media = _a.media, stallReported = _a.stallReported;
  4554. if (!stallReported) {
  4555. // Report stalled error once
  4556. this.stallReported = true;
  4557. logger_1.logger.warn("Playback stalling at @" + media.currentTime + " due to low buffer");
  4558. hls.trigger(events_1.default.ERROR, {
  4559. type: errors_1.ErrorTypes.MEDIA_ERROR,
  4560. details: errors_1.ErrorDetails.BUFFER_STALLED_ERROR,
  4561. fatal: false,
  4562. buffer: bufferLen
  4563. });
  4564. }
  4565. };
  4566. /**
  4567. * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments
  4568. * @param partial - The partial fragment found at the current time (where playback is stalling).
  4569. * @private
  4570. */
  4571. GapController.prototype._trySkipBufferHole = function (partial) {
  4572. var _a = this, hls = _a.hls, media = _a.media;
  4573. var currentTime = media.currentTime;
  4574. var lastEndTime = 0;
  4575. // Check if currentTime is between unbuffered regions of partial fragments
  4576. for (var i = 0; i < media.buffered.length; i++) {
  4577. var startTime = media.buffered.start(i);
  4578. if (currentTime >= lastEndTime && currentTime < startTime) {
  4579. media.currentTime = Math.max(startTime, media.currentTime + 0.1);
  4580. logger_1.logger.warn("skipping hole, adjusting currentTime from " + currentTime + " to " + media.currentTime);
  4581. this.stalled = null;
  4582. hls.trigger(events_1.default.ERROR, {
  4583. type: errors_1.ErrorTypes.MEDIA_ERROR,
  4584. details: errors_1.ErrorDetails.BUFFER_SEEK_OVER_HOLE,
  4585. fatal: false,
  4586. reason: "fragment loaded with buffer holes, seeking from " + currentTime + " to " + media.currentTime,
  4587. frag: partial
  4588. });
  4589. return;
  4590. }
  4591. lastEndTime = media.buffered.end(i);
  4592. }
  4593. };
  4594. /**
  4595. * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.
  4596. * @private
  4597. */
  4598. GapController.prototype._tryNudgeBuffer = function () {
  4599. var _a = this, config = _a.config, hls = _a.hls, media = _a.media;
  4600. var currentTime = media.currentTime;
  4601. var nudgeRetry = (this.nudgeRetry || 0) + 1;
  4602. this.nudgeRetry = nudgeRetry;
  4603. if (nudgeRetry < config.nudgeMaxRetry) {
  4604. var targetTime = currentTime + nudgeRetry * config.nudgeOffset;
  4605. logger_1.logger.log("adjust currentTime from " + currentTime + " to " + targetTime);
  4606. // playback stalled in buffered area ... let's nudge currentTime to try to overcome this
  4607. media.currentTime = targetTime;
  4608. hls.trigger(events_1.default.ERROR, {
  4609. type: errors_1.ErrorTypes.MEDIA_ERROR,
  4610. details: errors_1.ErrorDetails.BUFFER_NUDGE_ON_STALL,
  4611. fatal: false
  4612. });
  4613. }
  4614. else {
  4615. logger_1.logger.error("still stuck in high buffer @" + currentTime + " after " + config.nudgeMaxRetry + ", raise fatal error");
  4616. hls.trigger(events_1.default.ERROR, {
  4617. type: errors_1.ErrorTypes.MEDIA_ERROR,
  4618. details: errors_1.ErrorDetails.BUFFER_STALLED_ERROR,
  4619. fatal: true
  4620. });
  4621. }
  4622. };
  4623. return GapController;
  4624. }());
  4625. exports.default = GapController;
  4626. /***/ }),
  4627. /***/ "./src/controller/id3-track-controller.js":
  4628. /*!************************************************!*\
  4629. !*** ./src/controller/id3-track-controller.js ***!
  4630. \************************************************/
  4631. /*! no static exports found */
  4632. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  4633. /***/ (function(module, exports, __webpack_require__) {
  4634. "use strict";
  4635. /*
  4636. * id3 metadata track controller
  4637. */
  4638. var __extends = (this && this.__extends) || (function () {
  4639. var extendStatics = Object.setPrototypeOf ||
  4640. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4641. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4642. return function (d, b) {
  4643. extendStatics(d, b);
  4644. function __() { this.constructor = d; }
  4645. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4646. };
  4647. })();
  4648. Object.defineProperty(exports, "__esModule", { value: true });
  4649. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  4650. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  4651. var id3_1 = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.js");
  4652. var texttrack_utils_1 = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.js");
  4653. var ID3TrackController = /** @class */ (function (_super) {
  4654. __extends(ID3TrackController, _super);
  4655. function ID3TrackController(hls) {
  4656. var _this = _super.call(this, hls, events_1.default.MEDIA_ATTACHED, events_1.default.MEDIA_DETACHING, events_1.default.FRAG_PARSING_METADATA) || this;
  4657. _this.id3Track = undefined;
  4658. _this.media = undefined;
  4659. return _this;
  4660. }
  4661. ID3TrackController.prototype.destroy = function () {
  4662. event_handler_1.default.prototype.destroy.call(this);
  4663. };
  4664. // Add ID3 metatadata text track.
  4665. ID3TrackController.prototype.onMediaAttached = function (data) {
  4666. this.media = data.media;
  4667. if (!this.media) {
  4668. }
  4669. };
  4670. ID3TrackController.prototype.onMediaDetaching = function () {
  4671. texttrack_utils_1.clearCurrentCues(this.id3Track);
  4672. this.id3Track = undefined;
  4673. this.media = undefined;
  4674. };
  4675. ID3TrackController.prototype.getID3Track = function (textTracks) {
  4676. for (var i = 0; i < textTracks.length; i++) {
  4677. var textTrack = textTracks[i];
  4678. if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {
  4679. // send 'addtrack' when reusing the textTrack for metadata,
  4680. // same as what we do for captions
  4681. texttrack_utils_1.sendAddTrackEvent(textTrack, this.media);
  4682. return textTrack;
  4683. }
  4684. }
  4685. return this.media.addTextTrack('metadata', 'id3');
  4686. };
  4687. ID3TrackController.prototype.onFragParsingMetadata = function (data) {
  4688. var fragment = data.frag;
  4689. var samples = data.samples;
  4690. // create track dynamically
  4691. if (!this.id3Track) {
  4692. this.id3Track = this.getID3Track(this.media.textTracks);
  4693. this.id3Track.mode = 'hidden';
  4694. }
  4695. // Attempt to recreate Safari functionality by creating
  4696. // WebKitDataCue objects when available and store the decoded
  4697. // ID3 data in the value property of the cue
  4698. var Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;
  4699. for (var i = 0; i < samples.length; i++) {
  4700. var frames_1 = id3_1.default.getID3Frames(samples[i].data);
  4701. if (frames_1) {
  4702. var startTime = samples[i].pts;
  4703. var endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;
  4704. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  4705. if (startTime === endTime) {
  4706. endTime += 0.0001;
  4707. }
  4708. for (var j = 0; j < frames_1.length; j++) {
  4709. var frame = frames_1[j];
  4710. // Safari doesn't put the timestamp frame in the TextTrack
  4711. if (!id3_1.default.isTimeStampFrame(frame)) {
  4712. var cue = new Cue(startTime, endTime, '');
  4713. cue.value = frame;
  4714. this.id3Track.addCue(cue);
  4715. }
  4716. }
  4717. }
  4718. }
  4719. };
  4720. return ID3TrackController;
  4721. }(event_handler_1.default));
  4722. exports.default = ID3TrackController;
  4723. /***/ }),
  4724. /***/ "./src/controller/level-controller.js":
  4725. /*!********************************************!*\
  4726. !*** ./src/controller/level-controller.js ***!
  4727. \********************************************/
  4728. /*! no static exports found */
  4729. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  4730. /***/ (function(module, exports, __webpack_require__) {
  4731. "use strict";
  4732. /*
  4733. * Level Controller
  4734. */
  4735. var __extends = (this && this.__extends) || (function () {
  4736. var extendStatics = Object.setPrototypeOf ||
  4737. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  4738. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  4739. return function (d, b) {
  4740. extendStatics(d, b);
  4741. function __() { this.constructor = d; }
  4742. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  4743. };
  4744. })();
  4745. Object.defineProperty(exports, "__esModule", { value: true });
  4746. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  4747. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  4748. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  4749. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  4750. var codecs_1 = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.js");
  4751. var level_helper_1 = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.js");
  4752. var performance = window.performance;
  4753. var chromeOrFirefox;
  4754. var LevelController = /** @class */ (function (_super) {
  4755. __extends(LevelController, _super);
  4756. function LevelController(hls) {
  4757. var _this = _super.call(this, hls, events_1.default.MANIFEST_LOADED, events_1.default.LEVEL_LOADED, events_1.default.AUDIO_TRACK_SWITCHED, events_1.default.FRAG_LOADED, events_1.default.ERROR) || this;
  4758. _this.canload = false;
  4759. _this.currentLevelIndex = null;
  4760. _this.manualLevelIndex = -1;
  4761. _this.timer = null;
  4762. chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());
  4763. return _this;
  4764. }
  4765. LevelController.prototype.onHandlerDestroying = function () {
  4766. this.clearTimer();
  4767. this.manualLevelIndex = -1;
  4768. };
  4769. LevelController.prototype.clearTimer = function () {
  4770. if (this.timer !== null) {
  4771. clearTimeout(this.timer);
  4772. this.timer = null;
  4773. }
  4774. };
  4775. LevelController.prototype.startLoad = function () {
  4776. var levels = this._levels;
  4777. this.canload = true;
  4778. this.levelRetryCount = 0;
  4779. // clean up live level details to force reload them, and reset load errors
  4780. if (levels) {
  4781. levels.forEach(function (level) {
  4782. level.loadError = 0;
  4783. var levelDetails = level.details;
  4784. if (levelDetails && levelDetails.live) {
  4785. level.details = undefined;
  4786. }
  4787. });
  4788. }
  4789. // speed up live playlist refresh if timer exists
  4790. if (this.timer !== null) {
  4791. this.loadLevel();
  4792. }
  4793. };
  4794. LevelController.prototype.stopLoad = function () {
  4795. this.canload = false;
  4796. };
  4797. LevelController.prototype.onManifestLoaded = function (data) {
  4798. var levels = [];
  4799. var audioTracks = [];
  4800. var bitrateStart;
  4801. var levelSet = {};
  4802. var levelFromSet = null;
  4803. var videoCodecFound = false;
  4804. var audioCodecFound = false;
  4805. // regroup redundant levels together
  4806. data.levels.forEach(function (level) {
  4807. var attributes = level.attrs;
  4808. level.loadError = 0;
  4809. level.fragmentError = false;
  4810. videoCodecFound = videoCodecFound || !!level.videoCodec;
  4811. audioCodecFound = audioCodecFound || !!level.audioCodec;
  4812. // erase audio codec info if browser does not support mp4a.40.34.
  4813. // demuxer will autodetect codec and fallback to mpeg/audio
  4814. if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {
  4815. level.audioCodec = undefined;
  4816. }
  4817. levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here
  4818. if (!levelFromSet) {
  4819. level.url = [level.url];
  4820. level.urlId = 0;
  4821. levelSet[level.bitrate] = level;
  4822. levels.push(level);
  4823. }
  4824. else {
  4825. levelFromSet.url.push(level.url);
  4826. }
  4827. if (attributes) {
  4828. if (attributes.AUDIO) {
  4829. audioCodecFound = true;
  4830. level_helper_1.addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);
  4831. }
  4832. if (attributes.SUBTITLES) {
  4833. level_helper_1.addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);
  4834. }
  4835. }
  4836. });
  4837. // remove audio-only level if we also have levels with audio+video codecs signalled
  4838. if (videoCodecFound && audioCodecFound) {
  4839. levels = levels.filter(function (_a) {
  4840. var videoCodec = _a.videoCodec;
  4841. return !!videoCodec;
  4842. });
  4843. }
  4844. // only keep levels with supported audio/video codecs
  4845. levels = levels.filter(function (_a) {
  4846. var audioCodec = _a.audioCodec, videoCodec = _a.videoCodec;
  4847. return (!audioCodec || codecs_1.isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || codecs_1.isCodecSupportedInMp4(videoCodec, 'video'));
  4848. });
  4849. if (data.audioTracks) {
  4850. audioTracks = data.audioTracks.filter(function (track) { return !track.audioCodec || codecs_1.isCodecSupportedInMp4(track.audioCodec, 'audio'); });
  4851. // Reassign id's after filtering since they're used as array indices
  4852. audioTracks.forEach(function (track, index) {
  4853. track.id = index;
  4854. });
  4855. }
  4856. if (levels.length > 0) {
  4857. // start bitrate is the first bitrate of the manifest
  4858. bitrateStart = levels[0].bitrate;
  4859. // sort level on bitrate
  4860. levels.sort(function (a, b) { return a.bitrate - b.bitrate; });
  4861. this._levels = levels;
  4862. // find index of first level in sorted levels
  4863. for (var i = 0; i < levels.length; i++) {
  4864. if (levels[i].bitrate === bitrateStart) {
  4865. this._firstLevel = i;
  4866. logger_1.logger.log("manifest loaded," + levels.length + " level(s) found, first bitrate:" + bitrateStart);
  4867. break;
  4868. }
  4869. }
  4870. // Audio is only alternate if manifest include a URI along with the audio group tag
  4871. this.hls.trigger(events_1.default.MANIFEST_PARSED, {
  4872. levels: levels,
  4873. audioTracks: audioTracks,
  4874. firstLevel: this._firstLevel,
  4875. stats: data.stats,
  4876. audio: audioCodecFound,
  4877. video: videoCodecFound,
  4878. altAudio: audioTracks.some(function (t) { return !!t.url; })
  4879. });
  4880. }
  4881. else {
  4882. this.hls.trigger(events_1.default.ERROR, {
  4883. type: errors_1.ErrorTypes.MEDIA_ERROR,
  4884. details: errors_1.ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,
  4885. fatal: true,
  4886. url: this.hls.url,
  4887. reason: 'no level with compatible codecs found in manifest'
  4888. });
  4889. }
  4890. };
  4891. Object.defineProperty(LevelController.prototype, "levels", {
  4892. get: function () {
  4893. return this._levels;
  4894. },
  4895. enumerable: true,
  4896. configurable: true
  4897. });
  4898. Object.defineProperty(LevelController.prototype, "level", {
  4899. get: function () {
  4900. return this.currentLevelIndex;
  4901. },
  4902. set: function (newLevel) {
  4903. var levels = this._levels;
  4904. if (levels) {
  4905. newLevel = Math.min(newLevel, levels.length - 1);
  4906. if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {
  4907. this.setLevelInternal(newLevel);
  4908. }
  4909. }
  4910. },
  4911. enumerable: true,
  4912. configurable: true
  4913. });
  4914. LevelController.prototype.setLevelInternal = function (newLevel) {
  4915. var levels = this._levels;
  4916. var hls = this.hls;
  4917. // check if level idx is valid
  4918. if (newLevel >= 0 && newLevel < levels.length) {
  4919. // stopping live reloading timer if any
  4920. this.clearTimer();
  4921. if (this.currentLevelIndex !== newLevel) {
  4922. logger_1.logger.log("switching to level " + newLevel);
  4923. this.currentLevelIndex = newLevel;
  4924. var levelProperties = levels[newLevel];
  4925. levelProperties.level = newLevel;
  4926. hls.trigger(events_1.default.LEVEL_SWITCHING, levelProperties);
  4927. }
  4928. var level = levels[newLevel];
  4929. var levelDetails = level.details;
  4930. // check if we need to load playlist for this level
  4931. if (!levelDetails || levelDetails.live) {
  4932. // level not retrieved yet, or live playlist we need to (re)load it
  4933. var urlId = level.urlId;
  4934. hls.trigger(events_1.default.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });
  4935. }
  4936. }
  4937. else {
  4938. // invalid level id given, trigger error
  4939. hls.trigger(events_1.default.ERROR, {
  4940. type: errors_1.ErrorTypes.OTHER_ERROR,
  4941. details: errors_1.ErrorDetails.LEVEL_SWITCH_ERROR,
  4942. level: newLevel,
  4943. fatal: false,
  4944. reason: 'invalid level idx'
  4945. });
  4946. }
  4947. };
  4948. Object.defineProperty(LevelController.prototype, "manualLevel", {
  4949. get: function () {
  4950. return this.manualLevelIndex;
  4951. },
  4952. set: function (newLevel) {
  4953. this.manualLevelIndex = newLevel;
  4954. if (this._startLevel === undefined) {
  4955. this._startLevel = newLevel;
  4956. }
  4957. if (newLevel !== -1) {
  4958. this.level = newLevel;
  4959. }
  4960. },
  4961. enumerable: true,
  4962. configurable: true
  4963. });
  4964. Object.defineProperty(LevelController.prototype, "firstLevel", {
  4965. get: function () {
  4966. return this._firstLevel;
  4967. },
  4968. set: function (newLevel) {
  4969. this._firstLevel = newLevel;
  4970. },
  4971. enumerable: true,
  4972. configurable: true
  4973. });
  4974. Object.defineProperty(LevelController.prototype, "startLevel", {
  4975. get: function () {
  4976. // hls.startLevel takes precedence over config.startLevel
  4977. // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)
  4978. if (this._startLevel === undefined) {
  4979. var configStartLevel = this.hls.config.startLevel;
  4980. if (configStartLevel !== undefined) {
  4981. return configStartLevel;
  4982. }
  4983. else {
  4984. return this._firstLevel;
  4985. }
  4986. }
  4987. else {
  4988. return this._startLevel;
  4989. }
  4990. },
  4991. set: function (newLevel) {
  4992. this._startLevel = newLevel;
  4993. },
  4994. enumerable: true,
  4995. configurable: true
  4996. });
  4997. LevelController.prototype.onError = function (data) {
  4998. if (data.fatal) {
  4999. if (data.type === errors_1.ErrorTypes.NETWORK_ERROR) {
  5000. this.clearTimer();
  5001. }
  5002. return;
  5003. }
  5004. var levelError = false, fragmentError = false;
  5005. var levelIndex;
  5006. // try to recover not fatal errors
  5007. switch (data.details) {
  5008. case errors_1.ErrorDetails.FRAG_LOAD_ERROR:
  5009. case errors_1.ErrorDetails.FRAG_LOAD_TIMEOUT:
  5010. case errors_1.ErrorDetails.KEY_LOAD_ERROR:
  5011. case errors_1.ErrorDetails.KEY_LOAD_TIMEOUT:
  5012. levelIndex = data.frag.level;
  5013. fragmentError = true;
  5014. break;
  5015. case errors_1.ErrorDetails.LEVEL_LOAD_ERROR:
  5016. case errors_1.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  5017. levelIndex = data.context.level;
  5018. levelError = true;
  5019. break;
  5020. case errors_1.ErrorDetails.REMUX_ALLOC_ERROR:
  5021. levelIndex = data.level;
  5022. levelError = true;
  5023. break;
  5024. }
  5025. if (levelIndex !== undefined) {
  5026. this.recoverLevel(data, levelIndex, levelError, fragmentError);
  5027. }
  5028. };
  5029. /**
  5030. * Switch to a redundant stream if any available.
  5031. * If redundant stream is not available, emergency switch down if ABR mode is enabled.
  5032. *
  5033. * @param {Object} errorEvent
  5034. * @param {Number} levelIndex current level index
  5035. * @param {Boolean} levelError
  5036. * @param {Boolean} fragmentError
  5037. */
  5038. // FIXME Find a better abstraction where fragment/level retry management is well decoupled
  5039. LevelController.prototype.recoverLevel = function (errorEvent, levelIndex, levelError, fragmentError) {
  5040. var _this = this;
  5041. var config = this.hls.config;
  5042. var errorDetails = errorEvent.details;
  5043. var level = this._levels[levelIndex];
  5044. var redundantLevels, delay, nextLevel;
  5045. level.loadError++;
  5046. level.fragmentError = fragmentError;
  5047. if (levelError) {
  5048. if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {
  5049. // exponential backoff capped to max retry timeout
  5050. delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);
  5051. // Schedule level reload
  5052. this.timer = setTimeout(function () { return _this.loadLevel(); }, delay);
  5053. // boolean used to inform stream controller not to switch back to IDLE on non fatal error
  5054. errorEvent.levelRetry = true;
  5055. this.levelRetryCount++;
  5056. logger_1.logger.warn("level controller, " + errorDetails + ", retry in " + delay + " ms, current retry count is " + this.levelRetryCount);
  5057. }
  5058. else {
  5059. logger_1.logger.error("level controller, cannot recover from " + errorDetails + " error");
  5060. this.currentLevelIndex = null;
  5061. // stopping live reloading timer if any
  5062. this.clearTimer();
  5063. // switch error to fatal
  5064. errorEvent.fatal = true;
  5065. return;
  5066. }
  5067. }
  5068. // Try any redundant streams if available for both errors: level and fragment
  5069. // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down
  5070. if (levelError || fragmentError) {
  5071. redundantLevels = level.url.length;
  5072. if (redundantLevels > 1 && level.loadError < redundantLevels) {
  5073. level.urlId = (level.urlId + 1) % redundantLevels;
  5074. level.details = undefined;
  5075. logger_1.logger.warn("level controller, " + errorDetails + " for level " + levelIndex + ": switching to redundant URL-id " + level.urlId);
  5076. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  5077. // console.log('New video quality level audio group id:', level.attrs.AUDIO);
  5078. }
  5079. else {
  5080. // Search for available level
  5081. if (this.manualLevelIndex === -1) {
  5082. // When lowest level has been reached, let's start hunt from the top
  5083. nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;
  5084. logger_1.logger.warn("level controller, " + errorDetails + ": switch to " + nextLevel);
  5085. this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;
  5086. }
  5087. else if (fragmentError) {
  5088. // Allow fragment retry as long as configuration allows.
  5089. // reset this._level so that another call to set level() will trigger again a frag load
  5090. logger_1.logger.warn("level controller, " + errorDetails + ": reload a fragment");
  5091. this.currentLevelIndex = null;
  5092. }
  5093. }
  5094. }
  5095. };
  5096. // reset errors on the successful load of a fragment
  5097. LevelController.prototype.onFragLoaded = function (_a) {
  5098. var frag = _a.frag;
  5099. if (frag !== undefined && frag.type === 'main') {
  5100. var level = this._levels[frag.level];
  5101. if (level !== undefined) {
  5102. level.fragmentError = false;
  5103. level.loadError = 0;
  5104. this.levelRetryCount = 0;
  5105. }
  5106. }
  5107. };
  5108. LevelController.prototype.onLevelLoaded = function (data) {
  5109. var _this = this;
  5110. var level = data.level, details = data.details;
  5111. // only process level loaded events matching with expected level
  5112. if (level !== this.currentLevelIndex) {
  5113. return;
  5114. }
  5115. var curLevel = this._levels[level];
  5116. // reset level load error counter on successful level loaded only if there is no issues with fragments
  5117. if (!curLevel.fragmentError) {
  5118. curLevel.loadError = 0;
  5119. this.levelRetryCount = 0;
  5120. }
  5121. // if current playlist is a live playlist, arm a timer to reload it
  5122. if (details.live) {
  5123. var reloadInterval = level_helper_1.computeReloadInterval(curLevel.details, details, data.stats.trequest);
  5124. logger_1.logger.log("live playlist, reload in " + Math.round(reloadInterval) + " ms");
  5125. this.timer = setTimeout(function () { return _this.loadLevel(); }, reloadInterval);
  5126. }
  5127. else {
  5128. this.clearTimer();
  5129. }
  5130. };
  5131. LevelController.prototype.onAudioTrackSwitched = function (data) {
  5132. var audioGroupId = this.hls.audioTracks[data.id].groupId;
  5133. var currentLevel = this.hls.levels[this.currentLevelIndex];
  5134. if (!currentLevel) {
  5135. return;
  5136. }
  5137. if (currentLevel.audioGroupIds) {
  5138. var urlId = -1;
  5139. for (var i = 0; i < currentLevel.audioGroupIds.length; i++) {
  5140. if (currentLevel.audioGroupIds[i] === audioGroupId) {
  5141. urlId = i;
  5142. break;
  5143. }
  5144. }
  5145. if (urlId !== currentLevel.urlId) {
  5146. currentLevel.urlId = urlId;
  5147. this.startLoad();
  5148. }
  5149. }
  5150. };
  5151. LevelController.prototype.loadLevel = function () {
  5152. logger_1.logger.debug('call to loadLevel');
  5153. if (this.currentLevelIndex !== null && this.canload) {
  5154. var levelObject = this._levels[this.currentLevelIndex];
  5155. if (typeof levelObject === 'object' &&
  5156. levelObject.url.length > 0) {
  5157. var level = this.currentLevelIndex;
  5158. var id = levelObject.urlId;
  5159. var url = levelObject.url[id];
  5160. logger_1.logger.log("Attempt loading level index " + level + " with URL-id " + id);
  5161. // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);
  5162. // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);
  5163. this.hls.trigger(events_1.default.LEVEL_LOADING, { url: url, level: level, id: id });
  5164. }
  5165. }
  5166. };
  5167. Object.defineProperty(LevelController.prototype, "nextLoadLevel", {
  5168. get: function () {
  5169. if (this.manualLevelIndex !== -1) {
  5170. return this.manualLevelIndex;
  5171. }
  5172. else {
  5173. return this.hls.nextAutoLevel;
  5174. }
  5175. },
  5176. set: function (nextLevel) {
  5177. this.level = nextLevel;
  5178. if (this.manualLevelIndex === -1) {
  5179. this.hls.nextAutoLevel = nextLevel;
  5180. }
  5181. },
  5182. enumerable: true,
  5183. configurable: true
  5184. });
  5185. return LevelController;
  5186. }(event_handler_1.default));
  5187. exports.default = LevelController;
  5188. /***/ }),
  5189. /***/ "./src/controller/level-helper.js":
  5190. /*!****************************************!*\
  5191. !*** ./src/controller/level-helper.js ***!
  5192. \****************************************/
  5193. /*! no static exports found */
  5194. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  5195. /***/ (function(module, exports, __webpack_require__) {
  5196. "use strict";
  5197. /* WEBPACK VAR INJECTION */(function(Number) {
  5198. /**
  5199. * @module LevelHelper
  5200. *
  5201. * Providing methods dealing with playlist sliding and drift
  5202. *
  5203. * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.
  5204. *
  5205. * */
  5206. Object.defineProperty(exports, "__esModule", { value: true });
  5207. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  5208. function addGroupId(level, type, id) {
  5209. switch (type) {
  5210. case 'audio':
  5211. if (!level.audioGroupIds) {
  5212. level.audioGroupIds = [];
  5213. }
  5214. level.audioGroupIds.push(id);
  5215. break;
  5216. case 'text':
  5217. if (!level.textGroupIds) {
  5218. level.textGroupIds = [];
  5219. }
  5220. level.textGroupIds.push(id);
  5221. break;
  5222. }
  5223. }
  5224. exports.addGroupId = addGroupId;
  5225. function updatePTS(fragments, fromIdx, toIdx) {
  5226. var fragFrom = fragments[fromIdx], fragTo = fragments[toIdx], fragToPTS = fragTo.startPTS;
  5227. // if we know startPTS[toIdx]
  5228. if (Number.isFinite(fragToPTS)) {
  5229. // update fragment duration.
  5230. // it helps to fix drifts between playlist reported duration and fragment real duration
  5231. if (toIdx > fromIdx) {
  5232. fragFrom.duration = fragToPTS - fragFrom.start;
  5233. if (fragFrom.duration < 0) {
  5234. logger_1.logger.warn("negative duration computed for frag " + fragFrom.sn + ",level " + fragFrom.level + ", there should be some duration drift between playlist and fragment!");
  5235. }
  5236. }
  5237. else {
  5238. fragTo.duration = fragFrom.start - fragToPTS;
  5239. if (fragTo.duration < 0) {
  5240. logger_1.logger.warn("negative duration computed for frag " + fragTo.sn + ",level " + fragTo.level + ", there should be some duration drift between playlist and fragment!");
  5241. }
  5242. }
  5243. }
  5244. else {
  5245. // we dont know startPTS[toIdx]
  5246. if (toIdx > fromIdx) {
  5247. fragTo.start = fragFrom.start + fragFrom.duration;
  5248. }
  5249. else {
  5250. fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);
  5251. }
  5252. }
  5253. }
  5254. exports.updatePTS = updatePTS;
  5255. function updateFragPTSDTS(details, frag, startPTS, endPTS, startDTS, endDTS) {
  5256. // update frag PTS/DTS
  5257. var maxStartPTS = startPTS;
  5258. if (Number.isFinite(frag.startPTS)) {
  5259. // delta PTS between audio and video
  5260. var deltaPTS = Math.abs(frag.startPTS - startPTS);
  5261. if (!Number.isFinite(frag.deltaPTS)) {
  5262. frag.deltaPTS = deltaPTS;
  5263. }
  5264. else {
  5265. frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);
  5266. }
  5267. maxStartPTS = Math.max(startPTS, frag.startPTS);
  5268. startPTS = Math.min(startPTS, frag.startPTS);
  5269. endPTS = Math.max(endPTS, frag.endPTS);
  5270. startDTS = Math.min(startDTS, frag.startDTS);
  5271. endDTS = Math.max(endDTS, frag.endDTS);
  5272. }
  5273. var drift = startPTS - frag.start;
  5274. frag.start = frag.startPTS = startPTS;
  5275. frag.maxStartPTS = maxStartPTS;
  5276. frag.endPTS = endPTS;
  5277. frag.startDTS = startDTS;
  5278. frag.endDTS = endDTS;
  5279. frag.duration = endPTS - startPTS;
  5280. var sn = frag.sn;
  5281. // exit if sn out of range
  5282. if (!details || sn < details.startSN || sn > details.endSN) {
  5283. return 0;
  5284. }
  5285. var fragIdx, fragments, i;
  5286. fragIdx = sn - details.startSN;
  5287. fragments = details.fragments;
  5288. // update frag reference in fragments array
  5289. // rationale is that fragments array might not contain this frag object.
  5290. // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()
  5291. // if we don't update frag, we won't be able to propagate PTS info on the playlist
  5292. // resulting in invalid sliding computation
  5293. fragments[fragIdx] = frag;
  5294. // adjust fragment PTS/duration from seqnum-1 to frag 0
  5295. for (i = fragIdx; i > 0; i--) {
  5296. updatePTS(fragments, i, i - 1);
  5297. }
  5298. // adjust fragment PTS/duration from seqnum to last frag
  5299. for (i = fragIdx; i < fragments.length - 1; i++) {
  5300. updatePTS(fragments, i, i + 1);
  5301. }
  5302. details.PTSKnown = true;
  5303. return drift;
  5304. }
  5305. exports.updateFragPTSDTS = updateFragPTSDTS;
  5306. function mergeDetails(oldDetails, newDetails) {
  5307. // potentially retrieve cached initsegment
  5308. if (newDetails.initSegment && oldDetails.initSegment) {
  5309. newDetails.initSegment = oldDetails.initSegment;
  5310. }
  5311. // check if old/new playlists have fragments in common
  5312. // loop through overlapping SN and update startPTS , cc, and duration if any found
  5313. var ccOffset = 0;
  5314. var PTSFrag;
  5315. mapFragmentIntersection(oldDetails, newDetails, function (oldFrag, newFrag) {
  5316. ccOffset = oldFrag.cc - newFrag.cc;
  5317. if (Number.isFinite(oldFrag.startPTS)) {
  5318. newFrag.start = newFrag.startPTS = oldFrag.startPTS;
  5319. newFrag.endPTS = oldFrag.endPTS;
  5320. newFrag.duration = oldFrag.duration;
  5321. newFrag.backtracked = oldFrag.backtracked;
  5322. newFrag.dropped = oldFrag.dropped;
  5323. PTSFrag = newFrag;
  5324. }
  5325. // PTS is known when there are overlapping segments
  5326. newDetails.PTSKnown = true;
  5327. });
  5328. if (!newDetails.PTSKnown) {
  5329. return;
  5330. }
  5331. if (ccOffset) {
  5332. logger_1.logger.log('discontinuity sliding from playlist, take drift into account');
  5333. var newFragments = newDetails.fragments;
  5334. for (var i = 0; i < newFragments.length; i++) {
  5335. newFragments[i].cc += ccOffset;
  5336. }
  5337. }
  5338. // if at least one fragment contains PTS info, recompute PTS information for all fragments
  5339. if (PTSFrag) {
  5340. updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);
  5341. }
  5342. else {
  5343. // ensure that delta is within oldFragments range
  5344. // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])
  5345. // in that case we also need to adjust start offset of all fragments
  5346. adjustSliding(oldDetails, newDetails);
  5347. }
  5348. // if we are here, it means we have fragments overlapping between
  5349. // old and new level. reliable PTS info is thus relying on old level
  5350. newDetails.PTSKnown = oldDetails.PTSKnown;
  5351. }
  5352. exports.mergeDetails = mergeDetails;
  5353. function mergeSubtitlePlaylists(oldPlaylist, newPlaylist, referenceStart) {
  5354. if (referenceStart === void 0) { referenceStart = 0; }
  5355. var lastIndex = -1;
  5356. mapFragmentIntersection(oldPlaylist, newPlaylist, function (oldFrag, newFrag, index) {
  5357. newFrag.start = oldFrag.start;
  5358. lastIndex = index;
  5359. });
  5360. var frags = newPlaylist.fragments;
  5361. if (lastIndex < 0) {
  5362. frags.forEach(function (frag) {
  5363. frag.start += referenceStart;
  5364. });
  5365. return;
  5366. }
  5367. for (var i = lastIndex + 1; i < frags.length; i++) {
  5368. frags[i].start = (frags[i - 1].start + frags[i - 1].duration);
  5369. }
  5370. }
  5371. exports.mergeSubtitlePlaylists = mergeSubtitlePlaylists;
  5372. function mapFragmentIntersection(oldPlaylist, newPlaylist, intersectionFn) {
  5373. if (!oldPlaylist || !newPlaylist) {
  5374. return;
  5375. }
  5376. var start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;
  5377. var end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;
  5378. var delta = newPlaylist.startSN - oldPlaylist.startSN;
  5379. for (var i = start; i <= end; i++) {
  5380. var oldFrag = oldPlaylist.fragments[delta + i];
  5381. var newFrag = newPlaylist.fragments[i];
  5382. if (!oldFrag || !newFrag) {
  5383. break;
  5384. }
  5385. intersectionFn(oldFrag, newFrag, i);
  5386. }
  5387. }
  5388. exports.mapFragmentIntersection = mapFragmentIntersection;
  5389. function adjustSliding(oldPlaylist, newPlaylist) {
  5390. var delta = newPlaylist.startSN - oldPlaylist.startSN;
  5391. var oldFragments = oldPlaylist.fragments;
  5392. var newFragments = newPlaylist.fragments;
  5393. if (delta < 0 || delta > oldFragments.length) {
  5394. return;
  5395. }
  5396. for (var i = 0; i < newFragments.length; i++) {
  5397. newFragments[i].start += oldFragments[delta].start;
  5398. }
  5399. }
  5400. exports.adjustSliding = adjustSliding;
  5401. function computeReloadInterval(currentPlaylist, newPlaylist, lastRequestTime) {
  5402. var reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);
  5403. var minReloadInterval = reloadInterval / 2;
  5404. if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {
  5405. // follow HLS Spec, If the client reloads a Playlist file and finds that it has not
  5406. // changed then it MUST wait for a period of one-half the target
  5407. // duration before retrying.
  5408. reloadInterval = minReloadInterval;
  5409. }
  5410. if (lastRequestTime) {
  5411. reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));
  5412. }
  5413. // in any case, don't reload more than half of target duration
  5414. return Math.round(reloadInterval);
  5415. }
  5416. exports.computeReloadInterval = computeReloadInterval;
  5417. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  5418. /***/ }),
  5419. /***/ "./src/controller/stream-controller.js":
  5420. /*!*********************************************!*\
  5421. !*** ./src/controller/stream-controller.js ***!
  5422. \*********************************************/
  5423. /*! no static exports found */
  5424. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  5425. /***/ (function(module, exports, __webpack_require__) {
  5426. "use strict";
  5427. /* WEBPACK VAR INJECTION */(function(Number) {
  5428. /*
  5429. * Stream Controller
  5430. */
  5431. var __extends = (this && this.__extends) || (function () {
  5432. var extendStatics = Object.setPrototypeOf ||
  5433. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  5434. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  5435. return function (d, b) {
  5436. extendStatics(d, b);
  5437. function __() { this.constructor = d; }
  5438. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  5439. };
  5440. })();
  5441. Object.defineProperty(exports, "__esModule", { value: true });
  5442. var binary_search_1 = __webpack_require__(/*! ../utils/binary-search */ "./src/utils/binary-search.js");
  5443. var buffer_helper_1 = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.js");
  5444. var demuxer_1 = __webpack_require__(/*! ../demux/demuxer */ "./src/demux/demuxer.js");
  5445. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  5446. var fragment_tracker_1 = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.js");
  5447. var fragment_1 = __webpack_require__(/*! ../loader/fragment */ "./src/loader/fragment.js");
  5448. var playlist_loader_1 = __webpack_require__(/*! ../loader/playlist-loader */ "./src/loader/playlist-loader.js");
  5449. var LevelHelper = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.js");
  5450. var time_ranges_1 = __webpack_require__(/*! ../utils/time-ranges */ "./src/utils/time-ranges.js");
  5451. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  5452. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  5453. var discontinuities_1 = __webpack_require__(/*! ../utils/discontinuities */ "./src/utils/discontinuities.js");
  5454. var fragment_finders_1 = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.js");
  5455. var gap_controller_1 = __webpack_require__(/*! ./gap-controller */ "./src/controller/gap-controller.js");
  5456. var base_stream_controller_1 = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.js");
  5457. var TICK_INTERVAL = 100; // how often to tick in ms
  5458. var StreamController = /** @class */ (function (_super) {
  5459. __extends(StreamController, _super);
  5460. function StreamController(hls, fragmentTracker) {
  5461. var _this = _super.call(this, hls, events_1.default.MEDIA_ATTACHED, events_1.default.MEDIA_DETACHING, events_1.default.MANIFEST_LOADING, events_1.default.MANIFEST_PARSED, events_1.default.LEVEL_LOADED, events_1.default.KEY_LOADED, events_1.default.FRAG_LOADED, events_1.default.FRAG_LOAD_EMERGENCY_ABORTED, events_1.default.FRAG_PARSING_INIT_SEGMENT, events_1.default.FRAG_PARSING_DATA, events_1.default.FRAG_PARSED, events_1.default.ERROR, events_1.default.AUDIO_TRACK_SWITCHING, events_1.default.AUDIO_TRACK_SWITCHED, events_1.default.BUFFER_CREATED, events_1.default.BUFFER_APPENDED, events_1.default.BUFFER_FLUSHED) || this;
  5462. _this.fragmentTracker = fragmentTracker;
  5463. _this.config = hls.config;
  5464. _this.audioCodecSwap = false;
  5465. _this._state = base_stream_controller_1.State.STOPPED;
  5466. _this.stallReported = false;
  5467. _this.gapController = null;
  5468. return _this;
  5469. }
  5470. StreamController.prototype.startLoad = function (startPosition) {
  5471. if (this.levels) {
  5472. var lastCurrentTime = this.lastCurrentTime, hls_1 = this.hls;
  5473. this.stopLoad();
  5474. this.setInterval(TICK_INTERVAL);
  5475. this.level = -1;
  5476. this.fragLoadError = 0;
  5477. if (!this.startFragRequested) {
  5478. // determine load level
  5479. var startLevel = hls_1.startLevel;
  5480. if (startLevel === -1) {
  5481. // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level
  5482. startLevel = 0;
  5483. this.bitrateTest = true;
  5484. }
  5485. // set new level to playlist loader : this will trigger start level load
  5486. // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded
  5487. this.level = hls_1.nextLoadLevel = startLevel;
  5488. this.loadedmetadata = false;
  5489. }
  5490. // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime
  5491. if (lastCurrentTime > 0 && startPosition === -1) {
  5492. logger_1.logger.log("override startPosition with lastCurrentTime @" + lastCurrentTime.toFixed(3));
  5493. startPosition = lastCurrentTime;
  5494. }
  5495. this.state = base_stream_controller_1.State.IDLE;
  5496. this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;
  5497. this.tick();
  5498. }
  5499. else {
  5500. this.forceStartLoad = true;
  5501. this.state = base_stream_controller_1.State.STOPPED;
  5502. }
  5503. };
  5504. StreamController.prototype.stopLoad = function () {
  5505. this.forceStartLoad = false;
  5506. _super.prototype.stopLoad.call(this);
  5507. };
  5508. StreamController.prototype.doTick = function () {
  5509. switch (this.state) {
  5510. case base_stream_controller_1.State.BUFFER_FLUSHING:
  5511. // in buffer flushing state, reset fragLoadError counter
  5512. this.fragLoadError = 0;
  5513. break;
  5514. case base_stream_controller_1.State.IDLE:
  5515. this._doTickIdle();
  5516. break;
  5517. case base_stream_controller_1.State.WAITING_LEVEL:
  5518. var level = this.levels[this.level];
  5519. // check if playlist is already loaded
  5520. if (level && level.details) {
  5521. this.state = base_stream_controller_1.State.IDLE;
  5522. }
  5523. break;
  5524. case base_stream_controller_1.State.FRAG_LOADING_WAITING_RETRY:
  5525. var now = window.performance.now();
  5526. var retryDate = this.retryDate;
  5527. // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading
  5528. if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {
  5529. logger_1.logger.log('mediaController: retryDate reached, switch back to IDLE state');
  5530. this.state = base_stream_controller_1.State.IDLE;
  5531. }
  5532. break;
  5533. case base_stream_controller_1.State.ERROR:
  5534. case base_stream_controller_1.State.STOPPED:
  5535. case base_stream_controller_1.State.FRAG_LOADING:
  5536. case base_stream_controller_1.State.PARSING:
  5537. case base_stream_controller_1.State.PARSED:
  5538. case base_stream_controller_1.State.ENDED:
  5539. break;
  5540. default:
  5541. break;
  5542. }
  5543. // check buffer
  5544. this._checkBuffer();
  5545. // check/update current fragment
  5546. this._checkFragmentChanged();
  5547. };
  5548. // Ironically the "idle" state is the on we do the most logic in it seems ....
  5549. // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently
  5550. // played segment, or on pause/play/seek instead of naively checking every 100ms?
  5551. StreamController.prototype._doTickIdle = function () {
  5552. var hls = this.hls, config = hls.config, media = this.media;
  5553. // if start level not parsed yet OR
  5554. // if video not attached AND start fragment already requested OR start frag prefetch disable
  5555. // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment
  5556. if (this.levelLastLoaded === undefined || (!media && (this.startFragRequested || !config.startFragPrefetch))) {
  5557. return;
  5558. }
  5559. // if we have not yet loaded any fragment, start loading from start position
  5560. var pos;
  5561. if (this.loadedmetadata) {
  5562. pos = media.currentTime;
  5563. }
  5564. else {
  5565. pos = this.nextLoadPosition;
  5566. }
  5567. // determine next load level
  5568. var level = hls.nextLoadLevel, levelInfo = this.levels[level];
  5569. if (!levelInfo) {
  5570. return;
  5571. }
  5572. var levelBitrate = levelInfo.bitrate, maxBufLen;
  5573. // compute max Buffer Length that we could get from this load level, based on level bitrate. don't buffer more than 60 MB and more than 30s
  5574. if (levelBitrate) {
  5575. maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);
  5576. }
  5577. else {
  5578. maxBufLen = config.maxBufferLength;
  5579. }
  5580. maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);
  5581. // determine next candidate fragment to be loaded, based on current position and end of buffer position
  5582. // ensure up to `config.maxMaxBufferLength` of buffer upfront
  5583. var bufferInfo = buffer_helper_1.BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, config.maxBufferHole), bufferLen = bufferInfo.len;
  5584. // Stay idle if we are still with buffer margins
  5585. if (bufferLen >= maxBufLen) {
  5586. return;
  5587. }
  5588. // if buffer length is less than maxBufLen try to load a new fragment ...
  5589. logger_1.logger.trace("buffer length of " + bufferLen.toFixed(3) + " is below max of " + maxBufLen.toFixed(3) + ". checking for more payload ...");
  5590. // set next load level : this will trigger a playlist load if needed
  5591. this.level = hls.nextLoadLevel = level;
  5592. var levelDetails = levelInfo.details;
  5593. // if level info not retrieved yet, switch state and wait for level retrieval
  5594. // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load
  5595. // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)
  5596. if (!levelDetails || (levelDetails.live && this.levelLastLoaded !== level)) {
  5597. this.state = base_stream_controller_1.State.WAITING_LEVEL;
  5598. return;
  5599. }
  5600. if (this._streamEnded(bufferInfo, levelDetails)) {
  5601. var data = {};
  5602. if (this.altAudio) {
  5603. data.type = 'video';
  5604. }
  5605. this.hls.trigger(events_1.default.BUFFER_EOS, data);
  5606. this.state = base_stream_controller_1.State.ENDED;
  5607. return;
  5608. }
  5609. // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)
  5610. this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);
  5611. };
  5612. StreamController.prototype._fetchPayloadOrEos = function (pos, bufferInfo, levelDetails) {
  5613. var fragPrevious = this.fragPrevious, level = this.level, fragments = levelDetails.fragments, fragLen = fragments.length;
  5614. // empty playlist
  5615. if (fragLen === 0) {
  5616. return;
  5617. }
  5618. // find fragment index, contiguous with end of buffer position
  5619. var start = fragments[0].start, end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration, bufferEnd = bufferInfo.end, frag;
  5620. if (levelDetails.initSegment && !levelDetails.initSegment.data) {
  5621. frag = levelDetails.initSegment;
  5622. }
  5623. else {
  5624. // in case of live playlist we need to ensure that requested position is not located before playlist start
  5625. if (levelDetails.live) {
  5626. var initialLiveManifestSize = this.config.initialLiveManifestSize;
  5627. if (fragLen < initialLiveManifestSize) {
  5628. logger_1.logger.warn("Can not start playback of a level, reason: not enough fragments " + fragLen + " < " + initialLiveManifestSize);
  5629. return;
  5630. }
  5631. frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen);
  5632. // if it explicitely returns null don't load any fragment and exit function now
  5633. if (frag === null) {
  5634. return;
  5635. }
  5636. }
  5637. else {
  5638. // VoD playlist: if bufferEnd before start of playlist, load first fragment
  5639. if (bufferEnd < start) {
  5640. frag = fragments[0];
  5641. }
  5642. }
  5643. }
  5644. if (!frag) {
  5645. frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);
  5646. }
  5647. if (frag) {
  5648. if (frag.encrypted) {
  5649. logger_1.logger.log("Loading key for " + frag.sn + " of [" + levelDetails.startSN + " ," + levelDetails.endSN + "],level " + level);
  5650. this._loadKey(frag);
  5651. }
  5652. else {
  5653. logger_1.logger.log("Loading " + frag.sn + " of [" + levelDetails.startSN + " ," + levelDetails.endSN + "],level " + level + ", currentTime:" + pos.toFixed(3) + ",bufferEnd:" + bufferEnd.toFixed(3));
  5654. this._loadFragment(frag);
  5655. }
  5656. }
  5657. };
  5658. StreamController.prototype._ensureFragmentAtLivePoint = function (levelDetails, bufferEnd, start, end, fragPrevious, fragments, fragLen) {
  5659. var config = this.hls.config, media = this.media;
  5660. var frag;
  5661. // check if requested position is within seekable boundaries :
  5662. // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);
  5663. var maxLatency = config.liveMaxLatencyDuration !== undefined ? config.liveMaxLatencyDuration : config.liveMaxLatencyDurationCount * levelDetails.targetduration;
  5664. if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {
  5665. var liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);
  5666. logger_1.logger.log("buffer end: " + bufferEnd.toFixed(3) + " is located too far from the end of live sliding playlist, reset currentTime to : " + liveSyncPosition.toFixed(3));
  5667. bufferEnd = liveSyncPosition;
  5668. if (media && media.readyState && media.duration > liveSyncPosition) {
  5669. media.currentTime = liveSyncPosition;
  5670. }
  5671. this.nextLoadPosition = liveSyncPosition;
  5672. }
  5673. // if end of buffer greater than live edge, don't load any fragment
  5674. // this could happen if live playlist intermittently slides in the past.
  5675. // level 1 loaded [182580161,182580167]
  5676. // level 1 loaded [182580162,182580169]
  5677. // Loading 182580168 of [182580162 ,182580169],level 1 ..
  5678. // Loading 182580169 of [182580162 ,182580169],level 1 ..
  5679. // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168
  5680. // level 1 loaded [182580164,182580171]
  5681. //
  5682. // don't return null in case media not loaded yet (readystate === 0)
  5683. if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {
  5684. return null;
  5685. }
  5686. if (this.startFragRequested && !levelDetails.PTSKnown) {
  5687. /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...
  5688. try to load frag matching with next SN.
  5689. even if SN are not synchronized between playlists, loading this frag will help us
  5690. compute playlist sliding and find the right one after in case it was not the right consecutive one */
  5691. if (fragPrevious) {
  5692. if (levelDetails.hasProgramDateTime) {
  5693. // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)
  5694. logger_1.logger.log("live playlist, switching playlist, load frag with same PDT: " + fragPrevious.programDateTime);
  5695. frag = fragment_finders_1.findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);
  5696. }
  5697. else {
  5698. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  5699. var targetSN = fragPrevious.sn + 1;
  5700. if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {
  5701. var fragNext = fragments[targetSN - levelDetails.startSN];
  5702. if (fragPrevious.cc === fragNext.cc) {
  5703. frag = fragNext;
  5704. logger_1.logger.log("live playlist, switching playlist, load frag with next SN: " + frag.sn);
  5705. }
  5706. }
  5707. // next frag SN not available (or not with same continuity counter)
  5708. // look for a frag sharing the same CC
  5709. if (!frag) {
  5710. frag = binary_search_1.default.search(fragments, function (frag) {
  5711. return fragPrevious.cc - frag.cc;
  5712. });
  5713. if (frag) {
  5714. logger_1.logger.log("live playlist, switching playlist, load frag with same CC: " + frag.sn);
  5715. }
  5716. }
  5717. }
  5718. }
  5719. if (!frag) {
  5720. /* we have no idea about which fragment should be loaded.
  5721. so let's load mid fragment. it will help computing playlist sliding and find the right one
  5722. */
  5723. frag = fragments[Math.min(fragLen - 1, Math.round(fragLen / 2))];
  5724. logger_1.logger.log("live playlist, switching playlist, unknown, load middle frag : " + frag.sn);
  5725. }
  5726. }
  5727. return frag;
  5728. };
  5729. StreamController.prototype._findFragment = function (start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails) {
  5730. var config = this.hls.config;
  5731. var frag;
  5732. if (bufferEnd < end) {
  5733. var lookupTolerance = (bufferEnd > end - config.maxFragLookUpTolerance) ? 0 : config.maxFragLookUpTolerance;
  5734. // Remove the tolerance if it would put the bufferEnd past the actual end of stream
  5735. // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)
  5736. frag = fragment_finders_1.findFragmentByPTS(fragPrevious, fragments, bufferEnd, lookupTolerance);
  5737. }
  5738. else {
  5739. // reach end of playlist
  5740. frag = fragments[fragLen - 1];
  5741. }
  5742. if (frag) {
  5743. var curSNIdx = frag.sn - levelDetails.startSN;
  5744. var sameLevel = fragPrevious && frag.level === fragPrevious.level;
  5745. var prevFrag = fragments[curSNIdx - 1];
  5746. var nextFrag = fragments[curSNIdx + 1];
  5747. // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);
  5748. if (fragPrevious && frag.sn === fragPrevious.sn) {
  5749. if (sameLevel && !frag.backtracked) {
  5750. if (frag.sn < levelDetails.endSN) {
  5751. var deltaPTS = fragPrevious.deltaPTS;
  5752. // if there is a significant delta between audio and video, larger than max allowed hole,
  5753. // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)
  5754. // let's try to load previous fragment again to get last keyframe
  5755. // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)
  5756. if (deltaPTS && deltaPTS > config.maxBufferHole && fragPrevious.dropped && curSNIdx) {
  5757. frag = prevFrag;
  5758. logger_1.logger.warn('SN just loaded, with large PTS gap between audio and video, maybe frag is not starting with a keyframe ? load previous one to try to overcome this');
  5759. }
  5760. else {
  5761. frag = nextFrag;
  5762. logger_1.logger.log("SN just loaded, load next one: " + frag.sn, frag);
  5763. }
  5764. }
  5765. else {
  5766. frag = null;
  5767. }
  5768. }
  5769. else if (frag.backtracked) {
  5770. // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes
  5771. if (nextFrag && nextFrag.backtracked) {
  5772. logger_1.logger.warn("Already backtracked from fragment " + nextFrag.sn + ", will not backtrack to fragment " + frag.sn + ". Loading fragment " + nextFrag.sn);
  5773. frag = nextFrag;
  5774. }
  5775. else {
  5776. // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe
  5777. // Reset the dropped count now since it won't be reset until we parse the fragment again, which prevents infinite backtracking on the same segment
  5778. logger_1.logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');
  5779. frag.dropped = 0;
  5780. if (prevFrag) {
  5781. frag = prevFrag;
  5782. frag.backtracked = true;
  5783. }
  5784. else if (curSNIdx) {
  5785. // can't backtrack on very first fragment
  5786. frag = null;
  5787. }
  5788. }
  5789. }
  5790. }
  5791. }
  5792. return frag;
  5793. };
  5794. StreamController.prototype._loadKey = function (frag) {
  5795. this.state = base_stream_controller_1.State.KEY_LOADING;
  5796. this.hls.trigger(events_1.default.KEY_LOADING, { frag: frag });
  5797. };
  5798. StreamController.prototype._loadFragment = function (frag) {
  5799. // Check if fragment is not loaded
  5800. var fragState = this.fragmentTracker.getState(frag);
  5801. this.fragCurrent = frag;
  5802. this.startFragRequested = true;
  5803. // Don't update nextLoadPosition for fragments which are not buffered
  5804. if (Number.isFinite(frag.sn) && !frag.bitrateTest) {
  5805. this.nextLoadPosition = frag.start + frag.duration;
  5806. }
  5807. // Allow backtracked fragments to load
  5808. if (frag.backtracked || fragState === fragment_tracker_1.FragmentState.NOT_LOADED || fragState === fragment_tracker_1.FragmentState.PARTIAL) {
  5809. frag.autoLevel = this.hls.autoLevelEnabled;
  5810. frag.bitrateTest = this.bitrateTest;
  5811. this.hls.trigger(events_1.default.FRAG_LOADING, { frag: frag });
  5812. // lazy demuxer init, as this could take some time ... do it during frag loading
  5813. if (!this.demuxer) {
  5814. this.demuxer = new demuxer_1.default(this.hls, 'main');
  5815. }
  5816. this.state = base_stream_controller_1.State.FRAG_LOADING;
  5817. }
  5818. else if (fragState === fragment_tracker_1.FragmentState.APPENDING) {
  5819. // Lower the buffer size and try again
  5820. if (this._reduceMaxBufferLength(frag.duration)) {
  5821. this.fragmentTracker.removeFragment(frag);
  5822. }
  5823. }
  5824. };
  5825. Object.defineProperty(StreamController.prototype, "state", {
  5826. get: function () {
  5827. return this._state;
  5828. },
  5829. set: function (nextState) {
  5830. if (this.state !== nextState) {
  5831. var previousState = this.state;
  5832. this._state = nextState;
  5833. logger_1.logger.log("main stream:" + previousState + "->" + nextState);
  5834. this.hls.trigger(events_1.default.STREAM_STATE_TRANSITION, { previousState: previousState, nextState: nextState });
  5835. }
  5836. },
  5837. enumerable: true,
  5838. configurable: true
  5839. });
  5840. StreamController.prototype.getBufferedFrag = function (position) {
  5841. return this.fragmentTracker.getBufferedFrag(position, playlist_loader_1.default.LevelType.MAIN);
  5842. };
  5843. Object.defineProperty(StreamController.prototype, "currentLevel", {
  5844. get: function () {
  5845. var media = this.media;
  5846. if (media) {
  5847. var frag = this.getBufferedFrag(media.currentTime);
  5848. if (frag) {
  5849. return frag.level;
  5850. }
  5851. }
  5852. return -1;
  5853. },
  5854. enumerable: true,
  5855. configurable: true
  5856. });
  5857. Object.defineProperty(StreamController.prototype, "nextBufferedFrag", {
  5858. get: function () {
  5859. var media = this.media;
  5860. if (media) {
  5861. // first get end range of current fragment
  5862. return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));
  5863. }
  5864. else {
  5865. return null;
  5866. }
  5867. },
  5868. enumerable: true,
  5869. configurable: true
  5870. });
  5871. StreamController.prototype.followingBufferedFrag = function (frag) {
  5872. if (frag) {
  5873. // try to get range of next fragment (500ms after this range)
  5874. return this.getBufferedFrag(frag.endPTS + 0.5);
  5875. }
  5876. return null;
  5877. };
  5878. Object.defineProperty(StreamController.prototype, "nextLevel", {
  5879. get: function () {
  5880. var frag = this.nextBufferedFrag;
  5881. if (frag) {
  5882. return frag.level;
  5883. }
  5884. else {
  5885. return -1;
  5886. }
  5887. },
  5888. enumerable: true,
  5889. configurable: true
  5890. });
  5891. StreamController.prototype._checkFragmentChanged = function () {
  5892. var fragPlayingCurrent, currentTime, video = this.media;
  5893. if (video && video.readyState && video.seeking === false) {
  5894. currentTime = video.currentTime;
  5895. /* if video element is in seeked state, currentTime can only increase.
  5896. (assuming that playback rate is positive ...)
  5897. As sometimes currentTime jumps back to zero after a
  5898. media decode error, check this, to avoid seeking back to
  5899. wrong position after a media decode error
  5900. */
  5901. if (currentTime > this.lastCurrentTime) {
  5902. this.lastCurrentTime = currentTime;
  5903. }
  5904. if (buffer_helper_1.BufferHelper.isBuffered(video, currentTime)) {
  5905. fragPlayingCurrent = this.getBufferedFrag(currentTime);
  5906. }
  5907. else if (buffer_helper_1.BufferHelper.isBuffered(video, currentTime + 0.1)) {
  5908. /* ensure that FRAG_CHANGED event is triggered at startup,
  5909. when first video frame is displayed and playback is paused.
  5910. add a tolerance of 100ms, in case current position is not buffered,
  5911. check if current pos+100ms is buffered and use that buffer range
  5912. for FRAG_CHANGED event reporting */
  5913. fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);
  5914. }
  5915. if (fragPlayingCurrent) {
  5916. var fragPlaying = fragPlayingCurrent;
  5917. if (fragPlaying !== this.fragPlaying) {
  5918. this.hls.trigger(events_1.default.FRAG_CHANGED, { frag: fragPlaying });
  5919. var fragPlayingLevel = fragPlaying.level;
  5920. if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {
  5921. this.hls.trigger(events_1.default.LEVEL_SWITCHED, { level: fragPlayingLevel });
  5922. }
  5923. this.fragPlaying = fragPlaying;
  5924. }
  5925. }
  5926. }
  5927. };
  5928. /*
  5929. on immediate level switch :
  5930. - pause playback if playing
  5931. - cancel any pending load request
  5932. - and trigger a buffer flush
  5933. */
  5934. StreamController.prototype.immediateLevelSwitch = function () {
  5935. logger_1.logger.log('immediateLevelSwitch');
  5936. if (!this.immediateSwitch) {
  5937. this.immediateSwitch = true;
  5938. var media = this.media, previouslyPaused = void 0;
  5939. if (media) {
  5940. previouslyPaused = media.paused;
  5941. media.pause();
  5942. }
  5943. else {
  5944. // don't restart playback after instant level switch in case media not attached
  5945. previouslyPaused = true;
  5946. }
  5947. this.previouslyPaused = previouslyPaused;
  5948. }
  5949. var fragCurrent = this.fragCurrent;
  5950. if (fragCurrent && fragCurrent.loader) {
  5951. fragCurrent.loader.abort();
  5952. }
  5953. this.fragCurrent = null;
  5954. // flush everything
  5955. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  5956. };
  5957. /**
  5958. * on immediate level switch end, after new fragment has been buffered:
  5959. * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)
  5960. * - resume the playback if needed
  5961. */
  5962. StreamController.prototype.immediateLevelSwitchEnd = function () {
  5963. var media = this.media;
  5964. if (media && media.buffered.length) {
  5965. this.immediateSwitch = false;
  5966. if (buffer_helper_1.BufferHelper.isBuffered(media, media.currentTime)) {
  5967. // only nudge if currentTime is buffered
  5968. media.currentTime -= 0.0001;
  5969. }
  5970. if (!this.previouslyPaused) {
  5971. media.play();
  5972. }
  5973. }
  5974. };
  5975. /**
  5976. * try to switch ASAP without breaking video playback:
  5977. * in order to ensure smooth but quick level switching,
  5978. * we need to find the next flushable buffer range
  5979. * we should take into account new segment fetch time
  5980. */
  5981. StreamController.prototype.nextLevelSwitch = function () {
  5982. var media = this.media;
  5983. // ensure that media is defined and that metadata are available (to retrieve currentTime)
  5984. if (media && media.readyState) {
  5985. var fetchdelay = void 0, fragPlayingCurrent = void 0, nextBufferedFrag = void 0;
  5986. fragPlayingCurrent = this.getBufferedFrag(media.currentTime);
  5987. if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {
  5988. // flush buffer preceding current fragment (flush until current fragment start offset)
  5989. // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...
  5990. this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);
  5991. }
  5992. if (!media.paused) {
  5993. // add a safety delay of 1s
  5994. var nextLevelId = this.hls.nextLoadLevel, nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps;
  5995. if (fragLastKbps && this.fragCurrent) {
  5996. fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;
  5997. }
  5998. else {
  5999. fetchdelay = 0;
  6000. }
  6001. }
  6002. else {
  6003. fetchdelay = 0;
  6004. }
  6005. // logger.log('fetchdelay:'+fetchdelay);
  6006. // find buffer range that will be reached once new fragment will be fetched
  6007. nextBufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);
  6008. if (nextBufferedFrag) {
  6009. // we can flush buffer range following this one without stalling playback
  6010. nextBufferedFrag = this.followingBufferedFrag(nextBufferedFrag);
  6011. if (nextBufferedFrag) {
  6012. // if we are here, we can also cancel any loading/demuxing in progress, as they are useless
  6013. var fragCurrent = this.fragCurrent;
  6014. if (fragCurrent && fragCurrent.loader) {
  6015. fragCurrent.loader.abort();
  6016. }
  6017. this.fragCurrent = null;
  6018. // start flush position is the start PTS of next buffered frag.
  6019. // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).
  6020. // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment
  6021. this.flushMainBuffer(nextBufferedFrag.maxStartPTS, Number.POSITIVE_INFINITY);
  6022. }
  6023. }
  6024. }
  6025. };
  6026. StreamController.prototype.flushMainBuffer = function (startOffset, endOffset) {
  6027. this.state = base_stream_controller_1.State.BUFFER_FLUSHING;
  6028. var flushScope = { startOffset: startOffset, endOffset: endOffset };
  6029. // if alternate audio tracks are used, only flush video, otherwise flush everything
  6030. if (this.altAudio) {
  6031. flushScope.type = 'video';
  6032. }
  6033. this.hls.trigger(events_1.default.BUFFER_FLUSHING, flushScope);
  6034. };
  6035. StreamController.prototype.onMediaAttached = function (data) {
  6036. var media = this.media = this.mediaBuffer = data.media;
  6037. this.onvseeking = this.onMediaSeeking.bind(this);
  6038. this.onvseeked = this.onMediaSeeked.bind(this);
  6039. this.onvended = this.onMediaEnded.bind(this);
  6040. media.addEventListener('seeking', this.onvseeking);
  6041. media.addEventListener('seeked', this.onvseeked);
  6042. media.addEventListener('ended', this.onvended);
  6043. var config = this.config;
  6044. if (this.levels && config.autoStartLoad) {
  6045. this.hls.startLoad(config.startPosition);
  6046. }
  6047. this.gapController = new gap_controller_1.default(config, media, this.fragmentTracker, this.hls);
  6048. };
  6049. StreamController.prototype.onMediaDetaching = function () {
  6050. var media = this.media;
  6051. if (media && media.ended) {
  6052. logger_1.logger.log('MSE detaching and video ended, reset startPosition');
  6053. this.startPosition = this.lastCurrentTime = 0;
  6054. }
  6055. // reset fragment backtracked flag
  6056. var levels = this.levels;
  6057. if (levels) {
  6058. levels.forEach(function (level) {
  6059. if (level.details) {
  6060. level.details.fragments.forEach(function (fragment) {
  6061. fragment.backtracked = undefined;
  6062. });
  6063. }
  6064. });
  6065. }
  6066. // remove video listeners
  6067. if (media) {
  6068. media.removeEventListener('seeking', this.onvseeking);
  6069. media.removeEventListener('seeked', this.onvseeked);
  6070. media.removeEventListener('ended', this.onvended);
  6071. this.onvseeking = this.onvseeked = this.onvended = null;
  6072. }
  6073. this.media = this.mediaBuffer = null;
  6074. this.loadedmetadata = false;
  6075. this.stopLoad();
  6076. };
  6077. StreamController.prototype.onMediaSeeked = function () {
  6078. var media = this.media, currentTime = media ? media.currentTime : undefined;
  6079. if (Number.isFinite(currentTime)) {
  6080. logger_1.logger.log("media seeked to " + currentTime.toFixed(3));
  6081. }
  6082. // tick to speed up FRAGMENT_PLAYING triggering
  6083. this.tick();
  6084. };
  6085. StreamController.prototype.onManifestLoading = function () {
  6086. // reset buffer on manifest loading
  6087. logger_1.logger.log('trigger BUFFER_RESET');
  6088. this.hls.trigger(events_1.default.BUFFER_RESET);
  6089. this.fragmentTracker.removeAllFragments();
  6090. this.stalled = false;
  6091. this.startPosition = this.lastCurrentTime = 0;
  6092. };
  6093. StreamController.prototype.onManifestParsed = function (data) {
  6094. var aac = false, heaac = false, codec;
  6095. data.levels.forEach(function (level) {
  6096. // detect if we have different kind of audio codecs used amongst playlists
  6097. codec = level.audioCodec;
  6098. if (codec) {
  6099. if (codec.indexOf('mp4a.40.2') !== -1) {
  6100. aac = true;
  6101. }
  6102. if (codec.indexOf('mp4a.40.5') !== -1) {
  6103. heaac = true;
  6104. }
  6105. }
  6106. });
  6107. this.audioCodecSwitch = (aac && heaac);
  6108. if (this.audioCodecSwitch) {
  6109. logger_1.logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');
  6110. }
  6111. this.levels = data.levels;
  6112. this.startFragRequested = false;
  6113. var config = this.config;
  6114. if (config.autoStartLoad || this.forceStartLoad) {
  6115. this.hls.startLoad(config.startPosition);
  6116. }
  6117. };
  6118. StreamController.prototype.onLevelLoaded = function (data) {
  6119. var newDetails = data.details;
  6120. var newLevelId = data.level;
  6121. var lastLevel = this.levels[this.levelLastLoaded];
  6122. var curLevel = this.levels[newLevelId];
  6123. var duration = newDetails.totalduration;
  6124. var sliding = 0;
  6125. logger_1.logger.log("level " + newLevelId + " loaded [" + newDetails.startSN + "," + newDetails.endSN + "],duration:" + duration);
  6126. if (newDetails.live) {
  6127. var curDetails = curLevel.details;
  6128. if (curDetails && newDetails.fragments.length > 0) {
  6129. // we already have details for that level, merge them
  6130. LevelHelper.mergeDetails(curDetails, newDetails);
  6131. sliding = newDetails.fragments[0].start;
  6132. this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);
  6133. if (newDetails.PTSKnown && Number.isFinite(sliding)) {
  6134. logger_1.logger.log("live playlist sliding:" + sliding.toFixed(3));
  6135. }
  6136. else {
  6137. logger_1.logger.log('live playlist - outdated PTS, unknown sliding');
  6138. discontinuities_1.alignStream(this.fragPrevious, lastLevel, newDetails);
  6139. }
  6140. }
  6141. else {
  6142. logger_1.logger.log('live playlist - first load, unknown sliding');
  6143. newDetails.PTSKnown = false;
  6144. discontinuities_1.alignStream(this.fragPrevious, lastLevel, newDetails);
  6145. }
  6146. }
  6147. else {
  6148. newDetails.PTSKnown = false;
  6149. }
  6150. // override level info
  6151. curLevel.details = newDetails;
  6152. this.levelLastLoaded = newLevelId;
  6153. this.hls.trigger(events_1.default.LEVEL_UPDATED, { details: newDetails, level: newLevelId });
  6154. if (this.startFragRequested === false) {
  6155. // compute start position if set to -1. use it straight away if value is defined
  6156. if (this.startPosition === -1 || this.lastCurrentTime === -1) {
  6157. // first, check if start time offset has been set in playlist, if yes, use this value
  6158. var startTimeOffset = newDetails.startTimeOffset;
  6159. if (Number.isFinite(startTimeOffset)) {
  6160. if (startTimeOffset < 0) {
  6161. logger_1.logger.log("negative start time offset " + startTimeOffset + ", count from end of last fragment");
  6162. startTimeOffset = sliding + duration + startTimeOffset;
  6163. }
  6164. logger_1.logger.log("start time offset found in playlist, adjust startPosition to " + startTimeOffset);
  6165. this.startPosition = startTimeOffset;
  6166. }
  6167. else {
  6168. // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)
  6169. if (newDetails.live) {
  6170. this.startPosition = this.computeLivePosition(sliding, newDetails);
  6171. logger_1.logger.log("configure startPosition to " + this.startPosition);
  6172. }
  6173. else {
  6174. this.startPosition = 0;
  6175. }
  6176. }
  6177. this.lastCurrentTime = this.startPosition;
  6178. }
  6179. this.nextLoadPosition = this.startPosition;
  6180. }
  6181. // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment
  6182. if (this.state === base_stream_controller_1.State.WAITING_LEVEL) {
  6183. this.state = base_stream_controller_1.State.IDLE;
  6184. }
  6185. // trigger handler right now
  6186. this.tick();
  6187. };
  6188. StreamController.prototype.onKeyLoaded = function () {
  6189. if (this.state === base_stream_controller_1.State.KEY_LOADING) {
  6190. this.state = base_stream_controller_1.State.IDLE;
  6191. this.tick();
  6192. }
  6193. };
  6194. StreamController.prototype.onFragLoaded = function (data) {
  6195. var _a = this, fragCurrent = _a.fragCurrent, hls = _a.hls, levels = _a.levels, media = _a.media;
  6196. var fragLoaded = data.frag;
  6197. if (this.state === base_stream_controller_1.State.FRAG_LOADING &&
  6198. fragCurrent &&
  6199. fragLoaded.type === 'main' &&
  6200. fragLoaded.level === fragCurrent.level &&
  6201. fragLoaded.sn === fragCurrent.sn) {
  6202. var stats = data.stats;
  6203. var currentLevel = levels[fragCurrent.level];
  6204. var details = currentLevel.details;
  6205. // reset frag bitrate test in any case after frag loaded event
  6206. // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0
  6207. // then this means that we should be able to load a fragment at a higher quality level
  6208. this.bitrateTest = false;
  6209. this.stats = stats;
  6210. logger_1.logger.log("Loaded " + fragCurrent.sn + " of [" + details.startSN + " ," + details.endSN + "],level " + fragCurrent.level);
  6211. if (fragLoaded.bitrateTest && hls.nextLoadLevel) {
  6212. // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo
  6213. this.state = base_stream_controller_1.State.IDLE;
  6214. this.startFragRequested = false;
  6215. stats.tparsed = stats.tbuffered = window.performance.now();
  6216. hls.trigger(events_1.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  6217. this.tick();
  6218. }
  6219. else if (fragLoaded.sn === 'initSegment') {
  6220. this.state = base_stream_controller_1.State.IDLE;
  6221. stats.tparsed = stats.tbuffered = window.performance.now();
  6222. details.initSegment.data = data.payload;
  6223. hls.trigger(events_1.default.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });
  6224. this.tick();
  6225. }
  6226. else {
  6227. logger_1.logger.log("Parsing " + fragCurrent.sn + " of [" + details.startSN + " ," + details.endSN + "],level " + fragCurrent.level + ", cc " + fragCurrent.cc);
  6228. this.state = base_stream_controller_1.State.PARSING;
  6229. this.pendingBuffering = true;
  6230. this.appended = false;
  6231. // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer
  6232. // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.
  6233. if (fragLoaded.bitrateTest) {
  6234. fragLoaded.bitrateTest = false;
  6235. this.fragmentTracker.onFragLoaded({
  6236. frag: fragLoaded
  6237. });
  6238. }
  6239. // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live) and if media is not seeking (this is to overcome potential timestamp drifts between playlists and fragments)
  6240. var accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);
  6241. var initSegmentData = details.initSegment ? details.initSegment.data : [];
  6242. var audioCodec = this._getAudioCodec(currentLevel);
  6243. // transmux the MPEG-TS data to ISO-BMFF segments
  6244. var demuxer = this.demuxer = this.demuxer || new demuxer_1.default(this.hls, 'main');
  6245. demuxer.push(data.payload, initSegmentData, audioCodec, currentLevel.videoCodec, fragCurrent, details.totalduration, accurateTimeOffset);
  6246. }
  6247. }
  6248. this.fragLoadError = 0;
  6249. };
  6250. StreamController.prototype.onFragParsingInitSegment = function (data) {
  6251. var fragCurrent = this.fragCurrent;
  6252. var fragNew = data.frag;
  6253. if (fragCurrent &&
  6254. data.id === 'main' &&
  6255. fragNew.sn === fragCurrent.sn &&
  6256. fragNew.level === fragCurrent.level &&
  6257. this.state === base_stream_controller_1.State.PARSING) {
  6258. var tracks = data.tracks, trackName = void 0, track = void 0;
  6259. // if audio track is expected to come from audio stream controller, discard any coming from main
  6260. if (tracks.audio && this.altAudio) {
  6261. delete tracks.audio;
  6262. }
  6263. // include levelCodec in audio and video tracks
  6264. track = tracks.audio;
  6265. if (track) {
  6266. var audioCodec = this.levels[this.level].audioCodec, ua = navigator.userAgent.toLowerCase();
  6267. if (audioCodec && this.audioCodecSwap) {
  6268. logger_1.logger.log('swapping playlist audio codec');
  6269. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  6270. audioCodec = 'mp4a.40.2';
  6271. }
  6272. else {
  6273. audioCodec = 'mp4a.40.5';
  6274. }
  6275. }
  6276. // in case AAC and HE-AAC audio codecs are signalled in manifest
  6277. // force HE-AAC , as it seems that most browsers prefers that way,
  6278. // except for mono streams OR on FF
  6279. // these conditions might need to be reviewed ...
  6280. if (this.audioCodecSwitch) {
  6281. // don't force HE-AAC if mono stream
  6282. if (track.metadata.channelCount !== 1 &&
  6283. // don't force HE-AAC if firefox
  6284. ua.indexOf('firefox') === -1) {
  6285. audioCodec = 'mp4a.40.5';
  6286. }
  6287. }
  6288. // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise
  6289. if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { // Exclude mpeg audio
  6290. audioCodec = 'mp4a.40.2';
  6291. logger_1.logger.log("Android: force audio codec to " + audioCodec);
  6292. }
  6293. track.levelCodec = audioCodec;
  6294. track.id = data.id;
  6295. }
  6296. track = tracks.video;
  6297. if (track) {
  6298. track.levelCodec = this.levels[this.level].videoCodec;
  6299. track.id = data.id;
  6300. }
  6301. this.hls.trigger(events_1.default.BUFFER_CODECS, tracks);
  6302. // loop through tracks that are going to be provided to bufferController
  6303. for (trackName in tracks) {
  6304. track = tracks[trackName];
  6305. logger_1.logger.log("main track:" + trackName + ",container:" + track.container + ",codecs[level/parsed]=[" + track.levelCodec + "/" + track.codec + "]");
  6306. var initSegment = track.initSegment;
  6307. if (initSegment) {
  6308. this.appended = true;
  6309. // arm pending Buffering flag before appending a segment
  6310. this.pendingBuffering = true;
  6311. this.hls.trigger(events_1.default.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });
  6312. }
  6313. }
  6314. // trigger handler right now
  6315. this.tick();
  6316. }
  6317. };
  6318. StreamController.prototype.onFragParsingData = function (data) {
  6319. var _this = this;
  6320. var fragCurrent = this.fragCurrent;
  6321. var fragNew = data.frag;
  6322. if (fragCurrent &&
  6323. data.id === 'main' &&
  6324. fragNew.sn === fragCurrent.sn &&
  6325. fragNew.level === fragCurrent.level &&
  6326. !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller
  6327. this.state === base_stream_controller_1.State.PARSING) {
  6328. var level = this.levels[this.level], frag = fragCurrent;
  6329. if (!Number.isFinite(data.endPTS)) {
  6330. data.endPTS = data.startPTS + fragCurrent.duration;
  6331. data.endDTS = data.startDTS + fragCurrent.duration;
  6332. }
  6333. if (data.hasAudio === true) {
  6334. frag.addElementaryStream(fragment_1.default.ElementaryStreamTypes.AUDIO);
  6335. }
  6336. if (data.hasVideo === true) {
  6337. frag.addElementaryStream(fragment_1.default.ElementaryStreamTypes.VIDEO);
  6338. }
  6339. logger_1.logger.log("Parsed " + data.type + ",PTS:[" + data.startPTS.toFixed(3) + "," + data.endPTS.toFixed(3) + "],DTS:[" + data.startDTS.toFixed(3) + "/" + data.endDTS.toFixed(3) + "],nb:" + data.nb + ",dropped:" + (data.dropped || 0));
  6340. // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)
  6341. if (data.type === 'video') {
  6342. frag.dropped = data.dropped;
  6343. if (frag.dropped) {
  6344. if (!frag.backtracked) {
  6345. var levelDetails = level.details;
  6346. if (levelDetails && frag.sn === levelDetails.startSN) {
  6347. logger_1.logger.warn('missing video frame(s) on first frag, appending with gap', frag.sn);
  6348. }
  6349. else {
  6350. logger_1.logger.warn('missing video frame(s), backtracking fragment', frag.sn);
  6351. // Return back to the IDLE state without appending to buffer
  6352. // Causes findFragments to backtrack a segment and find the keyframe
  6353. // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment
  6354. this.fragmentTracker.removeFragment(frag);
  6355. frag.backtracked = true;
  6356. this.nextLoadPosition = data.startPTS;
  6357. this.state = base_stream_controller_1.State.IDLE;
  6358. this.fragPrevious = frag;
  6359. this.tick();
  6360. return;
  6361. }
  6362. }
  6363. else {
  6364. logger_1.logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);
  6365. }
  6366. }
  6367. else {
  6368. // Only reset the backtracked flag if we've loaded the frag without any dropped frames
  6369. frag.backtracked = false;
  6370. }
  6371. }
  6372. var drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS), hls_2 = this.hls;
  6373. hls_2.trigger(events_1.default.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });
  6374. // has remuxer dropped video frames located before first keyframe ?
  6375. [data.data1, data.data2].forEach(function (buffer) {
  6376. // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)
  6377. // in that case it is useless to append following segments
  6378. if (buffer && buffer.length && _this.state === base_stream_controller_1.State.PARSING) {
  6379. _this.appended = true;
  6380. // arm pending Buffering flag before appending a segment
  6381. _this.pendingBuffering = true;
  6382. hls_2.trigger(events_1.default.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });
  6383. }
  6384. });
  6385. // trigger handler right now
  6386. this.tick();
  6387. }
  6388. };
  6389. StreamController.prototype.onFragParsed = function (data) {
  6390. var fragCurrent = this.fragCurrent;
  6391. var fragNew = data.frag;
  6392. if (fragCurrent &&
  6393. data.id === 'main' &&
  6394. fragNew.sn === fragCurrent.sn &&
  6395. fragNew.level === fragCurrent.level &&
  6396. this.state === base_stream_controller_1.State.PARSING) {
  6397. this.stats.tparsed = window.performance.now();
  6398. this.state = base_stream_controller_1.State.PARSED;
  6399. this._checkAppendedParsed();
  6400. }
  6401. };
  6402. StreamController.prototype.onAudioTrackSwitching = function (data) {
  6403. // if any URL found on new audio track, it is an alternate audio track
  6404. var altAudio = !!data.url, trackId = data.id;
  6405. // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered
  6406. // don't do anything if we switch to alt audio: audio stream controller is handling it.
  6407. // we will just have to change buffer scheduling on audioTrackSwitched
  6408. if (!altAudio) {
  6409. if (this.mediaBuffer !== this.media) {
  6410. logger_1.logger.log('switching on main audio, use media.buffered to schedule main fragment loading');
  6411. this.mediaBuffer = this.media;
  6412. var fragCurrent = this.fragCurrent;
  6413. // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch
  6414. if (fragCurrent.loader) {
  6415. logger_1.logger.log('switching to main audio track, cancel main fragment load');
  6416. fragCurrent.loader.abort();
  6417. }
  6418. this.fragCurrent = null;
  6419. this.fragPrevious = null;
  6420. // destroy demuxer to force init segment generation (following audio switch)
  6421. if (this.demuxer) {
  6422. this.demuxer.destroy();
  6423. this.demuxer = null;
  6424. }
  6425. // switch to IDLE state to load new fragment
  6426. this.state = base_stream_controller_1.State.IDLE;
  6427. }
  6428. var hls_3 = this.hls;
  6429. // switching to main audio, flush all audio and trigger track switched
  6430. hls_3.trigger(events_1.default.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });
  6431. hls_3.trigger(events_1.default.AUDIO_TRACK_SWITCHED, { id: trackId });
  6432. this.altAudio = false;
  6433. }
  6434. };
  6435. StreamController.prototype.onAudioTrackSwitched = function (data) {
  6436. var trackId = data.id, altAudio = !!this.hls.audioTracks[trackId].url;
  6437. if (altAudio) {
  6438. var videoBuffer = this.videoBuffer;
  6439. // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered
  6440. if (videoBuffer && this.mediaBuffer !== videoBuffer) {
  6441. logger_1.logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');
  6442. this.mediaBuffer = videoBuffer;
  6443. }
  6444. }
  6445. this.altAudio = altAudio;
  6446. this.tick();
  6447. };
  6448. StreamController.prototype.onBufferCreated = function (data) {
  6449. var tracks = data.tracks, mediaTrack, name, alternate = false;
  6450. for (var type in tracks) {
  6451. var track = tracks[type];
  6452. if (track.id === 'main') {
  6453. name = type;
  6454. mediaTrack = track;
  6455. // keep video source buffer reference
  6456. if (type === 'video') {
  6457. this.videoBuffer = tracks[type].buffer;
  6458. }
  6459. }
  6460. else {
  6461. alternate = true;
  6462. }
  6463. }
  6464. if (alternate && mediaTrack) {
  6465. logger_1.logger.log("alternate track found, use " + name + ".buffered to schedule main fragment loading");
  6466. this.mediaBuffer = mediaTrack.buffer;
  6467. }
  6468. else {
  6469. this.mediaBuffer = this.media;
  6470. }
  6471. };
  6472. StreamController.prototype.onBufferAppended = function (data) {
  6473. if (data.parent === 'main') {
  6474. var state = this.state;
  6475. if (state === base_stream_controller_1.State.PARSING || state === base_stream_controller_1.State.PARSED) {
  6476. // check if all buffers have been appended
  6477. this.pendingBuffering = (data.pending > 0);
  6478. this._checkAppendedParsed();
  6479. }
  6480. }
  6481. };
  6482. StreamController.prototype._checkAppendedParsed = function () {
  6483. // trigger handler right now
  6484. if (this.state === base_stream_controller_1.State.PARSED && (!this.appended || !this.pendingBuffering)) {
  6485. var frag = this.fragCurrent;
  6486. if (frag) {
  6487. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  6488. logger_1.logger.log("main buffered : " + time_ranges_1.default.toString(media.buffered));
  6489. this.fragPrevious = frag;
  6490. var stats = this.stats;
  6491. stats.tbuffered = window.performance.now();
  6492. // we should get rid of this.fragLastKbps
  6493. this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));
  6494. this.hls.trigger(events_1.default.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });
  6495. this.state = base_stream_controller_1.State.IDLE;
  6496. }
  6497. this.tick();
  6498. }
  6499. };
  6500. StreamController.prototype.onError = function (data) {
  6501. var frag = data.frag || this.fragCurrent;
  6502. // don't handle frag error not related to main fragment
  6503. if (frag && frag.type !== 'main') {
  6504. return;
  6505. }
  6506. // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end
  6507. var mediaBuffered = !!this.media && buffer_helper_1.BufferHelper.isBuffered(this.media, this.media.currentTime) && buffer_helper_1.BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);
  6508. switch (data.details) {
  6509. case errors_1.ErrorDetails.FRAG_LOAD_ERROR:
  6510. case errors_1.ErrorDetails.FRAG_LOAD_TIMEOUT:
  6511. case errors_1.ErrorDetails.KEY_LOAD_ERROR:
  6512. case errors_1.ErrorDetails.KEY_LOAD_TIMEOUT:
  6513. if (!data.fatal) {
  6514. // keep retrying until the limit will be reached
  6515. if ((this.fragLoadError + 1) <= this.config.fragLoadingMaxRetry) {
  6516. // exponential backoff capped to config.fragLoadingMaxRetryTimeout
  6517. var delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);
  6518. logger_1.logger.warn("mediaController: frag loading failed, retry in " + delay + " ms");
  6519. this.retryDate = window.performance.now() + delay;
  6520. // retry loading state
  6521. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  6522. // in that case, reset startFragRequested flag
  6523. if (!this.loadedmetadata) {
  6524. this.startFragRequested = false;
  6525. this.nextLoadPosition = this.startPosition;
  6526. }
  6527. this.fragLoadError++;
  6528. this.state = base_stream_controller_1.State.FRAG_LOADING_WAITING_RETRY;
  6529. }
  6530. else {
  6531. logger_1.logger.error("mediaController: " + data.details + " reaches max retry, redispatch as fatal ...");
  6532. // switch error to fatal
  6533. data.fatal = true;
  6534. this.state = base_stream_controller_1.State.ERROR;
  6535. }
  6536. }
  6537. break;
  6538. case errors_1.ErrorDetails.LEVEL_LOAD_ERROR:
  6539. case errors_1.ErrorDetails.LEVEL_LOAD_TIMEOUT:
  6540. if (this.state !== base_stream_controller_1.State.ERROR) {
  6541. if (data.fatal) {
  6542. // if fatal error, stop processing
  6543. this.state = base_stream_controller_1.State.ERROR;
  6544. logger_1.logger.warn("streamController: " + data.details + ",switch to " + this.state + " state ...");
  6545. }
  6546. else {
  6547. // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE
  6548. if (!data.levelRetry && this.state === base_stream_controller_1.State.WAITING_LEVEL) {
  6549. this.state = base_stream_controller_1.State.IDLE;
  6550. }
  6551. }
  6552. }
  6553. break;
  6554. case errors_1.ErrorDetails.BUFFER_FULL_ERROR:
  6555. // if in appending state
  6556. if (data.parent === 'main' && (this.state === base_stream_controller_1.State.PARSING || this.state === base_stream_controller_1.State.PARSED)) {
  6557. // reduce max buf len if current position is buffered
  6558. if (mediaBuffered) {
  6559. this._reduceMaxBufferLength(this.config.maxBufferLength);
  6560. this.state = base_stream_controller_1.State.IDLE;
  6561. }
  6562. else {
  6563. // current position is not buffered, but browser is still complaining about buffer full error
  6564. // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708
  6565. // in that case flush the whole buffer to recover
  6566. logger_1.logger.warn('buffer full error also media.currentTime is not buffered, flush everything');
  6567. this.fragCurrent = null;
  6568. // flush everything
  6569. this.flushMainBuffer(0, Number.POSITIVE_INFINITY);
  6570. }
  6571. }
  6572. break;
  6573. default:
  6574. break;
  6575. }
  6576. };
  6577. StreamController.prototype._reduceMaxBufferLength = function (minLength) {
  6578. var config = this.config;
  6579. if (config.maxMaxBufferLength >= minLength) {
  6580. // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...
  6581. config.maxMaxBufferLength /= 2;
  6582. logger_1.logger.warn("main:reduce max buffer length to " + config.maxMaxBufferLength + "s");
  6583. return true;
  6584. }
  6585. return false;
  6586. };
  6587. /**
  6588. * Checks the health of the buffer and attempts to resolve playback stalls.
  6589. * @private
  6590. */
  6591. StreamController.prototype._checkBuffer = function () {
  6592. var media = this.media;
  6593. if (!media || media.readyState === 0) {
  6594. // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)
  6595. return;
  6596. }
  6597. var mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;
  6598. var buffered = mediaBuffer.buffered;
  6599. if (!this.loadedmetadata && buffered.length) {
  6600. this.loadedmetadata = true;
  6601. this._seekToStartPos();
  6602. }
  6603. else if (this.immediateSwitch) {
  6604. this.immediateLevelSwitchEnd();
  6605. }
  6606. else {
  6607. this.gapController.poll(this.lastCurrentTime, buffered);
  6608. }
  6609. };
  6610. StreamController.prototype.onFragLoadEmergencyAborted = function () {
  6611. this.state = base_stream_controller_1.State.IDLE;
  6612. // if loadedmetadata is not set, it means that we are emergency switch down on first frag
  6613. // in that case, reset startFragRequested flag
  6614. if (!this.loadedmetadata) {
  6615. this.startFragRequested = false;
  6616. this.nextLoadPosition = this.startPosition;
  6617. }
  6618. this.tick();
  6619. };
  6620. StreamController.prototype.onBufferFlushed = function () {
  6621. /* after successful buffer flushing, filter flushed fragments from bufferedFrags
  6622. use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)
  6623. */
  6624. var media = this.mediaBuffer ? this.mediaBuffer : this.media;
  6625. if (media) {
  6626. // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams
  6627. this.fragmentTracker.detectEvictedFragments(fragment_1.default.ElementaryStreamTypes.VIDEO, media.buffered);
  6628. }
  6629. // move to IDLE once flush complete. this should trigger new fragment loading
  6630. this.state = base_stream_controller_1.State.IDLE;
  6631. // reset reference to frag
  6632. this.fragPrevious = null;
  6633. };
  6634. StreamController.prototype.swapAudioCodec = function () {
  6635. this.audioCodecSwap = !this.audioCodecSwap;
  6636. };
  6637. StreamController.prototype.computeLivePosition = function (sliding, levelDetails) {
  6638. var targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;
  6639. return sliding + Math.max(0, levelDetails.totalduration - targetLatency);
  6640. };
  6641. /**
  6642. * Seeks to the set startPosition if not equal to the mediaElement's current time.
  6643. * @private
  6644. */
  6645. StreamController.prototype._seekToStartPos = function () {
  6646. var media = this.media;
  6647. var currentTime = media.currentTime;
  6648. // only adjust currentTime if different from startPosition or if startPosition not buffered
  6649. // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered
  6650. var startPosition = media.seeking ? currentTime : this.startPosition;
  6651. // if currentTime not matching with expected startPosition or startPosition not buffered but close to first buffered
  6652. if (currentTime !== startPosition) {
  6653. // if startPosition not buffered, let's seek to buffered.start(0)
  6654. logger_1.logger.log("target start position not buffered, seek to buffered.start(0) " + startPosition + " from current time " + currentTime + " ");
  6655. media.currentTime = startPosition;
  6656. }
  6657. };
  6658. StreamController.prototype._getAudioCodec = function (currentLevel) {
  6659. var audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;
  6660. if (this.audioCodecSwap) {
  6661. logger_1.logger.log('swapping playlist audio codec');
  6662. if (audioCodec) {
  6663. if (audioCodec.indexOf('mp4a.40.5') !== -1) {
  6664. audioCodec = 'mp4a.40.2';
  6665. }
  6666. else {
  6667. audioCodec = 'mp4a.40.5';
  6668. }
  6669. }
  6670. }
  6671. return audioCodec;
  6672. };
  6673. Object.defineProperty(StreamController.prototype, "liveSyncPosition", {
  6674. get: function () {
  6675. return this._liveSyncPosition;
  6676. },
  6677. set: function (value) {
  6678. this._liveSyncPosition = value;
  6679. },
  6680. enumerable: true,
  6681. configurable: true
  6682. });
  6683. return StreamController;
  6684. }(base_stream_controller_1.default));
  6685. exports.default = StreamController;
  6686. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  6687. /***/ }),
  6688. /***/ "./src/controller/subtitle-stream-controller.js":
  6689. /*!******************************************************!*\
  6690. !*** ./src/controller/subtitle-stream-controller.js ***!
  6691. \******************************************************/
  6692. /*! no static exports found */
  6693. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  6694. /***/ (function(module, exports, __webpack_require__) {
  6695. "use strict";
  6696. /**
  6697. * @class SubtitleStreamController
  6698. */
  6699. var __extends = (this && this.__extends) || (function () {
  6700. var extendStatics = Object.setPrototypeOf ||
  6701. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  6702. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  6703. return function (d, b) {
  6704. extendStatics(d, b);
  6705. function __() { this.constructor = d; }
  6706. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  6707. };
  6708. })();
  6709. Object.defineProperty(exports, "__esModule", { value: true });
  6710. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  6711. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  6712. var decrypter_1 = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.js");
  6713. var buffer_helper_1 = __webpack_require__(/*! ../utils/buffer-helper */ "./src/utils/buffer-helper.js");
  6714. var fragment_finders_1 = __webpack_require__(/*! ./fragment-finders */ "./src/controller/fragment-finders.js");
  6715. var fragment_tracker_1 = __webpack_require__(/*! ./fragment-tracker */ "./src/controller/fragment-tracker.js");
  6716. var base_stream_controller_1 = __webpack_require__(/*! ./base-stream-controller */ "./src/controller/base-stream-controller.js");
  6717. var level_helper_1 = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.js");
  6718. var performance = window.performance;
  6719. var TICK_INTERVAL = 500; // how often to tick in ms
  6720. var SubtitleStreamController = /** @class */ (function (_super) {
  6721. __extends(SubtitleStreamController, _super);
  6722. function SubtitleStreamController(hls, fragmentTracker) {
  6723. var _this = _super.call(this, hls, events_1.default.MEDIA_ATTACHED, events_1.default.MEDIA_DETACHING, events_1.default.ERROR, events_1.default.KEY_LOADED, events_1.default.FRAG_LOADED, events_1.default.SUBTITLE_TRACKS_UPDATED, events_1.default.SUBTITLE_TRACK_SWITCH, events_1.default.SUBTITLE_TRACK_LOADED, events_1.default.SUBTITLE_FRAG_PROCESSED, events_1.default.LEVEL_UPDATED) || this;
  6724. _this.fragmentTracker = fragmentTracker;
  6725. _this.config = hls.config;
  6726. _this.state = base_stream_controller_1.State.STOPPED;
  6727. _this.tracks = [];
  6728. _this.tracksBuffered = [];
  6729. _this.currentTrackId = -1;
  6730. _this.decrypter = new decrypter_1.default(hls, hls.config);
  6731. // lastAVStart stores the time in seconds for the start time of a level load
  6732. _this.lastAVStart = 0;
  6733. _this._onMediaSeeking = _this.onMediaSeeking.bind(_this);
  6734. return _this;
  6735. }
  6736. SubtitleStreamController.prototype.onSubtitleFragProcessed = function (data) {
  6737. var frag = data.frag, success = data.success;
  6738. this.fragPrevious = frag;
  6739. this.state = base_stream_controller_1.State.IDLE;
  6740. if (!success) {
  6741. return;
  6742. }
  6743. var buffered = this.tracksBuffered[this.currentTrackId];
  6744. if (!buffered) {
  6745. return;
  6746. }
  6747. // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo
  6748. // so we can re-use the logic used to detect how much have been buffered
  6749. var timeRange;
  6750. var fragStart = frag.start;
  6751. for (var i = 0; i < buffered.length; i++) {
  6752. if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {
  6753. timeRange = buffered[i];
  6754. break;
  6755. }
  6756. }
  6757. var fragEnd = frag.start + frag.duration;
  6758. if (timeRange) {
  6759. timeRange.end = fragEnd;
  6760. }
  6761. else {
  6762. timeRange = {
  6763. start: fragStart,
  6764. end: fragEnd
  6765. };
  6766. buffered.push(timeRange);
  6767. }
  6768. };
  6769. SubtitleStreamController.prototype.onMediaAttached = function (_a) {
  6770. var media = _a.media;
  6771. this.media = media;
  6772. media.addEventListener('seeking', this._onMediaSeeking);
  6773. this.state = base_stream_controller_1.State.IDLE;
  6774. };
  6775. SubtitleStreamController.prototype.onMediaDetaching = function () {
  6776. this.media.removeEventListener('seeking', this._onMediaSeeking);
  6777. this.media = null;
  6778. this.state = base_stream_controller_1.State.STOPPED;
  6779. };
  6780. // If something goes wrong, proceed to next frag, if we were processing one.
  6781. SubtitleStreamController.prototype.onError = function (data) {
  6782. var frag = data.frag;
  6783. // don't handle error not related to subtitle fragment
  6784. if (!frag || frag.type !== 'subtitle') {
  6785. return;
  6786. }
  6787. this.state = base_stream_controller_1.State.IDLE;
  6788. };
  6789. // Got all new subtitle tracks.
  6790. SubtitleStreamController.prototype.onSubtitleTracksUpdated = function (data) {
  6791. var _this = this;
  6792. logger_1.logger.log('subtitle tracks updated');
  6793. this.tracksBuffered = [];
  6794. this.tracks = data.subtitleTracks;
  6795. this.tracks.forEach(function (track) {
  6796. _this.tracksBuffered[track.id] = [];
  6797. });
  6798. };
  6799. SubtitleStreamController.prototype.onSubtitleTrackSwitch = function (data) {
  6800. this.currentTrackId = data.id;
  6801. if (!this.tracks || this.currentTrackId === -1) {
  6802. this.clearInterval();
  6803. return;
  6804. }
  6805. // Check if track has the necessary details to load fragments
  6806. var currentTrack = this.tracks[this.currentTrackId];
  6807. if (currentTrack && currentTrack.details) {
  6808. this.setInterval(TICK_INTERVAL);
  6809. }
  6810. };
  6811. // Got a new set of subtitle fragments.
  6812. SubtitleStreamController.prototype.onSubtitleTrackLoaded = function (data) {
  6813. var id = data.id, details = data.details;
  6814. var _a = this, currentTrackId = _a.currentTrackId, tracks = _a.tracks;
  6815. var currentTrack = tracks[currentTrackId];
  6816. if (id >= tracks.length || id !== currentTrackId || !currentTrack) {
  6817. return;
  6818. }
  6819. if (details.live) {
  6820. level_helper_1.mergeSubtitlePlaylists(currentTrack.details, details, this.lastAVStart);
  6821. }
  6822. currentTrack.details = details;
  6823. this.setInterval(TICK_INTERVAL);
  6824. };
  6825. SubtitleStreamController.prototype.onKeyLoaded = function () {
  6826. if (this.state === base_stream_controller_1.State.KEY_LOADING) {
  6827. this.state = base_stream_controller_1.State.IDLE;
  6828. }
  6829. };
  6830. SubtitleStreamController.prototype.onFragLoaded = function (data) {
  6831. var fragCurrent = this.fragCurrent;
  6832. var decryptData = data.frag.decryptdata;
  6833. var fragLoaded = data.frag;
  6834. var hls = this.hls;
  6835. if (this.state === base_stream_controller_1.State.FRAG_LOADING &&
  6836. fragCurrent &&
  6837. data.frag.type === 'subtitle' &&
  6838. fragCurrent.sn === data.frag.sn) {
  6839. // check to see if the payload needs to be decrypted
  6840. if (data.payload.byteLength > 0 && (decryptData && decryptData.key && decryptData.method === 'AES-128')) {
  6841. var startTime_1 = performance.now();
  6842. // decrypt the subtitles
  6843. this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {
  6844. var endTime = performance.now();
  6845. hls.trigger(events_1.default.FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime_1, tdecrypt: endTime } });
  6846. });
  6847. }
  6848. }
  6849. };
  6850. SubtitleStreamController.prototype.onLevelUpdated = function (_a) {
  6851. var details = _a.details;
  6852. var frags = details.fragments;
  6853. this.lastAVStart = frags.length ? frags[0].start : 0;
  6854. };
  6855. SubtitleStreamController.prototype.doTick = function () {
  6856. if (!this.media) {
  6857. this.state = base_stream_controller_1.State.IDLE;
  6858. return;
  6859. }
  6860. switch (this.state) {
  6861. case base_stream_controller_1.State.IDLE: {
  6862. var _a = this, config = _a.config, currentTrackId = _a.currentTrackId, fragmentTracker = _a.fragmentTracker, media = _a.media, tracks = _a.tracks;
  6863. if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {
  6864. break;
  6865. }
  6866. var maxBufferHole = config.maxBufferHole, maxFragLookUpTolerance = config.maxFragLookUpTolerance;
  6867. var maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);
  6868. var bufferedInfo = buffer_helper_1.BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);
  6869. var bufferEnd = bufferedInfo.end, bufferLen = bufferedInfo.len;
  6870. var trackDetails = tracks[currentTrackId].details;
  6871. var fragments = trackDetails.fragments;
  6872. var fragLen = fragments.length;
  6873. var end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;
  6874. if (bufferLen > maxConfigBuffer) {
  6875. return;
  6876. }
  6877. var foundFrag = void 0;
  6878. var fragPrevious = this.fragPrevious;
  6879. if (bufferEnd < end) {
  6880. if (fragPrevious && trackDetails.hasProgramDateTime) {
  6881. foundFrag = fragment_finders_1.findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);
  6882. }
  6883. if (!foundFrag) {
  6884. foundFrag = fragment_finders_1.findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);
  6885. }
  6886. }
  6887. else {
  6888. foundFrag = fragments[fragLen - 1];
  6889. }
  6890. if (foundFrag && foundFrag.encrypted) {
  6891. logger_1.logger.log("Loading key for " + foundFrag.sn);
  6892. this.state = base_stream_controller_1.State.KEY_LOADING;
  6893. this.hls.trigger(events_1.default.KEY_LOADING, { frag: foundFrag });
  6894. }
  6895. else if (foundFrag && fragmentTracker.getState(foundFrag) === fragment_tracker_1.FragmentState.NOT_LOADED) {
  6896. // only load if fragment is not loaded
  6897. this.fragCurrent = foundFrag;
  6898. this.state = base_stream_controller_1.State.FRAG_LOADING;
  6899. this.hls.trigger(events_1.default.FRAG_LOADING, { frag: foundFrag });
  6900. }
  6901. }
  6902. }
  6903. };
  6904. SubtitleStreamController.prototype.stopLoad = function () {
  6905. this.lastAVStart = 0;
  6906. _super.prototype.stopLoad.call(this);
  6907. };
  6908. SubtitleStreamController.prototype._getBuffered = function () {
  6909. return this.tracksBuffered[this.currentTrackId] || [];
  6910. };
  6911. SubtitleStreamController.prototype.onMediaSeeking = function () {
  6912. this.fragPrevious = null;
  6913. };
  6914. return SubtitleStreamController;
  6915. }(base_stream_controller_1.default));
  6916. exports.SubtitleStreamController = SubtitleStreamController;
  6917. /***/ }),
  6918. /***/ "./src/controller/subtitle-track-controller.js":
  6919. /*!*****************************************************!*\
  6920. !*** ./src/controller/subtitle-track-controller.js ***!
  6921. \*****************************************************/
  6922. /*! no static exports found */
  6923. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  6924. /***/ (function(module, exports, __webpack_require__) {
  6925. "use strict";
  6926. /* WEBPACK VAR INJECTION */(function(Number) {
  6927. var __extends = (this && this.__extends) || (function () {
  6928. var extendStatics = Object.setPrototypeOf ||
  6929. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  6930. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  6931. return function (d, b) {
  6932. extendStatics(d, b);
  6933. function __() { this.constructor = d; }
  6934. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  6935. };
  6936. })();
  6937. Object.defineProperty(exports, "__esModule", { value: true });
  6938. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  6939. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  6940. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  6941. var level_helper_1 = __webpack_require__(/*! ./level-helper */ "./src/controller/level-helper.js");
  6942. var SubtitleTrackController = /** @class */ (function (_super) {
  6943. __extends(SubtitleTrackController, _super);
  6944. function SubtitleTrackController(hls) {
  6945. var _this = _super.call(this, hls, events_1.default.MEDIA_ATTACHED, events_1.default.MEDIA_DETACHING, events_1.default.MANIFEST_LOADED, events_1.default.SUBTITLE_TRACK_LOADED) || this;
  6946. _this.tracks = [];
  6947. _this.trackId = -1;
  6948. _this.media = null;
  6949. _this.stopped = true;
  6950. /**
  6951. * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering
  6952. */
  6953. _this.subtitleDisplay = true;
  6954. return _this;
  6955. }
  6956. SubtitleTrackController.prototype.destroy = function () {
  6957. event_handler_1.default.prototype.destroy.call(this);
  6958. };
  6959. // Listen for subtitle track change, then extract the current track ID.
  6960. SubtitleTrackController.prototype.onMediaAttached = function (data) {
  6961. var _this = this;
  6962. this.media = data.media;
  6963. if (!this.media) {
  6964. return;
  6965. }
  6966. if (this.queuedDefaultTrack) {
  6967. this.subtitleTrack = this.queuedDefaultTrack;
  6968. delete this.queuedDefaultTrack;
  6969. }
  6970. this.trackChangeListener = this._onTextTracksChanged.bind(this);
  6971. this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);
  6972. if (this.useTextTrackPolling) {
  6973. this.subtitlePollingInterval = setInterval(function () {
  6974. _this.trackChangeListener();
  6975. }, 500);
  6976. }
  6977. else {
  6978. this.media.textTracks.addEventListener('change', this.trackChangeListener);
  6979. }
  6980. };
  6981. SubtitleTrackController.prototype.onMediaDetaching = function () {
  6982. if (!this.media) {
  6983. return;
  6984. }
  6985. if (this.useTextTrackPolling) {
  6986. clearInterval(this.subtitlePollingInterval);
  6987. }
  6988. else {
  6989. this.media.textTracks.removeEventListener('change', this.trackChangeListener);
  6990. }
  6991. this.media = null;
  6992. };
  6993. // Fired whenever a new manifest is loaded.
  6994. SubtitleTrackController.prototype.onManifestLoaded = function (data) {
  6995. var _this = this;
  6996. var tracks = data.subtitles || [];
  6997. this.tracks = tracks;
  6998. this.hls.trigger(events_1.default.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });
  6999. // loop through available subtitle tracks and autoselect default if needed
  7000. // TODO: improve selection logic to handle forced, etc
  7001. tracks.forEach(function (track) {
  7002. if (track.default) {
  7003. // setting this.subtitleTrack will trigger internal logic
  7004. // if media has not been attached yet, it will fail
  7005. // we keep a reference to the default track id
  7006. // and we'll set subtitleTrack when onMediaAttached is triggered
  7007. if (_this.media) {
  7008. _this.subtitleTrack = track.id;
  7009. }
  7010. else {
  7011. _this.queuedDefaultTrack = track.id;
  7012. }
  7013. }
  7014. });
  7015. };
  7016. SubtitleTrackController.prototype.onSubtitleTrackLoaded = function (data) {
  7017. var _this = this;
  7018. var id = data.id, details = data.details;
  7019. var _a = this, trackId = _a.trackId, tracks = _a.tracks;
  7020. var currentTrack = tracks[trackId];
  7021. if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {
  7022. this._clearReloadTimer();
  7023. return;
  7024. }
  7025. logger_1.logger.log("subtitle track " + id + " loaded");
  7026. if (details.live) {
  7027. var reloadInterval = level_helper_1.computeReloadInterval(currentTrack.details, details, data.stats.trequest);
  7028. logger_1.logger.log("Reloading live subtitle playlist in " + reloadInterval + "ms");
  7029. this.timer = setTimeout(function () {
  7030. _this._loadCurrentTrack();
  7031. }, reloadInterval);
  7032. }
  7033. else {
  7034. this._clearReloadTimer();
  7035. }
  7036. };
  7037. SubtitleTrackController.prototype.startLoad = function () {
  7038. this.stopped = false;
  7039. this._loadCurrentTrack();
  7040. };
  7041. SubtitleTrackController.prototype.stopLoad = function () {
  7042. this.stopped = true;
  7043. this._clearReloadTimer();
  7044. };
  7045. Object.defineProperty(SubtitleTrackController.prototype, "subtitleTracks", {
  7046. /** get alternate subtitle tracks list from playlist **/
  7047. get: function () {
  7048. return this.tracks;
  7049. },
  7050. enumerable: true,
  7051. configurable: true
  7052. });
  7053. Object.defineProperty(SubtitleTrackController.prototype, "subtitleTrack", {
  7054. /** get index of the selected subtitle track (index in subtitle track lists) **/
  7055. get: function () {
  7056. return this.trackId;
  7057. },
  7058. /** select a subtitle track, based on its index in subtitle track lists**/
  7059. set: function (subtitleTrackId) {
  7060. if (this.trackId !== subtitleTrackId) {
  7061. this._toggleTrackModes(subtitleTrackId);
  7062. this._setSubtitleTrackInternal(subtitleTrackId);
  7063. }
  7064. },
  7065. enumerable: true,
  7066. configurable: true
  7067. });
  7068. SubtitleTrackController.prototype._clearReloadTimer = function () {
  7069. if (this.timer) {
  7070. clearTimeout(this.timer);
  7071. this.timer = null;
  7072. }
  7073. };
  7074. SubtitleTrackController.prototype._loadCurrentTrack = function () {
  7075. var _a = this, trackId = _a.trackId, tracks = _a.tracks, hls = _a.hls;
  7076. var currentTrack = tracks[trackId];
  7077. if (trackId < 0 || !currentTrack || (currentTrack.details && !currentTrack.details.live)) {
  7078. return;
  7079. }
  7080. logger_1.logger.log("Loading subtitle track " + trackId);
  7081. hls.trigger(events_1.default.SUBTITLE_TRACK_LOADING, { url: currentTrack.url, id: trackId });
  7082. };
  7083. /**
  7084. * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.
  7085. * This operates on the DOM textTracks.
  7086. * A value of -1 will disable all subtitle tracks.
  7087. * @param newId - The id of the next track to enable
  7088. * @private
  7089. */
  7090. SubtitleTrackController.prototype._toggleTrackModes = function (newId) {
  7091. var _a = this, media = _a.media, subtitleDisplay = _a.subtitleDisplay, trackId = _a.trackId;
  7092. if (!media) {
  7093. return;
  7094. }
  7095. var textTracks = filterSubtitleTracks(media.textTracks);
  7096. if (newId === -1) {
  7097. [].slice.call(textTracks).forEach(function (track) {
  7098. track.mode = 'disabled';
  7099. });
  7100. }
  7101. else {
  7102. var oldTrack = textTracks[trackId];
  7103. if (oldTrack) {
  7104. oldTrack.mode = 'disabled';
  7105. }
  7106. }
  7107. var nextTrack = textTracks[newId];
  7108. if (nextTrack) {
  7109. nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';
  7110. }
  7111. };
  7112. /**
  7113. * This method is responsible for validating the subtitle index and periodically reloading if live.
  7114. * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.
  7115. * @param newId - The id of the subtitle track to activate.
  7116. */
  7117. SubtitleTrackController.prototype._setSubtitleTrackInternal = function (newId) {
  7118. var _a = this, hls = _a.hls, tracks = _a.tracks;
  7119. if (!Number.isFinite(newId) || newId < -1 || newId >= tracks.length) {
  7120. return;
  7121. }
  7122. this.trackId = newId;
  7123. logger_1.logger.log("Switching to subtitle track " + newId);
  7124. hls.trigger(events_1.default.SUBTITLE_TRACK_SWITCH, { id: newId });
  7125. this._loadCurrentTrack();
  7126. };
  7127. SubtitleTrackController.prototype._onTextTracksChanged = function () {
  7128. // Media is undefined when switching streams via loadSource()
  7129. if (!this.media) {
  7130. return;
  7131. }
  7132. var trackId = -1;
  7133. var tracks = filterSubtitleTracks(this.media.textTracks);
  7134. for (var id = 0; id < tracks.length; id++) {
  7135. if (tracks[id].mode === 'hidden') {
  7136. // Do not break in case there is a following track with showing.
  7137. trackId = id;
  7138. }
  7139. else if (tracks[id].mode === 'showing') {
  7140. trackId = id;
  7141. break;
  7142. }
  7143. }
  7144. // Setting current subtitleTrack will invoke code.
  7145. this.subtitleTrack = trackId;
  7146. };
  7147. return SubtitleTrackController;
  7148. }(event_handler_1.default));
  7149. function filterSubtitleTracks(textTrackList) {
  7150. var tracks = [];
  7151. for (var i = 0; i < textTrackList.length; i++) {
  7152. var track = textTrackList[i];
  7153. // Edge adds a track without a label; we don't want to use it
  7154. if (track.kind === 'subtitles' && track.label) {
  7155. tracks.push(textTrackList[i]);
  7156. }
  7157. }
  7158. return tracks;
  7159. }
  7160. exports.default = SubtitleTrackController;
  7161. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  7162. /***/ }),
  7163. /***/ "./src/controller/timeline-controller.js":
  7164. /*!***********************************************!*\
  7165. !*** ./src/controller/timeline-controller.js ***!
  7166. \***********************************************/
  7167. /*! no static exports found */
  7168. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  7169. /***/ (function(module, exports, __webpack_require__) {
  7170. "use strict";
  7171. /* WEBPACK VAR INJECTION */(function(Number) {
  7172. /*
  7173. * Timeline Controller
  7174. */
  7175. var __extends = (this && this.__extends) || (function () {
  7176. var extendStatics = Object.setPrototypeOf ||
  7177. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  7178. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  7179. return function (d, b) {
  7180. extendStatics(d, b);
  7181. function __() { this.constructor = d; }
  7182. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  7183. };
  7184. })();
  7185. Object.defineProperty(exports, "__esModule", { value: true });
  7186. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  7187. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  7188. var cea_608_parser_1 = __webpack_require__(/*! ../utils/cea-608-parser */ "./src/utils/cea-608-parser.js");
  7189. var output_filter_1 = __webpack_require__(/*! ../utils/output-filter */ "./src/utils/output-filter.js");
  7190. var webvtt_parser_1 = __webpack_require__(/*! ../utils/webvtt-parser */ "./src/utils/webvtt-parser.js");
  7191. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  7192. var texttrack_utils_1 = __webpack_require__(/*! ../utils/texttrack-utils */ "./src/utils/texttrack-utils.js");
  7193. function canReuseVttTextTrack(inUseTrack, manifestTrack) {
  7194. return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);
  7195. }
  7196. function intersection(x1, x2, y1, y2) {
  7197. return Math.min(x2, y2) - Math.max(x1, y1);
  7198. }
  7199. var TimelineController = /** @class */ (function (_super) {
  7200. __extends(TimelineController, _super);
  7201. function TimelineController(hls) {
  7202. var _this = _super.call(this, hls, events_1.default.MEDIA_ATTACHING, events_1.default.MEDIA_DETACHING, events_1.default.FRAG_PARSING_USERDATA, events_1.default.FRAG_DECRYPTED, events_1.default.MANIFEST_LOADING, events_1.default.MANIFEST_LOADED, events_1.default.FRAG_LOADED, events_1.default.LEVEL_SWITCHING, events_1.default.INIT_PTS_FOUND) || this;
  7203. _this.hls = hls;
  7204. _this.config = hls.config;
  7205. _this.enabled = true;
  7206. _this.Cues = hls.config.cueHandler;
  7207. _this.textTracks = [];
  7208. _this.tracks = [];
  7209. _this.unparsedVttFrags = [];
  7210. _this.initPTS = [];
  7211. _this.cueRanges = [];
  7212. _this.captionsTracks = {};
  7213. _this.captionsProperties = {
  7214. textTrack1: {
  7215. label: _this.config.captionsTextTrack1Label,
  7216. languageCode: _this.config.captionsTextTrack1LanguageCode
  7217. },
  7218. textTrack2: {
  7219. label: _this.config.captionsTextTrack2Label,
  7220. languageCode: _this.config.captionsTextTrack2LanguageCode
  7221. }
  7222. };
  7223. if (_this.config.enableCEA708Captions) {
  7224. var channel1 = new output_filter_1.default(_this, 'textTrack1');
  7225. var channel2 = new output_filter_1.default(_this, 'textTrack2');
  7226. _this.cea608Parser = new cea_608_parser_1.default(0, channel1, channel2);
  7227. }
  7228. return _this;
  7229. }
  7230. TimelineController.prototype.addCues = function (trackName, startTime, endTime, screen) {
  7231. // skip cues which overlap more than 50% with previously parsed time ranges
  7232. var ranges = this.cueRanges;
  7233. var merged = false;
  7234. for (var i = ranges.length; i--;) {
  7235. var cueRange = ranges[i];
  7236. var overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);
  7237. if (overlap >= 0) {
  7238. cueRange[0] = Math.min(cueRange[0], startTime);
  7239. cueRange[1] = Math.max(cueRange[1], endTime);
  7240. merged = true;
  7241. if ((overlap / (endTime - startTime)) > 0.5) {
  7242. return;
  7243. }
  7244. }
  7245. }
  7246. if (!merged) {
  7247. ranges.push([startTime, endTime]);
  7248. }
  7249. this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);
  7250. };
  7251. // Triggered when an initial PTS is found; used for synchronisation of WebVTT.
  7252. TimelineController.prototype.onInitPtsFound = function (data) {
  7253. var _this = this;
  7254. if (data.id === 'main') {
  7255. this.initPTS[data.frag.cc] = data.initPTS;
  7256. }
  7257. // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.
  7258. // Parse any unparsed fragments upon receiving the initial PTS.
  7259. if (this.unparsedVttFrags.length) {
  7260. var unparsedVttFrags = this.unparsedVttFrags;
  7261. this.unparsedVttFrags = [];
  7262. unparsedVttFrags.forEach(function (frag) {
  7263. _this.onFragLoaded(frag);
  7264. });
  7265. }
  7266. };
  7267. TimelineController.prototype.getExistingTrack = function (trackName) {
  7268. var media = this.media;
  7269. if (media) {
  7270. for (var i = 0; i < media.textTracks.length; i++) {
  7271. var textTrack = media.textTracks[i];
  7272. if (textTrack[trackName]) {
  7273. return textTrack;
  7274. }
  7275. }
  7276. }
  7277. return null;
  7278. };
  7279. TimelineController.prototype.createCaptionsTrack = function (trackName) {
  7280. var _a = this.captionsProperties[trackName], label = _a.label, languageCode = _a.languageCode;
  7281. var captionsTracks = this.captionsTracks;
  7282. if (!captionsTracks[trackName]) {
  7283. // Enable reuse of existing text track.
  7284. var existingTrack = this.getExistingTrack(trackName);
  7285. if (!existingTrack) {
  7286. var textTrack = this.createTextTrack('captions', label, languageCode);
  7287. if (textTrack) {
  7288. // Set a special property on the track so we know it's managed by Hls.js
  7289. textTrack[trackName] = true;
  7290. captionsTracks[trackName] = textTrack;
  7291. }
  7292. }
  7293. else {
  7294. captionsTracks[trackName] = existingTrack;
  7295. texttrack_utils_1.clearCurrentCues(captionsTracks[trackName]);
  7296. texttrack_utils_1.sendAddTrackEvent(captionsTracks[trackName], this.media);
  7297. }
  7298. }
  7299. };
  7300. TimelineController.prototype.createTextTrack = function (kind, label, lang) {
  7301. var media = this.media;
  7302. if (media) {
  7303. return media.addTextTrack(kind, label, lang);
  7304. }
  7305. };
  7306. TimelineController.prototype.destroy = function () {
  7307. event_handler_1.default.prototype.destroy.call(this);
  7308. };
  7309. TimelineController.prototype.onMediaAttaching = function (data) {
  7310. this.media = data.media;
  7311. this._cleanTracks();
  7312. };
  7313. TimelineController.prototype.onMediaDetaching = function () {
  7314. var captionsTracks = this.captionsTracks;
  7315. Object.keys(captionsTracks).forEach(function (trackName) {
  7316. texttrack_utils_1.clearCurrentCues(captionsTracks[trackName]);
  7317. delete captionsTracks[trackName];
  7318. });
  7319. };
  7320. TimelineController.prototype.onManifestLoading = function () {
  7321. this.lastSn = -1; // Detect discontiguity in fragment parsing
  7322. this.prevCC = -1;
  7323. this.vttCCs = {
  7324. ccOffset: 0,
  7325. presentationOffset: 0,
  7326. 0: {
  7327. start: 0, prevCC: -1, new: false
  7328. }
  7329. };
  7330. this._cleanTracks();
  7331. };
  7332. TimelineController.prototype._cleanTracks = function () {
  7333. // clear outdated subtitles
  7334. var media = this.media;
  7335. if (media) {
  7336. var textTracks = media.textTracks;
  7337. if (textTracks) {
  7338. for (var i = 0; i < textTracks.length; i++) {
  7339. texttrack_utils_1.clearCurrentCues(textTracks[i]);
  7340. }
  7341. }
  7342. }
  7343. };
  7344. TimelineController.prototype.onManifestLoaded = function (data) {
  7345. var _this = this;
  7346. this.textTracks = [];
  7347. this.unparsedVttFrags = this.unparsedVttFrags || [];
  7348. this.initPTS = [];
  7349. this.cueRanges = [];
  7350. if (this.config.enableWebVTT) {
  7351. this.tracks = data.subtitles || [];
  7352. var inUseTracks_1 = this.media ? this.media.textTracks : [];
  7353. this.tracks.forEach(function (track, index) {
  7354. var textTrack;
  7355. if (index < inUseTracks_1.length) {
  7356. var inUseTrack = null;
  7357. for (var i = 0; i < inUseTracks_1.length; i++) {
  7358. if (canReuseVttTextTrack(inUseTracks_1[i], track)) {
  7359. inUseTrack = inUseTracks_1[i];
  7360. break;
  7361. }
  7362. }
  7363. // Reuse tracks with the same label, but do not reuse 608/708 tracks
  7364. if (inUseTrack) {
  7365. textTrack = inUseTrack;
  7366. }
  7367. }
  7368. if (!textTrack) {
  7369. textTrack = _this.createTextTrack('subtitles', track.name, track.lang);
  7370. }
  7371. if (track.default) {
  7372. textTrack.mode = _this.hls.subtitleDisplay ? 'showing' : 'hidden';
  7373. }
  7374. else {
  7375. textTrack.mode = 'disabled';
  7376. }
  7377. _this.textTracks.push(textTrack);
  7378. });
  7379. }
  7380. };
  7381. TimelineController.prototype.onLevelSwitching = function () {
  7382. this.enabled = this.hls.currentLevel.closedCaptions !== 'NONE';
  7383. };
  7384. TimelineController.prototype.onFragLoaded = function (data) {
  7385. var frag = data.frag, payload = data.payload;
  7386. if (frag.type === 'main') {
  7387. var sn = frag.sn;
  7388. // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack
  7389. if (sn !== this.lastSn + 1) {
  7390. var cea608Parser = this.cea608Parser;
  7391. if (cea608Parser) {
  7392. cea608Parser.reset();
  7393. }
  7394. }
  7395. this.lastSn = sn;
  7396. } // eslint-disable-line brace-style
  7397. // If fragment is subtitle type, parse as WebVTT.
  7398. else if (frag.type === 'subtitle') {
  7399. if (payload.byteLength) {
  7400. // We need an initial synchronisation PTS. Store fragments as long as none has arrived.
  7401. if (!Number.isFinite(this.initPTS[frag.cc])) {
  7402. this.unparsedVttFrags.push(data);
  7403. if (this.initPTS.length) {
  7404. // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.
  7405. this.hls.trigger(events_1.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  7406. }
  7407. return;
  7408. }
  7409. var decryptData = frag.decryptdata;
  7410. // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.
  7411. if ((decryptData == null) || (decryptData.key == null) || (decryptData.method !== 'AES-128')) {
  7412. this._parseVTTs(frag, payload);
  7413. }
  7414. }
  7415. else {
  7416. // In case there is no payload, finish unsuccessfully.
  7417. this.hls.trigger(events_1.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  7418. }
  7419. }
  7420. };
  7421. TimelineController.prototype._parseVTTs = function (frag, payload) {
  7422. var vttCCs = this.vttCCs;
  7423. if (!vttCCs[frag.cc]) {
  7424. vttCCs[frag.cc] = { start: frag.start, prevCC: this.prevCC, new: true };
  7425. this.prevCC = frag.cc;
  7426. }
  7427. var textTracks = this.textTracks, hls = this.hls;
  7428. // Parse the WebVTT file contents.
  7429. webvtt_parser_1.default.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, function (cues) {
  7430. var currentTrack = textTracks[frag.level];
  7431. // WebVTTParser.parse is an async method and if the currently selected text track mode is set to "disabled"
  7432. // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null
  7433. // and trying to access getCueById method of cues will throw an exception
  7434. if (currentTrack.mode === 'disabled') {
  7435. hls.trigger(events_1.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  7436. return;
  7437. }
  7438. // Add cues and trigger event with success true.
  7439. cues.forEach(function (cue) {
  7440. // Sometimes there are cue overlaps on segmented vtts so the same
  7441. // cue can appear more than once in different vtt files.
  7442. // This avoid showing duplicated cues with same timecode and text.
  7443. if (!currentTrack.cues.getCueById(cue.id)) {
  7444. try {
  7445. currentTrack.addCue(cue);
  7446. }
  7447. catch (err) {
  7448. var textTrackCue = new window.TextTrackCue(cue.startTime, cue.endTime, cue.text);
  7449. textTrackCue.id = cue.id;
  7450. currentTrack.addCue(textTrackCue);
  7451. }
  7452. }
  7453. });
  7454. hls.trigger(events_1.default.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });
  7455. }, function (e) {
  7456. // Something went wrong while parsing. Trigger event with success false.
  7457. logger_1.logger.log("Failed to parse VTT cue: " + e);
  7458. hls.trigger(events_1.default.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });
  7459. });
  7460. };
  7461. TimelineController.prototype.onFragDecrypted = function (data) {
  7462. var decryptedData = data.payload, frag = data.frag;
  7463. if (frag.type === 'subtitle') {
  7464. if (!Number.isFinite(this.initPTS[frag.cc])) {
  7465. this.unparsedVttFrags.push(data);
  7466. return;
  7467. }
  7468. this._parseVTTs(frag, decryptedData);
  7469. }
  7470. };
  7471. TimelineController.prototype.onFragParsingUserdata = function (data) {
  7472. // push all of the CEA-708 messages into the interpreter
  7473. // immediately. It will create the proper timestamps based on our PTS value
  7474. if (this.enabled && this.config.enableCEA708Captions) {
  7475. for (var i = 0; i < data.samples.length; i++) {
  7476. var ccdatas = this.extractCea608Data(data.samples[i].bytes);
  7477. this.cea608Parser.addData(data.samples[i].pts, ccdatas);
  7478. }
  7479. }
  7480. };
  7481. TimelineController.prototype.extractCea608Data = function (byteArray) {
  7482. var count = byteArray[0] & 31;
  7483. var position = 2;
  7484. var tmpByte, ccbyte1, ccbyte2, ccValid, ccType;
  7485. var actualCCBytes = [];
  7486. for (var j = 0; j < count; j++) {
  7487. tmpByte = byteArray[position++];
  7488. ccbyte1 = 0x7F & byteArray[position++];
  7489. ccbyte2 = 0x7F & byteArray[position++];
  7490. ccValid = (4 & tmpByte) !== 0;
  7491. ccType = 3 & tmpByte;
  7492. if (ccbyte1 === 0 && ccbyte2 === 0) {
  7493. continue;
  7494. }
  7495. if (ccValid) {
  7496. if (ccType === 0) { // || ccType === 1
  7497. actualCCBytes.push(ccbyte1);
  7498. actualCCBytes.push(ccbyte2);
  7499. }
  7500. }
  7501. }
  7502. return actualCCBytes;
  7503. };
  7504. return TimelineController;
  7505. }(event_handler_1.default));
  7506. exports.default = TimelineController;
  7507. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  7508. /***/ }),
  7509. /***/ "./src/crypt/aes-crypto.js":
  7510. /*!*********************************!*\
  7511. !*** ./src/crypt/aes-crypto.js ***!
  7512. \*********************************/
  7513. /*! no static exports found */
  7514. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  7515. /***/ (function(module, exports, __webpack_require__) {
  7516. "use strict";
  7517. Object.defineProperty(exports, "__esModule", { value: true });
  7518. var AESCrypto = /** @class */ (function () {
  7519. function AESCrypto(subtle, iv) {
  7520. this.subtle = subtle;
  7521. this.aesIV = iv;
  7522. }
  7523. AESCrypto.prototype.decrypt = function (data, key) {
  7524. return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);
  7525. };
  7526. return AESCrypto;
  7527. }());
  7528. exports.default = AESCrypto;
  7529. /***/ }),
  7530. /***/ "./src/crypt/aes-decryptor.js":
  7531. /*!************************************!*\
  7532. !*** ./src/crypt/aes-decryptor.js ***!
  7533. \************************************/
  7534. /*! no static exports found */
  7535. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  7536. /***/ (function(module, exports, __webpack_require__) {
  7537. "use strict";
  7538. Object.defineProperty(exports, "__esModule", { value: true });
  7539. // PKCS7
  7540. function removePadding(buffer) {
  7541. var outputBytes = buffer.byteLength;
  7542. var paddingBytes = outputBytes && (new DataView(buffer)).getUint8(outputBytes - 1);
  7543. if (paddingBytes) {
  7544. return buffer.slice(0, outputBytes - paddingBytes);
  7545. }
  7546. else {
  7547. return buffer;
  7548. }
  7549. }
  7550. exports.removePadding = removePadding;
  7551. var AESDecryptor = /** @class */ (function () {
  7552. function AESDecryptor() {
  7553. // Static after running initTable
  7554. this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
  7555. this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  7556. this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];
  7557. this.sBox = new Uint32Array(256);
  7558. this.invSBox = new Uint32Array(256);
  7559. // Changes during runtime
  7560. this.key = new Uint32Array(0);
  7561. this.initTable();
  7562. }
  7563. // Using view.getUint32() also swaps the byte order.
  7564. AESDecryptor.prototype.uint8ArrayToUint32Array_ = function (arrayBuffer) {
  7565. var view = new DataView(arrayBuffer);
  7566. var newArray = new Uint32Array(4);
  7567. for (var i = 0; i < 4; i++) {
  7568. newArray[i] = view.getUint32(i * 4);
  7569. }
  7570. return newArray;
  7571. };
  7572. AESDecryptor.prototype.initTable = function () {
  7573. var sBox = this.sBox;
  7574. var invSBox = this.invSBox;
  7575. var subMix = this.subMix;
  7576. var subMix0 = subMix[0];
  7577. var subMix1 = subMix[1];
  7578. var subMix2 = subMix[2];
  7579. var subMix3 = subMix[3];
  7580. var invSubMix = this.invSubMix;
  7581. var invSubMix0 = invSubMix[0];
  7582. var invSubMix1 = invSubMix[1];
  7583. var invSubMix2 = invSubMix[2];
  7584. var invSubMix3 = invSubMix[3];
  7585. var d = new Uint32Array(256);
  7586. var x = 0;
  7587. var xi = 0;
  7588. var i = 0;
  7589. for (i = 0; i < 256; i++) {
  7590. if (i < 128) {
  7591. d[i] = i << 1;
  7592. }
  7593. else {
  7594. d[i] = (i << 1) ^ 0x11b;
  7595. }
  7596. }
  7597. for (i = 0; i < 256; i++) {
  7598. var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
  7599. sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
  7600. sBox[x] = sx;
  7601. invSBox[sx] = x;
  7602. // Compute multiplication
  7603. var x2 = d[x];
  7604. var x4 = d[x2];
  7605. var x8 = d[x4];
  7606. // Compute sub/invSub bytes, mix columns tables
  7607. var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
  7608. subMix0[x] = (t << 24) | (t >>> 8);
  7609. subMix1[x] = (t << 16) | (t >>> 16);
  7610. subMix2[x] = (t << 8) | (t >>> 24);
  7611. subMix3[x] = t;
  7612. // Compute inv sub bytes, inv mix columns tables
  7613. t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
  7614. invSubMix0[sx] = (t << 24) | (t >>> 8);
  7615. invSubMix1[sx] = (t << 16) | (t >>> 16);
  7616. invSubMix2[sx] = (t << 8) | (t >>> 24);
  7617. invSubMix3[sx] = t;
  7618. // Compute next counter
  7619. if (!x) {
  7620. x = xi = 1;
  7621. }
  7622. else {
  7623. x = x2 ^ d[d[d[x8 ^ x2]]];
  7624. xi ^= d[d[xi]];
  7625. }
  7626. }
  7627. };
  7628. AESDecryptor.prototype.expandKey = function (keyBuffer) {
  7629. // convert keyBuffer to Uint32Array
  7630. var key = this.uint8ArrayToUint32Array_(keyBuffer);
  7631. var sameKey = true;
  7632. var offset = 0;
  7633. while (offset < key.length && sameKey) {
  7634. sameKey = (key[offset] === this.key[offset]);
  7635. offset++;
  7636. }
  7637. if (sameKey) {
  7638. return;
  7639. }
  7640. this.key = key;
  7641. var keySize = this.keySize = key.length;
  7642. if (keySize !== 4 && keySize !== 6 && keySize !== 8) {
  7643. throw new Error('Invalid aes key size=' + keySize);
  7644. }
  7645. var ksRows = this.ksRows = (keySize + 6 + 1) * 4;
  7646. var ksRow;
  7647. var invKsRow;
  7648. var keySchedule = this.keySchedule = new Uint32Array(ksRows);
  7649. var invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);
  7650. var sbox = this.sBox;
  7651. var rcon = this.rcon;
  7652. var invSubMix = this.invSubMix;
  7653. var invSubMix0 = invSubMix[0];
  7654. var invSubMix1 = invSubMix[1];
  7655. var invSubMix2 = invSubMix[2];
  7656. var invSubMix3 = invSubMix[3];
  7657. var prev;
  7658. var t;
  7659. for (ksRow = 0; ksRow < ksRows; ksRow++) {
  7660. if (ksRow < keySize) {
  7661. prev = keySchedule[ksRow] = key[ksRow];
  7662. continue;
  7663. }
  7664. t = prev;
  7665. if (ksRow % keySize === 0) {
  7666. // Rot word
  7667. t = (t << 8) | (t >>> 24);
  7668. // Sub word
  7669. t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];
  7670. // Mix Rcon
  7671. t ^= rcon[(ksRow / keySize) | 0] << 24;
  7672. }
  7673. else if (keySize > 6 && ksRow % keySize === 4) {
  7674. // Sub word
  7675. t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];
  7676. }
  7677. keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;
  7678. }
  7679. for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {
  7680. ksRow = ksRows - invKsRow;
  7681. if (invKsRow & 3) {
  7682. t = keySchedule[ksRow];
  7683. }
  7684. else {
  7685. t = keySchedule[ksRow - 4];
  7686. }
  7687. if (invKsRow < 4 || ksRow <= 4) {
  7688. invKeySchedule[invKsRow] = t;
  7689. }
  7690. else {
  7691. invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[(t >>> 16) & 0xff]] ^ invSubMix2[sbox[(t >>> 8) & 0xff]] ^ invSubMix3[sbox[t & 0xff]];
  7692. }
  7693. invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;
  7694. }
  7695. };
  7696. // Adding this as a method greatly improves performance.
  7697. AESDecryptor.prototype.networkToHostOrderSwap = function (word) {
  7698. return (word << 24) | ((word & 0xff00) << 8) | ((word & 0xff0000) >> 8) | (word >>> 24);
  7699. };
  7700. AESDecryptor.prototype.decrypt = function (inputArrayBuffer, offset, aesIV, removePKCS7Padding) {
  7701. var nRounds = this.keySize + 6;
  7702. var invKeySchedule = this.invKeySchedule;
  7703. var invSBOX = this.invSBox;
  7704. var invSubMix = this.invSubMix;
  7705. var invSubMix0 = invSubMix[0];
  7706. var invSubMix1 = invSubMix[1];
  7707. var invSubMix2 = invSubMix[2];
  7708. var invSubMix3 = invSubMix[3];
  7709. var initVector = this.uint8ArrayToUint32Array_(aesIV);
  7710. var initVector0 = initVector[0];
  7711. var initVector1 = initVector[1];
  7712. var initVector2 = initVector[2];
  7713. var initVector3 = initVector[3];
  7714. var inputInt32 = new Int32Array(inputArrayBuffer);
  7715. var outputInt32 = new Int32Array(inputInt32.length);
  7716. var t0, t1, t2, t3;
  7717. var s0, s1, s2, s3;
  7718. var inputWords0, inputWords1, inputWords2, inputWords3;
  7719. var ksRow, i;
  7720. var swapWord = this.networkToHostOrderSwap;
  7721. while (offset < inputInt32.length) {
  7722. inputWords0 = swapWord(inputInt32[offset]);
  7723. inputWords1 = swapWord(inputInt32[offset + 1]);
  7724. inputWords2 = swapWord(inputInt32[offset + 2]);
  7725. inputWords3 = swapWord(inputInt32[offset + 3]);
  7726. s0 = inputWords0 ^ invKeySchedule[0];
  7727. s1 = inputWords3 ^ invKeySchedule[1];
  7728. s2 = inputWords2 ^ invKeySchedule[2];
  7729. s3 = inputWords1 ^ invKeySchedule[3];
  7730. ksRow = 4;
  7731. // Iterate through the rounds of decryption
  7732. for (i = 1; i < nRounds; i++) {
  7733. t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[(s1 >> 16) & 0xff] ^ invSubMix2[(s2 >> 8) & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];
  7734. t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[(s2 >> 16) & 0xff] ^ invSubMix2[(s3 >> 8) & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];
  7735. t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[(s3 >> 16) & 0xff] ^ invSubMix2[(s0 >> 8) & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];
  7736. t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[(s0 >> 16) & 0xff] ^ invSubMix2[(s1 >> 8) & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];
  7737. // Update state
  7738. s0 = t0;
  7739. s1 = t1;
  7740. s2 = t2;
  7741. s3 = t3;
  7742. ksRow = ksRow + 4;
  7743. }
  7744. // Shift rows, sub bytes, add round key
  7745. t0 = ((invSBOX[s0 >>> 24] << 24) ^ (invSBOX[(s1 >> 16) & 0xff] << 16) ^ (invSBOX[(s2 >> 8) & 0xff] << 8) ^ invSBOX[s3 & 0xff]) ^ invKeySchedule[ksRow];
  7746. t1 = ((invSBOX[s1 >>> 24] << 24) ^ (invSBOX[(s2 >> 16) & 0xff] << 16) ^ (invSBOX[(s3 >> 8) & 0xff] << 8) ^ invSBOX[s0 & 0xff]) ^ invKeySchedule[ksRow + 1];
  7747. t2 = ((invSBOX[s2 >>> 24] << 24) ^ (invSBOX[(s3 >> 16) & 0xff] << 16) ^ (invSBOX[(s0 >> 8) & 0xff] << 8) ^ invSBOX[s1 & 0xff]) ^ invKeySchedule[ksRow + 2];
  7748. t3 = ((invSBOX[s3 >>> 24] << 24) ^ (invSBOX[(s0 >> 16) & 0xff] << 16) ^ (invSBOX[(s1 >> 8) & 0xff] << 8) ^ invSBOX[s2 & 0xff]) ^ invKeySchedule[ksRow + 3];
  7749. ksRow = ksRow + 3;
  7750. // Write
  7751. outputInt32[offset] = swapWord(t0 ^ initVector0);
  7752. outputInt32[offset + 1] = swapWord(t3 ^ initVector1);
  7753. outputInt32[offset + 2] = swapWord(t2 ^ initVector2);
  7754. outputInt32[offset + 3] = swapWord(t1 ^ initVector3);
  7755. // reset initVector to last 4 unsigned int
  7756. initVector0 = inputWords0;
  7757. initVector1 = inputWords1;
  7758. initVector2 = inputWords2;
  7759. initVector3 = inputWords3;
  7760. offset = offset + 4;
  7761. }
  7762. return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;
  7763. };
  7764. AESDecryptor.prototype.destroy = function () {
  7765. this.key = undefined;
  7766. this.keySize = undefined;
  7767. this.ksRows = undefined;
  7768. this.sBox = undefined;
  7769. this.invSBox = undefined;
  7770. this.subMix = undefined;
  7771. this.invSubMix = undefined;
  7772. this.keySchedule = undefined;
  7773. this.invKeySchedule = undefined;
  7774. this.rcon = undefined;
  7775. };
  7776. return AESDecryptor;
  7777. }());
  7778. exports.default = AESDecryptor;
  7779. /***/ }),
  7780. /***/ "./src/crypt/decrypter.js":
  7781. /*!********************************!*\
  7782. !*** ./src/crypt/decrypter.js ***!
  7783. \********************************/
  7784. /*! no static exports found */
  7785. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  7786. /***/ (function(module, exports, __webpack_require__) {
  7787. "use strict";
  7788. Object.defineProperty(exports, "__esModule", { value: true });
  7789. var aes_crypto_1 = __webpack_require__(/*! ./aes-crypto */ "./src/crypt/aes-crypto.js");
  7790. var fast_aes_key_1 = __webpack_require__(/*! ./fast-aes-key */ "./src/crypt/fast-aes-key.js");
  7791. var aes_decryptor_1 = __webpack_require__(/*! ./aes-decryptor */ "./src/crypt/aes-decryptor.js");
  7792. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  7793. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  7794. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  7795. var get_self_scope_1 = __webpack_require__(/*! ../utils/get-self-scope */ "./src/utils/get-self-scope.js");
  7796. // see https://stackoverflow.com/a/11237259/589493
  7797. var global = get_self_scope_1.getSelfScope(); // safeguard for code that might run both on worker and main thread
  7798. var Decrypter = /** @class */ (function () {
  7799. function Decrypter(observer, config, _a) {
  7800. var _b = (_a === void 0 ? {} : _a).removePKCS7Padding, removePKCS7Padding = _b === void 0 ? true : _b;
  7801. this.logEnabled = true;
  7802. this.observer = observer;
  7803. this.config = config;
  7804. this.removePKCS7Padding = removePKCS7Padding;
  7805. // built in decryptor expects PKCS7 padding
  7806. if (removePKCS7Padding) {
  7807. try {
  7808. var browserCrypto = global.crypto;
  7809. if (browserCrypto) {
  7810. this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;
  7811. }
  7812. }
  7813. catch (e) { }
  7814. }
  7815. this.disableWebCrypto = !this.subtle;
  7816. }
  7817. Decrypter.prototype.isSync = function () {
  7818. return (this.disableWebCrypto && this.config.enableSoftwareAES);
  7819. };
  7820. Decrypter.prototype.decrypt = function (data, key, iv, callback) {
  7821. var _this = this;
  7822. if (this.disableWebCrypto && this.config.enableSoftwareAES) {
  7823. if (this.logEnabled) {
  7824. logger_1.logger.log('JS AES decrypt');
  7825. this.logEnabled = false;
  7826. }
  7827. var decryptor = this.decryptor;
  7828. if (!decryptor) {
  7829. this.decryptor = decryptor = new aes_decryptor_1.default();
  7830. }
  7831. decryptor.expandKey(key);
  7832. callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));
  7833. }
  7834. else {
  7835. if (this.logEnabled) {
  7836. logger_1.logger.log('WebCrypto AES decrypt');
  7837. this.logEnabled = false;
  7838. }
  7839. var subtle_1 = this.subtle;
  7840. if (this.key !== key) {
  7841. this.key = key;
  7842. this.fastAesKey = new fast_aes_key_1.default(subtle_1, key);
  7843. }
  7844. this.fastAesKey.expandKey()
  7845. .then(function (aesKey) {
  7846. // decrypt using web crypto
  7847. var crypto = new aes_crypto_1.default(subtle_1, iv);
  7848. crypto.decrypt(data, aesKey)
  7849. .catch(function (err) {
  7850. _this.onWebCryptoError(err, data, key, iv, callback);
  7851. })
  7852. .then(function (result) {
  7853. callback(result);
  7854. });
  7855. })
  7856. .catch(function (err) {
  7857. _this.onWebCryptoError(err, data, key, iv, callback);
  7858. });
  7859. }
  7860. };
  7861. Decrypter.prototype.onWebCryptoError = function (err, data, key, iv, callback) {
  7862. if (this.config.enableSoftwareAES) {
  7863. logger_1.logger.log('WebCrypto Error, disable WebCrypto API');
  7864. this.disableWebCrypto = true;
  7865. this.logEnabled = true;
  7866. this.decrypt(data, key, iv, callback);
  7867. }
  7868. else {
  7869. logger_1.logger.error("decrypting error : " + err.message);
  7870. this.observer.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });
  7871. }
  7872. };
  7873. Decrypter.prototype.destroy = function () {
  7874. var decryptor = this.decryptor;
  7875. if (decryptor) {
  7876. decryptor.destroy();
  7877. this.decryptor = undefined;
  7878. }
  7879. };
  7880. return Decrypter;
  7881. }());
  7882. exports.default = Decrypter;
  7883. /***/ }),
  7884. /***/ "./src/crypt/fast-aes-key.js":
  7885. /*!***********************************!*\
  7886. !*** ./src/crypt/fast-aes-key.js ***!
  7887. \***********************************/
  7888. /*! no static exports found */
  7889. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  7890. /***/ (function(module, exports, __webpack_require__) {
  7891. "use strict";
  7892. Object.defineProperty(exports, "__esModule", { value: true });
  7893. var FastAESKey = /** @class */ (function () {
  7894. function FastAESKey(subtle, key) {
  7895. this.subtle = subtle;
  7896. this.key = key;
  7897. }
  7898. FastAESKey.prototype.expandKey = function () {
  7899. return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);
  7900. };
  7901. return FastAESKey;
  7902. }());
  7903. exports.default = FastAESKey;
  7904. /***/ }),
  7905. /***/ "./src/demux/aacdemuxer.js":
  7906. /*!*********************************!*\
  7907. !*** ./src/demux/aacdemuxer.js ***!
  7908. \*********************************/
  7909. /*! no static exports found */
  7910. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  7911. /***/ (function(module, exports, __webpack_require__) {
  7912. "use strict";
  7913. /* WEBPACK VAR INJECTION */(function(Number) {
  7914. Object.defineProperty(exports, "__esModule", { value: true });
  7915. /**
  7916. * AAC demuxer
  7917. */
  7918. var ADTS = __webpack_require__(/*! ./adts */ "./src/demux/adts.js");
  7919. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  7920. var id3_1 = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.js");
  7921. var AACDemuxer = /** @class */ (function () {
  7922. function AACDemuxer(observer, remuxer, config) {
  7923. this.observer = observer;
  7924. this.config = config;
  7925. this.remuxer = remuxer;
  7926. }
  7927. AACDemuxer.prototype.resetInitSegment = function (initSegment, audioCodec, videoCodec, duration) {
  7928. this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  7929. };
  7930. AACDemuxer.prototype.resetTimeStamp = function () {
  7931. };
  7932. AACDemuxer.probe = function (data) {
  7933. if (!data) {
  7934. return false;
  7935. }
  7936. // Check for the ADTS sync word
  7937. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  7938. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  7939. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  7940. var id3Data = id3_1.default.getID3Data(data, 0) || [];
  7941. var offset = id3Data.length;
  7942. for (var length_1 = data.length; offset < length_1; offset++) {
  7943. if (ADTS.probe(data, offset)) {
  7944. logger_1.logger.log('ADTS sync word found !');
  7945. return true;
  7946. }
  7947. }
  7948. return false;
  7949. };
  7950. // feed incoming data to the front of the parsing pipeline
  7951. AACDemuxer.prototype.append = function (data, timeOffset, contiguous, accurateTimeOffset) {
  7952. var track = this._audioTrack;
  7953. var id3Data = id3_1.default.getID3Data(data, 0) || [];
  7954. var timestamp = id3_1.default.getTimeStamp(id3Data);
  7955. var pts = Number.isFinite(timestamp) ? timestamp * 90 : timeOffset * 90000;
  7956. var frameIndex = 0;
  7957. var stamp = pts;
  7958. var length = data.length;
  7959. var offset = id3Data.length;
  7960. var id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];
  7961. while (offset < length - 1) {
  7962. if (ADTS.isHeader(data, offset) && (offset + 5) < length) {
  7963. ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);
  7964. var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
  7965. if (frame) {
  7966. offset += frame.length;
  7967. stamp = frame.sample.pts;
  7968. frameIndex++;
  7969. }
  7970. else {
  7971. logger_1.logger.log('Unable to parse AAC frame');
  7972. break;
  7973. }
  7974. }
  7975. else if (id3_1.default.isHeader(data, offset)) {
  7976. id3Data = id3_1.default.getID3Data(data, offset);
  7977. id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
  7978. offset += id3Data.length;
  7979. }
  7980. else {
  7981. // nothing found, keep looking
  7982. offset++;
  7983. }
  7984. }
  7985. this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  7986. };
  7987. AACDemuxer.prototype.destroy = function () {
  7988. };
  7989. return AACDemuxer;
  7990. }());
  7991. exports.default = AACDemuxer;
  7992. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  7993. /***/ }),
  7994. /***/ "./src/demux/adts.js":
  7995. /*!***************************!*\
  7996. !*** ./src/demux/adts.js ***!
  7997. \***************************/
  7998. /*! no static exports found */
  7999. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  8000. /***/ (function(module, exports, __webpack_require__) {
  8001. "use strict";
  8002. Object.defineProperty(exports, "__esModule", { value: true });
  8003. /**
  8004. * ADTS parser helper
  8005. */
  8006. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  8007. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  8008. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  8009. function getAudioConfig(observer, data, offset, audioCodec) {
  8010. var adtsObjectType, // :int
  8011. adtsSampleingIndex, // :int
  8012. adtsExtensionSampleingIndex, // :int
  8013. adtsChanelConfig, // :int
  8014. config, userAgent = navigator.userAgent.toLowerCase(), manifestCodec = audioCodec, adtsSampleingRates = [
  8015. 96000, 88200,
  8016. 64000, 48000,
  8017. 44100, 32000,
  8018. 24000, 22050,
  8019. 16000, 12000,
  8020. 11025, 8000,
  8021. 7350
  8022. ];
  8023. // byte 2
  8024. adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;
  8025. adtsSampleingIndex = ((data[offset + 2] & 0x3C) >>> 2);
  8026. if (adtsSampleingIndex > adtsSampleingRates.length - 1) {
  8027. observer.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: "invalid ADTS sampling index:" + adtsSampleingIndex });
  8028. return;
  8029. }
  8030. adtsChanelConfig = ((data[offset + 2] & 0x01) << 2);
  8031. // byte 3
  8032. adtsChanelConfig |= ((data[offset + 3] & 0xC0) >>> 6);
  8033. logger_1.logger.log("manifest codec:" + audioCodec + ",ADTS data:type:" + adtsObjectType + ",sampleingIndex:" + adtsSampleingIndex + "[" + adtsSampleingRates[adtsSampleingIndex] + "Hz],channelConfig:" + adtsChanelConfig);
  8034. // firefox: freq less than 24kHz = AAC SBR (HE-AAC)
  8035. if (/firefox/i.test(userAgent)) {
  8036. if (adtsSampleingIndex >= 6) {
  8037. adtsObjectType = 5;
  8038. config = new Array(4);
  8039. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  8040. // there is a factor 2 between frame sample rate and output sample rate
  8041. // multiply frequency by 2 (see table below, equivalent to substract 3)
  8042. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  8043. }
  8044. else {
  8045. adtsObjectType = 2;
  8046. config = new Array(2);
  8047. adtsExtensionSampleingIndex = adtsSampleingIndex;
  8048. }
  8049. // Android : always use AAC
  8050. }
  8051. else if (userAgent.indexOf('android') !== -1) {
  8052. adtsObjectType = 2;
  8053. config = new Array(2);
  8054. adtsExtensionSampleingIndex = adtsSampleingIndex;
  8055. }
  8056. else {
  8057. /* for other browsers (Chrome/Vivaldi/Opera ...)
  8058. always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)
  8059. */
  8060. adtsObjectType = 5;
  8061. config = new Array(4);
  8062. // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)
  8063. if ((audioCodec && ((audioCodec.indexOf('mp4a.40.29') !== -1) ||
  8064. (audioCodec.indexOf('mp4a.40.5') !== -1))) ||
  8065. (!audioCodec && adtsSampleingIndex >= 6)) {
  8066. // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies
  8067. // there is a factor 2 between frame sample rate and output sample rate
  8068. // multiply frequency by 2 (see table below, equivalent to substract 3)
  8069. adtsExtensionSampleingIndex = adtsSampleingIndex - 3;
  8070. }
  8071. else {
  8072. // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)
  8073. // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.
  8074. if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && ((adtsSampleingIndex >= 6 && adtsChanelConfig === 1) ||
  8075. /vivaldi/i.test(userAgent)) ||
  8076. (!audioCodec && adtsChanelConfig === 1)) {
  8077. adtsObjectType = 2;
  8078. config = new Array(2);
  8079. }
  8080. adtsExtensionSampleingIndex = adtsSampleingIndex;
  8081. }
  8082. }
  8083. /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config
  8084. ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()
  8085. Audio Profile / Audio Object Type
  8086. 0: Null
  8087. 1: AAC Main
  8088. 2: AAC LC (Low Complexity)
  8089. 3: AAC SSR (Scalable Sample Rate)
  8090. 4: AAC LTP (Long Term Prediction)
  8091. 5: SBR (Spectral Band Replication)
  8092. 6: AAC Scalable
  8093. sampling freq
  8094. 0: 96000 Hz
  8095. 1: 88200 Hz
  8096. 2: 64000 Hz
  8097. 3: 48000 Hz
  8098. 4: 44100 Hz
  8099. 5: 32000 Hz
  8100. 6: 24000 Hz
  8101. 7: 22050 Hz
  8102. 8: 16000 Hz
  8103. 9: 12000 Hz
  8104. 10: 11025 Hz
  8105. 11: 8000 Hz
  8106. 12: 7350 Hz
  8107. 13: Reserved
  8108. 14: Reserved
  8109. 15: frequency is written explictly
  8110. Channel Configurations
  8111. These are the channel configurations:
  8112. 0: Defined in AOT Specifc Config
  8113. 1: 1 channel: front-center
  8114. 2: 2 channels: front-left, front-right
  8115. */
  8116. // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1
  8117. config[0] = adtsObjectType << 3;
  8118. // samplingFrequencyIndex
  8119. config[0] |= (adtsSampleingIndex & 0x0E) >> 1;
  8120. config[1] |= (adtsSampleingIndex & 0x01) << 7;
  8121. // channelConfiguration
  8122. config[1] |= adtsChanelConfig << 3;
  8123. if (adtsObjectType === 5) {
  8124. // adtsExtensionSampleingIndex
  8125. config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;
  8126. config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;
  8127. // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???
  8128. // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc
  8129. config[2] |= 2 << 2;
  8130. config[3] = 0;
  8131. }
  8132. return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: ('mp4a.40.' + adtsObjectType), manifestCodec: manifestCodec };
  8133. }
  8134. exports.getAudioConfig = getAudioConfig;
  8135. function isHeaderPattern(data, offset) {
  8136. return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;
  8137. }
  8138. exports.isHeaderPattern = isHeaderPattern;
  8139. function getHeaderLength(data, offset) {
  8140. return (data[offset + 1] & 0x01 ? 7 : 9);
  8141. }
  8142. exports.getHeaderLength = getHeaderLength;
  8143. function getFullFrameLength(data, offset) {
  8144. return ((data[offset + 3] & 0x03) << 11) |
  8145. (data[offset + 4] << 3) |
  8146. ((data[offset + 5] & 0xE0) >>> 5);
  8147. }
  8148. exports.getFullFrameLength = getFullFrameLength;
  8149. function isHeader(data, offset) {
  8150. // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1
  8151. // Layer bits (position 14 and 15) in header should be always 0 for ADTS
  8152. // More info https://wiki.multimedia.cx/index.php?title=ADTS
  8153. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  8154. return true;
  8155. }
  8156. return false;
  8157. }
  8158. exports.isHeader = isHeader;
  8159. function probe(data, offset) {
  8160. // same as isHeader but we also check that ADTS frame follows last ADTS frame
  8161. // or end of data is reached
  8162. if (offset + 1 < data.length && isHeaderPattern(data, offset)) {
  8163. // ADTS header Length
  8164. var headerLength = getHeaderLength(data, offset);
  8165. // ADTS frame Length
  8166. var frameLength = headerLength;
  8167. if (offset + 5 < data.length) {
  8168. frameLength = getFullFrameLength(data, offset);
  8169. }
  8170. var newOffset = offset + frameLength;
  8171. if (newOffset === data.length || (newOffset + 1 < data.length && isHeaderPattern(data, newOffset))) {
  8172. return true;
  8173. }
  8174. }
  8175. return false;
  8176. }
  8177. exports.probe = probe;
  8178. function initTrackConfig(track, observer, data, offset, audioCodec) {
  8179. if (!track.samplerate) {
  8180. var config = getAudioConfig(observer, data, offset, audioCodec);
  8181. track.config = config.config;
  8182. track.samplerate = config.samplerate;
  8183. track.channelCount = config.channelCount;
  8184. track.codec = config.codec;
  8185. track.manifestCodec = config.manifestCodec;
  8186. logger_1.logger.log("parsed codec:" + track.codec + ",rate:" + config.samplerate + ",nb channel:" + config.channelCount);
  8187. }
  8188. }
  8189. exports.initTrackConfig = initTrackConfig;
  8190. function getFrameDuration(samplerate) {
  8191. return 1024 * 90000 / samplerate;
  8192. }
  8193. exports.getFrameDuration = getFrameDuration;
  8194. function parseFrameHeader(data, offset, pts, frameIndex, frameDuration) {
  8195. var headerLength, frameLength, stamp;
  8196. var length = data.length;
  8197. // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header
  8198. headerLength = getHeaderLength(data, offset);
  8199. // retrieve frame size
  8200. frameLength = getFullFrameLength(data, offset);
  8201. frameLength -= headerLength;
  8202. if ((frameLength > 0) && ((offset + headerLength + frameLength) <= length)) {
  8203. stamp = pts + frameIndex * frameDuration;
  8204. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  8205. return { headerLength: headerLength, frameLength: frameLength, stamp: stamp };
  8206. }
  8207. return undefined;
  8208. }
  8209. exports.parseFrameHeader = parseFrameHeader;
  8210. function appendFrame(track, data, offset, pts, frameIndex) {
  8211. var frameDuration = getFrameDuration(track.samplerate);
  8212. var header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);
  8213. if (header) {
  8214. var stamp = header.stamp;
  8215. var headerLength = header.headerLength;
  8216. var frameLength = header.frameLength;
  8217. // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);
  8218. var aacSample = {
  8219. unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),
  8220. pts: stamp,
  8221. dts: stamp
  8222. };
  8223. track.samples.push(aacSample);
  8224. track.len += frameLength;
  8225. return { sample: aacSample, length: frameLength + headerLength };
  8226. }
  8227. return undefined;
  8228. }
  8229. exports.appendFrame = appendFrame;
  8230. /***/ }),
  8231. /***/ "./src/demux/demuxer-inline.js":
  8232. /*!*************************************!*\
  8233. !*** ./src/demux/demuxer-inline.js ***!
  8234. \*************************************/
  8235. /*! no static exports found */
  8236. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  8237. /***/ (function(module, exports, __webpack_require__) {
  8238. "use strict";
  8239. /**
  8240. *
  8241. * inline demuxer: probe fragments and instantiate
  8242. * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)
  8243. *
  8244. */
  8245. Object.defineProperty(exports, "__esModule", { value: true });
  8246. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  8247. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  8248. var decrypter_1 = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.js");
  8249. var aacdemuxer_1 = __webpack_require__(/*! ../demux/aacdemuxer */ "./src/demux/aacdemuxer.js");
  8250. var mp4demuxer_1 = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.js");
  8251. var tsdemuxer_1 = __webpack_require__(/*! ../demux/tsdemuxer */ "./src/demux/tsdemuxer.js");
  8252. var mp3demuxer_1 = __webpack_require__(/*! ../demux/mp3demuxer */ "./src/demux/mp3demuxer.js");
  8253. var mp4_remuxer_1 = __webpack_require__(/*! ../remux/mp4-remuxer */ "./src/remux/mp4-remuxer.js");
  8254. var passthrough_remuxer_1 = __webpack_require__(/*! ../remux/passthrough-remuxer */ "./src/remux/passthrough-remuxer.js");
  8255. var get_self_scope_1 = __webpack_require__(/*! ../utils/get-self-scope */ "./src/utils/get-self-scope.js");
  8256. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  8257. // see https://stackoverflow.com/a/11237259/589493
  8258. var global = get_self_scope_1.getSelfScope(); // safeguard for code that might run both on worker and main thread
  8259. var now;
  8260. // performance.now() not available on WebWorker, at least on Safari Desktop
  8261. try {
  8262. now = global.performance.now.bind(global.performance);
  8263. }
  8264. catch (err) {
  8265. logger_1.logger.debug('Unable to use Performance API on this environment');
  8266. now = global.Date.now;
  8267. }
  8268. var DemuxerInline = /** @class */ (function () {
  8269. function DemuxerInline(observer, typeSupported, config, vendor) {
  8270. this.observer = observer;
  8271. this.typeSupported = typeSupported;
  8272. this.config = config;
  8273. this.vendor = vendor;
  8274. }
  8275. DemuxerInline.prototype.destroy = function () {
  8276. var demuxer = this.demuxer;
  8277. if (demuxer) {
  8278. demuxer.destroy();
  8279. }
  8280. };
  8281. DemuxerInline.prototype.push = function (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  8282. var _this = this;
  8283. if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {
  8284. var decrypter = this.decrypter;
  8285. if (decrypter == null) {
  8286. decrypter = this.decrypter = new decrypter_1.default(this.observer, this.config);
  8287. }
  8288. var startTime_1 = now();
  8289. decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, function (decryptedData) {
  8290. var endTime = now();
  8291. _this.observer.trigger(events_1.default.FRAG_DECRYPTED, { stats: { tstart: startTime_1, tdecrypt: endTime } });
  8292. _this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  8293. });
  8294. }
  8295. else {
  8296. this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  8297. }
  8298. };
  8299. DemuxerInline.prototype.pushDecrypted = function (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {
  8300. var demuxer = this.demuxer;
  8301. if (!demuxer ||
  8302. // in case of continuity change, or track switch
  8303. // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)
  8304. // so let's check that current demuxer is still valid
  8305. ((discontinuity || trackSwitch) && !this.probe(data))) {
  8306. var observer = this.observer;
  8307. var typeSupported = this.typeSupported;
  8308. var config = this.config;
  8309. // probing order is TS/AAC/MP3/MP4
  8310. var muxConfig = [
  8311. { demux: tsdemuxer_1.default, remux: mp4_remuxer_1.default },
  8312. { demux: mp4demuxer_1.default, remux: passthrough_remuxer_1.default },
  8313. { demux: aacdemuxer_1.default, remux: mp4_remuxer_1.default },
  8314. { demux: mp3demuxer_1.default, remux: mp4_remuxer_1.default }
  8315. ];
  8316. // probe for content type
  8317. for (var i = 0, len = muxConfig.length; i < len; i++) {
  8318. var mux = muxConfig[i];
  8319. var probe = mux.demux.probe;
  8320. if (probe(data)) {
  8321. var remuxer_1 = this.remuxer = new mux.remux(observer, config, typeSupported, this.vendor);
  8322. demuxer = new mux.demux(observer, remuxer_1, config, typeSupported);
  8323. this.probe = probe;
  8324. break;
  8325. }
  8326. }
  8327. if (!demuxer) {
  8328. observer.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });
  8329. return;
  8330. }
  8331. this.demuxer = demuxer;
  8332. }
  8333. var remuxer = this.remuxer;
  8334. if (discontinuity || trackSwitch) {
  8335. demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);
  8336. remuxer.resetInitSegment();
  8337. }
  8338. if (discontinuity) {
  8339. demuxer.resetTimeStamp(defaultInitPTS);
  8340. remuxer.resetTimeStamp(defaultInitPTS);
  8341. }
  8342. if (typeof demuxer.setDecryptData === 'function') {
  8343. demuxer.setDecryptData(decryptdata);
  8344. }
  8345. demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);
  8346. };
  8347. return DemuxerInline;
  8348. }());
  8349. exports.default = DemuxerInline;
  8350. /***/ }),
  8351. /***/ "./src/demux/demuxer-worker.js":
  8352. /*!*************************************!*\
  8353. !*** ./src/demux/demuxer-worker.js ***!
  8354. \*************************************/
  8355. /*! no static exports found */
  8356. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  8357. /***/ (function(module, exports, __webpack_require__) {
  8358. "use strict";
  8359. /* demuxer web worker.
  8360. * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.
  8361. * - provides MP4 Boxes back to main thread using [transferable objects](https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast) in order to minimize message passing overhead.
  8362. */
  8363. Object.defineProperty(exports, "__esModule", { value: true });
  8364. var demuxer_inline_1 = __webpack_require__(/*! ../demux/demuxer-inline */ "./src/demux/demuxer-inline.js");
  8365. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  8366. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  8367. var events_2 = __webpack_require__(/*! events */ "./node_modules/node-libs-browser/node_modules/events/events.js");
  8368. var DemuxerWorker = function (self) {
  8369. // observer setup
  8370. var observer = new events_2.EventEmitter();
  8371. observer.trigger = function trigger(event) {
  8372. var data = [];
  8373. for (var _i = 1; _i < arguments.length; _i++) {
  8374. data[_i - 1] = arguments[_i];
  8375. }
  8376. observer.emit.apply(observer, [event, event].concat(data));
  8377. };
  8378. observer.off = function off(event) {
  8379. var data = [];
  8380. for (var _i = 1; _i < arguments.length; _i++) {
  8381. data[_i - 1] = arguments[_i];
  8382. }
  8383. observer.removeListener.apply(observer, [event].concat(data));
  8384. };
  8385. var forwardMessage = function (ev, data) {
  8386. self.postMessage({ event: ev, data: data });
  8387. };
  8388. self.addEventListener('message', function (ev) {
  8389. var data = ev.data;
  8390. // console.log('demuxer cmd:' + data.cmd);
  8391. switch (data.cmd) {
  8392. case 'init':
  8393. var config = JSON.parse(data.config);
  8394. self.demuxer = new demuxer_inline_1.default(observer, data.typeSupported, config, data.vendor);
  8395. logger_1.enableLogs(config.debug);
  8396. // signal end of worker init
  8397. forwardMessage('init', null);
  8398. break;
  8399. case 'demux':
  8400. self.demuxer.push(data.data, data.decryptdata, data.initSegment, data.audioCodec, data.videoCodec, data.timeOffset, data.discontinuity, data.trackSwitch, data.contiguous, data.duration, data.accurateTimeOffset, data.defaultInitPTS);
  8401. break;
  8402. default:
  8403. break;
  8404. }
  8405. });
  8406. // forward events to main thread
  8407. observer.on(events_1.default.FRAG_DECRYPTED, forwardMessage);
  8408. observer.on(events_1.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  8409. observer.on(events_1.default.FRAG_PARSED, forwardMessage);
  8410. observer.on(events_1.default.ERROR, forwardMessage);
  8411. observer.on(events_1.default.FRAG_PARSING_METADATA, forwardMessage);
  8412. observer.on(events_1.default.FRAG_PARSING_USERDATA, forwardMessage);
  8413. observer.on(events_1.default.INIT_PTS_FOUND, forwardMessage);
  8414. // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)
  8415. observer.on(events_1.default.FRAG_PARSING_DATA, function (ev, data) {
  8416. var transferable = [];
  8417. var message = { event: ev, data: data };
  8418. if (data.data1) {
  8419. message.data1 = data.data1.buffer;
  8420. transferable.push(data.data1.buffer);
  8421. delete data.data1;
  8422. }
  8423. if (data.data2) {
  8424. message.data2 = data.data2.buffer;
  8425. transferable.push(data.data2.buffer);
  8426. delete data.data2;
  8427. }
  8428. self.postMessage(message, transferable);
  8429. });
  8430. };
  8431. exports.default = DemuxerWorker;
  8432. /***/ }),
  8433. /***/ "./src/demux/demuxer.js":
  8434. /*!******************************!*\
  8435. !*** ./src/demux/demuxer.js ***!
  8436. \******************************/
  8437. /*! no static exports found */
  8438. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  8439. /***/ (function(module, exports, __webpack_require__) {
  8440. "use strict";
  8441. /* WEBPACK VAR INJECTION */(function(Number) {
  8442. Object.defineProperty(exports, "__esModule", { value: true });
  8443. var work = __webpack_require__(/*! webworkify-webpack */ "./node_modules/webworkify-webpack/index.js");
  8444. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  8445. var demuxer_inline_1 = __webpack_require__(/*! ../demux/demuxer-inline */ "./src/demux/demuxer-inline.js");
  8446. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  8447. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  8448. var mediasource_helper_1 = __webpack_require__(/*! ../utils/mediasource-helper */ "./src/utils/mediasource-helper.js");
  8449. var get_self_scope_1 = __webpack_require__(/*! ../utils/get-self-scope */ "./src/utils/get-self-scope.js");
  8450. var observer_1 = __webpack_require__(/*! ../observer */ "./src/observer.js");
  8451. // see https://stackoverflow.com/a/11237259/589493
  8452. var global = get_self_scope_1.getSelfScope(); // safeguard for code that might run both on worker and main thread
  8453. var MediaSource = mediasource_helper_1.getMediaSource();
  8454. var Demuxer = /** @class */ (function () {
  8455. function Demuxer(hls, id) {
  8456. var _this = this;
  8457. this.hls = hls;
  8458. this.id = id;
  8459. var observer = this.observer = new observer_1.Observer();
  8460. var config = hls.config;
  8461. var forwardMessage = function (ev, data) {
  8462. data = data || {};
  8463. data.frag = _this.frag;
  8464. data.id = _this.id;
  8465. hls.trigger(ev, data);
  8466. };
  8467. // forward events to main thread
  8468. observer.on(events_1.default.FRAG_DECRYPTED, forwardMessage);
  8469. observer.on(events_1.default.FRAG_PARSING_INIT_SEGMENT, forwardMessage);
  8470. observer.on(events_1.default.FRAG_PARSING_DATA, forwardMessage);
  8471. observer.on(events_1.default.FRAG_PARSED, forwardMessage);
  8472. observer.on(events_1.default.ERROR, forwardMessage);
  8473. observer.on(events_1.default.FRAG_PARSING_METADATA, forwardMessage);
  8474. observer.on(events_1.default.FRAG_PARSING_USERDATA, forwardMessage);
  8475. observer.on(events_1.default.INIT_PTS_FOUND, forwardMessage);
  8476. var typeSupported = {
  8477. mp4: MediaSource.isTypeSupported('video/mp4'),
  8478. mpeg: MediaSource.isTypeSupported('audio/mpeg'),
  8479. mp3: MediaSource.isTypeSupported('audio/mp4; codecs="mp3"')
  8480. };
  8481. // navigator.vendor is not always available in Web Worker
  8482. // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator
  8483. var vendor = navigator.vendor;
  8484. if (config.enableWorker && (typeof (Worker) !== 'undefined')) {
  8485. logger_1.logger.log('demuxing in webworker');
  8486. var w = void 0;
  8487. try {
  8488. w = this.w = work(/*require.resolve*/(/*! ../demux/demuxer-worker.js */ "./src/demux/demuxer-worker.js"));
  8489. this.onwmsg = this.onWorkerMessage.bind(this);
  8490. w.addEventListener('message', this.onwmsg);
  8491. w.onerror = function (event) {
  8492. hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.OTHER_ERROR, details: errors_1.ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });
  8493. };
  8494. w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });
  8495. }
  8496. catch (err) {
  8497. logger_1.logger.warn('Error in worker:', err);
  8498. logger_1.logger.error('Error while initializing DemuxerWorker, fallback on DemuxerInline');
  8499. if (w) {
  8500. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  8501. global.URL.revokeObjectURL(w.objectURL);
  8502. }
  8503. this.demuxer = new demuxer_inline_1.default(observer, typeSupported, config, vendor);
  8504. this.w = undefined;
  8505. }
  8506. }
  8507. else {
  8508. this.demuxer = new demuxer_inline_1.default(observer, typeSupported, config, vendor);
  8509. }
  8510. }
  8511. Demuxer.prototype.destroy = function () {
  8512. var w = this.w;
  8513. if (w) {
  8514. w.removeEventListener('message', this.onwmsg);
  8515. w.terminate();
  8516. this.w = null;
  8517. }
  8518. else {
  8519. var demuxer = this.demuxer;
  8520. if (demuxer) {
  8521. demuxer.destroy();
  8522. this.demuxer = null;
  8523. }
  8524. }
  8525. var observer = this.observer;
  8526. if (observer) {
  8527. observer.removeAllListeners();
  8528. this.observer = null;
  8529. }
  8530. };
  8531. Demuxer.prototype.push = function (data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {
  8532. var w = this.w;
  8533. var timeOffset = Number.isFinite(frag.startPTS) ? frag.startPTS : frag.start;
  8534. var decryptdata = frag.decryptdata;
  8535. var lastFrag = this.frag;
  8536. var discontinuity = !(lastFrag && (frag.cc === lastFrag.cc));
  8537. var trackSwitch = !(lastFrag && (frag.level === lastFrag.level));
  8538. var nextSN = lastFrag && (frag.sn === (lastFrag.sn + 1));
  8539. var contiguous = !trackSwitch && nextSN;
  8540. if (discontinuity) {
  8541. logger_1.logger.log(this.id + ":discontinuity detected");
  8542. }
  8543. if (trackSwitch) {
  8544. logger_1.logger.log(this.id + ":switch detected");
  8545. }
  8546. this.frag = frag;
  8547. if (w) {
  8548. // post fragment payload as transferable objects for ArrayBuffer (no copy)
  8549. w.postMessage({ cmd: 'demux', data: data, decryptdata: decryptdata, initSegment: initSegment, audioCodec: audioCodec, videoCodec: videoCodec, timeOffset: timeOffset, discontinuity: discontinuity, trackSwitch: trackSwitch, contiguous: contiguous, duration: duration, accurateTimeOffset: accurateTimeOffset, defaultInitPTS: defaultInitPTS }, data instanceof ArrayBuffer ? [data] : []);
  8550. }
  8551. else {
  8552. var demuxer = this.demuxer;
  8553. if (demuxer) {
  8554. demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);
  8555. }
  8556. }
  8557. };
  8558. Demuxer.prototype.onWorkerMessage = function (ev) {
  8559. var data = ev.data, hls = this.hls;
  8560. switch (data.event) {
  8561. case 'init':
  8562. // revoke the Object URL that was used to create demuxer worker, so as not to leak it
  8563. global.URL.revokeObjectURL(this.w.objectURL);
  8564. break;
  8565. // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects
  8566. case events_1.default.FRAG_PARSING_DATA:
  8567. data.data.data1 = new Uint8Array(data.data1);
  8568. if (data.data2) {
  8569. data.data.data2 = new Uint8Array(data.data2);
  8570. }
  8571. /* falls through */
  8572. default:
  8573. data.data = data.data || {};
  8574. data.data.frag = this.frag;
  8575. data.data.id = this.id;
  8576. hls.trigger(data.event, data.data);
  8577. break;
  8578. }
  8579. };
  8580. return Demuxer;
  8581. }());
  8582. exports.default = Demuxer;
  8583. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  8584. /***/ }),
  8585. /***/ "./src/demux/exp-golomb.js":
  8586. /*!*********************************!*\
  8587. !*** ./src/demux/exp-golomb.js ***!
  8588. \*********************************/
  8589. /*! no static exports found */
  8590. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  8591. /***/ (function(module, exports, __webpack_require__) {
  8592. "use strict";
  8593. /**
  8594. * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.
  8595. */
  8596. Object.defineProperty(exports, "__esModule", { value: true });
  8597. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  8598. var ExpGolomb = /** @class */ (function () {
  8599. function ExpGolomb(data) {
  8600. this.data = data;
  8601. // the number of bytes left to examine in this.data
  8602. this.bytesAvailable = data.byteLength;
  8603. // the current word being examined
  8604. this.word = 0; // :uint
  8605. // the number of bits left to examine in the current word
  8606. this.bitsAvailable = 0; // :uint
  8607. }
  8608. // ():void
  8609. ExpGolomb.prototype.loadWord = function () {
  8610. var data = this.data, bytesAvailable = this.bytesAvailable, position = data.byteLength - bytesAvailable, workingBytes = new Uint8Array(4), availableBytes = Math.min(4, bytesAvailable);
  8611. if (availableBytes === 0) {
  8612. throw new Error('no bytes available');
  8613. }
  8614. workingBytes.set(data.subarray(position, position + availableBytes));
  8615. this.word = new DataView(workingBytes.buffer).getUint32(0);
  8616. // track the amount of this.data that has been processed
  8617. this.bitsAvailable = availableBytes * 8;
  8618. this.bytesAvailable -= availableBytes;
  8619. };
  8620. // (count:int):void
  8621. ExpGolomb.prototype.skipBits = function (count) {
  8622. var skipBytes; // :int
  8623. if (this.bitsAvailable > count) {
  8624. this.word <<= count;
  8625. this.bitsAvailable -= count;
  8626. }
  8627. else {
  8628. count -= this.bitsAvailable;
  8629. skipBytes = count >> 3;
  8630. count -= (skipBytes >> 3);
  8631. this.bytesAvailable -= skipBytes;
  8632. this.loadWord();
  8633. this.word <<= count;
  8634. this.bitsAvailable -= count;
  8635. }
  8636. };
  8637. // (size:int):uint
  8638. ExpGolomb.prototype.readBits = function (size) {
  8639. var bits = Math.min(this.bitsAvailable, size), // :uint
  8640. valu = this.word >>> (32 - bits); // :uint
  8641. if (size > 32) {
  8642. logger_1.logger.error('Cannot read more than 32 bits at a time');
  8643. }
  8644. this.bitsAvailable -= bits;
  8645. if (this.bitsAvailable > 0) {
  8646. this.word <<= bits;
  8647. }
  8648. else if (this.bytesAvailable > 0) {
  8649. this.loadWord();
  8650. }
  8651. bits = size - bits;
  8652. if (bits > 0 && this.bitsAvailable) {
  8653. return valu << bits | this.readBits(bits);
  8654. }
  8655. else {
  8656. return valu;
  8657. }
  8658. };
  8659. // ():uint
  8660. ExpGolomb.prototype.skipLZ = function () {
  8661. var leadingZeroCount; // :uint
  8662. for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {
  8663. if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {
  8664. // the first bit of working word is 1
  8665. this.word <<= leadingZeroCount;
  8666. this.bitsAvailable -= leadingZeroCount;
  8667. return leadingZeroCount;
  8668. }
  8669. }
  8670. // we exhausted word and still have not found a 1
  8671. this.loadWord();
  8672. return leadingZeroCount + this.skipLZ();
  8673. };
  8674. // ():void
  8675. ExpGolomb.prototype.skipUEG = function () {
  8676. this.skipBits(1 + this.skipLZ());
  8677. };
  8678. // ():void
  8679. ExpGolomb.prototype.skipEG = function () {
  8680. this.skipBits(1 + this.skipLZ());
  8681. };
  8682. // ():uint
  8683. ExpGolomb.prototype.readUEG = function () {
  8684. var clz = this.skipLZ(); // :uint
  8685. return this.readBits(clz + 1) - 1;
  8686. };
  8687. // ():int
  8688. ExpGolomb.prototype.readEG = function () {
  8689. var valu = this.readUEG(); // :int
  8690. if (0x01 & valu) {
  8691. // the number is odd if the low order bit is set
  8692. return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
  8693. }
  8694. else {
  8695. return -1 * (valu >>> 1); // divide by two then make it negative
  8696. }
  8697. };
  8698. // Some convenience functions
  8699. // :Boolean
  8700. ExpGolomb.prototype.readBoolean = function () {
  8701. return this.readBits(1) === 1;
  8702. };
  8703. // ():int
  8704. ExpGolomb.prototype.readUByte = function () {
  8705. return this.readBits(8);
  8706. };
  8707. // ():int
  8708. ExpGolomb.prototype.readUShort = function () {
  8709. return this.readBits(16);
  8710. };
  8711. // ():int
  8712. ExpGolomb.prototype.readUInt = function () {
  8713. return this.readBits(32);
  8714. };
  8715. /**
  8716. * Advance the ExpGolomb decoder past a scaling list. The scaling
  8717. * list is optionally transmitted as part of a sequence parameter
  8718. * set and is not relevant to transmuxing.
  8719. * @param count {number} the number of entries in this scaling list
  8720. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  8721. */
  8722. ExpGolomb.prototype.skipScalingList = function (count) {
  8723. var lastScale = 8, nextScale = 8, j, deltaScale;
  8724. for (j = 0; j < count; j++) {
  8725. if (nextScale !== 0) {
  8726. deltaScale = this.readEG();
  8727. nextScale = (lastScale + deltaScale + 256) % 256;
  8728. }
  8729. lastScale = (nextScale === 0) ? lastScale : nextScale;
  8730. }
  8731. };
  8732. /**
  8733. * Read a sequence parameter set and return some interesting video
  8734. * properties. A sequence parameter set is the H264 metadata that
  8735. * describes the properties of upcoming video frames.
  8736. * @param data {Uint8Array} the bytes of a sequence parameter set
  8737. * @return {object} an object with configuration parsed from the
  8738. * sequence parameter set, including the dimensions of the
  8739. * associated video frames.
  8740. */
  8741. ExpGolomb.prototype.readSPS = function () {
  8742. var frameCropLeftOffset = 0, frameCropRightOffset = 0, frameCropTopOffset = 0, frameCropBottomOffset = 0, profileIdc, profileCompat, levelIdc, numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1, picHeightInMapUnitsMinus1, frameMbsOnlyFlag, scalingListCount, i, readUByte = this.readUByte.bind(this), readBits = this.readBits.bind(this), readUEG = this.readUEG.bind(this), readBoolean = this.readBoolean.bind(this), skipBits = this.skipBits.bind(this), skipEG = this.skipEG.bind(this), skipUEG = this.skipUEG.bind(this), skipScalingList = this.skipScalingList.bind(this);
  8743. readUByte();
  8744. profileIdc = readUByte(); // profile_idc
  8745. profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)
  8746. skipBits(3); // reserved_zero_3bits u(3),
  8747. levelIdc = readUByte(); // level_idc u(8)
  8748. skipUEG(); // seq_parameter_set_id
  8749. // some profiles have more optional data we don't need
  8750. if (profileIdc === 100 ||
  8751. profileIdc === 110 ||
  8752. profileIdc === 122 ||
  8753. profileIdc === 244 ||
  8754. profileIdc === 44 ||
  8755. profileIdc === 83 ||
  8756. profileIdc === 86 ||
  8757. profileIdc === 118 ||
  8758. profileIdc === 128) {
  8759. var chromaFormatIdc = readUEG();
  8760. if (chromaFormatIdc === 3) {
  8761. skipBits(1);
  8762. } // separate_colour_plane_flag
  8763. skipUEG(); // bit_depth_luma_minus8
  8764. skipUEG(); // bit_depth_chroma_minus8
  8765. skipBits(1); // qpprime_y_zero_transform_bypass_flag
  8766. if (readBoolean()) { // seq_scaling_matrix_present_flag
  8767. scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;
  8768. for (i = 0; i < scalingListCount; i++) {
  8769. if (readBoolean()) { // seq_scaling_list_present_flag[ i ]
  8770. if (i < 6) {
  8771. skipScalingList(16);
  8772. }
  8773. else {
  8774. skipScalingList(64);
  8775. }
  8776. }
  8777. }
  8778. }
  8779. }
  8780. skipUEG(); // log2_max_frame_num_minus4
  8781. var picOrderCntType = readUEG();
  8782. if (picOrderCntType === 0) {
  8783. readUEG(); // log2_max_pic_order_cnt_lsb_minus4
  8784. }
  8785. else if (picOrderCntType === 1) {
  8786. skipBits(1); // delta_pic_order_always_zero_flag
  8787. skipEG(); // offset_for_non_ref_pic
  8788. skipEG(); // offset_for_top_to_bottom_field
  8789. numRefFramesInPicOrderCntCycle = readUEG();
  8790. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  8791. skipEG();
  8792. } // offset_for_ref_frame[ i ]
  8793. }
  8794. skipUEG(); // max_num_ref_frames
  8795. skipBits(1); // gaps_in_frame_num_value_allowed_flag
  8796. picWidthInMbsMinus1 = readUEG();
  8797. picHeightInMapUnitsMinus1 = readUEG();
  8798. frameMbsOnlyFlag = readBits(1);
  8799. if (frameMbsOnlyFlag === 0) {
  8800. skipBits(1);
  8801. } // mb_adaptive_frame_field_flag
  8802. skipBits(1); // direct_8x8_inference_flag
  8803. if (readBoolean()) { // frame_cropping_flag
  8804. frameCropLeftOffset = readUEG();
  8805. frameCropRightOffset = readUEG();
  8806. frameCropTopOffset = readUEG();
  8807. frameCropBottomOffset = readUEG();
  8808. }
  8809. var pixelRatio = [1, 1];
  8810. if (readBoolean()) {
  8811. // vui_parameters_present_flag
  8812. if (readBoolean()) {
  8813. // aspect_ratio_info_present_flag
  8814. var aspectRatioIdc = readUByte();
  8815. switch (aspectRatioIdc) {
  8816. case 1:
  8817. pixelRatio = [1, 1];
  8818. break;
  8819. case 2:
  8820. pixelRatio = [12, 11];
  8821. break;
  8822. case 3:
  8823. pixelRatio = [10, 11];
  8824. break;
  8825. case 4:
  8826. pixelRatio = [16, 11];
  8827. break;
  8828. case 5:
  8829. pixelRatio = [40, 33];
  8830. break;
  8831. case 6:
  8832. pixelRatio = [24, 11];
  8833. break;
  8834. case 7:
  8835. pixelRatio = [20, 11];
  8836. break;
  8837. case 8:
  8838. pixelRatio = [32, 11];
  8839. break;
  8840. case 9:
  8841. pixelRatio = [80, 33];
  8842. break;
  8843. case 10:
  8844. pixelRatio = [18, 11];
  8845. break;
  8846. case 11:
  8847. pixelRatio = [15, 11];
  8848. break;
  8849. case 12:
  8850. pixelRatio = [64, 33];
  8851. break;
  8852. case 13:
  8853. pixelRatio = [160, 99];
  8854. break;
  8855. case 14:
  8856. pixelRatio = [4, 3];
  8857. break;
  8858. case 15:
  8859. pixelRatio = [3, 2];
  8860. break;
  8861. case 16:
  8862. pixelRatio = [2, 1];
  8863. break;
  8864. case 255: {
  8865. pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];
  8866. break;
  8867. }
  8868. }
  8869. }
  8870. }
  8871. return {
  8872. width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2)),
  8873. height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - ((frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)),
  8874. pixelRatio: pixelRatio
  8875. };
  8876. };
  8877. ExpGolomb.prototype.readSliceType = function () {
  8878. // skip NALu type
  8879. this.readUByte();
  8880. // discard first_mb_in_slice
  8881. this.readUEG();
  8882. // return slice_type
  8883. return this.readUEG();
  8884. };
  8885. return ExpGolomb;
  8886. }());
  8887. exports.default = ExpGolomb;
  8888. /***/ }),
  8889. /***/ "./src/demux/id3.js":
  8890. /*!**************************!*\
  8891. !*** ./src/demux/id3.js ***!
  8892. \**************************/
  8893. /*! no static exports found */
  8894. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  8895. /***/ (function(module, exports, __webpack_require__) {
  8896. "use strict";
  8897. Object.defineProperty(exports, "__esModule", { value: true });
  8898. /**
  8899. * ID3 parser
  8900. */
  8901. var ID3 = /** @class */ (function () {
  8902. function ID3() {
  8903. }
  8904. /**
  8905. * Returns true if an ID3 header can be found at offset in data
  8906. * @param {Uint8Array} data - The data to search in
  8907. * @param {number} offset - The offset at which to start searching
  8908. * @return {boolean} - True if an ID3 header is found
  8909. */
  8910. ID3.isHeader = function (data, offset) {
  8911. /*
  8912. * http://id3.org/id3v2.3.0
  8913. * [0] = 'I'
  8914. * [1] = 'D'
  8915. * [2] = '3'
  8916. * [3,4] = {Version}
  8917. * [5] = {Flags}
  8918. * [6-9] = {ID3 Size}
  8919. *
  8920. * An ID3v2 tag can be detected with the following pattern:
  8921. * $49 44 33 yy yy xx zz zz zz zz
  8922. * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80
  8923. */
  8924. if (offset + 10 <= data.length) {
  8925. // look for 'ID3' identifier
  8926. if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {
  8927. // check version is within range
  8928. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  8929. // check size is within range
  8930. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  8931. return true;
  8932. }
  8933. }
  8934. }
  8935. }
  8936. return false;
  8937. };
  8938. /**
  8939. * Returns true if an ID3 footer can be found at offset in data
  8940. * @param {Uint8Array} data - The data to search in
  8941. * @param {number} offset - The offset at which to start searching
  8942. * @return {boolean} - True if an ID3 footer is found
  8943. */
  8944. ID3.isFooter = function (data, offset) {
  8945. /*
  8946. * The footer is a copy of the header, but with a different identifier
  8947. */
  8948. if (offset + 10 <= data.length) {
  8949. // look for '3DI' identifier
  8950. if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {
  8951. // check version is within range
  8952. if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {
  8953. // check size is within range
  8954. if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {
  8955. return true;
  8956. }
  8957. }
  8958. }
  8959. }
  8960. return false;
  8961. };
  8962. /**
  8963. * Returns any adjacent ID3 tags found in data starting at offset, as one block of data
  8964. * @param {Uint8Array} data - The data to search in
  8965. * @param {number} offset - The offset at which to start searching
  8966. * @return {Uint8Array} - The block of data containing any ID3 tags found
  8967. */
  8968. ID3.getID3Data = function (data, offset) {
  8969. var front = offset;
  8970. var length = 0;
  8971. while (ID3.isHeader(data, offset)) {
  8972. // ID3 header is 10 bytes
  8973. length += 10;
  8974. var size = ID3._readSize(data, offset + 6);
  8975. length += size;
  8976. if (ID3.isFooter(data, offset + 10)) {
  8977. // ID3 footer is 10 bytes
  8978. length += 10;
  8979. }
  8980. offset += length;
  8981. }
  8982. if (length > 0) {
  8983. return data.subarray(front, front + length);
  8984. }
  8985. return undefined;
  8986. };
  8987. ID3._readSize = function (data, offset) {
  8988. var size = 0;
  8989. size = ((data[offset] & 0x7f) << 21);
  8990. size |= ((data[offset + 1] & 0x7f) << 14);
  8991. size |= ((data[offset + 2] & 0x7f) << 7);
  8992. size |= (data[offset + 3] & 0x7f);
  8993. return size;
  8994. };
  8995. /**
  8996. * Searches for the Elementary Stream timestamp found in the ID3 data chunk
  8997. * @param {Uint8Array} data - Block of data containing one or more ID3 tags
  8998. * @return {number} - The timestamp
  8999. */
  9000. ID3.getTimeStamp = function (data) {
  9001. var frames = ID3.getID3Frames(data);
  9002. for (var i = 0; i < frames.length; i++) {
  9003. var frame = frames[i];
  9004. if (ID3.isTimeStampFrame(frame)) {
  9005. return ID3._readTimeStamp(frame);
  9006. }
  9007. }
  9008. return undefined;
  9009. };
  9010. /**
  9011. * Returns true if the ID3 frame is an Elementary Stream timestamp frame
  9012. * @param {ID3 frame} frame
  9013. */
  9014. ID3.isTimeStampFrame = function (frame) {
  9015. return (frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp');
  9016. };
  9017. ID3._getFrameData = function (data) {
  9018. /*
  9019. Frame ID $xx xx xx xx (four characters)
  9020. Size $xx xx xx xx
  9021. Flags $xx xx
  9022. */
  9023. var type = String.fromCharCode(data[0], data[1], data[2], data[3]);
  9024. var size = ID3._readSize(data, 4);
  9025. // skip frame id, size, and flags
  9026. var offset = 10;
  9027. return { type: type, size: size, data: data.subarray(offset, offset + size) };
  9028. };
  9029. /**
  9030. * Returns an array of ID3 frames found in all the ID3 tags in the id3Data
  9031. * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags
  9032. * @return {ID3 frame[]} - Array of ID3 frame objects
  9033. */
  9034. ID3.getID3Frames = function (id3Data) {
  9035. var offset = 0;
  9036. var frames = [];
  9037. while (ID3.isHeader(id3Data, offset)) {
  9038. var size = ID3._readSize(id3Data, offset + 6);
  9039. // skip past ID3 header
  9040. offset += 10;
  9041. var end = offset + size;
  9042. // loop through frames in the ID3 tag
  9043. while (offset + 8 < end) {
  9044. var frameData = ID3._getFrameData(id3Data.subarray(offset));
  9045. var frame = ID3._decodeFrame(frameData);
  9046. if (frame) {
  9047. frames.push(frame);
  9048. }
  9049. // skip frame header and frame data
  9050. offset += frameData.size + 10;
  9051. }
  9052. if (ID3.isFooter(id3Data, offset)) {
  9053. offset += 10;
  9054. }
  9055. }
  9056. return frames;
  9057. };
  9058. ID3._decodeFrame = function (frame) {
  9059. if (frame.type === 'PRIV') {
  9060. return ID3._decodePrivFrame(frame);
  9061. }
  9062. else if (frame.type[0] === 'T') {
  9063. return ID3._decodeTextFrame(frame);
  9064. }
  9065. else if (frame.type[0] === 'W') {
  9066. return ID3._decodeURLFrame(frame);
  9067. }
  9068. return undefined;
  9069. };
  9070. ID3._readTimeStamp = function (timeStampFrame) {
  9071. if (timeStampFrame.data.byteLength === 8) {
  9072. var data = new Uint8Array(timeStampFrame.data);
  9073. // timestamp is 33 bit expressed as a big-endian eight-octet number,
  9074. // with the upper 31 bits set to zero.
  9075. var pts33Bit = data[3] & 0x1;
  9076. var timestamp = (data[4] << 23) +
  9077. (data[5] << 15) +
  9078. (data[6] << 7) +
  9079. data[7];
  9080. timestamp /= 45;
  9081. if (pts33Bit) {
  9082. timestamp += 47721858.84;
  9083. } // 2^32 / 90
  9084. return Math.round(timestamp);
  9085. }
  9086. return undefined;
  9087. };
  9088. ID3._decodePrivFrame = function (frame) {
  9089. /*
  9090. Format: <text string>\0<binary data>
  9091. */
  9092. if (frame.size < 2) {
  9093. return undefined;
  9094. }
  9095. var owner = ID3._utf8ArrayToStr(frame.data, true);
  9096. var privateData = new Uint8Array(frame.data.subarray(owner.length + 1));
  9097. return { key: frame.type, info: owner, data: privateData.buffer };
  9098. };
  9099. ID3._decodeTextFrame = function (frame) {
  9100. if (frame.size < 2) {
  9101. return undefined;
  9102. }
  9103. if (frame.type === 'TXXX') {
  9104. /*
  9105. Format:
  9106. [0] = {Text Encoding}
  9107. [1-?] = {Description}\0{Value}
  9108. */
  9109. var index = 1;
  9110. var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
  9111. index += description.length + 1;
  9112. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  9113. return { key: frame.type, info: description, data: value };
  9114. }
  9115. else {
  9116. /*
  9117. Format:
  9118. [0] = {Text Encoding}
  9119. [1-?] = {Value}
  9120. */
  9121. var text = ID3._utf8ArrayToStr(frame.data.subarray(1));
  9122. return { key: frame.type, data: text };
  9123. }
  9124. };
  9125. ID3._decodeURLFrame = function (frame) {
  9126. if (frame.type === 'WXXX') {
  9127. /*
  9128. Format:
  9129. [0] = {Text Encoding}
  9130. [1-?] = {Description}\0{URL}
  9131. */
  9132. if (frame.size < 2) {
  9133. return undefined;
  9134. }
  9135. var index = 1;
  9136. var description = ID3._utf8ArrayToStr(frame.data.subarray(index));
  9137. index += description.length + 1;
  9138. var value = ID3._utf8ArrayToStr(frame.data.subarray(index));
  9139. return { key: frame.type, info: description, data: value };
  9140. }
  9141. else {
  9142. /*
  9143. Format:
  9144. [0-?] = {URL}
  9145. */
  9146. var url = ID3._utf8ArrayToStr(frame.data);
  9147. return { key: frame.type, data: url };
  9148. }
  9149. };
  9150. // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197
  9151. // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt
  9152. /* utf.js - UTF-8 <=> UTF-16 convertion
  9153. *
  9154. * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
  9155. * Version: 1.0
  9156. * LastModified: Dec 25 1999
  9157. * This library is free. You can redistribute it and/or modify it.
  9158. */
  9159. ID3._utf8ArrayToStr = function (array, exitOnNull) {
  9160. if (exitOnNull === void 0) { exitOnNull = false; }
  9161. var len = array.length;
  9162. var c;
  9163. var char2;
  9164. var char3;
  9165. var out = '';
  9166. var i = 0;
  9167. while (i < len) {
  9168. c = array[i++];
  9169. if (c === 0x00 && exitOnNull) {
  9170. return out;
  9171. }
  9172. else if (c === 0x00 || c === 0x03) {
  9173. // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it
  9174. continue;
  9175. }
  9176. switch (c >> 4) {
  9177. case 0:
  9178. case 1:
  9179. case 2:
  9180. case 3:
  9181. case 4:
  9182. case 5:
  9183. case 6:
  9184. case 7:
  9185. // 0xxxxxxx
  9186. out += String.fromCharCode(c);
  9187. break;
  9188. case 12:
  9189. case 13:
  9190. // 110x xxxx 10xx xxxx
  9191. char2 = array[i++];
  9192. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
  9193. break;
  9194. case 14:
  9195. // 1110 xxxx 10xx xxxx 10xx xxxx
  9196. char2 = array[i++];
  9197. char3 = array[i++];
  9198. out += String.fromCharCode(((c & 0x0F) << 12) |
  9199. ((char2 & 0x3F) << 6) |
  9200. ((char3 & 0x3F) << 0));
  9201. break;
  9202. default:
  9203. }
  9204. }
  9205. return out;
  9206. };
  9207. return ID3;
  9208. }());
  9209. var utf8ArrayToStr = ID3._utf8ArrayToStr;
  9210. exports.utf8ArrayToStr = utf8ArrayToStr;
  9211. exports.default = ID3;
  9212. /***/ }),
  9213. /***/ "./src/demux/mp3demuxer.js":
  9214. /*!*********************************!*\
  9215. !*** ./src/demux/mp3demuxer.js ***!
  9216. \*********************************/
  9217. /*! no static exports found */
  9218. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  9219. /***/ (function(module, exports, __webpack_require__) {
  9220. "use strict";
  9221. Object.defineProperty(exports, "__esModule", { value: true });
  9222. /**
  9223. * MP3 demuxer
  9224. */
  9225. var id3_1 = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.js");
  9226. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  9227. var mpegaudio_1 = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.js");
  9228. var MP3Demuxer = /** @class */ (function () {
  9229. function MP3Demuxer(observer, remuxer, config) {
  9230. this.observer = observer;
  9231. this.config = config;
  9232. this.remuxer = remuxer;
  9233. }
  9234. MP3Demuxer.prototype.resetInitSegment = function (initSegment, audioCodec, videoCodec, duration) {
  9235. this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };
  9236. };
  9237. MP3Demuxer.prototype.resetTimeStamp = function () {
  9238. };
  9239. MP3Demuxer.probe = function (data) {
  9240. // check if data contains ID3 timestamp and MPEG sync word
  9241. var offset, length;
  9242. var id3Data = id3_1.default.getID3Data(data, 0);
  9243. if (id3Data && id3_1.default.getTimeStamp(id3Data) !== undefined) {
  9244. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  9245. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  9246. // More info http://www.mp3-tech.org/programmer/frame_header.html
  9247. for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {
  9248. if (mpegaudio_1.default.probe(data, offset)) {
  9249. logger_1.logger.log('MPEG Audio sync word found !');
  9250. return true;
  9251. }
  9252. }
  9253. }
  9254. return false;
  9255. };
  9256. // feed incoming data to the front of the parsing pipeline
  9257. MP3Demuxer.prototype.append = function (data, timeOffset, contiguous, accurateTimeOffset) {
  9258. var id3Data = id3_1.default.getID3Data(data, 0);
  9259. var timestamp = id3_1.default.getTimeStamp(id3Data);
  9260. var pts = timestamp ? 90 * timestamp : timeOffset * 90000;
  9261. var offset = id3Data.length;
  9262. var length = data.length;
  9263. var frameIndex = 0, stamp = 0;
  9264. var track = this._audioTrack;
  9265. var id3Samples = [{ pts: pts, dts: pts, data: id3Data }];
  9266. while (offset < length) {
  9267. if (mpegaudio_1.default.isHeader(data, offset)) {
  9268. var frame = mpegaudio_1.default.appendFrame(track, data, offset, pts, frameIndex);
  9269. if (frame) {
  9270. offset += frame.length;
  9271. stamp = frame.sample.pts;
  9272. frameIndex++;
  9273. }
  9274. else {
  9275. // logger.log('Unable to parse Mpeg audio frame');
  9276. break;
  9277. }
  9278. }
  9279. else if (id3_1.default.isHeader(data, offset)) {
  9280. id3Data = id3_1.default.getID3Data(data, offset);
  9281. id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });
  9282. offset += id3Data.length;
  9283. }
  9284. else {
  9285. // nothing found, keep looking
  9286. offset++;
  9287. }
  9288. }
  9289. this.remuxer.remux(track, { samples: [] }, { samples: id3Samples, inputTimeScale: 90000 }, { samples: [] }, timeOffset, contiguous, accurateTimeOffset);
  9290. };
  9291. MP3Demuxer.prototype.destroy = function () {
  9292. };
  9293. return MP3Demuxer;
  9294. }());
  9295. exports.default = MP3Demuxer;
  9296. /***/ }),
  9297. /***/ "./src/demux/mp4demuxer.js":
  9298. /*!*********************************!*\
  9299. !*** ./src/demux/mp4demuxer.js ***!
  9300. \*********************************/
  9301. /*! no static exports found */
  9302. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  9303. /***/ (function(module, exports, __webpack_require__) {
  9304. "use strict";
  9305. Object.defineProperty(exports, "__esModule", { value: true });
  9306. /**
  9307. * MP4 demuxer
  9308. */
  9309. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  9310. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  9311. var UINT32_MAX = Math.pow(2, 32) - 1;
  9312. var MP4Demuxer = /** @class */ (function () {
  9313. function MP4Demuxer(observer, remuxer) {
  9314. this.observer = observer;
  9315. this.remuxer = remuxer;
  9316. }
  9317. MP4Demuxer.prototype.resetTimeStamp = function (initPTS) {
  9318. this.initPTS = initPTS;
  9319. };
  9320. MP4Demuxer.prototype.resetInitSegment = function (initSegment, audioCodec, videoCodec, duration) {
  9321. // jshint unused:false
  9322. if (initSegment && initSegment.byteLength) {
  9323. var initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);
  9324. // default audio codec if nothing specified
  9325. // TODO : extract that from initsegment
  9326. if (audioCodec == null) {
  9327. audioCodec = 'mp4a.40.5';
  9328. }
  9329. if (videoCodec == null) {
  9330. videoCodec = 'avc1.42e01e';
  9331. }
  9332. var tracks = {};
  9333. if (initData.audio && initData.video) {
  9334. tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };
  9335. }
  9336. else {
  9337. if (initData.audio) {
  9338. tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };
  9339. }
  9340. if (initData.video) {
  9341. tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };
  9342. }
  9343. }
  9344. this.observer.trigger(events_1.default.FRAG_PARSING_INIT_SEGMENT, { tracks: tracks });
  9345. }
  9346. else {
  9347. if (audioCodec) {
  9348. this.audioCodec = audioCodec;
  9349. }
  9350. if (videoCodec) {
  9351. this.videoCodec = videoCodec;
  9352. }
  9353. }
  9354. };
  9355. MP4Demuxer.probe = function (data) {
  9356. // ensure we find a moof box in the first 16 kB
  9357. return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;
  9358. };
  9359. MP4Demuxer.bin2str = function (buffer) {
  9360. return String.fromCharCode.apply(null, buffer);
  9361. };
  9362. MP4Demuxer.readUint16 = function (buffer, offset) {
  9363. if (buffer.data) {
  9364. offset += buffer.start;
  9365. buffer = buffer.data;
  9366. }
  9367. var val = buffer[offset] << 8 |
  9368. buffer[offset + 1];
  9369. return val < 0 ? 65536 + val : val;
  9370. };
  9371. MP4Demuxer.readUint32 = function (buffer, offset) {
  9372. if (buffer.data) {
  9373. offset += buffer.start;
  9374. buffer = buffer.data;
  9375. }
  9376. var val = buffer[offset] << 24 |
  9377. buffer[offset + 1] << 16 |
  9378. buffer[offset + 2] << 8 |
  9379. buffer[offset + 3];
  9380. return val < 0 ? 4294967296 + val : val;
  9381. };
  9382. MP4Demuxer.writeUint32 = function (buffer, offset, value) {
  9383. if (buffer.data) {
  9384. offset += buffer.start;
  9385. buffer = buffer.data;
  9386. }
  9387. buffer[offset] = value >> 24;
  9388. buffer[offset + 1] = (value >> 16) & 0xff;
  9389. buffer[offset + 2] = (value >> 8) & 0xff;
  9390. buffer[offset + 3] = value & 0xff;
  9391. };
  9392. // Find the data for a box specified by its path
  9393. MP4Demuxer.findBox = function (data, path) {
  9394. var results = [], i, size, type, end, subresults, start, endbox;
  9395. if (data.data) {
  9396. start = data.start;
  9397. end = data.end;
  9398. data = data.data;
  9399. }
  9400. else {
  9401. start = 0;
  9402. end = data.byteLength;
  9403. }
  9404. if (!path.length) {
  9405. // short-circuit the search for empty paths
  9406. return null;
  9407. }
  9408. for (i = start; i < end;) {
  9409. size = MP4Demuxer.readUint32(data, i);
  9410. type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));
  9411. endbox = size > 1 ? i + size : end;
  9412. if (type === path[0]) {
  9413. if (path.length === 1) {
  9414. // this is the end of the path and we've found the box we were
  9415. // looking for
  9416. results.push({ data: data, start: i + 8, end: endbox });
  9417. }
  9418. else {
  9419. // recursively search for the next box along the path
  9420. subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));
  9421. if (subresults.length) {
  9422. results = results.concat(subresults);
  9423. }
  9424. }
  9425. }
  9426. i = endbox;
  9427. }
  9428. // we've finished searching all of data
  9429. return results;
  9430. };
  9431. MP4Demuxer.parseSegmentIndex = function (initSegment) {
  9432. var moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];
  9433. var moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data
  9434. var index = 0;
  9435. var sidx = MP4Demuxer.findBox(initSegment, ['sidx']);
  9436. var references;
  9437. if (!sidx || !sidx[0]) {
  9438. return null;
  9439. }
  9440. references = [];
  9441. sidx = sidx[0];
  9442. var version = sidx.data[0];
  9443. // set initial offset, we skip the reference ID (not needed)
  9444. index = version === 0 ? 8 : 16;
  9445. var timescale = MP4Demuxer.readUint32(sidx, index);
  9446. index += 4;
  9447. // TODO: parse earliestPresentationTime and firstOffset
  9448. // usually zero in our case
  9449. var earliestPresentationTime = 0;
  9450. var firstOffset = 0;
  9451. if (version === 0) {
  9452. index += 8;
  9453. }
  9454. else {
  9455. index += 16;
  9456. }
  9457. // skip reserved
  9458. index += 2;
  9459. var startByte = sidx.end + firstOffset;
  9460. var referencesCount = MP4Demuxer.readUint16(sidx, index);
  9461. index += 2;
  9462. for (var i = 0; i < referencesCount; i++) {
  9463. var referenceIndex = index;
  9464. var referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);
  9465. referenceIndex += 4;
  9466. var referenceSize = referenceInfo & 0x7FFFFFFF;
  9467. var referenceType = (referenceInfo & 0x80000000) >>> 31;
  9468. if (referenceType === 1) {
  9469. console.warn('SIDX has hierarchical references (not supported)');
  9470. return;
  9471. }
  9472. var subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);
  9473. referenceIndex += 4;
  9474. references.push({
  9475. referenceSize: referenceSize,
  9476. subsegmentDuration: subsegmentDuration,
  9477. info: {
  9478. duration: subsegmentDuration / timescale,
  9479. start: startByte,
  9480. end: startByte + referenceSize - 1
  9481. }
  9482. });
  9483. startByte += referenceSize;
  9484. // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits
  9485. // for |sapDelta|.
  9486. referenceIndex += 4;
  9487. // skip to next ref
  9488. index = referenceIndex;
  9489. }
  9490. return {
  9491. earliestPresentationTime: earliestPresentationTime,
  9492. timescale: timescale,
  9493. version: version,
  9494. referencesCount: referencesCount,
  9495. references: references,
  9496. moovEndOffset: moovEndOffset
  9497. };
  9498. };
  9499. /**
  9500. * Parses an MP4 initialization segment and extracts stream type and
  9501. * timescale values for any declared tracks. Timescale values indicate the
  9502. * number of clock ticks per second to assume for time-based values
  9503. * elsewhere in the MP4.
  9504. *
  9505. * To determine the start time of an MP4, you need two pieces of
  9506. * information: the timescale unit and the earliest base media decode
  9507. * time. Multiple timescales can be specified within an MP4 but the
  9508. * base media decode time is always expressed in the timescale from
  9509. * the media header box for the track:
  9510. * ```
  9511. * moov > trak > mdia > mdhd.timescale
  9512. * moov > trak > mdia > hdlr
  9513. * ```
  9514. * @param init {Uint8Array} the bytes of the init segment
  9515. * @return {object} a hash of track type to timescale values or null if
  9516. * the init segment is malformed.
  9517. */
  9518. MP4Demuxer.parseInitSegment = function (initSegment) {
  9519. var result = [];
  9520. var traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);
  9521. traks.forEach(function (trak) {
  9522. var tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];
  9523. if (tkhd) {
  9524. var version = tkhd.data[tkhd.start];
  9525. var index = version === 0 ? 12 : 20;
  9526. var trackId = MP4Demuxer.readUint32(tkhd, index);
  9527. var mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];
  9528. if (mdhd) {
  9529. version = mdhd.data[mdhd.start];
  9530. index = version === 0 ? 12 : 20;
  9531. var timescale = MP4Demuxer.readUint32(mdhd, index);
  9532. var hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];
  9533. if (hdlr) {
  9534. var hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));
  9535. var type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];
  9536. if (type) {
  9537. // extract codec info. TODO : parse codec details to be able to build MIME type
  9538. var codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);
  9539. if (codecBox.length) {
  9540. codecBox = codecBox[0];
  9541. var codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));
  9542. logger_1.logger.log("MP4Demuxer:" + type + ":" + codecType + " found");
  9543. }
  9544. result[trackId] = { timescale: timescale, type: type };
  9545. result[type] = { timescale: timescale, id: trackId };
  9546. }
  9547. }
  9548. }
  9549. }
  9550. });
  9551. return result;
  9552. };
  9553. /**
  9554. * Determine the base media decode start time, in seconds, for an MP4
  9555. * fragment. If multiple fragments are specified, the earliest time is
  9556. * returned.
  9557. *
  9558. * The base media decode time can be parsed from track fragment
  9559. * metadata:
  9560. * ```
  9561. * moof > traf > tfdt.baseMediaDecodeTime
  9562. * ```
  9563. * It requires the timescale value from the mdhd to interpret.
  9564. *
  9565. * @param timescale {object} a hash of track ids to timescale values.
  9566. * @return {number} the earliest base media decode start time for the
  9567. * fragment, in seconds
  9568. */
  9569. MP4Demuxer.getStartDTS = function (initData, fragment) {
  9570. var trafs, baseTimes, result;
  9571. // we need info from two childrend of each track fragment box
  9572. trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);
  9573. // determine the start times for each track
  9574. baseTimes = [].concat.apply([], trafs.map(function (traf) {
  9575. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  9576. var id, scale, baseTime;
  9577. // get the track id from the tfhd
  9578. id = MP4Demuxer.readUint32(tfhd, 4);
  9579. // assume a 90kHz clock if no timescale was specified
  9580. scale = initData[id].timescale || 90e3;
  9581. // get the base media decode time from the tfdt
  9582. baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  9583. var version, result;
  9584. version = tfdt.data[tfdt.start];
  9585. result = MP4Demuxer.readUint32(tfdt, 4);
  9586. if (version === 1) {
  9587. result *= Math.pow(2, 32);
  9588. result += MP4Demuxer.readUint32(tfdt, 8);
  9589. }
  9590. return result;
  9591. })[0];
  9592. // convert base time to seconds
  9593. return baseTime / scale;
  9594. });
  9595. }));
  9596. // return the minimum
  9597. result = Math.min.apply(null, baseTimes);
  9598. return isFinite(result) ? result : 0;
  9599. };
  9600. MP4Demuxer.offsetStartDTS = function (initData, fragment, timeOffset) {
  9601. MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {
  9602. return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {
  9603. // get the track id from the tfhd
  9604. var id = MP4Demuxer.readUint32(tfhd, 4);
  9605. // assume a 90kHz clock if no timescale was specified
  9606. var timescale = initData[id].timescale || 90e3;
  9607. // get the base media decode time from the tfdt
  9608. MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {
  9609. var version = tfdt.data[tfdt.start];
  9610. var baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);
  9611. if (version === 0) {
  9612. MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);
  9613. }
  9614. else {
  9615. baseMediaDecodeTime *= Math.pow(2, 32);
  9616. baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);
  9617. baseMediaDecodeTime -= timeOffset * timescale;
  9618. baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);
  9619. var upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));
  9620. var lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  9621. MP4Demuxer.writeUint32(tfdt, 4, upper);
  9622. MP4Demuxer.writeUint32(tfdt, 8, lower);
  9623. }
  9624. });
  9625. });
  9626. });
  9627. };
  9628. // feed incoming data to the front of the parsing pipeline
  9629. MP4Demuxer.prototype.append = function (data, timeOffset, contiguous, accurateTimeOffset) {
  9630. var initData = this.initData;
  9631. if (!initData) {
  9632. this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);
  9633. initData = this.initData;
  9634. }
  9635. var startDTS, initPTS = this.initPTS;
  9636. if (initPTS === undefined) {
  9637. var startDTS_1 = MP4Demuxer.getStartDTS(initData, data);
  9638. this.initPTS = initPTS = startDTS_1 - timeOffset;
  9639. this.observer.trigger(events_1.default.INIT_PTS_FOUND, { initPTS: initPTS });
  9640. }
  9641. MP4Demuxer.offsetStartDTS(initData, data, initPTS);
  9642. startDTS = MP4Demuxer.getStartDTS(initData, data);
  9643. this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);
  9644. };
  9645. MP4Demuxer.prototype.destroy = function () { };
  9646. return MP4Demuxer;
  9647. }());
  9648. exports.default = MP4Demuxer;
  9649. /***/ }),
  9650. /***/ "./src/demux/mpegaudio.js":
  9651. /*!********************************!*\
  9652. !*** ./src/demux/mpegaudio.js ***!
  9653. \********************************/
  9654. /*! no static exports found */
  9655. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  9656. /***/ (function(module, exports, __webpack_require__) {
  9657. "use strict";
  9658. /**
  9659. * MPEG parser helper
  9660. */
  9661. Object.defineProperty(exports, "__esModule", { value: true });
  9662. var MpegAudio = {
  9663. BitratesMap: [
  9664. 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,
  9665. 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,
  9666. 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
  9667. 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,
  9668. 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160
  9669. ],
  9670. SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],
  9671. SamplesCoefficients: [
  9672. // MPEG 2.5
  9673. [
  9674. 0,
  9675. 72,
  9676. 144,
  9677. 12 // Layer1
  9678. ],
  9679. // Reserved
  9680. [
  9681. 0,
  9682. 0,
  9683. 0,
  9684. 0 // Layer1
  9685. ],
  9686. // MPEG 2
  9687. [
  9688. 0,
  9689. 72,
  9690. 144,
  9691. 12 // Layer1
  9692. ],
  9693. // MPEG 1
  9694. [
  9695. 0,
  9696. 144,
  9697. 144,
  9698. 12 // Layer1
  9699. ]
  9700. ],
  9701. BytesInSlot: [
  9702. 0,
  9703. 1,
  9704. 1,
  9705. 4 // Layer1
  9706. ],
  9707. appendFrame: function (track, data, offset, pts, frameIndex) {
  9708. // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference
  9709. if (offset + 24 > data.length) {
  9710. return undefined;
  9711. }
  9712. var header = this.parseHeader(data, offset);
  9713. if (header && offset + header.frameLength <= data.length) {
  9714. var frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;
  9715. var stamp = pts + frameIndex * frameDuration;
  9716. var sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };
  9717. track.config = [];
  9718. track.channelCount = header.channelCount;
  9719. track.samplerate = header.sampleRate;
  9720. track.samples.push(sample);
  9721. track.len += header.frameLength;
  9722. return { sample: sample, length: header.frameLength };
  9723. }
  9724. return undefined;
  9725. },
  9726. parseHeader: function (data, offset) {
  9727. var headerB = (data[offset + 1] >> 3) & 3;
  9728. var headerC = (data[offset + 1] >> 1) & 3;
  9729. var headerE = (data[offset + 2] >> 4) & 15;
  9730. var headerF = (data[offset + 2] >> 2) & 3;
  9731. var headerG = (data[offset + 2] >> 1) & 1;
  9732. if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {
  9733. var columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);
  9734. var bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;
  9735. var columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;
  9736. var sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];
  9737. var channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)
  9738. var sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];
  9739. var bytesInSlot = MpegAudio.BytesInSlot[headerC];
  9740. var samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;
  9741. var frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;
  9742. return { sampleRate: sampleRate, channelCount: channelCount, frameLength: frameLength, samplesPerFrame: samplesPerFrame };
  9743. }
  9744. return undefined;
  9745. },
  9746. isHeaderPattern: function (data, offset) {
  9747. return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;
  9748. },
  9749. isHeader: function (data, offset) {
  9750. // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1
  9751. // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)
  9752. // More info http://www.mp3-tech.org/programmer/frame_header.html
  9753. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  9754. return true;
  9755. }
  9756. return false;
  9757. },
  9758. probe: function (data, offset) {
  9759. // same as isHeader but we also check that MPEG frame follows last MPEG frame
  9760. // or end of data is reached
  9761. if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {
  9762. // MPEG header Length
  9763. var headerLength = 4;
  9764. // MPEG frame Length
  9765. var header = this.parseHeader(data, offset);
  9766. var frameLength = headerLength;
  9767. if (header && header.frameLength) {
  9768. frameLength = header.frameLength;
  9769. }
  9770. var newOffset = offset + frameLength;
  9771. if (newOffset === data.length || (newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset))) {
  9772. return true;
  9773. }
  9774. }
  9775. return false;
  9776. }
  9777. };
  9778. exports.default = MpegAudio;
  9779. /***/ }),
  9780. /***/ "./src/demux/sample-aes.js":
  9781. /*!*********************************!*\
  9782. !*** ./src/demux/sample-aes.js ***!
  9783. \*********************************/
  9784. /*! no static exports found */
  9785. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  9786. /***/ (function(module, exports, __webpack_require__) {
  9787. "use strict";
  9788. /**
  9789. * SAMPLE-AES decrypter
  9790. */
  9791. Object.defineProperty(exports, "__esModule", { value: true });
  9792. var decrypter_1 = __webpack_require__(/*! ../crypt/decrypter */ "./src/crypt/decrypter.js");
  9793. var SampleAesDecrypter = /** @class */ (function () {
  9794. function SampleAesDecrypter(observer, config, decryptdata, discardEPB) {
  9795. this.decryptdata = decryptdata;
  9796. this.discardEPB = discardEPB;
  9797. this.decrypter = new decrypter_1.default(observer, config, { removePKCS7Padding: false });
  9798. }
  9799. SampleAesDecrypter.prototype.decryptBuffer = function (encryptedData, callback) {
  9800. this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);
  9801. };
  9802. // AAC - encrypt all full 16 bytes blocks starting from offset 16
  9803. SampleAesDecrypter.prototype.decryptAacSample = function (samples, sampleIndex, callback, sync) {
  9804. var curUnit = samples[sampleIndex].unit;
  9805. var encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);
  9806. var encryptedBuffer = encryptedData.buffer.slice(encryptedData.byteOffset, encryptedData.byteOffset + encryptedData.length);
  9807. var localthis = this;
  9808. this.decryptBuffer(encryptedBuffer, function (decryptedData) {
  9809. decryptedData = new Uint8Array(decryptedData);
  9810. curUnit.set(decryptedData, 16);
  9811. if (!sync) {
  9812. localthis.decryptAacSamples(samples, sampleIndex + 1, callback);
  9813. }
  9814. });
  9815. };
  9816. SampleAesDecrypter.prototype.decryptAacSamples = function (samples, sampleIndex, callback) {
  9817. for (;; sampleIndex++) {
  9818. if (sampleIndex >= samples.length) {
  9819. callback();
  9820. return;
  9821. }
  9822. if (samples[sampleIndex].unit.length < 32) {
  9823. continue;
  9824. }
  9825. var sync = this.decrypter.isSync();
  9826. this.decryptAacSample(samples, sampleIndex, callback, sync);
  9827. if (!sync) {
  9828. return;
  9829. }
  9830. }
  9831. };
  9832. // AVC - encrypt one 16 bytes block out of ten, starting from offset 32
  9833. SampleAesDecrypter.prototype.getAvcEncryptedData = function (decodedData) {
  9834. var encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;
  9835. var encryptedData = new Int8Array(encryptedDataLen);
  9836. var outputPos = 0;
  9837. for (var inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {
  9838. encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);
  9839. }
  9840. return encryptedData;
  9841. };
  9842. SampleAesDecrypter.prototype.getAvcDecryptedUnit = function (decodedData, decryptedData) {
  9843. decryptedData = new Uint8Array(decryptedData);
  9844. var inputPos = 0;
  9845. for (var outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {
  9846. decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);
  9847. }
  9848. return decodedData;
  9849. };
  9850. SampleAesDecrypter.prototype.decryptAvcSample = function (samples, sampleIndex, unitIndex, callback, curUnit, sync) {
  9851. var decodedData = this.discardEPB(curUnit.data);
  9852. var encryptedData = this.getAvcEncryptedData(decodedData);
  9853. var localthis = this;
  9854. this.decryptBuffer(encryptedData.buffer, function (decryptedData) {
  9855. curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);
  9856. if (!sync) {
  9857. localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);
  9858. }
  9859. });
  9860. };
  9861. SampleAesDecrypter.prototype.decryptAvcSamples = function (samples, sampleIndex, unitIndex, callback) {
  9862. for (;; sampleIndex++, unitIndex = 0) {
  9863. if (sampleIndex >= samples.length) {
  9864. callback();
  9865. return;
  9866. }
  9867. var curUnits = samples[sampleIndex].units;
  9868. for (;; unitIndex++) {
  9869. if (unitIndex >= curUnits.length) {
  9870. break;
  9871. }
  9872. var curUnit = curUnits[unitIndex];
  9873. if (curUnit.length <= 48 || (curUnit.type !== 1 && curUnit.type !== 5)) {
  9874. continue;
  9875. }
  9876. var sync = this.decrypter.isSync();
  9877. this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);
  9878. if (!sync) {
  9879. return;
  9880. }
  9881. }
  9882. }
  9883. };
  9884. return SampleAesDecrypter;
  9885. }());
  9886. exports.default = SampleAesDecrypter;
  9887. /***/ }),
  9888. /***/ "./src/demux/tsdemuxer.js":
  9889. /*!********************************!*\
  9890. !*** ./src/demux/tsdemuxer.js ***!
  9891. \********************************/
  9892. /*! no static exports found */
  9893. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  9894. /***/ (function(module, exports, __webpack_require__) {
  9895. "use strict";
  9896. /**
  9897. * highly optimized TS demuxer:
  9898. * parse PAT, PMT
  9899. * extract PES packet from audio and video PIDs
  9900. * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet
  9901. * trigger the remuxer upon parsing completion
  9902. * it also tries to workaround as best as it can audio codec switch (HE-AAC to AAC and vice versa), without having to restart the MediaSource.
  9903. * it also controls the remuxing process :
  9904. * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.
  9905. */
  9906. Object.defineProperty(exports, "__esModule", { value: true });
  9907. var ADTS = __webpack_require__(/*! ./adts */ "./src/demux/adts.js");
  9908. var mpegaudio_1 = __webpack_require__(/*! ./mpegaudio */ "./src/demux/mpegaudio.js");
  9909. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  9910. var exp_golomb_1 = __webpack_require__(/*! ./exp-golomb */ "./src/demux/exp-golomb.js");
  9911. var sample_aes_1 = __webpack_require__(/*! ./sample-aes */ "./src/demux/sample-aes.js");
  9912. // import Hex from '../utils/hex';
  9913. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  9914. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  9915. // We are using fixed track IDs for driving the MP4 remuxer
  9916. // instead of following the TS PIDs.
  9917. // There is no reason not to do this and some browsers/SourceBuffer-demuxers
  9918. // may not like if there are TrackID "switches"
  9919. // See https://github.com/video-dev/hls.js/issues/1331
  9920. // Here we are mapping our internal track types to constant MP4 track IDs
  9921. // With MSE currently one can only have one track of each, and we are muxing
  9922. // whatever video/audio rendition in them.
  9923. var RemuxerTrackIdConfig = {
  9924. video: 1,
  9925. audio: 2,
  9926. id3: 3,
  9927. text: 4
  9928. };
  9929. var TSDemuxer = /** @class */ (function () {
  9930. function TSDemuxer(observer, remuxer, config, typeSupported) {
  9931. this.observer = observer;
  9932. this.config = config;
  9933. this.typeSupported = typeSupported;
  9934. this.remuxer = remuxer;
  9935. this.sampleAes = null;
  9936. }
  9937. TSDemuxer.prototype.setDecryptData = function (decryptdata) {
  9938. if ((decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'SAMPLE-AES')) {
  9939. this.sampleAes = new sample_aes_1.default(this.observer, this.config, decryptdata, this.discardEPB);
  9940. }
  9941. else {
  9942. this.sampleAes = null;
  9943. }
  9944. };
  9945. TSDemuxer.probe = function (data) {
  9946. var syncOffset = TSDemuxer._syncOffset(data);
  9947. if (syncOffset < 0) {
  9948. return false;
  9949. }
  9950. else {
  9951. if (syncOffset) {
  9952. logger_1.logger.warn("MPEG2-TS detected but first sync word found @ offset " + syncOffset + ", junk ahead ?");
  9953. }
  9954. return true;
  9955. }
  9956. };
  9957. TSDemuxer._syncOffset = function (data) {
  9958. // scan 1000 first bytes
  9959. var scanwindow = Math.min(1000, data.length - 3 * 188);
  9960. var i = 0;
  9961. while (i < scanwindow) {
  9962. // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47
  9963. if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {
  9964. return i;
  9965. }
  9966. else {
  9967. i++;
  9968. }
  9969. }
  9970. return -1;
  9971. };
  9972. /**
  9973. * Creates a track model internal to demuxer used to drive remuxing input
  9974. *
  9975. * @param {string} type 'audio' | 'video' | 'id3' | 'text'
  9976. * @param {number} duration
  9977. * @return {object} TSDemuxer's internal track model
  9978. */
  9979. TSDemuxer.createTrack = function (type, duration) {
  9980. return {
  9981. container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,
  9982. type: type,
  9983. id: RemuxerTrackIdConfig[type],
  9984. pid: -1,
  9985. inputTimeScale: 90000,
  9986. sequenceNumber: 0,
  9987. samples: [],
  9988. len: 0,
  9989. dropped: type === 'video' ? 0 : undefined,
  9990. isAAC: type === 'audio' ? true : undefined,
  9991. duration: type === 'audio' ? duration : undefined
  9992. };
  9993. };
  9994. /**
  9995. * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)
  9996. * Resets all internal track instances of the demuxer.
  9997. *
  9998. * @override Implements generic demuxing/remuxing interface (see DemuxerInline)
  9999. * @param {object} initSegment
  10000. * @param {string} audioCodec
  10001. * @param {string} videoCodec
  10002. * @param {number} duration (in TS timescale = 90kHz)
  10003. */
  10004. TSDemuxer.prototype.resetInitSegment = function (initSegment, audioCodec, videoCodec, duration) {
  10005. this.pmtParsed = false;
  10006. this._pmtId = -1;
  10007. this._avcTrack = TSDemuxer.createTrack('video', duration);
  10008. this._audioTrack = TSDemuxer.createTrack('audio', duration);
  10009. this._id3Track = TSDemuxer.createTrack('id3', duration);
  10010. this._txtTrack = TSDemuxer.createTrack('text', duration);
  10011. // flush any partial content
  10012. this.aacOverFlow = null;
  10013. this.aacLastPTS = null;
  10014. this.avcSample = null;
  10015. this.audioCodec = audioCodec;
  10016. this.videoCodec = videoCodec;
  10017. this._duration = duration;
  10018. };
  10019. /**
  10020. *
  10021. * @override
  10022. */
  10023. TSDemuxer.prototype.resetTimeStamp = function () { };
  10024. // feed incoming data to the front of the parsing pipeline
  10025. TSDemuxer.prototype.append = function (data, timeOffset, contiguous, accurateTimeOffset) {
  10026. var start, len = data.length, stt, pid, atf, offset, pes, unknownPIDs = false;
  10027. this.contiguous = contiguous;
  10028. var pmtParsed = this.pmtParsed, avcTrack = this._avcTrack, audioTrack = this._audioTrack, id3Track = this._id3Track, avcId = avcTrack.pid, audioId = audioTrack.pid, id3Id = id3Track.pid, pmtId = this._pmtId, avcData = avcTrack.pesData, audioData = audioTrack.pesData, id3Data = id3Track.pesData, parsePAT = this._parsePAT, parsePMT = this._parsePMT, parsePES = this._parsePES, parseAVCPES = this._parseAVCPES.bind(this), parseAACPES = this._parseAACPES.bind(this), parseMPEGPES = this._parseMPEGPES.bind(this), parseID3PES = this._parseID3PES.bind(this);
  10029. var syncOffset = TSDemuxer._syncOffset(data);
  10030. // don't parse last TS packet if incomplete
  10031. len -= (len + syncOffset) % 188;
  10032. // loop through TS packets
  10033. for (start = syncOffset; start < len; start += 188) {
  10034. if (data[start] === 0x47) {
  10035. stt = !!(data[start + 1] & 0x40);
  10036. // pid is a 13-bit field starting at the last bit of TS[1]
  10037. pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];
  10038. atf = (data[start + 3] & 0x30) >> 4;
  10039. // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.
  10040. if (atf > 1) {
  10041. offset = start + 5 + data[start + 4];
  10042. // continue if there is only adaptation field
  10043. if (offset === (start + 188)) {
  10044. continue;
  10045. }
  10046. }
  10047. else {
  10048. offset = start + 4;
  10049. }
  10050. switch (pid) {
  10051. case avcId:
  10052. if (stt) {
  10053. if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
  10054. parseAVCPES(pes, false);
  10055. }
  10056. avcData = { data: [], size: 0 };
  10057. }
  10058. if (avcData) {
  10059. avcData.data.push(data.subarray(offset, start + 188));
  10060. avcData.size += start + 188 - offset;
  10061. }
  10062. break;
  10063. case audioId:
  10064. if (stt) {
  10065. if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
  10066. if (audioTrack.isAAC) {
  10067. parseAACPES(pes);
  10068. }
  10069. else {
  10070. parseMPEGPES(pes);
  10071. }
  10072. }
  10073. audioData = { data: [], size: 0 };
  10074. }
  10075. if (audioData) {
  10076. audioData.data.push(data.subarray(offset, start + 188));
  10077. audioData.size += start + 188 - offset;
  10078. }
  10079. break;
  10080. case id3Id:
  10081. if (stt) {
  10082. if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
  10083. parseID3PES(pes);
  10084. }
  10085. id3Data = { data: [], size: 0 };
  10086. }
  10087. if (id3Data) {
  10088. id3Data.data.push(data.subarray(offset, start + 188));
  10089. id3Data.size += start + 188 - offset;
  10090. }
  10091. break;
  10092. case 0:
  10093. if (stt) {
  10094. offset += data[offset] + 1;
  10095. }
  10096. pmtId = this._pmtId = parsePAT(data, offset);
  10097. break;
  10098. case pmtId:
  10099. if (stt) {
  10100. offset += data[offset] + 1;
  10101. }
  10102. var parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);
  10103. // only update track id if track PID found while parsing PMT
  10104. // this is to avoid resetting the PID to -1 in case
  10105. // track PID transiently disappears from the stream
  10106. // this could happen in case of transient missing audio samples for example
  10107. // NOTE this is only the PID of the track as found in TS,
  10108. // but we are not using this for MP4 track IDs.
  10109. avcId = parsedPIDs.avc;
  10110. if (avcId > 0) {
  10111. avcTrack.pid = avcId;
  10112. }
  10113. audioId = parsedPIDs.audio;
  10114. if (audioId > 0) {
  10115. audioTrack.pid = audioId;
  10116. audioTrack.isAAC = parsedPIDs.isAAC;
  10117. }
  10118. id3Id = parsedPIDs.id3;
  10119. if (id3Id > 0) {
  10120. id3Track.pid = id3Id;
  10121. }
  10122. if (unknownPIDs && !pmtParsed) {
  10123. logger_1.logger.log('reparse from beginning');
  10124. unknownPIDs = false;
  10125. // we set it to -188, the += 188 in the for loop will reset start to 0
  10126. start = syncOffset - 188;
  10127. }
  10128. pmtParsed = this.pmtParsed = true;
  10129. break;
  10130. case 17:
  10131. case 0x1fff:
  10132. break;
  10133. default:
  10134. unknownPIDs = true;
  10135. break;
  10136. }
  10137. }
  10138. else {
  10139. this.observer.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });
  10140. }
  10141. }
  10142. // try to parse last PES packets
  10143. if (avcData && (pes = parsePES(avcData)) && pes.pts !== undefined) {
  10144. parseAVCPES(pes, true);
  10145. avcTrack.pesData = null;
  10146. }
  10147. else {
  10148. // either avcData null or PES truncated, keep it for next frag parsing
  10149. avcTrack.pesData = avcData;
  10150. }
  10151. if (audioData && (pes = parsePES(audioData)) && pes.pts !== undefined) {
  10152. if (audioTrack.isAAC) {
  10153. parseAACPES(pes);
  10154. }
  10155. else {
  10156. parseMPEGPES(pes);
  10157. }
  10158. audioTrack.pesData = null;
  10159. }
  10160. else {
  10161. if (audioData && audioData.size) {
  10162. logger_1.logger.log('last AAC PES packet truncated,might overlap between fragments');
  10163. }
  10164. // either audioData null or PES truncated, keep it for next frag parsing
  10165. audioTrack.pesData = audioData;
  10166. }
  10167. if (id3Data && (pes = parsePES(id3Data)) && pes.pts !== undefined) {
  10168. parseID3PES(pes);
  10169. id3Track.pesData = null;
  10170. }
  10171. else {
  10172. // either id3Data null or PES truncated, keep it for next frag parsing
  10173. id3Track.pesData = id3Data;
  10174. }
  10175. if (this.sampleAes == null) {
  10176. this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  10177. }
  10178. else {
  10179. this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);
  10180. }
  10181. };
  10182. TSDemuxer.prototype.decryptAndRemux = function (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  10183. if (audioTrack.samples && audioTrack.isAAC) {
  10184. var localthis_1 = this;
  10185. this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {
  10186. localthis_1.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  10187. });
  10188. }
  10189. else {
  10190. this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  10191. }
  10192. };
  10193. TSDemuxer.prototype.decryptAndRemuxAvc = function (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  10194. if (videoTrack.samples) {
  10195. var localthis_2 = this;
  10196. this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {
  10197. localthis_2.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  10198. });
  10199. }
  10200. else {
  10201. this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);
  10202. }
  10203. };
  10204. TSDemuxer.prototype.destroy = function () {
  10205. this._initPTS = this._initDTS = undefined;
  10206. this._duration = 0;
  10207. };
  10208. TSDemuxer.prototype._parsePAT = function (data, offset) {
  10209. // skip the PSI header and parse the first PMT entry
  10210. return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];
  10211. // logger.log('PMT PID:' + this._pmtId);
  10212. };
  10213. TSDemuxer.prototype._parsePMT = function (data, offset, mpegSupported, isSampleAes) {
  10214. var sectionLength, tableEnd, programInfoLength, pid, result = { audio: -1, avc: -1, id3: -1, isAAC: true };
  10215. sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];
  10216. tableEnd = offset + 3 + sectionLength - 4;
  10217. // to determine where the table is, we have to figure out how
  10218. // long the program info descriptors are
  10219. programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];
  10220. // advance the offset to the first entry in the mapping table
  10221. offset += 12 + programInfoLength;
  10222. while (offset < tableEnd) {
  10223. pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];
  10224. switch (data[offset]) {
  10225. case 0xcf: // SAMPLE-AES AAC
  10226. if (!isSampleAes) {
  10227. logger_1.logger.log('unkown stream type:' + data[offset]);
  10228. break;
  10229. }
  10230. /* falls through */
  10231. // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)
  10232. case 0x0f:
  10233. // logger.log('AAC PID:' + pid);
  10234. if (result.audio === -1) {
  10235. result.audio = pid;
  10236. }
  10237. break;
  10238. // Packetized metadata (ID3)
  10239. case 0x15:
  10240. // logger.log('ID3 PID:' + pid);
  10241. if (result.id3 === -1) {
  10242. result.id3 = pid;
  10243. }
  10244. break;
  10245. case 0xdb: // SAMPLE-AES AVC
  10246. if (!isSampleAes) {
  10247. logger_1.logger.log('unkown stream type:' + data[offset]);
  10248. break;
  10249. }
  10250. /* falls through */
  10251. // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)
  10252. case 0x1b:
  10253. // logger.log('AVC PID:' + pid);
  10254. if (result.avc === -1) {
  10255. result.avc = pid;
  10256. }
  10257. break;
  10258. // ISO/IEC 11172-3 (MPEG-1 audio)
  10259. // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)
  10260. case 0x03:
  10261. case 0x04:
  10262. // logger.log('MPEG PID:' + pid);
  10263. if (!mpegSupported) {
  10264. logger_1.logger.log('MPEG audio found, not supported in this browser for now');
  10265. }
  10266. else if (result.audio === -1) {
  10267. result.audio = pid;
  10268. result.isAAC = false;
  10269. }
  10270. break;
  10271. case 0x24:
  10272. logger_1.logger.warn('HEVC stream type found, not supported for now');
  10273. break;
  10274. default:
  10275. logger_1.logger.log('unkown stream type:' + data[offset]);
  10276. break;
  10277. }
  10278. // move to the next table entry
  10279. // skip past the elementary stream descriptors, if present
  10280. offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;
  10281. }
  10282. return result;
  10283. };
  10284. TSDemuxer.prototype._parsePES = function (stream) {
  10285. var i = 0, frag, pesFlags, pesPrefix, pesLen, pesHdrLen, pesData, pesPts, pesDts, payloadStartOffset, data = stream.data;
  10286. // safety check
  10287. if (!stream || stream.size === 0) {
  10288. return null;
  10289. }
  10290. // we might need up to 19 bytes to read PES header
  10291. // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes
  10292. // usually only one merge is needed (and this is rare ...)
  10293. while (data[0].length < 19 && data.length > 1) {
  10294. var newData = new Uint8Array(data[0].length + data[1].length);
  10295. newData.set(data[0]);
  10296. newData.set(data[1], data[0].length);
  10297. data[0] = newData;
  10298. data.splice(1, 1);
  10299. }
  10300. // retrieve PTS/DTS from first fragment
  10301. frag = data[0];
  10302. pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];
  10303. if (pesPrefix === 1) {
  10304. pesLen = (frag[4] << 8) + frag[5];
  10305. // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated
  10306. // minus 6 : PES header size
  10307. if (pesLen && pesLen > stream.size - 6) {
  10308. return null;
  10309. }
  10310. pesFlags = frag[7];
  10311. if (pesFlags & 0xC0) {
  10312. /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  10313. as PTS / DTS is 33 bit we cannot use bitwise operator in JS,
  10314. as Bitwise operators treat their operands as a sequence of 32 bits */
  10315. pesPts = (frag[9] & 0x0E) * 536870912 + // 1 << 29
  10316. (frag[10] & 0xFF) * 4194304 + // 1 << 22
  10317. (frag[11] & 0xFE) * 16384 + // 1 << 14
  10318. (frag[12] & 0xFF) * 128 + // 1 << 7
  10319. (frag[13] & 0xFE) / 2;
  10320. // check if greater than 2^32 -1
  10321. if (pesPts > 4294967295) {
  10322. // decrement 2^33
  10323. pesPts -= 8589934592;
  10324. }
  10325. if (pesFlags & 0x40) {
  10326. pesDts = (frag[14] & 0x0E) * 536870912 + // 1 << 29
  10327. (frag[15] & 0xFF) * 4194304 + // 1 << 22
  10328. (frag[16] & 0xFE) * 16384 + // 1 << 14
  10329. (frag[17] & 0xFF) * 128 + // 1 << 7
  10330. (frag[18] & 0xFE) / 2;
  10331. // check if greater than 2^32 -1
  10332. if (pesDts > 4294967295) {
  10333. // decrement 2^33
  10334. pesDts -= 8589934592;
  10335. }
  10336. if (pesPts - pesDts > 60 * 90000) {
  10337. logger_1.logger.warn(Math.round((pesPts - pesDts) / 90000) + "s delta between PTS and DTS, align them");
  10338. pesPts = pesDts;
  10339. }
  10340. }
  10341. else {
  10342. pesDts = pesPts;
  10343. }
  10344. }
  10345. pesHdrLen = frag[8];
  10346. // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension
  10347. payloadStartOffset = pesHdrLen + 9;
  10348. stream.size -= payloadStartOffset;
  10349. // reassemble PES packet
  10350. pesData = new Uint8Array(stream.size);
  10351. for (var j = 0, dataLen = data.length; j < dataLen; j++) {
  10352. frag = data[j];
  10353. var len = frag.byteLength;
  10354. if (payloadStartOffset) {
  10355. if (payloadStartOffset > len) {
  10356. // trim full frag if PES header bigger than frag
  10357. payloadStartOffset -= len;
  10358. continue;
  10359. }
  10360. else {
  10361. // trim partial frag if PES header smaller than frag
  10362. frag = frag.subarray(payloadStartOffset);
  10363. len -= payloadStartOffset;
  10364. payloadStartOffset = 0;
  10365. }
  10366. }
  10367. pesData.set(frag, i);
  10368. i += len;
  10369. }
  10370. if (pesLen) {
  10371. // payload size : remove PES header + PES extension
  10372. pesLen -= pesHdrLen + 3;
  10373. }
  10374. return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };
  10375. }
  10376. else {
  10377. return null;
  10378. }
  10379. };
  10380. TSDemuxer.prototype.pushAccesUnit = function (avcSample, avcTrack) {
  10381. if (avcSample.units.length && avcSample.frame) {
  10382. var samples = avcTrack.samples;
  10383. var nbSamples = samples.length;
  10384. // only push AVC sample if starting with a keyframe is not mandatory OR
  10385. // if keyframe already found in this fragment OR
  10386. // keyframe found in last fragment (track.sps) AND
  10387. // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous
  10388. if (!this.config.forceKeyFrameOnDiscontinuity ||
  10389. avcSample.key === true ||
  10390. (avcTrack.sps && (nbSamples || this.contiguous))) {
  10391. avcSample.id = nbSamples;
  10392. samples.push(avcSample);
  10393. }
  10394. else {
  10395. // dropped samples, track it
  10396. avcTrack.dropped++;
  10397. }
  10398. }
  10399. if (avcSample.debug.length) {
  10400. logger_1.logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);
  10401. }
  10402. };
  10403. TSDemuxer.prototype._parseAVCPES = function (pes, last) {
  10404. var _this = this;
  10405. // logger.log('parse new PES');
  10406. var track = this._avcTrack, units = this._parseAVCNALu(pes.data), debug = false, expGolombDecoder, avcSample = this.avcSample, push, spsfound = false, i, pushAccesUnit = this.pushAccesUnit.bind(this), createAVCSample = function (key, pts, dts, debug) {
  10407. return { key: key, pts: pts, dts: dts, units: [], debug: debug };
  10408. };
  10409. // free pes.data to save up some memory
  10410. pes.data = null;
  10411. // if new NAL units found and last sample still there, let's push ...
  10412. // this helps parsing streams with missing AUD (only do this if AUD never found)
  10413. if (avcSample && units.length && !track.audFound) {
  10414. pushAccesUnit(avcSample, track);
  10415. avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');
  10416. }
  10417. units.forEach(function (unit) {
  10418. switch (unit.type) {
  10419. // NDR
  10420. case 1:
  10421. push = true;
  10422. if (!avcSample) {
  10423. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  10424. }
  10425. if (debug) {
  10426. avcSample.debug += 'NDR ';
  10427. }
  10428. avcSample.frame = true;
  10429. var data = unit.data;
  10430. // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)
  10431. if (spsfound && data.length > 4) {
  10432. // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR
  10433. var sliceType = new exp_golomb_1.default(data).readSliceType();
  10434. // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice
  10435. // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.
  10436. // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.
  10437. // I slice: A slice that is not an SI slice that is decoded using intra prediction only.
  10438. // if (sliceType === 2 || sliceType === 7) {
  10439. if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {
  10440. avcSample.key = true;
  10441. }
  10442. }
  10443. break;
  10444. // IDR
  10445. case 5:
  10446. push = true;
  10447. // handle PES not starting with AUD
  10448. if (!avcSample) {
  10449. avcSample = _this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');
  10450. }
  10451. if (debug) {
  10452. avcSample.debug += 'IDR ';
  10453. }
  10454. avcSample.key = true;
  10455. avcSample.frame = true;
  10456. break;
  10457. // SEI
  10458. case 6:
  10459. push = true;
  10460. if (debug && avcSample) {
  10461. avcSample.debug += 'SEI ';
  10462. }
  10463. expGolombDecoder = new exp_golomb_1.default(_this.discardEPB(unit.data));
  10464. // skip frameType
  10465. expGolombDecoder.readUByte();
  10466. var payloadType = 0;
  10467. var payloadSize = 0;
  10468. var endOfCaptions = false;
  10469. var b = 0;
  10470. while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {
  10471. payloadType = 0;
  10472. do {
  10473. b = expGolombDecoder.readUByte();
  10474. payloadType += b;
  10475. } while (b === 0xFF);
  10476. // Parse payload size.
  10477. payloadSize = 0;
  10478. do {
  10479. b = expGolombDecoder.readUByte();
  10480. payloadSize += b;
  10481. } while (b === 0xFF);
  10482. // TODO: there can be more than one payload in an SEI packet...
  10483. // TODO: need to read type and size in a while loop to get them all
  10484. if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {
  10485. endOfCaptions = true;
  10486. var countryCode = expGolombDecoder.readUByte();
  10487. if (countryCode === 181) {
  10488. var providerCode = expGolombDecoder.readUShort();
  10489. if (providerCode === 49) {
  10490. var userStructure = expGolombDecoder.readUInt();
  10491. if (userStructure === 0x47413934) {
  10492. var userDataType = expGolombDecoder.readUByte();
  10493. // Raw CEA-608 bytes wrapped in CEA-708 packet
  10494. if (userDataType === 3) {
  10495. var firstByte = expGolombDecoder.readUByte();
  10496. var secondByte = expGolombDecoder.readUByte();
  10497. var totalCCs = 31 & firstByte;
  10498. var byteArray = [firstByte, secondByte];
  10499. for (i = 0; i < totalCCs; i++) {
  10500. // 3 bytes per CC
  10501. byteArray.push(expGolombDecoder.readUByte());
  10502. byteArray.push(expGolombDecoder.readUByte());
  10503. byteArray.push(expGolombDecoder.readUByte());
  10504. }
  10505. _this._insertSampleInOrder(_this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });
  10506. }
  10507. }
  10508. }
  10509. }
  10510. }
  10511. else if (payloadSize < expGolombDecoder.bytesAvailable) {
  10512. for (i = 0; i < payloadSize; i++) {
  10513. expGolombDecoder.readUByte();
  10514. }
  10515. }
  10516. }
  10517. break;
  10518. // SPS
  10519. case 7:
  10520. push = true;
  10521. spsfound = true;
  10522. if (debug && avcSample) {
  10523. avcSample.debug += 'SPS ';
  10524. }
  10525. if (!track.sps) {
  10526. expGolombDecoder = new exp_golomb_1.default(unit.data);
  10527. var config = expGolombDecoder.readSPS();
  10528. track.width = config.width;
  10529. track.height = config.height;
  10530. track.pixelRatio = config.pixelRatio;
  10531. track.sps = [unit.data];
  10532. track.duration = _this._duration;
  10533. var codecarray = unit.data.subarray(1, 4);
  10534. var codecstring = 'avc1.';
  10535. for (i = 0; i < 3; i++) {
  10536. var h = codecarray[i].toString(16);
  10537. if (h.length < 2) {
  10538. h = '0' + h;
  10539. }
  10540. codecstring += h;
  10541. }
  10542. track.codec = codecstring;
  10543. }
  10544. break;
  10545. // PPS
  10546. case 8:
  10547. push = true;
  10548. if (debug && avcSample) {
  10549. avcSample.debug += 'PPS ';
  10550. }
  10551. if (!track.pps) {
  10552. track.pps = [unit.data];
  10553. }
  10554. break;
  10555. // AUD
  10556. case 9:
  10557. push = false;
  10558. track.audFound = true;
  10559. if (avcSample) {
  10560. pushAccesUnit(avcSample, track);
  10561. }
  10562. avcSample = _this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');
  10563. break;
  10564. // Filler Data
  10565. case 12:
  10566. push = false;
  10567. break;
  10568. default:
  10569. push = false;
  10570. if (avcSample) {
  10571. avcSample.debug += 'unknown NAL ' + unit.type + ' ';
  10572. }
  10573. break;
  10574. }
  10575. if (avcSample && push) {
  10576. var units_1 = avcSample.units;
  10577. units_1.push(unit);
  10578. }
  10579. });
  10580. // if last PES packet, push samples
  10581. if (last && avcSample) {
  10582. pushAccesUnit(avcSample, track);
  10583. this.avcSample = null;
  10584. }
  10585. };
  10586. TSDemuxer.prototype._insertSampleInOrder = function (arr, data) {
  10587. var len = arr.length;
  10588. if (len > 0) {
  10589. if (data.pts >= arr[len - 1].pts) {
  10590. arr.push(data);
  10591. }
  10592. else {
  10593. for (var pos = len - 1; pos >= 0; pos--) {
  10594. if (data.pts < arr[pos].pts) {
  10595. arr.splice(pos, 0, data);
  10596. break;
  10597. }
  10598. }
  10599. }
  10600. }
  10601. else {
  10602. arr.push(data);
  10603. }
  10604. };
  10605. TSDemuxer.prototype._getLastNalUnit = function () {
  10606. var avcSample = this.avcSample, lastUnit;
  10607. // try to fallback to previous sample if current one is empty
  10608. if (!avcSample || avcSample.units.length === 0) {
  10609. var track = this._avcTrack, samples = track.samples;
  10610. avcSample = samples[samples.length - 1];
  10611. }
  10612. if (avcSample) {
  10613. var units = avcSample.units;
  10614. lastUnit = units[units.length - 1];
  10615. }
  10616. return lastUnit;
  10617. };
  10618. TSDemuxer.prototype._parseAVCNALu = function (array) {
  10619. var i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;
  10620. var units = [], unit, unitType, lastUnitStart = -1, lastUnitType;
  10621. // logger.log('PES:' + Hex.hexDump(array));
  10622. if (state === -1) {
  10623. // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet
  10624. lastUnitStart = 0;
  10625. // NALu type is value read from offset 0
  10626. lastUnitType = array[0] & 0x1f;
  10627. state = 0;
  10628. i = 1;
  10629. }
  10630. while (i < len) {
  10631. value = array[i++];
  10632. // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case
  10633. if (!state) {
  10634. state = value ? 0 : 1;
  10635. continue;
  10636. }
  10637. if (state === 1) {
  10638. state = value ? 0 : 2;
  10639. continue;
  10640. }
  10641. // here we have state either equal to 2 or 3
  10642. if (!value) {
  10643. state = 3;
  10644. }
  10645. else if (value === 1) {
  10646. if (lastUnitStart >= 0) {
  10647. unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };
  10648. // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);
  10649. units.push(unit);
  10650. }
  10651. else {
  10652. // lastUnitStart is undefined => this is the first start code found in this PES packet
  10653. // first check if start code delimiter is overlapping between 2 PES packets,
  10654. // ie it started in last packet (lastState not zero)
  10655. // and ended at the beginning of this PES packet (i <= 4 - lastState)
  10656. var lastUnit = this._getLastNalUnit();
  10657. if (lastUnit) {
  10658. if (lastState && (i <= 4 - lastState)) {
  10659. // start delimiter overlapping between PES packets
  10660. // strip start delimiter bytes from the end of last NAL unit
  10661. // check if lastUnit had a state different from zero
  10662. if (lastUnit.state) {
  10663. // strip last bytes
  10664. lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);
  10665. }
  10666. }
  10667. // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.
  10668. overflow = i - state - 1;
  10669. if (overflow > 0) {
  10670. // logger.log('first NALU found with overflow:' + overflow);
  10671. var tmp = new Uint8Array(lastUnit.data.byteLength + overflow);
  10672. tmp.set(lastUnit.data, 0);
  10673. tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);
  10674. lastUnit.data = tmp;
  10675. }
  10676. }
  10677. }
  10678. // check if we can read unit type
  10679. if (i < len) {
  10680. unitType = array[i] & 0x1f;
  10681. // logger.log('find NALU @ offset:' + i + ',type:' + unitType);
  10682. lastUnitStart = i;
  10683. lastUnitType = unitType;
  10684. state = 0;
  10685. }
  10686. else {
  10687. // not enough byte to read unit type. let's read it on next PES parsing
  10688. state = -1;
  10689. }
  10690. }
  10691. else {
  10692. state = 0;
  10693. }
  10694. }
  10695. if (lastUnitStart >= 0 && state >= 0) {
  10696. unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };
  10697. units.push(unit);
  10698. // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);
  10699. }
  10700. // no NALu found
  10701. if (units.length === 0) {
  10702. // append pes.data to previous NAL unit
  10703. var lastUnit = this._getLastNalUnit();
  10704. if (lastUnit) {
  10705. var tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);
  10706. tmp.set(lastUnit.data, 0);
  10707. tmp.set(array, lastUnit.data.byteLength);
  10708. lastUnit.data = tmp;
  10709. }
  10710. }
  10711. track.naluState = state;
  10712. return units;
  10713. };
  10714. /**
  10715. * remove Emulation Prevention bytes from a RBSP
  10716. */
  10717. TSDemuxer.prototype.discardEPB = function (data) {
  10718. var length = data.byteLength, EPBPositions = [], i = 1, newLength, newData;
  10719. // Find all `Emulation Prevention Bytes`
  10720. while (i < length - 2) {
  10721. if (data[i] === 0 &&
  10722. data[i + 1] === 0 &&
  10723. data[i + 2] === 0x03) {
  10724. EPBPositions.push(i + 2);
  10725. i += 2;
  10726. }
  10727. else {
  10728. i++;
  10729. }
  10730. }
  10731. // If no Emulation Prevention Bytes were found just return the original
  10732. // array
  10733. if (EPBPositions.length === 0) {
  10734. return data;
  10735. }
  10736. // Create a new array to hold the NAL unit data
  10737. newLength = length - EPBPositions.length;
  10738. newData = new Uint8Array(newLength);
  10739. var sourceIndex = 0;
  10740. for (i = 0; i < newLength; sourceIndex++, i++) {
  10741. if (sourceIndex === EPBPositions[0]) {
  10742. // Skip this byte
  10743. sourceIndex++;
  10744. // Remove this position index
  10745. EPBPositions.shift();
  10746. }
  10747. newData[i] = data[sourceIndex];
  10748. }
  10749. return newData;
  10750. };
  10751. TSDemuxer.prototype._parseAACPES = function (pes) {
  10752. var track = this._audioTrack, data = pes.data, pts = pes.pts, startOffset = 0, aacOverFlow = this.aacOverFlow, aacLastPTS = this.aacLastPTS, frameDuration, frameIndex, offset, stamp, len;
  10753. if (aacOverFlow) {
  10754. var tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);
  10755. tmp.set(aacOverFlow, 0);
  10756. tmp.set(data, aacOverFlow.byteLength);
  10757. // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);
  10758. data = tmp;
  10759. }
  10760. // look for ADTS header (0xFFFx)
  10761. for (offset = startOffset, len = data.length; offset < len - 1; offset++) {
  10762. if (ADTS.isHeader(data, offset)) {
  10763. break;
  10764. }
  10765. }
  10766. // if ADTS header does not start straight from the beginning of the PES payload, raise an error
  10767. if (offset) {
  10768. var reason = void 0, fatal = void 0;
  10769. if (offset < len - 1) {
  10770. reason = "AAC PES did not start with ADTS header,offset:" + offset;
  10771. fatal = false;
  10772. }
  10773. else {
  10774. reason = 'no ADTS header found in AAC PES';
  10775. fatal = true;
  10776. }
  10777. logger_1.logger.warn("parsing error:" + reason);
  10778. this.observer.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });
  10779. if (fatal) {
  10780. return;
  10781. }
  10782. }
  10783. ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);
  10784. frameIndex = 0;
  10785. frameDuration = ADTS.getFrameDuration(track.samplerate);
  10786. // if last AAC frame is overflowing, we should ensure timestamps are contiguous:
  10787. // first sample PTS should be equal to last sample PTS + frameDuration
  10788. if (aacOverFlow && aacLastPTS) {
  10789. var newPTS = aacLastPTS + frameDuration;
  10790. if (Math.abs(newPTS - pts) > 1) {
  10791. logger_1.logger.log("AAC: align PTS for overlapping frames by " + Math.round((newPTS - pts) / 90));
  10792. pts = newPTS;
  10793. }
  10794. }
  10795. // scan for aac samples
  10796. while (offset < len) {
  10797. if (ADTS.isHeader(data, offset) && (offset + 5) < len) {
  10798. var frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);
  10799. if (frame) {
  10800. // logger.log(`${Math.round(frame.sample.pts)} : AAC`);
  10801. offset += frame.length;
  10802. stamp = frame.sample.pts;
  10803. frameIndex++;
  10804. }
  10805. else {
  10806. // logger.log('Unable to parse AAC frame');
  10807. break;
  10808. }
  10809. }
  10810. else {
  10811. // nothing found, keep looking
  10812. offset++;
  10813. }
  10814. }
  10815. if (offset < len) {
  10816. aacOverFlow = data.subarray(offset, len);
  10817. // logger.log(`AAC: overflow detected:${len-offset}`);
  10818. }
  10819. else {
  10820. aacOverFlow = null;
  10821. }
  10822. this.aacOverFlow = aacOverFlow;
  10823. this.aacLastPTS = stamp;
  10824. };
  10825. TSDemuxer.prototype._parseMPEGPES = function (pes) {
  10826. var data = pes.data;
  10827. var length = data.length;
  10828. var frameIndex = 0;
  10829. var offset = 0;
  10830. var pts = pes.pts;
  10831. while (offset < length) {
  10832. if (mpegaudio_1.default.isHeader(data, offset)) {
  10833. var frame = mpegaudio_1.default.appendFrame(this._audioTrack, data, offset, pts, frameIndex);
  10834. if (frame) {
  10835. offset += frame.length;
  10836. frameIndex++;
  10837. }
  10838. else {
  10839. // logger.log('Unable to parse Mpeg audio frame');
  10840. break;
  10841. }
  10842. }
  10843. else {
  10844. // nothing found, keep looking
  10845. offset++;
  10846. }
  10847. }
  10848. };
  10849. TSDemuxer.prototype._parseID3PES = function (pes) {
  10850. this._id3Track.samples.push(pes);
  10851. };
  10852. return TSDemuxer;
  10853. }());
  10854. exports.default = TSDemuxer;
  10855. /***/ }),
  10856. /***/ "./src/errors.js":
  10857. /*!***********************!*\
  10858. !*** ./src/errors.js ***!
  10859. \***********************/
  10860. /*! no static exports found */
  10861. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  10862. /***/ (function(module, exports, __webpack_require__) {
  10863. "use strict";
  10864. Object.defineProperty(exports, "__esModule", { value: true });
  10865. exports.ErrorTypes = {
  10866. // Identifier for a network error (loading error / timeout ...)
  10867. NETWORK_ERROR: 'networkError',
  10868. // Identifier for a media Error (video/parsing/mediasource error)
  10869. MEDIA_ERROR: 'mediaError',
  10870. // EME (encrypted media extensions) errors
  10871. KEY_SYSTEM_ERROR: 'keySystemError',
  10872. // Identifier for a mux Error (demuxing/remuxing)
  10873. MUX_ERROR: 'muxError',
  10874. // Identifier for all other errors
  10875. OTHER_ERROR: 'otherError'
  10876. };
  10877. /**
  10878. * @enum {ErrorDetails}
  10879. * @typedef {string} ErrorDetail
  10880. */
  10881. exports.ErrorDetails = {
  10882. KEY_SYSTEM_NO_KEYS: 'keySystemNoKeys',
  10883. KEY_SYSTEM_NO_ACCESS: 'keySystemNoAccess',
  10884. KEY_SYSTEM_NO_SESSION: 'keySystemNoSession',
  10885. KEY_SYSTEM_LICENSE_REQUEST_FAILED: 'keySystemLicenseRequestFailed',
  10886. // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  10887. MANIFEST_LOAD_ERROR: 'manifestLoadError',
  10888. // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  10889. MANIFEST_LOAD_TIMEOUT: 'manifestLoadTimeOut',
  10890. // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}
  10891. MANIFEST_PARSING_ERROR: 'manifestParsingError',
  10892. // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}
  10893. MANIFEST_INCOMPATIBLE_CODECS_ERROR: 'manifestIncompatibleCodecsError',
  10894. // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  10895. LEVEL_LOAD_ERROR: 'levelLoadError',
  10896. // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  10897. LEVEL_LOAD_TIMEOUT: 'levelLoadTimeOut',
  10898. // Identifier for a level switch error - data: { level : faulty level Id, event : error description}
  10899. LEVEL_SWITCH_ERROR: 'levelSwitchError',
  10900. // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}
  10901. AUDIO_TRACK_LOAD_ERROR: 'audioTrackLoadError',
  10902. // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}
  10903. AUDIO_TRACK_LOAD_TIMEOUT: 'audioTrackLoadTimeOut',
  10904. // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  10905. FRAG_LOAD_ERROR: 'fragLoadError',
  10906. // Identifier for fragment load timeout error - data: { frag : fragment object}
  10907. FRAG_LOAD_TIMEOUT: 'fragLoadTimeOut',
  10908. // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }
  10909. FRAG_DECRYPT_ERROR: 'fragDecryptError',
  10910. // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }
  10911. // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release
  10912. FRAG_PARSING_ERROR: 'fragParsingError',
  10913. // Identifier for a remux alloc error event - data: { id : demuxer Id, frag : fragment object, bytes : nb of bytes on which allocation failed , reason : error text }
  10914. REMUX_ALLOC_ERROR: 'remuxAllocError',
  10915. // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}
  10916. KEY_LOAD_ERROR: 'keyLoadError',
  10917. // Identifier for decrypt key load timeout error - data: { frag : fragment object}
  10918. KEY_LOAD_TIMEOUT: 'keyLoadTimeOut',
  10919. // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }
  10920. BUFFER_ADD_CODEC_ERROR: 'bufferAddCodecError',
  10921. // Identifier for a buffer append error - data: append error description
  10922. BUFFER_APPEND_ERROR: 'bufferAppendError',
  10923. // Identifier for a buffer appending error event - data: appending error description
  10924. BUFFER_APPENDING_ERROR: 'bufferAppendingError',
  10925. // Identifier for a buffer stalled error event
  10926. BUFFER_STALLED_ERROR: 'bufferStalledError',
  10927. // Identifier for a buffer full event
  10928. BUFFER_FULL_ERROR: 'bufferFullError',
  10929. // Identifier for a buffer seek over hole event
  10930. BUFFER_SEEK_OVER_HOLE: 'bufferSeekOverHole',
  10931. // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)
  10932. BUFFER_NUDGE_ON_STALL: 'bufferNudgeOnStall',
  10933. // Identifier for an internal exception happening inside hls.js while handling an event
  10934. INTERNAL_EXCEPTION: 'internalException'
  10935. };
  10936. /***/ }),
  10937. /***/ "./src/event-handler.js":
  10938. /*!******************************!*\
  10939. !*** ./src/event-handler.js ***!
  10940. \******************************/
  10941. /*! no static exports found */
  10942. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  10943. /***/ (function(module, exports, __webpack_require__) {
  10944. "use strict";
  10945. /*
  10946. *
  10947. * All objects in the event handling chain should inherit from this class
  10948. *
  10949. */
  10950. Object.defineProperty(exports, "__esModule", { value: true });
  10951. var logger_1 = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.js");
  10952. var errors_1 = __webpack_require__(/*! ./errors */ "./src/errors.js");
  10953. var events_1 = __webpack_require__(/*! ./events */ "./src/events.js");
  10954. var FORBIDDEN_EVENT_NAMES = {
  10955. 'hlsEventGeneric': true,
  10956. 'hlsHandlerDestroying': true,
  10957. 'hlsHandlerDestroyed': true
  10958. };
  10959. var EventHandler = /** @class */ (function () {
  10960. function EventHandler(hls) {
  10961. var events = [];
  10962. for (var _i = 1; _i < arguments.length; _i++) {
  10963. events[_i - 1] = arguments[_i];
  10964. }
  10965. this.hls = hls;
  10966. this.onEvent = this.onEvent.bind(this);
  10967. this.handledEvents = events;
  10968. this.useGenericHandler = true;
  10969. this.registerListeners();
  10970. }
  10971. EventHandler.prototype.destroy = function () {
  10972. this.onHandlerDestroying();
  10973. this.unregisterListeners();
  10974. this.onHandlerDestroyed();
  10975. };
  10976. EventHandler.prototype.onHandlerDestroying = function () { };
  10977. EventHandler.prototype.onHandlerDestroyed = function () { };
  10978. EventHandler.prototype.isEventHandler = function () {
  10979. return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';
  10980. };
  10981. EventHandler.prototype.registerListeners = function () {
  10982. if (this.isEventHandler()) {
  10983. this.handledEvents.forEach(function (event) {
  10984. if (FORBIDDEN_EVENT_NAMES[event]) {
  10985. throw new Error('Forbidden event-name: ' + event);
  10986. }
  10987. this.hls.on(event, this.onEvent);
  10988. }, this);
  10989. }
  10990. };
  10991. EventHandler.prototype.unregisterListeners = function () {
  10992. if (this.isEventHandler()) {
  10993. this.handledEvents.forEach(function (event) {
  10994. this.hls.off(event, this.onEvent);
  10995. }, this);
  10996. }
  10997. };
  10998. /**
  10999. * arguments: event (string), data (any)
  11000. */
  11001. EventHandler.prototype.onEvent = function (event, data) {
  11002. this.onEventGeneric(event, data);
  11003. };
  11004. EventHandler.prototype.onEventGeneric = function (event, data) {
  11005. var eventToFunction = function (event, data) {
  11006. var funcName = 'on' + event.replace('hls', '');
  11007. if (typeof this[funcName] !== 'function') {
  11008. throw new Error("Event " + event + " has no generic handler in this " + this.constructor.name + " class (tried " + funcName + ")");
  11009. }
  11010. return this[funcName].bind(this, data);
  11011. };
  11012. try {
  11013. eventToFunction.call(this, event, data).call();
  11014. }
  11015. catch (err) {
  11016. logger_1.logger.error("An internal error happened while handling event " + event + ". Error message: \"" + err.message + "\". Here is a stacktrace:", err);
  11017. this.hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.OTHER_ERROR, details: errors_1.ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });
  11018. }
  11019. };
  11020. return EventHandler;
  11021. }());
  11022. exports.default = EventHandler;
  11023. /***/ }),
  11024. /***/ "./src/events.js":
  11025. /*!***********************!*\
  11026. !*** ./src/events.js ***!
  11027. \***********************/
  11028. /*! no static exports found */
  11029. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  11030. /***/ (function(module, exports, __webpack_require__) {
  11031. "use strict";
  11032. Object.defineProperty(exports, "__esModule", { value: true });
  11033. /**
  11034. * @readonly
  11035. * @enum {string}
  11036. */
  11037. var HlsEvents = {
  11038. // fired before MediaSource is attaching to media element - data: { media }
  11039. MEDIA_ATTACHING: 'hlsMediaAttaching',
  11040. // fired when MediaSource has been succesfully attached to media element - data: { }
  11041. MEDIA_ATTACHED: 'hlsMediaAttached',
  11042. // fired before detaching MediaSource from media element - data: { }
  11043. MEDIA_DETACHING: 'hlsMediaDetaching',
  11044. // fired when MediaSource has been detached from media element - data: { }
  11045. MEDIA_DETACHED: 'hlsMediaDetached',
  11046. // fired when we buffer is going to be reset - data: { }
  11047. BUFFER_RESET: 'hlsBufferReset',
  11048. // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}
  11049. BUFFER_CODECS: 'hlsBufferCodecs',
  11050. // fired when sourcebuffers have been created - data: { tracks : tracks }
  11051. BUFFER_CREATED: 'hlsBufferCreated',
  11052. // fired when we append a segment to the buffer - data: { segment: segment object }
  11053. BUFFER_APPENDING: 'hlsBufferAppending',
  11054. // fired when we are done with appending a media segment to the buffer - data : { parent : segment parent that triggered BUFFER_APPENDING, pending : nb of segments waiting for appending for this segment parent}
  11055. BUFFER_APPENDED: 'hlsBufferAppended',
  11056. // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }
  11057. BUFFER_EOS: 'hlsBufferEos',
  11058. // fired when the media buffer should be flushed - data { startOffset, endOffset }
  11059. BUFFER_FLUSHING: 'hlsBufferFlushing',
  11060. // fired when the media buffer has been flushed - data: { }
  11061. BUFFER_FLUSHED: 'hlsBufferFlushed',
  11062. // fired to signal that a manifest loading starts - data: { url : manifestURL}
  11063. MANIFEST_LOADING: 'hlsManifestLoading',
  11064. // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}
  11065. MANIFEST_LOADED: 'hlsManifestLoaded',
  11066. // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}
  11067. MANIFEST_PARSED: 'hlsManifestParsed',
  11068. // fired when a level switch is requested - data: { level : id of new level }
  11069. LEVEL_SWITCHING: 'hlsLevelSwitching',
  11070. // fired when a level switch is effective - data: { level : id of new level }
  11071. LEVEL_SWITCHED: 'hlsLevelSwitched',
  11072. // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}
  11073. LEVEL_LOADING: 'hlsLevelLoading',
  11074. // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }
  11075. LEVEL_LOADED: 'hlsLevelLoaded',
  11076. // fired when a level's details have been updated based on previous details, after it has been loaded - data: { details : levelDetails object, level : id of updated level }
  11077. LEVEL_UPDATED: 'hlsLevelUpdated',
  11078. // fired when a level's PTS information has been updated after parsing a fragment - data: { details : levelDetails object, level : id of updated level, drift: PTS drift observed when parsing last fragment }
  11079. LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',
  11080. // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }
  11081. AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',
  11082. // fired when an audio track switching is requested - data: { id : audio track id }
  11083. AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',
  11084. // fired when an audio track switch actually occurs - data: { id : audio track id }
  11085. AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',
  11086. // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }
  11087. AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',
  11088. // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }
  11089. AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',
  11090. // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }
  11091. SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',
  11092. // fired when an subtitle track switch occurs - data: { id : subtitle track id }
  11093. SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',
  11094. // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }
  11095. SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',
  11096. // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }
  11097. SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',
  11098. // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }
  11099. SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',
  11100. // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }
  11101. INIT_PTS_FOUND: 'hlsInitPtsFound',
  11102. // fired when a fragment loading starts - data: { frag : fragment object }
  11103. FRAG_LOADING: 'hlsFragLoading',
  11104. // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }
  11105. FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',
  11106. // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }
  11107. FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',
  11108. // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }
  11109. FRAG_LOADED: 'hlsFragLoaded',
  11110. // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }
  11111. FRAG_DECRYPTED: 'hlsFragDecrypted',
  11112. // fired when Init Segment has been extracted from fragment - data: { id : demuxer id, frag: fragment object, moov : moov MP4 box, codecs : codecs found while parsing fragment }
  11113. FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',
  11114. // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }
  11115. FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',
  11116. // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }
  11117. FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',
  11118. // fired when data have been extracted from fragment - data: { id : demuxer id, frag: fragment object, data1 : moof MP4 box or TS fragments, data2 : mdat MP4 box or null}
  11119. FRAG_PARSING_DATA: 'hlsFragParsingData',
  11120. // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }
  11121. FRAG_PARSED: 'hlsFragParsed',
  11122. // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : { trequest, tfirst, tload, tparsed, tbuffered, length, bwEstimate } }
  11123. FRAG_BUFFERED: 'hlsFragBuffered',
  11124. // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }
  11125. FRAG_CHANGED: 'hlsFragChanged',
  11126. // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }
  11127. FPS_DROP: 'hlsFpsDrop',
  11128. // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }
  11129. FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',
  11130. // Identifier for an error event - data: { type : error type, details : error details, fatal : if true, hls.js cannot/will not try to recover, if false, hls.js will try to recover,other error specific data }
  11131. ERROR: 'hlsError',
  11132. // fired when hls.js instance starts destroying. Different from MEDIA_DETACHED as one could want to detach and reattach a media to the instance of hls.js to handle mid-rolls for example - data: { }
  11133. DESTROYING: 'hlsDestroying',
  11134. // fired when a decrypt key loading starts - data: { frag : fragment object }
  11135. KEY_LOADING: 'hlsKeyLoading',
  11136. // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }
  11137. KEY_LOADED: 'hlsKeyLoaded',
  11138. // fired upon stream controller state transitions - data: { previousState, nextState }
  11139. STREAM_STATE_TRANSITION: 'hlsStreamStateTransition'
  11140. };
  11141. exports.default = HlsEvents;
  11142. /***/ }),
  11143. /***/ "./src/hls.js":
  11144. /*!********************!*\
  11145. !*** ./src/hls.js ***!
  11146. \********************/
  11147. /*! no static exports found */
  11148. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  11149. /***/ (function(module, exports, __webpack_require__) {
  11150. "use strict";
  11151. var __extends = (this && this.__extends) || (function () {
  11152. var extendStatics = Object.setPrototypeOf ||
  11153. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  11154. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11155. return function (d, b) {
  11156. extendStatics(d, b);
  11157. function __() { this.constructor = d; }
  11158. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11159. };
  11160. })();
  11161. Object.defineProperty(exports, "__esModule", { value: true });
  11162. var URLToolkit = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
  11163. var errors_1 = __webpack_require__(/*! ./errors */ "./src/errors.js");
  11164. var playlist_loader_1 = __webpack_require__(/*! ./loader/playlist-loader */ "./src/loader/playlist-loader.js");
  11165. var fragment_loader_1 = __webpack_require__(/*! ./loader/fragment-loader */ "./src/loader/fragment-loader.js");
  11166. var key_loader_1 = __webpack_require__(/*! ./loader/key-loader */ "./src/loader/key-loader.js");
  11167. var fragment_tracker_1 = __webpack_require__(/*! ./controller/fragment-tracker */ "./src/controller/fragment-tracker.js");
  11168. var stream_controller_1 = __webpack_require__(/*! ./controller/stream-controller */ "./src/controller/stream-controller.js");
  11169. var level_controller_1 = __webpack_require__(/*! ./controller/level-controller */ "./src/controller/level-controller.js");
  11170. var id3_track_controller_1 = __webpack_require__(/*! ./controller/id3-track-controller */ "./src/controller/id3-track-controller.js");
  11171. var is_supported_1 = __webpack_require__(/*! ./is-supported */ "./src/is-supported.js");
  11172. var logger_1 = __webpack_require__(/*! ./utils/logger */ "./src/utils/logger.js");
  11173. var config_1 = __webpack_require__(/*! ./config */ "./src/config.js");
  11174. var events_1 = __webpack_require__(/*! ./events */ "./src/events.js");
  11175. var observer_1 = __webpack_require__(/*! ./observer */ "./src/observer.js");
  11176. /**
  11177. * @module Hls
  11178. * @class
  11179. * @constructor
  11180. */
  11181. var Hls = /** @class */ (function (_super) {
  11182. __extends(Hls, _super);
  11183. /**
  11184. * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.
  11185. *
  11186. * @constructs Hls
  11187. * @param {HlsConfig} config
  11188. */
  11189. function Hls(config) {
  11190. if (config === void 0) { config = {}; }
  11191. var _this = _super.call(this) || this;
  11192. var defaultConfig = Hls.DefaultConfig;
  11193. if ((config.liveSyncDurationCount || config.liveMaxLatencyDurationCount) && (config.liveSyncDuration || config.liveMaxLatencyDuration)) {
  11194. throw new Error('Illegal hls.js config: don\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');
  11195. }
  11196. for (var prop in defaultConfig) {
  11197. if (prop in config)
  11198. continue;
  11199. config[prop] = defaultConfig[prop];
  11200. }
  11201. if (config.liveMaxLatencyDurationCount !== undefined && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {
  11202. throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be gt "liveSyncDurationCount"');
  11203. }
  11204. if (config.liveMaxLatencyDuration !== undefined && (config.liveMaxLatencyDuration <= config.liveSyncDuration || config.liveSyncDuration === undefined)) {
  11205. throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be gt "liveSyncDuration"');
  11206. }
  11207. logger_1.enableLogs(config.debug);
  11208. _this.config = config;
  11209. _this._autoLevelCapping = -1;
  11210. // core controllers and network loaders
  11211. /**
  11212. * @member {AbrController} abrController
  11213. */
  11214. var abrController = _this.abrController = new config.abrController(_this);
  11215. var bufferController = new config.bufferController(_this);
  11216. var capLevelController = new config.capLevelController(_this);
  11217. var fpsController = new config.fpsController(_this);
  11218. var playListLoader = new playlist_loader_1.default(_this);
  11219. var fragmentLoader = new fragment_loader_1.default(_this);
  11220. var keyLoader = new key_loader_1.default(_this);
  11221. var id3TrackController = new id3_track_controller_1.default(_this);
  11222. // network controllers
  11223. /**
  11224. * @member {LevelController} levelController
  11225. */
  11226. var levelController = _this.levelController = new level_controller_1.default(_this);
  11227. // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important
  11228. var fragmentTracker = new fragment_tracker_1.FragmentTracker(_this);
  11229. /**
  11230. * @member {StreamController} streamController
  11231. */
  11232. var streamController = _this.streamController = new stream_controller_1.default(_this, fragmentTracker);
  11233. var networkControllers = [levelController, streamController];
  11234. // optional audio stream controller
  11235. /**
  11236. * @var {ICoreComponent | Controller}
  11237. */
  11238. var Controller = config.audioStreamController;
  11239. if (Controller) {
  11240. networkControllers.push(new Controller(_this, fragmentTracker));
  11241. }
  11242. /**
  11243. * @member {INetworkController[]} networkControllers
  11244. */
  11245. _this.networkControllers = networkControllers;
  11246. /**
  11247. * @var {ICoreComponent[]}
  11248. */
  11249. var coreComponents = [
  11250. playListLoader,
  11251. fragmentLoader,
  11252. keyLoader,
  11253. abrController,
  11254. bufferController,
  11255. capLevelController,
  11256. fpsController,
  11257. id3TrackController,
  11258. fragmentTracker
  11259. ];
  11260. // optional audio track and subtitle controller
  11261. Controller = config.audioTrackController;
  11262. if (Controller) {
  11263. var audioTrackController = new Controller(_this);
  11264. /**
  11265. * @member {AudioTrackController} audioTrackController
  11266. */
  11267. _this.audioTrackController = audioTrackController;
  11268. coreComponents.push(audioTrackController);
  11269. }
  11270. Controller = config.subtitleTrackController;
  11271. if (Controller) {
  11272. var subtitleTrackController = new Controller(_this);
  11273. /**
  11274. * @member {SubtitleTrackController} subtitleTrackController
  11275. */
  11276. _this.subtitleTrackController = subtitleTrackController;
  11277. networkControllers.push(subtitleTrackController);
  11278. }
  11279. Controller = config.emeController;
  11280. if (Controller) {
  11281. var emeController = new Controller(_this);
  11282. /**
  11283. * @member {EMEController} emeController
  11284. */
  11285. _this.emeController = emeController;
  11286. coreComponents.push(emeController);
  11287. }
  11288. // optional subtitle controllers
  11289. Controller = config.subtitleStreamController;
  11290. if (Controller) {
  11291. networkControllers.push(new Controller(_this, fragmentTracker));
  11292. }
  11293. Controller = config.timelineController;
  11294. if (Controller) {
  11295. coreComponents.push(new Controller(_this));
  11296. }
  11297. /**
  11298. * @member {ICoreComponent[]}
  11299. */
  11300. _this.coreComponents = coreComponents;
  11301. return _this;
  11302. }
  11303. Object.defineProperty(Hls, "version", {
  11304. /**
  11305. * @type {string}
  11306. */
  11307. get: function () {
  11308. return "0.12.4";
  11309. },
  11310. enumerable: true,
  11311. configurable: true
  11312. });
  11313. /**
  11314. * @type {boolean}
  11315. */
  11316. Hls.isSupported = function () {
  11317. return is_supported_1.isSupported();
  11318. };
  11319. Object.defineProperty(Hls, "Events", {
  11320. /**
  11321. * @type {HlsEvents}
  11322. */
  11323. get: function () {
  11324. return events_1.default;
  11325. },
  11326. enumerable: true,
  11327. configurable: true
  11328. });
  11329. Object.defineProperty(Hls, "ErrorTypes", {
  11330. /**
  11331. * @type {HlsErrorTypes}
  11332. */
  11333. get: function () {
  11334. return errors_1.ErrorTypes;
  11335. },
  11336. enumerable: true,
  11337. configurable: true
  11338. });
  11339. Object.defineProperty(Hls, "ErrorDetails", {
  11340. /**
  11341. * @type {HlsErrorDetails}
  11342. */
  11343. get: function () {
  11344. return errors_1.ErrorDetails;
  11345. },
  11346. enumerable: true,
  11347. configurable: true
  11348. });
  11349. Object.defineProperty(Hls, "DefaultConfig", {
  11350. /**
  11351. * @type {HlsConfig}
  11352. */
  11353. get: function () {
  11354. if (!Hls.defaultConfig) {
  11355. return config_1.hlsDefaultConfig;
  11356. }
  11357. return Hls.defaultConfig;
  11358. },
  11359. /**
  11360. * @type {HlsConfig}
  11361. */
  11362. set: function (defaultConfig) {
  11363. Hls.defaultConfig = defaultConfig;
  11364. },
  11365. enumerable: true,
  11366. configurable: true
  11367. });
  11368. /**
  11369. * Dispose of the instance
  11370. */
  11371. Hls.prototype.destroy = function () {
  11372. logger_1.logger.log('destroy');
  11373. this.trigger(events_1.default.DESTROYING);
  11374. this.detachMedia();
  11375. this.coreComponents.concat(this.networkControllers).forEach(function (component) {
  11376. component.destroy();
  11377. });
  11378. this.url = null;
  11379. this.removeAllListeners();
  11380. this._autoLevelCapping = -1;
  11381. };
  11382. /**
  11383. * Attach a media element
  11384. * @param {HTMLMediaElement} media
  11385. */
  11386. Hls.prototype.attachMedia = function (media) {
  11387. logger_1.logger.log('attachMedia');
  11388. this.media = media;
  11389. this.trigger(events_1.default.MEDIA_ATTACHING, { media: media });
  11390. };
  11391. /**
  11392. * Detach from the media
  11393. */
  11394. Hls.prototype.detachMedia = function () {
  11395. logger_1.logger.log('detachMedia');
  11396. this.trigger(events_1.default.MEDIA_DETACHING);
  11397. this.media = null;
  11398. };
  11399. /**
  11400. * Set the source URL. Can be relative or absolute.
  11401. * @param {string} url
  11402. */
  11403. Hls.prototype.loadSource = function (url) {
  11404. url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });
  11405. logger_1.logger.log("loadSource:" + url);
  11406. this.url = url;
  11407. // when attaching to a source URL, trigger a playlist load
  11408. this.trigger(events_1.default.MANIFEST_LOADING, { url: url });
  11409. };
  11410. /**
  11411. * Start loading data from the stream source.
  11412. * Depending on default config, client starts loading automatically when a source is set.
  11413. *
  11414. * @param {number} startPosition Set the start position to stream from
  11415. * @default -1 None (from earliest point)
  11416. */
  11417. Hls.prototype.startLoad = function (startPosition) {
  11418. if (startPosition === void 0) { startPosition = -1; }
  11419. logger_1.logger.log("startLoad(" + startPosition + ")");
  11420. this.networkControllers.forEach(function (controller) {
  11421. controller.startLoad(startPosition);
  11422. });
  11423. };
  11424. /**
  11425. * Stop loading of any stream data.
  11426. */
  11427. Hls.prototype.stopLoad = function () {
  11428. logger_1.logger.log('stopLoad');
  11429. this.networkControllers.forEach(function (controller) {
  11430. controller.stopLoad();
  11431. });
  11432. };
  11433. /**
  11434. * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)
  11435. */
  11436. Hls.prototype.swapAudioCodec = function () {
  11437. logger_1.logger.log('swapAudioCodec');
  11438. this.streamController.swapAudioCodec();
  11439. };
  11440. /**
  11441. * When the media-element fails, this allows to detach and then re-attach it
  11442. * as one call (convenience method).
  11443. *
  11444. * Automatic recovery of media-errors by this process is configurable.
  11445. */
  11446. Hls.prototype.recoverMediaError = function () {
  11447. logger_1.logger.log('recoverMediaError');
  11448. var media = this.media;
  11449. this.detachMedia();
  11450. this.attachMedia(media);
  11451. };
  11452. Object.defineProperty(Hls.prototype, "levels", {
  11453. /**
  11454. * @type {QualityLevel[]}
  11455. */
  11456. get: function () {
  11457. return this.levelController.levels;
  11458. },
  11459. enumerable: true,
  11460. configurable: true
  11461. });
  11462. Object.defineProperty(Hls.prototype, "currentLevel", {
  11463. /**
  11464. * Index of quality level currently played
  11465. * @type {number}
  11466. */
  11467. get: function () {
  11468. return this.streamController.currentLevel;
  11469. },
  11470. /**
  11471. * Set quality level index immediately .
  11472. * This will flush the current buffer to replace the quality asap.
  11473. * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.
  11474. * @type {number} -1 for automatic level selection
  11475. */
  11476. set: function (newLevel) {
  11477. logger_1.logger.log("set currentLevel:" + newLevel);
  11478. this.loadLevel = newLevel;
  11479. this.streamController.immediateLevelSwitch();
  11480. },
  11481. enumerable: true,
  11482. configurable: true
  11483. });
  11484. Object.defineProperty(Hls.prototype, "nextLevel", {
  11485. /**
  11486. * Index of next quality level loaded as scheduled by stream controller.
  11487. * @type {number}
  11488. */
  11489. get: function () {
  11490. return this.streamController.nextLevel;
  11491. },
  11492. /**
  11493. * Set quality level index for next loaded data.
  11494. * This will switch the video quality asap, without interrupting playback.
  11495. * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).
  11496. * @type {number} -1 for automatic level selection
  11497. */
  11498. set: function (newLevel) {
  11499. logger_1.logger.log("set nextLevel:" + newLevel);
  11500. this.levelController.manualLevel = newLevel;
  11501. this.streamController.nextLevelSwitch();
  11502. },
  11503. enumerable: true,
  11504. configurable: true
  11505. });
  11506. Object.defineProperty(Hls.prototype, "loadLevel", {
  11507. /**
  11508. * Return the quality level of the currently or last (of none is loaded currently) segment
  11509. * @type {number}
  11510. */
  11511. get: function () {
  11512. return this.levelController.level;
  11513. },
  11514. /**
  11515. * Set quality level index for next loaded data in a conservative way.
  11516. * This will switch the quality without flushing, but interrupt current loading.
  11517. * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.
  11518. * @type {number} newLevel -1 for automatic level selection
  11519. */
  11520. set: function (newLevel) {
  11521. logger_1.logger.log("set loadLevel:" + newLevel);
  11522. this.levelController.manualLevel = newLevel;
  11523. },
  11524. enumerable: true,
  11525. configurable: true
  11526. });
  11527. Object.defineProperty(Hls.prototype, "nextLoadLevel", {
  11528. /**
  11529. * get next quality level loaded
  11530. * @type {number}
  11531. */
  11532. get: function () {
  11533. return this.levelController.nextLoadLevel;
  11534. },
  11535. /**
  11536. * Set quality level of next loaded segment in a fully "non-destructive" way.
  11537. * Same as `loadLevel` but will wait for next switch (until current loading is done).
  11538. * @type {number} level
  11539. */
  11540. set: function (level) {
  11541. this.levelController.nextLoadLevel = level;
  11542. },
  11543. enumerable: true,
  11544. configurable: true
  11545. });
  11546. Object.defineProperty(Hls.prototype, "firstLevel", {
  11547. /**
  11548. * Return "first level": like a default level, if not set,
  11549. * falls back to index of first level referenced in manifest
  11550. * @type {number}
  11551. */
  11552. get: function () {
  11553. return Math.max(this.levelController.firstLevel, this.minAutoLevel);
  11554. },
  11555. /**
  11556. * Sets "first-level", see getter.
  11557. * @type {number}
  11558. */
  11559. set: function (newLevel) {
  11560. logger_1.logger.log("set firstLevel:" + newLevel);
  11561. this.levelController.firstLevel = newLevel;
  11562. },
  11563. enumerable: true,
  11564. configurable: true
  11565. });
  11566. Object.defineProperty(Hls.prototype, "startLevel", {
  11567. /**
  11568. * Return start level (level of first fragment that will be played back)
  11569. * if not overrided by user, first level appearing in manifest will be used as start level
  11570. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  11571. * (determined from download of first segment)
  11572. * @type {number}
  11573. */
  11574. get: function () {
  11575. return this.levelController.startLevel;
  11576. },
  11577. /**
  11578. * set start level (level of first fragment that will be played back)
  11579. * if not overrided by user, first level appearing in manifest will be used as start level
  11580. * if -1 : automatic start level selection, playback will start from level matching download bandwidth
  11581. * (determined from download of first segment)
  11582. * @type {number} newLevel
  11583. */
  11584. set: function (newLevel) {
  11585. logger_1.logger.log("set startLevel:" + newLevel);
  11586. var hls = this;
  11587. // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel
  11588. if (newLevel !== -1) {
  11589. newLevel = Math.max(newLevel, hls.minAutoLevel);
  11590. }
  11591. hls.levelController.startLevel = newLevel;
  11592. },
  11593. enumerable: true,
  11594. configurable: true
  11595. });
  11596. Object.defineProperty(Hls.prototype, "autoLevelCapping", {
  11597. /**
  11598. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  11599. * @type {number}
  11600. */
  11601. get: function () {
  11602. return this._autoLevelCapping;
  11603. },
  11604. /**
  11605. * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)
  11606. * @type {number}
  11607. */
  11608. set: function (newLevel) {
  11609. logger_1.logger.log("set autoLevelCapping:" + newLevel);
  11610. this._autoLevelCapping = newLevel;
  11611. },
  11612. enumerable: true,
  11613. configurable: true
  11614. });
  11615. Object.defineProperty(Hls.prototype, "autoLevelEnabled", {
  11616. /**
  11617. * True when automatic level selection enabled
  11618. * @type {boolean}
  11619. */
  11620. get: function () {
  11621. return (this.levelController.manualLevel === -1);
  11622. },
  11623. enumerable: true,
  11624. configurable: true
  11625. });
  11626. Object.defineProperty(Hls.prototype, "manualLevel", {
  11627. /**
  11628. * Level set manually (if any)
  11629. * @type {number}
  11630. */
  11631. get: function () {
  11632. return this.levelController.manualLevel;
  11633. },
  11634. enumerable: true,
  11635. configurable: true
  11636. });
  11637. Object.defineProperty(Hls.prototype, "minAutoLevel", {
  11638. /**
  11639. * min level selectable in auto mode according to config.minAutoBitrate
  11640. * @type {number}
  11641. */
  11642. get: function () {
  11643. var hls = this, levels = hls.levels, minAutoBitrate = hls.config.minAutoBitrate, len = levels ? levels.length : 0;
  11644. for (var i = 0; i < len; i++) {
  11645. var levelNextBitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;
  11646. if (levelNextBitrate > minAutoBitrate) {
  11647. return i;
  11648. }
  11649. }
  11650. return 0;
  11651. },
  11652. enumerable: true,
  11653. configurable: true
  11654. });
  11655. Object.defineProperty(Hls.prototype, "maxAutoLevel", {
  11656. /**
  11657. * max level selectable in auto mode according to autoLevelCapping
  11658. * @type {number}
  11659. */
  11660. get: function () {
  11661. var hls = this;
  11662. var levels = hls.levels;
  11663. var autoLevelCapping = hls.autoLevelCapping;
  11664. var maxAutoLevel;
  11665. if (autoLevelCapping === -1 && levels && levels.length) {
  11666. maxAutoLevel = levels.length - 1;
  11667. }
  11668. else {
  11669. maxAutoLevel = autoLevelCapping;
  11670. }
  11671. return maxAutoLevel;
  11672. },
  11673. enumerable: true,
  11674. configurable: true
  11675. });
  11676. Object.defineProperty(Hls.prototype, "nextAutoLevel", {
  11677. /**
  11678. * next automatically selected quality level
  11679. * @type {number}
  11680. */
  11681. get: function () {
  11682. var hls = this;
  11683. // ensure next auto level is between min and max auto level
  11684. return Math.min(Math.max(hls.abrController.nextAutoLevel, hls.minAutoLevel), hls.maxAutoLevel);
  11685. },
  11686. /**
  11687. * this setter is used to force next auto level.
  11688. * this is useful to force a switch down in auto mode:
  11689. * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)
  11690. * forced value is valid for one fragment. upon succesful frag loading at forced level,
  11691. * this value will be resetted to -1 by ABR controller.
  11692. * @type {number}
  11693. */
  11694. set: function (nextLevel) {
  11695. var hls = this;
  11696. hls.abrController.nextAutoLevel = Math.max(hls.minAutoLevel, nextLevel);
  11697. },
  11698. enumerable: true,
  11699. configurable: true
  11700. });
  11701. Object.defineProperty(Hls.prototype, "audioTracks", {
  11702. /**
  11703. * @type {AudioTrack[]}
  11704. */
  11705. get: function () {
  11706. var audioTrackController = this.audioTrackController;
  11707. return audioTrackController ? audioTrackController.audioTracks : [];
  11708. },
  11709. enumerable: true,
  11710. configurable: true
  11711. });
  11712. Object.defineProperty(Hls.prototype, "audioTrack", {
  11713. /**
  11714. * index of the selected audio track (index in audio track lists)
  11715. * @type {number}
  11716. */
  11717. get: function () {
  11718. var audioTrackController = this.audioTrackController;
  11719. return audioTrackController ? audioTrackController.audioTrack : -1;
  11720. },
  11721. /**
  11722. * selects an audio track, based on its index in audio track lists
  11723. * @type {number}
  11724. */
  11725. set: function (audioTrackId) {
  11726. var audioTrackController = this.audioTrackController;
  11727. if (audioTrackController) {
  11728. audioTrackController.audioTrack = audioTrackId;
  11729. }
  11730. },
  11731. enumerable: true,
  11732. configurable: true
  11733. });
  11734. Object.defineProperty(Hls.prototype, "liveSyncPosition", {
  11735. /**
  11736. * @type {Seconds}
  11737. */
  11738. get: function () {
  11739. return this.streamController.liveSyncPosition;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(Hls.prototype, "subtitleTracks", {
  11745. /**
  11746. * get alternate subtitle tracks list from playlist
  11747. * @type {SubtitleTrack[]}
  11748. */
  11749. get: function () {
  11750. var subtitleTrackController = this.subtitleTrackController;
  11751. return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];
  11752. },
  11753. enumerable: true,
  11754. configurable: true
  11755. });
  11756. Object.defineProperty(Hls.prototype, "subtitleTrack", {
  11757. /**
  11758. * index of the selected subtitle track (index in subtitle track lists)
  11759. * @type {number}
  11760. */
  11761. get: function () {
  11762. var subtitleTrackController = this.subtitleTrackController;
  11763. return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;
  11764. },
  11765. /**
  11766. * select an subtitle track, based on its index in subtitle track lists
  11767. * @type{number}
  11768. */
  11769. set: function (subtitleTrackId) {
  11770. var subtitleTrackController = this.subtitleTrackController;
  11771. if (subtitleTrackController) {
  11772. subtitleTrackController.subtitleTrack = subtitleTrackId;
  11773. }
  11774. },
  11775. enumerable: true,
  11776. configurable: true
  11777. });
  11778. Object.defineProperty(Hls.prototype, "subtitleDisplay", {
  11779. /**
  11780. * @type {boolean}
  11781. */
  11782. get: function () {
  11783. var subtitleTrackController = this.subtitleTrackController;
  11784. return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;
  11785. },
  11786. /**
  11787. * Enable/disable subtitle display rendering
  11788. * @type {boolean}
  11789. */
  11790. set: function (value) {
  11791. var subtitleTrackController = this.subtitleTrackController;
  11792. if (subtitleTrackController) {
  11793. subtitleTrackController.subtitleDisplay = value;
  11794. }
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. return Hls;
  11800. }(observer_1.Observer));
  11801. exports.default = Hls;
  11802. /***/ }),
  11803. /***/ "./src/is-supported.js":
  11804. /*!*****************************!*\
  11805. !*** ./src/is-supported.js ***!
  11806. \*****************************/
  11807. /*! no static exports found */
  11808. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  11809. /***/ (function(module, exports, __webpack_require__) {
  11810. "use strict";
  11811. Object.defineProperty(exports, "__esModule", { value: true });
  11812. var mediasource_helper_1 = __webpack_require__(/*! ./utils/mediasource-helper */ "./src/utils/mediasource-helper.js");
  11813. function isSupported() {
  11814. var mediaSource = mediasource_helper_1.getMediaSource();
  11815. var sourceBuffer = window.SourceBuffer || window.WebKitSourceBuffer;
  11816. var isTypeSupported = mediaSource &&
  11817. typeof mediaSource.isTypeSupported === 'function' &&
  11818. mediaSource.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"');
  11819. // if SourceBuffer is exposed ensure its API is valid
  11820. // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible
  11821. var sourceBufferValidAPI = !sourceBuffer ||
  11822. (sourceBuffer.prototype &&
  11823. typeof sourceBuffer.prototype.appendBuffer === 'function' &&
  11824. typeof sourceBuffer.prototype.remove === 'function');
  11825. return !!isTypeSupported && !!sourceBufferValidAPI;
  11826. }
  11827. exports.isSupported = isSupported;
  11828. /***/ }),
  11829. /***/ "./src/loader/fragment-loader.js":
  11830. /*!***************************************!*\
  11831. !*** ./src/loader/fragment-loader.js ***!
  11832. \***************************************/
  11833. /*! no static exports found */
  11834. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  11835. /***/ (function(module, exports, __webpack_require__) {
  11836. "use strict";
  11837. /* WEBPACK VAR INJECTION */(function(Number) {
  11838. /*
  11839. * Fragment Loader
  11840. */
  11841. var __extends = (this && this.__extends) || (function () {
  11842. var extendStatics = Object.setPrototypeOf ||
  11843. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  11844. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11845. return function (d, b) {
  11846. extendStatics(d, b);
  11847. function __() { this.constructor = d; }
  11848. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  11849. };
  11850. })();
  11851. Object.defineProperty(exports, "__esModule", { value: true });
  11852. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  11853. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  11854. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  11855. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  11856. var FragmentLoader = /** @class */ (function (_super) {
  11857. __extends(FragmentLoader, _super);
  11858. function FragmentLoader(hls) {
  11859. var _this = _super.call(this, hls, events_1.default.FRAG_LOADING) || this;
  11860. _this.loaders = {};
  11861. return _this;
  11862. }
  11863. FragmentLoader.prototype.destroy = function () {
  11864. var loaders = this.loaders;
  11865. for (var loaderName in loaders) {
  11866. var loader = loaders[loaderName];
  11867. if (loader) {
  11868. loader.destroy();
  11869. }
  11870. }
  11871. this.loaders = {};
  11872. _super.prototype.destroy.call(this);
  11873. };
  11874. FragmentLoader.prototype.onFragLoading = function (data) {
  11875. var frag = data.frag, type = frag.type, loaders = this.loaders, config = this.hls.config, FragmentILoader = config.fLoader, DefaultILoader = config.loader;
  11876. // reset fragment state
  11877. frag.loaded = 0;
  11878. var loader = loaders[type];
  11879. if (loader) {
  11880. logger_1.logger.warn("abort previous fragment loader for type: " + type);
  11881. loader.abort();
  11882. }
  11883. loader = loaders[type] = frag.loader =
  11884. config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);
  11885. var loaderContext, loaderConfig, loaderCallbacks;
  11886. loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };
  11887. var start = frag.byteRangeStartOffset, end = frag.byteRangeEndOffset;
  11888. if (Number.isFinite(start) && Number.isFinite(end)) {
  11889. loaderContext.rangeStart = start;
  11890. loaderContext.rangeEnd = end;
  11891. }
  11892. loaderConfig = {
  11893. timeout: config.fragLoadingTimeOut,
  11894. maxRetry: 0,
  11895. retryDelay: 0,
  11896. maxRetryDelay: config.fragLoadingMaxRetryTimeout
  11897. };
  11898. loaderCallbacks = {
  11899. onSuccess: this.loadsuccess.bind(this),
  11900. onError: this.loaderror.bind(this),
  11901. onTimeout: this.loadtimeout.bind(this),
  11902. onProgress: this.loadprogress.bind(this)
  11903. };
  11904. loader.load(loaderContext, loaderConfig, loaderCallbacks);
  11905. };
  11906. FragmentLoader.prototype.loadsuccess = function (response, stats, context, networkDetails) {
  11907. if (networkDetails === void 0) { networkDetails = null; }
  11908. var payload = response.data, frag = context.frag;
  11909. // detach fragment loader on load success
  11910. frag.loader = undefined;
  11911. this.loaders[frag.type] = undefined;
  11912. this.hls.trigger(events_1.default.FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });
  11913. };
  11914. FragmentLoader.prototype.loaderror = function (response, context, networkDetails) {
  11915. if (networkDetails === void 0) { networkDetails = null; }
  11916. var frag = context.frag;
  11917. var loader = frag.loader;
  11918. if (loader) {
  11919. loader.abort();
  11920. }
  11921. this.loaders[frag.type] = undefined;
  11922. this.hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.NETWORK_ERROR, details: errors_1.ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });
  11923. };
  11924. FragmentLoader.prototype.loadtimeout = function (stats, context, networkDetails) {
  11925. if (networkDetails === void 0) { networkDetails = null; }
  11926. var frag = context.frag;
  11927. var loader = frag.loader;
  11928. if (loader) {
  11929. loader.abort();
  11930. }
  11931. this.loaders[frag.type] = undefined;
  11932. this.hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.NETWORK_ERROR, details: errors_1.ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });
  11933. };
  11934. // data will be used for progressive parsing
  11935. FragmentLoader.prototype.loadprogress = function (stats, context, data, networkDetails) {
  11936. if (networkDetails === void 0) { networkDetails = null; }
  11937. var frag = context.frag;
  11938. frag.loaded = stats.loaded;
  11939. this.hls.trigger(events_1.default.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });
  11940. };
  11941. return FragmentLoader;
  11942. }(event_handler_1.default));
  11943. exports.default = FragmentLoader;
  11944. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  11945. /***/ }),
  11946. /***/ "./src/loader/fragment.js":
  11947. /*!********************************!*\
  11948. !*** ./src/loader/fragment.js ***!
  11949. \********************************/
  11950. /*! no static exports found */
  11951. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  11952. /***/ (function(module, exports, __webpack_require__) {
  11953. "use strict";
  11954. /* WEBPACK VAR INJECTION */(function(Number) {
  11955. Object.defineProperty(exports, "__esModule", { value: true });
  11956. var URLToolkit = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
  11957. var level_key_1 = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.js");
  11958. var Fragment = /** @class */ (function () {
  11959. function Fragment() {
  11960. var _a;
  11961. this._url = null;
  11962. this._byteRange = null;
  11963. this._decryptdata = null;
  11964. this.tagList = [];
  11965. this.programDateTime = null;
  11966. this.rawProgramDateTime = null;
  11967. // Holds the types of data this fragment supports
  11968. this._elementaryStreams = (_a = {},
  11969. _a[Fragment.ElementaryStreamTypes.AUDIO] = false,
  11970. _a[Fragment.ElementaryStreamTypes.VIDEO] = false,
  11971. _a);
  11972. }
  11973. Object.defineProperty(Fragment, "ElementaryStreamTypes", {
  11974. /**
  11975. * `type` property for this._elementaryStreams
  11976. *
  11977. * @enum
  11978. */
  11979. get: function () {
  11980. return {
  11981. AUDIO: 'audio',
  11982. VIDEO: 'video'
  11983. };
  11984. },
  11985. enumerable: true,
  11986. configurable: true
  11987. });
  11988. Object.defineProperty(Fragment.prototype, "url", {
  11989. get: function () {
  11990. if (!this._url && this.relurl) {
  11991. this._url = URLToolkit.buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });
  11992. }
  11993. return this._url;
  11994. },
  11995. set: function (value) {
  11996. this._url = value;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Fragment.prototype, "byteRange", {
  12002. get: function () {
  12003. if (!this._byteRange && !this.rawByteRange) {
  12004. return [];
  12005. }
  12006. if (this._byteRange) {
  12007. return this._byteRange;
  12008. }
  12009. var byteRange = [];
  12010. if (this.rawByteRange) {
  12011. var params = this.rawByteRange.split('@', 2);
  12012. if (params.length === 1) {
  12013. var lastByteRangeEndOffset = this.lastByteRangeEndOffset;
  12014. byteRange[0] = lastByteRangeEndOffset || 0;
  12015. }
  12016. else {
  12017. byteRange[0] = parseInt(params[1]);
  12018. }
  12019. byteRange[1] = parseInt(params[0]) + byteRange[0];
  12020. this._byteRange = byteRange;
  12021. }
  12022. return byteRange;
  12023. },
  12024. enumerable: true,
  12025. configurable: true
  12026. });
  12027. Object.defineProperty(Fragment.prototype, "byteRangeStartOffset", {
  12028. /**
  12029. * @type {number}
  12030. */
  12031. get: function () {
  12032. return this.byteRange[0];
  12033. },
  12034. enumerable: true,
  12035. configurable: true
  12036. });
  12037. Object.defineProperty(Fragment.prototype, "byteRangeEndOffset", {
  12038. get: function () {
  12039. return this.byteRange[1];
  12040. },
  12041. enumerable: true,
  12042. configurable: true
  12043. });
  12044. Object.defineProperty(Fragment.prototype, "decryptdata", {
  12045. get: function () {
  12046. if (!this._decryptdata) {
  12047. this._decryptdata = this.fragmentDecryptdataFromLevelkey(this.levelkey, this.sn);
  12048. }
  12049. return this._decryptdata;
  12050. },
  12051. enumerable: true,
  12052. configurable: true
  12053. });
  12054. Object.defineProperty(Fragment.prototype, "endProgramDateTime", {
  12055. get: function () {
  12056. if (!Number.isFinite(this.programDateTime)) {
  12057. return null;
  12058. }
  12059. var duration = !Number.isFinite(this.duration) ? 0 : this.duration;
  12060. return this.programDateTime + (duration * 1000);
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(Fragment.prototype, "encrypted", {
  12066. get: function () {
  12067. return !!((this.decryptdata && this.decryptdata.uri !== null) && (this.decryptdata.key === null));
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. /**
  12073. * @param {ElementaryStreamType} type
  12074. */
  12075. Fragment.prototype.addElementaryStream = function (type) {
  12076. this._elementaryStreams[type] = true;
  12077. };
  12078. /**
  12079. * @param {ElementaryStreamType} type
  12080. */
  12081. Fragment.prototype.hasElementaryStream = function (type) {
  12082. return this._elementaryStreams[type] === true;
  12083. };
  12084. /**
  12085. * Utility method for parseLevelPlaylist to create an initialization vector for a given segment
  12086. * @returns {Uint8Array}
  12087. */
  12088. Fragment.prototype.createInitializationVector = function (segmentNumber) {
  12089. var uint8View = new Uint8Array(16);
  12090. for (var i = 12; i < 16; i++) {
  12091. uint8View[i] = (segmentNumber >> 8 * (15 - i)) & 0xff;
  12092. }
  12093. return uint8View;
  12094. };
  12095. /**
  12096. * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data
  12097. * @param levelkey - a playlist's encryption info
  12098. * @param segmentNumber - the fragment's segment number
  12099. * @returns {*} - an object to be applied as a fragment's decryptdata
  12100. */
  12101. Fragment.prototype.fragmentDecryptdataFromLevelkey = function (levelkey, segmentNumber) {
  12102. var decryptdata = levelkey;
  12103. if (levelkey && levelkey.method && levelkey.uri && !levelkey.iv) {
  12104. decryptdata = new level_key_1.default();
  12105. decryptdata.method = levelkey.method;
  12106. decryptdata.baseuri = levelkey.baseuri;
  12107. decryptdata.reluri = levelkey.reluri;
  12108. decryptdata.iv = this.createInitializationVector(segmentNumber);
  12109. }
  12110. return decryptdata;
  12111. };
  12112. return Fragment;
  12113. }());
  12114. exports.default = Fragment;
  12115. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  12116. /***/ }),
  12117. /***/ "./src/loader/key-loader.js":
  12118. /*!**********************************!*\
  12119. !*** ./src/loader/key-loader.js ***!
  12120. \**********************************/
  12121. /*! no static exports found */
  12122. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  12123. /***/ (function(module, exports, __webpack_require__) {
  12124. "use strict";
  12125. /*
  12126. * Decrypt key Loader
  12127. */
  12128. var __extends = (this && this.__extends) || (function () {
  12129. var extendStatics = Object.setPrototypeOf ||
  12130. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  12131. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  12132. return function (d, b) {
  12133. extendStatics(d, b);
  12134. function __() { this.constructor = d; }
  12135. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12136. };
  12137. })();
  12138. Object.defineProperty(exports, "__esModule", { value: true });
  12139. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  12140. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  12141. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  12142. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  12143. var KeyLoader = /** @class */ (function (_super) {
  12144. __extends(KeyLoader, _super);
  12145. function KeyLoader(hls) {
  12146. var _this = _super.call(this, hls, events_1.default.KEY_LOADING) || this;
  12147. _this.loaders = {};
  12148. _this.decryptkey = null;
  12149. _this.decrypturl = null;
  12150. return _this;
  12151. }
  12152. KeyLoader.prototype.destroy = function () {
  12153. for (var loaderName in this.loaders) {
  12154. var loader = this.loaders[loaderName];
  12155. if (loader) {
  12156. loader.destroy();
  12157. }
  12158. }
  12159. this.loaders = {};
  12160. event_handler_1.default.prototype.destroy.call(this);
  12161. };
  12162. KeyLoader.prototype.onKeyLoading = function (data) {
  12163. var frag = data.frag, type = frag.type, loader = this.loaders[type], decryptdata = frag.decryptdata, uri = decryptdata.uri;
  12164. // if uri is different from previous one or if decrypt key not retrieved yet
  12165. if (uri !== this.decrypturl || this.decryptkey === null) {
  12166. var config = this.hls.config;
  12167. if (loader) {
  12168. logger_1.logger.warn("abort previous key loader for type:" + type);
  12169. loader.abort();
  12170. }
  12171. frag.loader = this.loaders[type] = new config.loader(config);
  12172. this.decrypturl = uri;
  12173. this.decryptkey = null;
  12174. var loaderContext = void 0, loaderConfig = void 0, loaderCallbacks = void 0;
  12175. loaderContext = { url: uri, frag: frag, responseType: 'arraybuffer' };
  12176. // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,
  12177. // key-loader will trigger an error and rely on stream-controller to handle retry logic.
  12178. // this will also align retry logic with fragment-loader
  12179. loaderConfig = { timeout: config.fragLoadingTimeOut, maxRetry: 0, retryDelay: config.fragLoadingRetryDelay, maxRetryDelay: config.fragLoadingMaxRetryTimeout };
  12180. loaderCallbacks = { onSuccess: this.loadsuccess.bind(this), onError: this.loaderror.bind(this), onTimeout: this.loadtimeout.bind(this) };
  12181. frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);
  12182. }
  12183. else if (this.decryptkey) {
  12184. // we already loaded this key, return it
  12185. decryptdata.key = this.decryptkey;
  12186. this.hls.trigger(events_1.default.KEY_LOADED, { frag: frag });
  12187. }
  12188. };
  12189. KeyLoader.prototype.loadsuccess = function (response, stats, context) {
  12190. var frag = context.frag;
  12191. this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data);
  12192. // detach fragment loader on load success
  12193. frag.loader = undefined;
  12194. this.loaders[frag.type] = undefined;
  12195. this.hls.trigger(events_1.default.KEY_LOADED, { frag: frag });
  12196. };
  12197. KeyLoader.prototype.loaderror = function (response, context) {
  12198. var frag = context.frag, loader = frag.loader;
  12199. if (loader) {
  12200. loader.abort();
  12201. }
  12202. this.loaders[context.type] = undefined;
  12203. this.hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.NETWORK_ERROR, details: errors_1.ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag: frag, response: response });
  12204. };
  12205. KeyLoader.prototype.loadtimeout = function (stats, context) {
  12206. var frag = context.frag, loader = frag.loader;
  12207. if (loader) {
  12208. loader.abort();
  12209. }
  12210. this.loaders[context.type] = undefined;
  12211. this.hls.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.NETWORK_ERROR, details: errors_1.ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag: frag });
  12212. };
  12213. return KeyLoader;
  12214. }(event_handler_1.default));
  12215. exports.default = KeyLoader;
  12216. /***/ }),
  12217. /***/ "./src/loader/level-key.js":
  12218. /*!*********************************!*\
  12219. !*** ./src/loader/level-key.js ***!
  12220. \*********************************/
  12221. /*! no static exports found */
  12222. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  12223. /***/ (function(module, exports, __webpack_require__) {
  12224. "use strict";
  12225. Object.defineProperty(exports, "__esModule", { value: true });
  12226. var URLToolkit = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
  12227. var LevelKey = /** @class */ (function () {
  12228. function LevelKey() {
  12229. this.method = null;
  12230. this.key = null;
  12231. this.iv = null;
  12232. this._uri = null;
  12233. }
  12234. Object.defineProperty(LevelKey.prototype, "uri", {
  12235. get: function () {
  12236. if (!this._uri && this.reluri) {
  12237. this._uri = URLToolkit.buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });
  12238. }
  12239. return this._uri;
  12240. },
  12241. enumerable: true,
  12242. configurable: true
  12243. });
  12244. return LevelKey;
  12245. }());
  12246. exports.default = LevelKey;
  12247. /***/ }),
  12248. /***/ "./src/loader/level.js":
  12249. /*!*****************************!*\
  12250. !*** ./src/loader/level.js ***!
  12251. \*****************************/
  12252. /*! no static exports found */
  12253. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  12254. /***/ (function(module, exports, __webpack_require__) {
  12255. "use strict";
  12256. /* WEBPACK VAR INJECTION */(function(Number) {
  12257. Object.defineProperty(exports, "__esModule", { value: true });
  12258. var Level = /** @class */ (function () {
  12259. function Level(baseUrl) {
  12260. // Please keep properties in alphabetical order
  12261. this.endCC = 0;
  12262. this.endSN = 0;
  12263. this.fragments = [];
  12264. this.initSegment = null;
  12265. this.live = true;
  12266. this.needSidxRanges = false;
  12267. this.startCC = 0;
  12268. this.startSN = 0;
  12269. this.startTimeOffset = null;
  12270. this.targetduration = 0;
  12271. this.totalduration = 0;
  12272. this.type = null;
  12273. this.url = baseUrl;
  12274. this.version = null;
  12275. }
  12276. Object.defineProperty(Level.prototype, "hasProgramDateTime", {
  12277. get: function () {
  12278. return !!(this.fragments[0] && Number.isFinite(this.fragments[0].programDateTime));
  12279. },
  12280. enumerable: true,
  12281. configurable: true
  12282. });
  12283. return Level;
  12284. }());
  12285. exports.default = Level;
  12286. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  12287. /***/ }),
  12288. /***/ "./src/loader/m3u8-parser.js":
  12289. /*!***********************************!*\
  12290. !*** ./src/loader/m3u8-parser.js ***!
  12291. \***********************************/
  12292. /*! no static exports found */
  12293. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  12294. /***/ (function(module, exports, __webpack_require__) {
  12295. "use strict";
  12296. /* WEBPACK VAR INJECTION */(function(Number) {
  12297. Object.defineProperty(exports, "__esModule", { value: true });
  12298. var URLToolkit = __webpack_require__(/*! url-toolkit */ "./node_modules/url-toolkit/src/url-toolkit.js");
  12299. var fragment_1 = __webpack_require__(/*! ./fragment */ "./src/loader/fragment.js");
  12300. var level_1 = __webpack_require__(/*! ./level */ "./src/loader/level.js");
  12301. var level_key_1 = __webpack_require__(/*! ./level-key */ "./src/loader/level-key.js");
  12302. var attr_list_1 = __webpack_require__(/*! ../utils/attr-list */ "./src/utils/attr-list.js");
  12303. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  12304. var codecs_1 = __webpack_require__(/*! ../utils/codecs */ "./src/utils/codecs.js");
  12305. /**
  12306. * M3U8 parser
  12307. * @module
  12308. */
  12309. // https://regex101.com is your friend
  12310. var MASTER_PLAYLIST_REGEX = /#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)/g;
  12311. var MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;
  12312. var LEVEL_PLAYLIST_REGEX_FAST = new RegExp([
  12313. /#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,
  12314. /|(?!#)([\S+ ?]+)/.source,
  12315. /|#EXT-X-BYTERANGE:*(.+)/.source,
  12316. /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,
  12317. /|#.*/.source // All other non-segment oriented tags will match with all groups empty
  12318. ].join(''), 'g');
  12319. var LEVEL_PLAYLIST_REGEX_SLOW = /(?:(?:#(EXTM3U))|(?:#EXT-X-(PLAYLIST-TYPE):(.+))|(?:#EXT-X-(MEDIA-SEQUENCE): *(\d+))|(?:#EXT-X-(TARGETDURATION): *(\d+))|(?:#EXT-X-(KEY):(.+))|(?:#EXT-X-(START):(.+))|(?:#EXT-X-(ENDLIST))|(?:#EXT-X-(DISCONTINUITY-SEQ)UENCE:(\d+))|(?:#EXT-X-(DIS)CONTINUITY))|(?:#EXT-X-(VERSION):(\d+))|(?:#EXT-X-(MAP):(.+))|(?:(#)([^:]*):(.*))|(?:(#)(.*))(?:.*)\r?\n?/;
  12320. var MP4_REGEX_SUFFIX = /\.(mp4|m4s|m4v|m4a)$/i;
  12321. var M3U8Parser = /** @class */ (function () {
  12322. function M3U8Parser() {
  12323. }
  12324. M3U8Parser.findGroup = function (groups, mediaGroupId) {
  12325. if (!groups) {
  12326. return null;
  12327. }
  12328. var matchingGroup = null;
  12329. for (var i = 0; i < groups.length; i++) {
  12330. var group = groups[i];
  12331. if (group.id === mediaGroupId) {
  12332. matchingGroup = group;
  12333. }
  12334. }
  12335. return matchingGroup;
  12336. };
  12337. M3U8Parser.convertAVC1ToAVCOTI = function (codec) {
  12338. var result, avcdata = codec.split('.');
  12339. if (avcdata.length > 2) {
  12340. result = avcdata.shift() + '.';
  12341. result += parseInt(avcdata.shift()).toString(16);
  12342. result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);
  12343. }
  12344. else {
  12345. result = codec;
  12346. }
  12347. return result;
  12348. };
  12349. M3U8Parser.resolve = function (url, baseUrl) {
  12350. return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });
  12351. };
  12352. M3U8Parser.parseMasterPlaylist = function (string, baseurl) {
  12353. var levels = [], result;
  12354. MASTER_PLAYLIST_REGEX.lastIndex = 0;
  12355. function setCodecs(codecs, level) {
  12356. ['video', 'audio'].forEach(function (type) {
  12357. var filtered = codecs.filter(function (codec) { return codecs_1.isCodecType(codec, type); });
  12358. if (filtered.length) {
  12359. var preferred = filtered.filter(function (codec) {
  12360. return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;
  12361. });
  12362. level[type + "Codec"] = preferred.length > 0 ? preferred[0] : filtered[0];
  12363. // remove from list
  12364. codecs = codecs.filter(function (codec) { return filtered.indexOf(codec) === -1; });
  12365. }
  12366. });
  12367. level.unknownCodecs = codecs;
  12368. }
  12369. while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {
  12370. var level = {};
  12371. var attrs = level.attrs = new attr_list_1.default(result[1]);
  12372. level.url = M3U8Parser.resolve(result[2], baseurl);
  12373. var resolution = attrs.decimalResolution('RESOLUTION');
  12374. if (resolution) {
  12375. level.width = resolution.width;
  12376. level.height = resolution.height;
  12377. }
  12378. level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');
  12379. level.name = attrs.NAME;
  12380. setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);
  12381. if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {
  12382. level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);
  12383. }
  12384. levels.push(level);
  12385. }
  12386. return levels;
  12387. };
  12388. M3U8Parser.parseMasterPlaylistMedia = function (string, baseurl, type, audioGroups) {
  12389. if (audioGroups === void 0) { audioGroups = []; }
  12390. var result;
  12391. var medias = [];
  12392. var id = 0;
  12393. MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;
  12394. while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {
  12395. var media = {};
  12396. var attrs = new attr_list_1.default(result[1]);
  12397. if (attrs.TYPE === type) {
  12398. media.groupId = attrs['GROUP-ID'];
  12399. media.name = attrs.NAME;
  12400. media.type = type;
  12401. media.default = (attrs.DEFAULT === 'YES');
  12402. media.autoselect = (attrs.AUTOSELECT === 'YES');
  12403. media.forced = (attrs.FORCED === 'YES');
  12404. if (attrs.URI) {
  12405. media.url = M3U8Parser.resolve(attrs.URI, baseurl);
  12406. }
  12407. media.lang = attrs.LANGUAGE;
  12408. if (!media.name) {
  12409. media.name = media.lang;
  12410. }
  12411. if (audioGroups.length) {
  12412. var groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId);
  12413. media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;
  12414. }
  12415. media.id = id++;
  12416. medias.push(media);
  12417. }
  12418. }
  12419. return medias;
  12420. };
  12421. M3U8Parser.parseLevelPlaylist = function (string, baseurl, id, type, levelUrlId) {
  12422. var currentSN = 0;
  12423. var totalduration = 0;
  12424. var level = new level_1.default(baseurl);
  12425. var levelkey = new level_key_1.default();
  12426. var cc = 0;
  12427. var prevFrag = null;
  12428. var frag = new fragment_1.default();
  12429. var result;
  12430. var i;
  12431. var firstPdtIndex = null;
  12432. LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;
  12433. while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {
  12434. var duration = result[1];
  12435. if (duration) { // INF
  12436. frag.duration = parseFloat(duration);
  12437. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  12438. var title = (' ' + result[2]).slice(1);
  12439. frag.title = title || null;
  12440. frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);
  12441. }
  12442. else if (result[3]) { // url
  12443. if (Number.isFinite(frag.duration)) {
  12444. var sn = currentSN++;
  12445. frag.type = type;
  12446. frag.start = totalduration;
  12447. frag.levelkey = levelkey;
  12448. frag.sn = sn;
  12449. frag.level = id;
  12450. frag.cc = cc;
  12451. frag.urlId = levelUrlId;
  12452. frag.baseurl = baseurl;
  12453. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  12454. frag.relurl = (' ' + result[3]).slice(1);
  12455. assignProgramDateTime(frag, prevFrag);
  12456. level.fragments.push(frag);
  12457. prevFrag = frag;
  12458. totalduration += frag.duration;
  12459. frag = new fragment_1.default();
  12460. }
  12461. }
  12462. else if (result[4]) { // X-BYTERANGE
  12463. frag.rawByteRange = (' ' + result[4]).slice(1);
  12464. if (prevFrag) {
  12465. var lastByteRangeEndOffset = prevFrag.byteRangeEndOffset;
  12466. if (lastByteRangeEndOffset) {
  12467. frag.lastByteRangeEndOffset = lastByteRangeEndOffset;
  12468. }
  12469. }
  12470. }
  12471. else if (result[5]) { // PROGRAM-DATE-TIME
  12472. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  12473. frag.rawProgramDateTime = (' ' + result[5]).slice(1);
  12474. frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);
  12475. if (firstPdtIndex === null) {
  12476. firstPdtIndex = level.fragments.length;
  12477. }
  12478. }
  12479. else {
  12480. result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);
  12481. for (i = 1; i < result.length; i++) {
  12482. if (result[i] !== undefined) {
  12483. break;
  12484. }
  12485. }
  12486. // avoid sliced strings https://github.com/video-dev/hls.js/issues/939
  12487. var value1 = (' ' + result[i + 1]).slice(1);
  12488. var value2 = (' ' + result[i + 2]).slice(1);
  12489. switch (result[i]) {
  12490. case '#':
  12491. frag.tagList.push(value2 ? [value1, value2] : [value1]);
  12492. break;
  12493. case 'PLAYLIST-TYPE':
  12494. level.type = value1.toUpperCase();
  12495. break;
  12496. case 'MEDIA-SEQUENCE':
  12497. currentSN = level.startSN = parseInt(value1);
  12498. break;
  12499. case 'TARGETDURATION':
  12500. level.targetduration = parseFloat(value1);
  12501. break;
  12502. case 'VERSION':
  12503. level.version = parseInt(value1);
  12504. break;
  12505. case 'EXTM3U':
  12506. break;
  12507. case 'ENDLIST':
  12508. level.live = false;
  12509. break;
  12510. case 'DIS':
  12511. cc++;
  12512. frag.tagList.push(['DIS']);
  12513. break;
  12514. case 'DISCONTINUITY-SEQ':
  12515. cc = parseInt(value1);
  12516. break;
  12517. case 'KEY':
  12518. // https://tools.ietf.org/html/draft-pantos-http-live-streaming-08#section-3.4.4
  12519. var decryptparams = value1;
  12520. var keyAttrs = new attr_list_1.default(decryptparams);
  12521. var decryptmethod = keyAttrs.enumeratedString('METHOD'), decrypturi = keyAttrs.URI, decryptiv = keyAttrs.hexadecimalInteger('IV');
  12522. if (decryptmethod) {
  12523. levelkey = new level_key_1.default();
  12524. if ((decrypturi) && (['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0)) {
  12525. levelkey.method = decryptmethod;
  12526. // URI to get the key
  12527. levelkey.baseuri = baseurl;
  12528. levelkey.reluri = decrypturi;
  12529. levelkey.key = null;
  12530. // Initialization Vector (IV)
  12531. levelkey.iv = decryptiv;
  12532. }
  12533. }
  12534. break;
  12535. case 'START':
  12536. var startParams = value1;
  12537. var startAttrs = new attr_list_1.default(startParams);
  12538. var startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');
  12539. // TIME-OFFSET can be 0
  12540. if (Number.isFinite(startTimeOffset)) {
  12541. level.startTimeOffset = startTimeOffset;
  12542. }
  12543. break;
  12544. case 'MAP':
  12545. var mapAttrs = new attr_list_1.default(value1);
  12546. frag.relurl = mapAttrs.URI;
  12547. frag.rawByteRange = mapAttrs.BYTERANGE;
  12548. frag.baseurl = baseurl;
  12549. frag.level = id;
  12550. frag.type = type;
  12551. frag.sn = 'initSegment';
  12552. level.initSegment = frag;
  12553. frag = new fragment_1.default();
  12554. frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;
  12555. break;
  12556. default:
  12557. logger_1.logger.warn("line parsed but not handled: " + result);
  12558. break;
  12559. }
  12560. }
  12561. }
  12562. frag = prevFrag;
  12563. // logger.log('found ' + level.fragments.length + ' fragments');
  12564. if (frag && !frag.relurl) {
  12565. level.fragments.pop();
  12566. totalduration -= frag.duration;
  12567. }
  12568. level.totalduration = totalduration;
  12569. level.averagetargetduration = totalduration / level.fragments.length;
  12570. level.endSN = currentSN - 1;
  12571. level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;
  12572. level.endCC = cc;
  12573. if (!level.initSegment && level.fragments.length) {
  12574. // this is a bit lurky but HLS really has no other way to tell us
  12575. // if the fragments are TS or MP4, except if we download them :/
  12576. // but this is to be able to handle SIDX.
  12577. if (level.fragments.every(function (frag) { return MP4_REGEX_SUFFIX.test(frag.relurl); })) {
  12578. logger_1.logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');
  12579. frag = new fragment_1.default();
  12580. frag.relurl = level.fragments[0].relurl;
  12581. frag.baseurl = baseurl;
  12582. frag.level = id;
  12583. frag.type = type;
  12584. frag.sn = 'initSegment';
  12585. level.initSegment = frag;
  12586. level.needSidxRanges = true;
  12587. }
  12588. }
  12589. /**
  12590. * Backfill any missing PDT values
  12591. "If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after
  12592. one or more Media Segment URIs, the client SHOULD extrapolate
  12593. backward from that tag (using EXTINF durations and/or media
  12594. timestamps) to associate dates with those segments."
  12595. * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs
  12596. * computed.
  12597. */
  12598. if (firstPdtIndex) {
  12599. backfillProgramDateTimes(level.fragments, firstPdtIndex);
  12600. }
  12601. return level;
  12602. };
  12603. return M3U8Parser;
  12604. }());
  12605. exports.default = M3U8Parser;
  12606. function backfillProgramDateTimes(fragments, startIndex) {
  12607. var fragPrev = fragments[startIndex];
  12608. for (var i = startIndex - 1; i >= 0; i--) {
  12609. var frag = fragments[i];
  12610. frag.programDateTime = fragPrev.programDateTime - (frag.duration * 1000);
  12611. fragPrev = frag;
  12612. }
  12613. }
  12614. function assignProgramDateTime(frag, prevFrag) {
  12615. if (frag.rawProgramDateTime) {
  12616. frag.programDateTime = Date.parse(frag.rawProgramDateTime);
  12617. }
  12618. else if (prevFrag && prevFrag.programDateTime) {
  12619. frag.programDateTime = prevFrag.endProgramDateTime;
  12620. }
  12621. if (!Number.isFinite(frag.programDateTime)) {
  12622. frag.programDateTime = null;
  12623. frag.rawProgramDateTime = null;
  12624. }
  12625. }
  12626. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  12627. /***/ }),
  12628. /***/ "./src/loader/playlist-loader.js":
  12629. /*!***************************************!*\
  12630. !*** ./src/loader/playlist-loader.js ***!
  12631. \***************************************/
  12632. /*! no static exports found */
  12633. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  12634. /***/ (function(module, exports, __webpack_require__) {
  12635. "use strict";
  12636. /* WEBPACK VAR INJECTION */(function(Number) {
  12637. /**
  12638. * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.
  12639. *
  12640. * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.
  12641. *
  12642. * Uses loader(s) set in config to do actual internal loading of resource tasks.
  12643. *
  12644. * @module
  12645. *
  12646. */
  12647. var __extends = (this && this.__extends) || (function () {
  12648. var extendStatics = Object.setPrototypeOf ||
  12649. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  12650. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  12651. return function (d, b) {
  12652. extendStatics(d, b);
  12653. function __() { this.constructor = d; }
  12654. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  12655. };
  12656. })();
  12657. Object.defineProperty(exports, "__esModule", { value: true });
  12658. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  12659. var event_handler_1 = __webpack_require__(/*! ../event-handler */ "./src/event-handler.js");
  12660. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  12661. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  12662. var mp4demuxer_1 = __webpack_require__(/*! ../demux/mp4demuxer */ "./src/demux/mp4demuxer.js");
  12663. var m3u8_parser_1 = __webpack_require__(/*! ./m3u8-parser */ "./src/loader/m3u8-parser.js");
  12664. var performance = window.performance;
  12665. /**
  12666. * `type` property values for this loaders' context object
  12667. * @enum
  12668. *
  12669. */
  12670. var ContextType = {
  12671. MANIFEST: 'manifest',
  12672. LEVEL: 'level',
  12673. AUDIO_TRACK: 'audioTrack',
  12674. SUBTITLE_TRACK: 'subtitleTrack'
  12675. };
  12676. /**
  12677. * @enum {string}
  12678. */
  12679. var LevelType = {
  12680. MAIN: 'main',
  12681. AUDIO: 'audio',
  12682. SUBTITLE: 'subtitle'
  12683. };
  12684. /**
  12685. * @constructor
  12686. */
  12687. var PlaylistLoader = /** @class */ (function (_super) {
  12688. __extends(PlaylistLoader, _super);
  12689. /**
  12690. * @constructs
  12691. * @param {Hls} hls
  12692. */
  12693. function PlaylistLoader(hls) {
  12694. var _this = _super.call(this, hls, events_1.default.MANIFEST_LOADING, events_1.default.LEVEL_LOADING, events_1.default.AUDIO_TRACK_LOADING, events_1.default.SUBTITLE_TRACK_LOADING) || this;
  12695. _this.loaders = {};
  12696. return _this;
  12697. }
  12698. Object.defineProperty(PlaylistLoader, "ContextType", {
  12699. get: function () {
  12700. return ContextType;
  12701. },
  12702. enumerable: true,
  12703. configurable: true
  12704. });
  12705. Object.defineProperty(PlaylistLoader, "LevelType", {
  12706. get: function () {
  12707. return LevelType;
  12708. },
  12709. enumerable: true,
  12710. configurable: true
  12711. });
  12712. /**
  12713. * @param {ContextType} type
  12714. * @returns {boolean}
  12715. */
  12716. PlaylistLoader.canHaveQualityLevels = function (type) {
  12717. return (type !== ContextType.AUDIO_TRACK &&
  12718. type !== ContextType.SUBTITLE_TRACK);
  12719. };
  12720. /**
  12721. * Map context.type to LevelType
  12722. * @param {{type: ContextType}} context
  12723. * @returns {LevelType}
  12724. */
  12725. PlaylistLoader.mapContextToLevelType = function (context) {
  12726. var type = context.type;
  12727. switch (type) {
  12728. case ContextType.AUDIO_TRACK:
  12729. return LevelType.AUDIO;
  12730. case ContextType.SUBTITLE_TRACK:
  12731. return LevelType.SUBTITLE;
  12732. default:
  12733. return LevelType.MAIN;
  12734. }
  12735. };
  12736. PlaylistLoader.getResponseUrl = function (response, context) {
  12737. var url = response.url;
  12738. // responseURL not supported on some browsers (it is used to detect URL redirection)
  12739. // data-uri mode also not supported (but no need to detect redirection)
  12740. if (url === undefined || url.indexOf('data:') === 0) {
  12741. // fallback to initial URL
  12742. url = context.url;
  12743. }
  12744. return url;
  12745. };
  12746. /**
  12747. * Returns defaults or configured loader-type overloads (pLoader and loader config params)
  12748. * Default loader is XHRLoader (see utils)
  12749. * @param {object} context
  12750. * @returns {XHRLoader} or other compatible configured overload
  12751. */
  12752. PlaylistLoader.prototype.createInternalLoader = function (context) {
  12753. var config = this.hls.config;
  12754. var PLoader = config.pLoader;
  12755. var Loader = config.loader;
  12756. var InternalLoader = PLoader || Loader;
  12757. var loader = new InternalLoader(config);
  12758. context.loader = loader;
  12759. this.loaders[context.type] = loader;
  12760. return loader;
  12761. };
  12762. PlaylistLoader.prototype.getInternalLoader = function (context) {
  12763. return this.loaders[context.type];
  12764. };
  12765. PlaylistLoader.prototype.resetInternalLoader = function (contextType) {
  12766. if (this.loaders[contextType]) {
  12767. delete this.loaders[contextType];
  12768. }
  12769. };
  12770. /**
  12771. * Call `destroy` on all internal loader instances mapped (one per context type)
  12772. */
  12773. PlaylistLoader.prototype.destroyInternalLoaders = function () {
  12774. for (var contextType in this.loaders) {
  12775. var loader = this.loaders[contextType];
  12776. if (loader) {
  12777. loader.destroy();
  12778. }
  12779. this.resetInternalLoader(contextType);
  12780. }
  12781. };
  12782. PlaylistLoader.prototype.destroy = function () {
  12783. this.destroyInternalLoaders();
  12784. _super.prototype.destroy.call(this);
  12785. };
  12786. PlaylistLoader.prototype.onManifestLoading = function (data) {
  12787. this.load(data.url, { type: ContextType.MANIFEST, level: 0, id: null });
  12788. };
  12789. PlaylistLoader.prototype.onLevelLoading = function (data) {
  12790. this.load(data.url, { type: ContextType.LEVEL, level: data.level, id: data.id });
  12791. };
  12792. PlaylistLoader.prototype.onAudioTrackLoading = function (data) {
  12793. this.load(data.url, { type: ContextType.AUDIO_TRACK, level: null, id: data.id });
  12794. };
  12795. PlaylistLoader.prototype.onSubtitleTrackLoading = function (data) {
  12796. this.load(data.url, { type: ContextType.SUBTITLE_TRACK, level: null, id: data.id });
  12797. };
  12798. PlaylistLoader.prototype.load = function (url, context) {
  12799. var config = this.hls.config;
  12800. logger_1.logger.debug("Loading playlist of type " + context.type + ", level: " + context.level + ", id: " + context.id);
  12801. // Check if a loader for this context already exists
  12802. var loader = this.getInternalLoader(context);
  12803. if (loader) {
  12804. var loaderContext = loader.context;
  12805. if (loaderContext && loaderContext.url === url) { // same URL can't overlap
  12806. logger_1.logger.trace('playlist request ongoing');
  12807. return false;
  12808. }
  12809. else {
  12810. logger_1.logger.warn("aborting previous loader for type: " + context.type);
  12811. loader.abort();
  12812. }
  12813. }
  12814. var maxRetry, timeout, retryDelay, maxRetryDelay;
  12815. // apply different configs for retries depending on
  12816. // context (manifest, level, audio/subs playlist)
  12817. switch (context.type) {
  12818. case ContextType.MANIFEST:
  12819. maxRetry = config.manifestLoadingMaxRetry;
  12820. timeout = config.manifestLoadingTimeOut;
  12821. retryDelay = config.manifestLoadingRetryDelay;
  12822. maxRetryDelay = config.manifestLoadingMaxRetryTimeout;
  12823. break;
  12824. case ContextType.LEVEL:
  12825. // Disable internal loader retry logic, since we are managing retries in Level Controller
  12826. maxRetry = 0;
  12827. timeout = config.levelLoadingTimeOut;
  12828. // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config
  12829. break;
  12830. default:
  12831. maxRetry = config.levelLoadingMaxRetry;
  12832. timeout = config.levelLoadingTimeOut;
  12833. retryDelay = config.levelLoadingRetryDelay;
  12834. maxRetryDelay = config.levelLoadingMaxRetryTimeout;
  12835. break;
  12836. }
  12837. loader = this.createInternalLoader(context);
  12838. context.url = url;
  12839. context.responseType = context.responseType || ''; // FIXME: (should not be necessary to do this)
  12840. var loaderConfig = {
  12841. timeout: timeout,
  12842. maxRetry: maxRetry,
  12843. retryDelay: retryDelay,
  12844. maxRetryDelay: maxRetryDelay
  12845. };
  12846. var loaderCallbacks = {
  12847. onSuccess: this.loadsuccess.bind(this),
  12848. onError: this.loaderror.bind(this),
  12849. onTimeout: this.loadtimeout.bind(this)
  12850. };
  12851. logger_1.logger.debug("Calling internal loader delegate for URL: " + url);
  12852. loader.load(context, loaderConfig, loaderCallbacks);
  12853. return true;
  12854. };
  12855. PlaylistLoader.prototype.loadsuccess = function (response, stats, context, networkDetails) {
  12856. if (networkDetails === void 0) { networkDetails = null; }
  12857. if (context.isSidxRequest) {
  12858. this._handleSidxRequest(response, context);
  12859. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  12860. return;
  12861. }
  12862. this.resetInternalLoader(context.type);
  12863. var string = response.data;
  12864. stats.tload = performance.now();
  12865. // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));
  12866. // Validate if it is an M3U8 at all
  12867. if (string.indexOf('#EXTM3U') !== 0) {
  12868. this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);
  12869. return;
  12870. }
  12871. // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)
  12872. if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {
  12873. this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);
  12874. }
  12875. else {
  12876. this._handleMasterPlaylist(response, stats, context, networkDetails);
  12877. }
  12878. };
  12879. PlaylistLoader.prototype.loaderror = function (response, context, networkDetails) {
  12880. if (networkDetails === void 0) { networkDetails = null; }
  12881. this._handleNetworkError(context, networkDetails, false, response);
  12882. };
  12883. PlaylistLoader.prototype.loadtimeout = function (stats, context, networkDetails) {
  12884. if (networkDetails === void 0) { networkDetails = null; }
  12885. this._handleNetworkError(context, networkDetails, true);
  12886. };
  12887. PlaylistLoader.prototype._handleMasterPlaylist = function (response, stats, context, networkDetails) {
  12888. var hls = this.hls;
  12889. var string = response.data;
  12890. var url = PlaylistLoader.getResponseUrl(response, context);
  12891. var levels = m3u8_parser_1.default.parseMasterPlaylist(string, url);
  12892. if (!levels.length) {
  12893. this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);
  12894. return;
  12895. }
  12896. // multi level playlist, parse level info
  12897. var audioGroups = levels.map(function (level) { return ({
  12898. id: level.attrs.AUDIO,
  12899. codec: level.audioCodec
  12900. }); });
  12901. var audioTracks = m3u8_parser_1.default.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);
  12902. var subtitles = m3u8_parser_1.default.parseMasterPlaylistMedia(string, url, 'SUBTITLES');
  12903. if (audioTracks.length) {
  12904. // check if we have found an audio track embedded in main playlist (audio track without URI attribute)
  12905. var embeddedAudioFound_1 = false;
  12906. audioTracks.forEach(function (audioTrack) {
  12907. if (!audioTrack.url) {
  12908. embeddedAudioFound_1 = true;
  12909. }
  12910. });
  12911. // if no embedded audio track defined, but audio codec signaled in quality level,
  12912. // we need to signal this main audio track this could happen with playlists with
  12913. // alt audio rendition in which quality levels (main)
  12914. // contains both audio+video. but with mixed audio track not signaled
  12915. if (embeddedAudioFound_1 === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {
  12916. logger_1.logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');
  12917. audioTracks.unshift({
  12918. type: 'main',
  12919. name: 'main'
  12920. });
  12921. }
  12922. }
  12923. hls.trigger(events_1.default.MANIFEST_LOADED, {
  12924. levels: levels,
  12925. audioTracks: audioTracks,
  12926. subtitles: subtitles,
  12927. url: url,
  12928. stats: stats,
  12929. networkDetails: networkDetails
  12930. });
  12931. };
  12932. PlaylistLoader.prototype._handleTrackOrLevelPlaylist = function (response, stats, context, networkDetails) {
  12933. var hls = this.hls;
  12934. var id = context.id, level = context.level, type = context.type;
  12935. var url = PlaylistLoader.getResponseUrl(response, context);
  12936. var levelUrlId = Number.isFinite(id) ? id : 0;
  12937. var levelId = Number.isFinite(level) ? level : levelUrlId;
  12938. var levelType = PlaylistLoader.mapContextToLevelType(context);
  12939. var levelDetails = m3u8_parser_1.default.parseLevelPlaylist(response.data, url, levelId, levelType, levelUrlId);
  12940. // set stats on level structure
  12941. levelDetails.tload = stats.tload;
  12942. // We have done our first request (Manifest-type) and receive
  12943. // not a master playlist but a chunk-list (track/level)
  12944. // We fire the manifest-loaded event anyway with the parsed level-details
  12945. // by creating a single-level structure for it.
  12946. if (type === ContextType.MANIFEST) {
  12947. var singleLevel = {
  12948. url: url,
  12949. details: levelDetails
  12950. };
  12951. hls.trigger(events_1.default.MANIFEST_LOADED, {
  12952. levels: [singleLevel],
  12953. audioTracks: [],
  12954. url: url,
  12955. stats: stats,
  12956. networkDetails: networkDetails
  12957. });
  12958. }
  12959. // save parsing time
  12960. stats.tparsed = performance.now();
  12961. // in case we need SIDX ranges
  12962. // return early after calling load for
  12963. // the SIDX box.
  12964. if (levelDetails.needSidxRanges) {
  12965. var sidxUrl = levelDetails.initSegment.url;
  12966. this.load(sidxUrl, {
  12967. isSidxRequest: true,
  12968. type: type,
  12969. level: level,
  12970. levelDetails: levelDetails,
  12971. id: id,
  12972. rangeStart: 0,
  12973. rangeEnd: 2048,
  12974. responseType: 'arraybuffer'
  12975. });
  12976. return;
  12977. }
  12978. // extend the context with the new levelDetails property
  12979. context.levelDetails = levelDetails;
  12980. this._handlePlaylistLoaded(response, stats, context, networkDetails);
  12981. };
  12982. PlaylistLoader.prototype._handleSidxRequest = function (response, context) {
  12983. var sidxInfo = mp4demuxer_1.default.parseSegmentIndex(new Uint8Array(response.data));
  12984. // if provided fragment does not contain sidx, early return
  12985. if (!sidxInfo) {
  12986. return;
  12987. }
  12988. var sidxReferences = sidxInfo.references;
  12989. var levelDetails = context.levelDetails;
  12990. sidxReferences.forEach(function (segmentRef, index) {
  12991. var segRefInfo = segmentRef.info;
  12992. var frag = levelDetails.fragments[index];
  12993. if (frag.byteRange.length === 0) {
  12994. frag.rawByteRange = String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start);
  12995. }
  12996. });
  12997. levelDetails.initSegment.rawByteRange = String(sidxInfo.moovEndOffset) + '@0';
  12998. };
  12999. PlaylistLoader.prototype._handleManifestParsingError = function (response, context, reason, networkDetails) {
  13000. this.hls.trigger(events_1.default.ERROR, {
  13001. type: errors_1.ErrorTypes.NETWORK_ERROR,
  13002. details: errors_1.ErrorDetails.MANIFEST_PARSING_ERROR,
  13003. fatal: true,
  13004. url: response.url,
  13005. reason: reason,
  13006. networkDetails: networkDetails
  13007. });
  13008. };
  13009. PlaylistLoader.prototype._handleNetworkError = function (context, networkDetails, timeout, response) {
  13010. if (timeout === void 0) { timeout = false; }
  13011. if (response === void 0) { response = null; }
  13012. logger_1.logger.info("A network error occured while loading a " + context.type + "-type playlist");
  13013. var details;
  13014. var fatal;
  13015. var loader = this.getInternalLoader(context);
  13016. switch (context.type) {
  13017. case ContextType.MANIFEST:
  13018. details = (timeout ? errors_1.ErrorDetails.MANIFEST_LOAD_TIMEOUT : errors_1.ErrorDetails.MANIFEST_LOAD_ERROR);
  13019. fatal = true;
  13020. break;
  13021. case ContextType.LEVEL:
  13022. details = (timeout ? errors_1.ErrorDetails.LEVEL_LOAD_TIMEOUT : errors_1.ErrorDetails.LEVEL_LOAD_ERROR);
  13023. fatal = false;
  13024. break;
  13025. case ContextType.AUDIO_TRACK:
  13026. details = (timeout ? errors_1.ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : errors_1.ErrorDetails.AUDIO_TRACK_LOAD_ERROR);
  13027. fatal = false;
  13028. break;
  13029. default:
  13030. // details = ...?
  13031. fatal = false;
  13032. }
  13033. if (loader) {
  13034. loader.abort();
  13035. this.resetInternalLoader(context.type);
  13036. }
  13037. var errorData = {
  13038. type: errors_1.ErrorTypes.NETWORK_ERROR,
  13039. details: details,
  13040. fatal: fatal,
  13041. url: loader.url,
  13042. loader: loader,
  13043. context: context,
  13044. networkDetails: networkDetails
  13045. };
  13046. if (response) {
  13047. errorData.response = response;
  13048. }
  13049. this.hls.trigger(events_1.default.ERROR, errorData);
  13050. };
  13051. PlaylistLoader.prototype._handlePlaylistLoaded = function (response, stats, context, networkDetails) {
  13052. var type = context.type, level = context.level, id = context.id, levelDetails = context.levelDetails;
  13053. if (!levelDetails.targetduration) {
  13054. this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);
  13055. return;
  13056. }
  13057. var canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);
  13058. if (canHaveLevels) {
  13059. this.hls.trigger(events_1.default.LEVEL_LOADED, {
  13060. details: levelDetails,
  13061. level: level || 0,
  13062. id: id || 0,
  13063. stats: stats,
  13064. networkDetails: networkDetails
  13065. });
  13066. }
  13067. else {
  13068. switch (type) {
  13069. case ContextType.AUDIO_TRACK:
  13070. this.hls.trigger(events_1.default.AUDIO_TRACK_LOADED, {
  13071. details: levelDetails,
  13072. id: id,
  13073. stats: stats,
  13074. networkDetails: networkDetails
  13075. });
  13076. break;
  13077. case ContextType.SUBTITLE_TRACK:
  13078. this.hls.trigger(events_1.default.SUBTITLE_TRACK_LOADED, {
  13079. details: levelDetails,
  13080. id: id,
  13081. stats: stats,
  13082. networkDetails: networkDetails
  13083. });
  13084. break;
  13085. }
  13086. }
  13087. };
  13088. return PlaylistLoader;
  13089. }(event_handler_1.default));
  13090. exports.default = PlaylistLoader;
  13091. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  13092. /***/ }),
  13093. /***/ "./src/observer.js":
  13094. /*!*************************!*\
  13095. !*** ./src/observer.js ***!
  13096. \*************************/
  13097. /*! no static exports found */
  13098. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  13099. /***/ (function(module, exports, __webpack_require__) {
  13100. "use strict";
  13101. var __extends = (this && this.__extends) || (function () {
  13102. var extendStatics = Object.setPrototypeOf ||
  13103. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  13104. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  13105. return function (d, b) {
  13106. extendStatics(d, b);
  13107. function __() { this.constructor = d; }
  13108. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  13109. };
  13110. })();
  13111. Object.defineProperty(exports, "__esModule", { value: true });
  13112. var eventemitter3_1 = __webpack_require__(/*! eventemitter3 */ "./node_modules/eventemitter3/index.js");
  13113. /**
  13114. * @class
  13115. *
  13116. * Simple adapter sub-class of Nodejs-like EventEmitter.
  13117. *
  13118. * We simply want to pass along the event-name itself
  13119. * in every call to a handler, which is the purpose of our `trigger` method
  13120. * extending the standard API.
  13121. *
  13122. */
  13123. var Observer = /** @class */ (function (_super) {
  13124. __extends(Observer, _super);
  13125. function Observer() {
  13126. return _super !== null && _super.apply(this, arguments) || this;
  13127. }
  13128. /**
  13129. *
  13130. * @param {string} event
  13131. * @param {any} data
  13132. */
  13133. Observer.prototype.trigger = function (event) {
  13134. var data = [];
  13135. for (var _i = 1; _i < arguments.length; _i++) {
  13136. data[_i - 1] = arguments[_i];
  13137. }
  13138. this.emit.apply(this, [event, event].concat(data));
  13139. };
  13140. return Observer;
  13141. }(eventemitter3_1.EventEmitter));
  13142. exports.Observer = Observer;
  13143. /***/ }),
  13144. /***/ "./src/polyfills/number.js":
  13145. /*!*********************************!*\
  13146. !*** ./src/polyfills/number.js ***!
  13147. \*********************************/
  13148. /*! no static exports found */
  13149. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  13150. /***/ (function(module, exports, __webpack_require__) {
  13151. "use strict";
  13152. Object.defineProperty(exports, "__esModule", { value: true });
  13153. var get_self_scope_1 = __webpack_require__(/*! ../utils/get-self-scope */ "./src/utils/get-self-scope.js");
  13154. var self = get_self_scope_1.getSelfScope();
  13155. var Number = self.Number;
  13156. exports.Number = Number;
  13157. // TODO: get rid of global polyfills and replace them with wrappers ("ponyfills")
  13158. Number.isFinite = Number.isFinite || function (value) {
  13159. return typeof value === 'number' && isFinite(value);
  13160. };
  13161. /***/ }),
  13162. /***/ "./src/remux/aac-helper.js":
  13163. /*!*********************************!*\
  13164. !*** ./src/remux/aac-helper.js ***!
  13165. \*********************************/
  13166. /*! no static exports found */
  13167. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  13168. /***/ (function(module, exports, __webpack_require__) {
  13169. "use strict";
  13170. /**
  13171. * AAC helper
  13172. */
  13173. Object.defineProperty(exports, "__esModule", { value: true });
  13174. var AAC = /** @class */ (function () {
  13175. function AAC() {
  13176. }
  13177. AAC.getSilentFrame = function (codec, channelCount) {
  13178. switch (codec) {
  13179. case 'mp4a.40.2':
  13180. if (channelCount === 1) {
  13181. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);
  13182. }
  13183. else if (channelCount === 2) {
  13184. return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);
  13185. }
  13186. else if (channelCount === 3) {
  13187. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);
  13188. }
  13189. else if (channelCount === 4) {
  13190. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);
  13191. }
  13192. else if (channelCount === 5) {
  13193. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);
  13194. }
  13195. else if (channelCount === 6) {
  13196. return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2, 0x00, 0x20, 0x08, 0xe0]);
  13197. }
  13198. break;
  13199. // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)
  13200. default:
  13201. if (channelCount === 1) {
  13202. // ffmpeg -y -f lavfi -i "aevalsrc=0:d=0.05" -c:a libfdk_aac -profile:a aac_he -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  13203. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  13204. }
  13205. else if (channelCount === 2) {
  13206. // ffmpeg -y -f lavfi -i "aevalsrc=0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  13207. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  13208. }
  13209. else if (channelCount === 3) {
  13210. // ffmpeg -y -f lavfi -i "aevalsrc=0|0|0:d=0.05" -c:a libfdk_aac -profile:a aac_he_v2 -b:a 4k output.aac && hexdump -v -e '16/1 "0x%x," "\n"' -v output.aac
  13211. return new Uint8Array([0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0, 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5e]);
  13212. }
  13213. break;
  13214. }
  13215. return null;
  13216. };
  13217. return AAC;
  13218. }());
  13219. exports.default = AAC;
  13220. /***/ }),
  13221. /***/ "./src/remux/mp4-generator.js":
  13222. /*!************************************!*\
  13223. !*** ./src/remux/mp4-generator.js ***!
  13224. \************************************/
  13225. /*! no static exports found */
  13226. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  13227. /***/ (function(module, exports, __webpack_require__) {
  13228. "use strict";
  13229. /**
  13230. * Generate MP4 Box
  13231. */
  13232. Object.defineProperty(exports, "__esModule", { value: true });
  13233. var UINT32_MAX = Math.pow(2, 32) - 1;
  13234. var MP4 = /** @class */ (function () {
  13235. function MP4() {
  13236. }
  13237. MP4.init = function () {
  13238. MP4.types = {
  13239. avc1: [],
  13240. avcC: [],
  13241. btrt: [],
  13242. dinf: [],
  13243. dref: [],
  13244. esds: [],
  13245. ftyp: [],
  13246. hdlr: [],
  13247. mdat: [],
  13248. mdhd: [],
  13249. mdia: [],
  13250. mfhd: [],
  13251. minf: [],
  13252. moof: [],
  13253. moov: [],
  13254. mp4a: [],
  13255. '.mp3': [],
  13256. mvex: [],
  13257. mvhd: [],
  13258. pasp: [],
  13259. sdtp: [],
  13260. stbl: [],
  13261. stco: [],
  13262. stsc: [],
  13263. stsd: [],
  13264. stsz: [],
  13265. stts: [],
  13266. tfdt: [],
  13267. tfhd: [],
  13268. traf: [],
  13269. trak: [],
  13270. trun: [],
  13271. trex: [],
  13272. tkhd: [],
  13273. vmhd: [],
  13274. smhd: []
  13275. };
  13276. var i;
  13277. for (i in MP4.types) {
  13278. if (MP4.types.hasOwnProperty(i)) {
  13279. MP4.types[i] = [
  13280. i.charCodeAt(0),
  13281. i.charCodeAt(1),
  13282. i.charCodeAt(2),
  13283. i.charCodeAt(3)
  13284. ];
  13285. }
  13286. }
  13287. var videoHdlr = new Uint8Array([
  13288. 0x00,
  13289. 0x00, 0x00, 0x00,
  13290. 0x00, 0x00, 0x00, 0x00,
  13291. 0x76, 0x69, 0x64, 0x65,
  13292. 0x00, 0x00, 0x00, 0x00,
  13293. 0x00, 0x00, 0x00, 0x00,
  13294. 0x00, 0x00, 0x00, 0x00,
  13295. 0x56, 0x69, 0x64, 0x65,
  13296. 0x6f, 0x48, 0x61, 0x6e,
  13297. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  13298. ]);
  13299. var audioHdlr = new Uint8Array([
  13300. 0x00,
  13301. 0x00, 0x00, 0x00,
  13302. 0x00, 0x00, 0x00, 0x00,
  13303. 0x73, 0x6f, 0x75, 0x6e,
  13304. 0x00, 0x00, 0x00, 0x00,
  13305. 0x00, 0x00, 0x00, 0x00,
  13306. 0x00, 0x00, 0x00, 0x00,
  13307. 0x53, 0x6f, 0x75, 0x6e,
  13308. 0x64, 0x48, 0x61, 0x6e,
  13309. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  13310. ]);
  13311. MP4.HDLR_TYPES = {
  13312. 'video': videoHdlr,
  13313. 'audio': audioHdlr
  13314. };
  13315. var dref = new Uint8Array([
  13316. 0x00,
  13317. 0x00, 0x00, 0x00,
  13318. 0x00, 0x00, 0x00, 0x01,
  13319. 0x00, 0x00, 0x00, 0x0c,
  13320. 0x75, 0x72, 0x6c, 0x20,
  13321. 0x00,
  13322. 0x00, 0x00, 0x01 // entry_flags
  13323. ]);
  13324. var stco = new Uint8Array([
  13325. 0x00,
  13326. 0x00, 0x00, 0x00,
  13327. 0x00, 0x00, 0x00, 0x00 // entry_count
  13328. ]);
  13329. MP4.STTS = MP4.STSC = MP4.STCO = stco;
  13330. MP4.STSZ = new Uint8Array([
  13331. 0x00,
  13332. 0x00, 0x00, 0x00,
  13333. 0x00, 0x00, 0x00, 0x00,
  13334. 0x00, 0x00, 0x00, 0x00 // sample_count
  13335. ]);
  13336. MP4.VMHD = new Uint8Array([
  13337. 0x00,
  13338. 0x00, 0x00, 0x01,
  13339. 0x00, 0x00,
  13340. 0x00, 0x00,
  13341. 0x00, 0x00,
  13342. 0x00, 0x00 // opcolor
  13343. ]);
  13344. MP4.SMHD = new Uint8Array([
  13345. 0x00,
  13346. 0x00, 0x00, 0x00,
  13347. 0x00, 0x00,
  13348. 0x00, 0x00 // reserved
  13349. ]);
  13350. MP4.STSD = new Uint8Array([
  13351. 0x00,
  13352. 0x00, 0x00, 0x00,
  13353. 0x00, 0x00, 0x00, 0x01
  13354. ]); // entry_count
  13355. var majorBrand = new Uint8Array([105, 115, 111, 109]); // isom
  13356. var avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1
  13357. var minorVersion = new Uint8Array([0, 0, 0, 1]);
  13358. MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);
  13359. MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));
  13360. };
  13361. MP4.box = function (type) {
  13362. var payload = Array.prototype.slice.call(arguments, 1), size = 8, i = payload.length, len = i, result;
  13363. // calculate the total size we need to allocate
  13364. while (i--) {
  13365. size += payload[i].byteLength;
  13366. }
  13367. result = new Uint8Array(size);
  13368. result[0] = (size >> 24) & 0xff;
  13369. result[1] = (size >> 16) & 0xff;
  13370. result[2] = (size >> 8) & 0xff;
  13371. result[3] = size & 0xff;
  13372. result.set(type, 4);
  13373. // copy the payload into the result
  13374. for (i = 0, size = 8; i < len; i++) {
  13375. // copy payload[i] array @ offset size
  13376. result.set(payload[i], size);
  13377. size += payload[i].byteLength;
  13378. }
  13379. return result;
  13380. };
  13381. MP4.hdlr = function (type) {
  13382. return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);
  13383. };
  13384. MP4.mdat = function (data) {
  13385. return MP4.box(MP4.types.mdat, data);
  13386. };
  13387. MP4.mdhd = function (timescale, duration) {
  13388. duration *= timescale;
  13389. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  13390. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13391. return MP4.box(MP4.types.mdhd, new Uint8Array([
  13392. 0x01,
  13393. 0x00, 0x00, 0x00,
  13394. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  13395. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  13396. (timescale >> 24) & 0xFF,
  13397. (timescale >> 16) & 0xFF,
  13398. (timescale >> 8) & 0xFF,
  13399. timescale & 0xFF,
  13400. (upperWordDuration >> 24),
  13401. (upperWordDuration >> 16) & 0xFF,
  13402. (upperWordDuration >> 8) & 0xFF,
  13403. upperWordDuration & 0xFF,
  13404. (lowerWordDuration >> 24),
  13405. (lowerWordDuration >> 16) & 0xFF,
  13406. (lowerWordDuration >> 8) & 0xFF,
  13407. lowerWordDuration & 0xFF,
  13408. 0x55, 0xc4,
  13409. 0x00, 0x00
  13410. ]));
  13411. };
  13412. MP4.mdia = function (track) {
  13413. return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));
  13414. };
  13415. MP4.mfhd = function (sequenceNumber) {
  13416. return MP4.box(MP4.types.mfhd, new Uint8Array([
  13417. 0x00,
  13418. 0x00, 0x00, 0x00,
  13419. (sequenceNumber >> 24),
  13420. (sequenceNumber >> 16) & 0xFF,
  13421. (sequenceNumber >> 8) & 0xFF,
  13422. sequenceNumber & 0xFF // sequence_number
  13423. ]));
  13424. };
  13425. MP4.minf = function (track) {
  13426. if (track.type === 'audio') {
  13427. return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));
  13428. }
  13429. else {
  13430. return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));
  13431. }
  13432. };
  13433. MP4.moof = function (sn, baseMediaDecodeTime, track) {
  13434. return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));
  13435. };
  13436. /**
  13437. * @param tracks... (optional) {array} the tracks associated with this movie
  13438. */
  13439. MP4.moov = function (tracks) {
  13440. var i = tracks.length, boxes = [];
  13441. while (i--) {
  13442. boxes[i] = MP4.trak(tracks[i]);
  13443. }
  13444. return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));
  13445. };
  13446. MP4.mvex = function (tracks) {
  13447. var i = tracks.length, boxes = [];
  13448. while (i--) {
  13449. boxes[i] = MP4.trex(tracks[i]);
  13450. }
  13451. return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));
  13452. };
  13453. MP4.mvhd = function (timescale, duration) {
  13454. duration *= timescale;
  13455. var upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));
  13456. var lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13457. var bytes = new Uint8Array([
  13458. 0x01,
  13459. 0x00, 0x00, 0x00,
  13460. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  13461. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  13462. (timescale >> 24) & 0xFF,
  13463. (timescale >> 16) & 0xFF,
  13464. (timescale >> 8) & 0xFF,
  13465. timescale & 0xFF,
  13466. (upperWordDuration >> 24),
  13467. (upperWordDuration >> 16) & 0xFF,
  13468. (upperWordDuration >> 8) & 0xFF,
  13469. upperWordDuration & 0xFF,
  13470. (lowerWordDuration >> 24),
  13471. (lowerWordDuration >> 16) & 0xFF,
  13472. (lowerWordDuration >> 8) & 0xFF,
  13473. lowerWordDuration & 0xFF,
  13474. 0x00, 0x01, 0x00, 0x00,
  13475. 0x01, 0x00,
  13476. 0x00, 0x00,
  13477. 0x00, 0x00, 0x00, 0x00,
  13478. 0x00, 0x00, 0x00, 0x00,
  13479. 0x00, 0x01, 0x00, 0x00,
  13480. 0x00, 0x00, 0x00, 0x00,
  13481. 0x00, 0x00, 0x00, 0x00,
  13482. 0x00, 0x00, 0x00, 0x00,
  13483. 0x00, 0x01, 0x00, 0x00,
  13484. 0x00, 0x00, 0x00, 0x00,
  13485. 0x00, 0x00, 0x00, 0x00,
  13486. 0x00, 0x00, 0x00, 0x00,
  13487. 0x40, 0x00, 0x00, 0x00,
  13488. 0x00, 0x00, 0x00, 0x00,
  13489. 0x00, 0x00, 0x00, 0x00,
  13490. 0x00, 0x00, 0x00, 0x00,
  13491. 0x00, 0x00, 0x00, 0x00,
  13492. 0x00, 0x00, 0x00, 0x00,
  13493. 0x00, 0x00, 0x00, 0x00,
  13494. 0xff, 0xff, 0xff, 0xff // next_track_ID
  13495. ]);
  13496. return MP4.box(MP4.types.mvhd, bytes);
  13497. };
  13498. MP4.sdtp = function (track) {
  13499. var samples = track.samples || [], bytes = new Uint8Array(4 + samples.length), flags, i;
  13500. // leave the full box header (4 bytes) all zero
  13501. // write the sample table
  13502. for (i = 0; i < samples.length; i++) {
  13503. flags = samples[i].flags;
  13504. bytes[i + 4] = (flags.dependsOn << 4) |
  13505. (flags.isDependedOn << 2) |
  13506. (flags.hasRedundancy);
  13507. }
  13508. return MP4.box(MP4.types.sdtp, bytes);
  13509. };
  13510. MP4.stbl = function (track) {
  13511. return MP4.box(MP4.types.stbl, MP4.stsd(track), MP4.box(MP4.types.stts, MP4.STTS), MP4.box(MP4.types.stsc, MP4.STSC), MP4.box(MP4.types.stsz, MP4.STSZ), MP4.box(MP4.types.stco, MP4.STCO));
  13512. };
  13513. MP4.avc1 = function (track) {
  13514. var sps = [], pps = [], i, data, len;
  13515. // assemble the SPSs
  13516. for (i = 0; i < track.sps.length; i++) {
  13517. data = track.sps[i];
  13518. len = data.byteLength;
  13519. sps.push((len >>> 8) & 0xFF);
  13520. sps.push((len & 0xFF));
  13521. // SPS
  13522. sps = sps.concat(Array.prototype.slice.call(data));
  13523. }
  13524. // assemble the PPSs
  13525. for (i = 0; i < track.pps.length; i++) {
  13526. data = track.pps[i];
  13527. len = data.byteLength;
  13528. pps.push((len >>> 8) & 0xFF);
  13529. pps.push((len & 0xFF));
  13530. pps = pps.concat(Array.prototype.slice.call(data));
  13531. }
  13532. var avcc = MP4.box(MP4.types.avcC, new Uint8Array([
  13533. 0x01,
  13534. sps[3],
  13535. sps[4],
  13536. sps[5],
  13537. 0xfc | 3,
  13538. 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets
  13539. ].concat(sps).concat([
  13540. track.pps.length // numOfPictureParameterSets
  13541. ]).concat(pps))), // "PPS"
  13542. width = track.width, height = track.height, hSpacing = track.pixelRatio[0], vSpacing = track.pixelRatio[1];
  13543. return MP4.box(MP4.types.avc1, new Uint8Array([
  13544. 0x00, 0x00, 0x00,
  13545. 0x00, 0x00, 0x00,
  13546. 0x00, 0x01,
  13547. 0x00, 0x00,
  13548. 0x00, 0x00,
  13549. 0x00, 0x00, 0x00, 0x00,
  13550. 0x00, 0x00, 0x00, 0x00,
  13551. 0x00, 0x00, 0x00, 0x00,
  13552. (width >> 8) & 0xFF,
  13553. width & 0xff,
  13554. (height >> 8) & 0xFF,
  13555. height & 0xff,
  13556. 0x00, 0x48, 0x00, 0x00,
  13557. 0x00, 0x48, 0x00, 0x00,
  13558. 0x00, 0x00, 0x00, 0x00,
  13559. 0x00, 0x01,
  13560. 0x12,
  13561. 0x64, 0x61, 0x69, 0x6C,
  13562. 0x79, 0x6D, 0x6F, 0x74,
  13563. 0x69, 0x6F, 0x6E, 0x2F,
  13564. 0x68, 0x6C, 0x73, 0x2E,
  13565. 0x6A, 0x73, 0x00, 0x00,
  13566. 0x00, 0x00, 0x00, 0x00,
  13567. 0x00, 0x00, 0x00, 0x00,
  13568. 0x00, 0x00, 0x00,
  13569. 0x00, 0x18,
  13570. 0x11, 0x11
  13571. ]), // pre_defined = -1
  13572. avcc, MP4.box(MP4.types.btrt, new Uint8Array([
  13573. 0x00, 0x1c, 0x9c, 0x80,
  13574. 0x00, 0x2d, 0xc6, 0xc0,
  13575. 0x00, 0x2d, 0xc6, 0xc0
  13576. ])), // avgBitrate
  13577. MP4.box(MP4.types.pasp, new Uint8Array([
  13578. (hSpacing >> 24),
  13579. (hSpacing >> 16) & 0xFF,
  13580. (hSpacing >> 8) & 0xFF,
  13581. hSpacing & 0xFF,
  13582. (vSpacing >> 24),
  13583. (vSpacing >> 16) & 0xFF,
  13584. (vSpacing >> 8) & 0xFF,
  13585. vSpacing & 0xFF
  13586. ])));
  13587. };
  13588. MP4.esds = function (track) {
  13589. var configlen = track.config.length;
  13590. return new Uint8Array([
  13591. 0x00,
  13592. 0x00, 0x00, 0x00,
  13593. 0x03,
  13594. 0x17 + configlen,
  13595. 0x00, 0x01,
  13596. 0x00,
  13597. 0x04,
  13598. 0x0f + configlen,
  13599. 0x40,
  13600. 0x15,
  13601. 0x00, 0x00, 0x00,
  13602. 0x00, 0x00, 0x00, 0x00,
  13603. 0x00, 0x00, 0x00, 0x00,
  13604. 0x05 // descriptor_type
  13605. ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor
  13606. };
  13607. MP4.mp4a = function (track) {
  13608. var samplerate = track.samplerate;
  13609. return MP4.box(MP4.types.mp4a, new Uint8Array([
  13610. 0x00, 0x00, 0x00,
  13611. 0x00, 0x00, 0x00,
  13612. 0x00, 0x01,
  13613. 0x00, 0x00, 0x00, 0x00,
  13614. 0x00, 0x00, 0x00, 0x00,
  13615. 0x00, track.channelCount,
  13616. 0x00, 0x10,
  13617. 0x00, 0x00, 0x00, 0x00,
  13618. (samplerate >> 8) & 0xFF,
  13619. samplerate & 0xff,
  13620. 0x00, 0x00
  13621. ]), MP4.box(MP4.types.esds, MP4.esds(track)));
  13622. };
  13623. MP4.mp3 = function (track) {
  13624. var samplerate = track.samplerate;
  13625. return MP4.box(MP4.types['.mp3'], new Uint8Array([
  13626. 0x00, 0x00, 0x00,
  13627. 0x00, 0x00, 0x00,
  13628. 0x00, 0x01,
  13629. 0x00, 0x00, 0x00, 0x00,
  13630. 0x00, 0x00, 0x00, 0x00,
  13631. 0x00, track.channelCount,
  13632. 0x00, 0x10,
  13633. 0x00, 0x00, 0x00, 0x00,
  13634. (samplerate >> 8) & 0xFF,
  13635. samplerate & 0xff,
  13636. 0x00, 0x00
  13637. ]));
  13638. };
  13639. MP4.stsd = function (track) {
  13640. if (track.type === 'audio') {
  13641. if (!track.isAAC && track.codec === 'mp3') {
  13642. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));
  13643. }
  13644. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));
  13645. }
  13646. else {
  13647. return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));
  13648. }
  13649. };
  13650. MP4.tkhd = function (track) {
  13651. var id = track.id, duration = track.duration * track.timescale, width = track.width, height = track.height, upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)), lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));
  13652. return MP4.box(MP4.types.tkhd, new Uint8Array([
  13653. 0x01,
  13654. 0x00, 0x00, 0x07,
  13655. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
  13656. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
  13657. (id >> 24) & 0xFF,
  13658. (id >> 16) & 0xFF,
  13659. (id >> 8) & 0xFF,
  13660. id & 0xFF,
  13661. 0x00, 0x00, 0x00, 0x00,
  13662. (upperWordDuration >> 24),
  13663. (upperWordDuration >> 16) & 0xFF,
  13664. (upperWordDuration >> 8) & 0xFF,
  13665. upperWordDuration & 0xFF,
  13666. (lowerWordDuration >> 24),
  13667. (lowerWordDuration >> 16) & 0xFF,
  13668. (lowerWordDuration >> 8) & 0xFF,
  13669. lowerWordDuration & 0xFF,
  13670. 0x00, 0x00, 0x00, 0x00,
  13671. 0x00, 0x00, 0x00, 0x00,
  13672. 0x00, 0x00,
  13673. 0x00, 0x00,
  13674. 0x00, 0x00,
  13675. 0x00, 0x00,
  13676. 0x00, 0x01, 0x00, 0x00,
  13677. 0x00, 0x00, 0x00, 0x00,
  13678. 0x00, 0x00, 0x00, 0x00,
  13679. 0x00, 0x00, 0x00, 0x00,
  13680. 0x00, 0x01, 0x00, 0x00,
  13681. 0x00, 0x00, 0x00, 0x00,
  13682. 0x00, 0x00, 0x00, 0x00,
  13683. 0x00, 0x00, 0x00, 0x00,
  13684. 0x40, 0x00, 0x00, 0x00,
  13685. (width >> 8) & 0xFF,
  13686. width & 0xFF,
  13687. 0x00, 0x00,
  13688. (height >> 8) & 0xFF,
  13689. height & 0xFF,
  13690. 0x00, 0x00 // height
  13691. ]));
  13692. };
  13693. MP4.traf = function (track, baseMediaDecodeTime) {
  13694. var sampleDependencyTable = MP4.sdtp(track), id = track.id, upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)), lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));
  13695. return MP4.box(MP4.types.traf, MP4.box(MP4.types.tfhd, new Uint8Array([
  13696. 0x00,
  13697. 0x00, 0x00, 0x00,
  13698. (id >> 24),
  13699. (id >> 16) & 0XFF,
  13700. (id >> 8) & 0XFF,
  13701. (id & 0xFF) // track_ID
  13702. ])), MP4.box(MP4.types.tfdt, new Uint8Array([
  13703. 0x01,
  13704. 0x00, 0x00, 0x00,
  13705. (upperWordBaseMediaDecodeTime >> 24),
  13706. (upperWordBaseMediaDecodeTime >> 16) & 0XFF,
  13707. (upperWordBaseMediaDecodeTime >> 8) & 0XFF,
  13708. (upperWordBaseMediaDecodeTime & 0xFF),
  13709. (lowerWordBaseMediaDecodeTime >> 24),
  13710. (lowerWordBaseMediaDecodeTime >> 16) & 0XFF,
  13711. (lowerWordBaseMediaDecodeTime >> 8) & 0XFF,
  13712. (lowerWordBaseMediaDecodeTime & 0xFF)
  13713. ])), MP4.trun(track, sampleDependencyTable.length +
  13714. 16 + // tfhd
  13715. 20 + // tfdt
  13716. 8 + // traf header
  13717. 16 + // mfhd
  13718. 8 + // moof header
  13719. 8), // mdat header
  13720. sampleDependencyTable);
  13721. };
  13722. /**
  13723. * Generate a track box.
  13724. * @param track {object} a track definition
  13725. * @return {Uint8Array} the track box
  13726. */
  13727. MP4.trak = function (track) {
  13728. track.duration = track.duration || 0xffffffff;
  13729. return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));
  13730. };
  13731. MP4.trex = function (track) {
  13732. var id = track.id;
  13733. return MP4.box(MP4.types.trex, new Uint8Array([
  13734. 0x00,
  13735. 0x00, 0x00, 0x00,
  13736. (id >> 24),
  13737. (id >> 16) & 0XFF,
  13738. (id >> 8) & 0XFF,
  13739. (id & 0xFF),
  13740. 0x00, 0x00, 0x00, 0x01,
  13741. 0x00, 0x00, 0x00, 0x00,
  13742. 0x00, 0x00, 0x00, 0x00,
  13743. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  13744. ]));
  13745. };
  13746. MP4.trun = function (track, offset) {
  13747. var samples = track.samples || [], len = samples.length, arraylen = 12 + (16 * len), array = new Uint8Array(arraylen), i, sample, duration, size, flags, cts;
  13748. offset += 8 + arraylen;
  13749. array.set([
  13750. 0x00,
  13751. 0x00, 0x0f, 0x01,
  13752. (len >>> 24) & 0xFF,
  13753. (len >>> 16) & 0xFF,
  13754. (len >>> 8) & 0xFF,
  13755. len & 0xFF,
  13756. (offset >>> 24) & 0xFF,
  13757. (offset >>> 16) & 0xFF,
  13758. (offset >>> 8) & 0xFF,
  13759. offset & 0xFF // data_offset
  13760. ], 0);
  13761. for (i = 0; i < len; i++) {
  13762. sample = samples[i];
  13763. duration = sample.duration;
  13764. size = sample.size;
  13765. flags = sample.flags;
  13766. cts = sample.cts;
  13767. array.set([
  13768. (duration >>> 24) & 0xFF,
  13769. (duration >>> 16) & 0xFF,
  13770. (duration >>> 8) & 0xFF,
  13771. duration & 0xFF,
  13772. (size >>> 24) & 0xFF,
  13773. (size >>> 16) & 0xFF,
  13774. (size >>> 8) & 0xFF,
  13775. size & 0xFF,
  13776. (flags.isLeading << 2) | flags.dependsOn,
  13777. (flags.isDependedOn << 6) |
  13778. (flags.hasRedundancy << 4) |
  13779. (flags.paddingValue << 1) |
  13780. flags.isNonSync,
  13781. flags.degradPrio & 0xF0 << 8,
  13782. flags.degradPrio & 0x0F,
  13783. (cts >>> 24) & 0xFF,
  13784. (cts >>> 16) & 0xFF,
  13785. (cts >>> 8) & 0xFF,
  13786. cts & 0xFF // sample_composition_time_offset
  13787. ], 12 + 16 * i);
  13788. }
  13789. return MP4.box(MP4.types.trun, array);
  13790. };
  13791. MP4.initSegment = function (tracks) {
  13792. if (!MP4.types) {
  13793. MP4.init();
  13794. }
  13795. var movie = MP4.moov(tracks), result;
  13796. result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);
  13797. result.set(MP4.FTYP);
  13798. result.set(movie, MP4.FTYP.byteLength);
  13799. return result;
  13800. };
  13801. return MP4;
  13802. }());
  13803. exports.default = MP4;
  13804. /***/ }),
  13805. /***/ "./src/remux/mp4-remuxer.js":
  13806. /*!**********************************!*\
  13807. !*** ./src/remux/mp4-remuxer.js ***!
  13808. \**********************************/
  13809. /*! no static exports found */
  13810. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  13811. /***/ (function(module, exports, __webpack_require__) {
  13812. "use strict";
  13813. /**
  13814. * fMP4 remuxer
  13815. */
  13816. Object.defineProperty(exports, "__esModule", { value: true });
  13817. var aac_helper_1 = __webpack_require__(/*! ./aac-helper */ "./src/remux/aac-helper.js");
  13818. var mp4_generator_1 = __webpack_require__(/*! ./mp4-generator */ "./src/remux/mp4-generator.js");
  13819. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  13820. var errors_1 = __webpack_require__(/*! ../errors */ "./src/errors.js");
  13821. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  13822. // 10 seconds
  13823. var MAX_SILENT_FRAME_DURATION = 10 * 1000;
  13824. var MP4Remuxer = /** @class */ (function () {
  13825. function MP4Remuxer(observer, config, typeSupported, vendor) {
  13826. this.observer = observer;
  13827. this.config = config;
  13828. this.typeSupported = typeSupported;
  13829. var userAgent = navigator.userAgent;
  13830. this.isSafari = vendor && vendor.indexOf('Apple') > -1 && userAgent && !userAgent.match('CriOS');
  13831. this.ISGenerated = false;
  13832. }
  13833. MP4Remuxer.prototype.destroy = function () {
  13834. };
  13835. MP4Remuxer.prototype.resetTimeStamp = function (defaultTimeStamp) {
  13836. this._initPTS = this._initDTS = defaultTimeStamp;
  13837. };
  13838. MP4Remuxer.prototype.resetInitSegment = function () {
  13839. this.ISGenerated = false;
  13840. };
  13841. MP4Remuxer.prototype.remux = function (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {
  13842. // generate Init Segment if needed
  13843. if (!this.ISGenerated) {
  13844. this.generateIS(audioTrack, videoTrack, timeOffset);
  13845. }
  13846. if (this.ISGenerated) {
  13847. var nbAudioSamples = audioTrack.samples.length;
  13848. var nbVideoSamples = videoTrack.samples.length;
  13849. var audioTimeOffset = timeOffset;
  13850. var videoTimeOffset = timeOffset;
  13851. if (nbAudioSamples && nbVideoSamples) {
  13852. // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)
  13853. // if first audio DTS is not aligned with first video DTS then we need to take that into account
  13854. // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small
  13855. // drift between audio and video streams
  13856. var audiovideoDeltaDts = (audioTrack.samples[0].pts - videoTrack.samples[0].pts) / videoTrack.inputTimeScale;
  13857. audioTimeOffset += Math.max(0, audiovideoDeltaDts);
  13858. videoTimeOffset += Math.max(0, -audiovideoDeltaDts);
  13859. }
  13860. // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is
  13861. // calculated in remuxAudio.
  13862. // logger.log('nb AAC samples:' + audioTrack.samples.length);
  13863. if (nbAudioSamples) {
  13864. // if initSegment was generated without video samples, regenerate it again
  13865. if (!audioTrack.timescale) {
  13866. logger_1.logger.warn('regenerate InitSegment as audio detected');
  13867. this.generateIS(audioTrack, videoTrack, timeOffset);
  13868. }
  13869. var audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);
  13870. // logger.log('nb AVC samples:' + videoTrack.samples.length);
  13871. if (nbVideoSamples) {
  13872. var audioTrackLength = void 0;
  13873. if (audioData) {
  13874. audioTrackLength = audioData.endPTS - audioData.startPTS;
  13875. }
  13876. // if initSegment was generated without video samples, regenerate it again
  13877. if (!videoTrack.timescale) {
  13878. logger_1.logger.warn('regenerate InitSegment as video detected');
  13879. this.generateIS(audioTrack, videoTrack, timeOffset);
  13880. }
  13881. this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength, accurateTimeOffset);
  13882. }
  13883. }
  13884. else {
  13885. // logger.log('nb AVC samples:' + videoTrack.samples.length);
  13886. if (nbVideoSamples) {
  13887. var videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);
  13888. if (videoData && audioTrack.codec) {
  13889. this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);
  13890. }
  13891. }
  13892. }
  13893. }
  13894. // logger.log('nb ID3 samples:' + audioTrack.samples.length);
  13895. if (id3Track.samples.length) {
  13896. this.remuxID3(id3Track, timeOffset);
  13897. }
  13898. // logger.log('nb ID3 samples:' + audioTrack.samples.length);
  13899. if (textTrack.samples.length) {
  13900. this.remuxText(textTrack, timeOffset);
  13901. }
  13902. // notify end of parsing
  13903. this.observer.trigger(events_1.default.FRAG_PARSED);
  13904. };
  13905. MP4Remuxer.prototype.generateIS = function (audioTrack, videoTrack, timeOffset) {
  13906. var observer = this.observer, audioSamples = audioTrack.samples, videoSamples = videoTrack.samples, typeSupported = this.typeSupported, container = 'audio/mp4', tracks = {}, data = { tracks: tracks }, computePTSDTS = (this._initPTS === undefined), initPTS, initDTS;
  13907. if (computePTSDTS) {
  13908. initPTS = initDTS = Infinity;
  13909. }
  13910. if (audioTrack.config && audioSamples.length) {
  13911. // let's use audio sampling rate as MP4 time scale.
  13912. // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)
  13913. // using audio sampling rate here helps having an integer MP4 frame duration
  13914. // this avoids potential rounding issue and AV sync issue
  13915. audioTrack.timescale = audioTrack.samplerate;
  13916. logger_1.logger.log("audio sampling rate : " + audioTrack.samplerate);
  13917. if (!audioTrack.isAAC) {
  13918. if (typeSupported.mpeg) { // Chrome and Safari
  13919. container = 'audio/mpeg';
  13920. audioTrack.codec = '';
  13921. }
  13922. else if (typeSupported.mp3) { // Firefox
  13923. audioTrack.codec = 'mp3';
  13924. }
  13925. }
  13926. tracks.audio = {
  13927. container: container,
  13928. codec: audioTrack.codec,
  13929. initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : mp4_generator_1.default.initSegment([audioTrack]),
  13930. metadata: {
  13931. channelCount: audioTrack.channelCount
  13932. }
  13933. };
  13934. if (computePTSDTS) {
  13935. // remember first PTS of this demuxing context. for audio, PTS = DTS
  13936. initPTS = initDTS = audioSamples[0].pts - audioTrack.inputTimeScale * timeOffset;
  13937. }
  13938. }
  13939. if (videoTrack.sps && videoTrack.pps && videoSamples.length) {
  13940. // let's use input time scale as MP4 video timescale
  13941. // we use input time scale straight away to avoid rounding issues on frame duration / cts computation
  13942. var inputTimeScale = videoTrack.inputTimeScale;
  13943. videoTrack.timescale = inputTimeScale;
  13944. tracks.video = {
  13945. container: 'video/mp4',
  13946. codec: videoTrack.codec,
  13947. initSegment: mp4_generator_1.default.initSegment([videoTrack]),
  13948. metadata: {
  13949. width: videoTrack.width,
  13950. height: videoTrack.height
  13951. }
  13952. };
  13953. if (computePTSDTS) {
  13954. initPTS = Math.min(initPTS, videoSamples[0].pts - inputTimeScale * timeOffset);
  13955. initDTS = Math.min(initDTS, videoSamples[0].dts - inputTimeScale * timeOffset);
  13956. this.observer.trigger(events_1.default.INIT_PTS_FOUND, { initPTS: initPTS });
  13957. }
  13958. }
  13959. if (Object.keys(tracks).length) {
  13960. observer.trigger(events_1.default.FRAG_PARSING_INIT_SEGMENT, data);
  13961. this.ISGenerated = true;
  13962. if (computePTSDTS) {
  13963. this._initPTS = initPTS;
  13964. this._initDTS = initDTS;
  13965. }
  13966. }
  13967. else {
  13968. observer.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MEDIA_ERROR, details: errors_1.ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });
  13969. }
  13970. };
  13971. MP4Remuxer.prototype.remuxVideo = function (track, timeOffset, contiguous, audioTrackLength, accurateTimeOffset) {
  13972. var offset = 8;
  13973. var mp4SampleDuration;
  13974. var mdat;
  13975. var moof;
  13976. var firstPTS;
  13977. var firstDTS;
  13978. var lastPTS;
  13979. var lastDTS;
  13980. var timeScale = track.timescale;
  13981. var inputSamples = track.samples;
  13982. var outputSamples = [];
  13983. var nbSamples = inputSamples.length;
  13984. var ptsNormalize = this._PTSNormalize;
  13985. var initPTS = this._initPTS;
  13986. // if parsed fragment is contiguous with last one, let's use last DTS value as reference
  13987. var nextAvcDts = this.nextAvcDts;
  13988. var isSafari = this.isSafari;
  13989. if (nbSamples === 0) {
  13990. return;
  13991. }
  13992. // Safari does not like overlapping DTS on consecutive fragments. let's use nextAvcDts to overcome this if fragments are consecutive
  13993. if (isSafari) {
  13994. // also consider consecutive fragments as being contiguous (even if a level switch occurs),
  13995. // for sake of clarity:
  13996. // consecutive fragments are frags with
  13997. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  13998. // - less than 200 ms PTS gaps (timeScale/5)
  13999. contiguous |= (inputSamples.length && nextAvcDts &&
  14000. ((accurateTimeOffset && Math.abs(timeOffset - nextAvcDts / timeScale) < 0.1) ||
  14001. Math.abs((inputSamples[0].pts - nextAvcDts - initPTS)) < timeScale / 5));
  14002. }
  14003. if (!contiguous) {
  14004. // if not contiguous, let's use target timeOffset
  14005. nextAvcDts = timeOffset * timeScale;
  14006. }
  14007. // PTS is coded on 33bits, and can loop from -2^32 to 2^32
  14008. // ptsNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value
  14009. inputSamples.forEach(function (sample) {
  14010. sample.pts = ptsNormalize(sample.pts - initPTS, nextAvcDts);
  14011. sample.dts = ptsNormalize(sample.dts - initPTS, nextAvcDts);
  14012. });
  14013. // sort video samples by DTS then PTS then demux id order
  14014. inputSamples.sort(function (a, b) {
  14015. var deltadts = a.dts - b.dts;
  14016. var deltapts = a.pts - b.pts;
  14017. return deltadts || (deltapts || (a.id - b.id));
  14018. });
  14019. // handle broken streams with PTS < DTS, tolerance up 200ms (18000 in 90kHz timescale)
  14020. var PTSDTSshift = inputSamples.reduce(function (prev, curr) { return Math.max(Math.min(prev, curr.pts - curr.dts), -18000); }, 0);
  14021. if (PTSDTSshift < 0) {
  14022. logger_1.logger.warn("PTS < DTS detected in video samples, shifting DTS by " + Math.round(PTSDTSshift / 90) + " ms to overcome this issue");
  14023. for (var i = 0; i < inputSamples.length; i++) {
  14024. inputSamples[i].dts += PTSDTSshift;
  14025. }
  14026. }
  14027. // compute first DTS and last DTS, normalize them against reference value
  14028. var sample = inputSamples[0];
  14029. firstDTS = Math.max(sample.dts, 0);
  14030. firstPTS = Math.max(sample.pts, 0);
  14031. // check timestamp continuity accross consecutive fragments (this is to remove inter-fragment gap/hole)
  14032. var delta = Math.round((firstDTS - nextAvcDts) / 90);
  14033. // if fragment are contiguous, detect hole/overlapping between fragments
  14034. if (contiguous) {
  14035. if (delta) {
  14036. if (delta > 1) {
  14037. logger_1.logger.log("AVC:" + delta + " ms hole between fragments detected,filling it");
  14038. }
  14039. else if (delta < -1) {
  14040. logger_1.logger.log("AVC:" + (-delta) + " ms overlapping between fragments detected");
  14041. }
  14042. // remove hole/gap : set DTS to next expected DTS
  14043. firstDTS = nextAvcDts;
  14044. inputSamples[0].dts = firstDTS;
  14045. // offset PTS as well, ensure that PTS is smaller or equal than new DTS
  14046. firstPTS = Math.max(firstPTS - delta, nextAvcDts);
  14047. inputSamples[0].pts = firstPTS;
  14048. logger_1.logger.log("Video/PTS/DTS adjusted: " + Math.round(firstPTS / 90) + "/" + Math.round(firstDTS / 90) + ",delta:" + delta + " ms");
  14049. }
  14050. }
  14051. // compute lastPTS/lastDTS
  14052. sample = inputSamples[inputSamples.length - 1];
  14053. lastDTS = Math.max(sample.dts, 0);
  14054. lastPTS = Math.max(sample.pts, 0, lastDTS);
  14055. // on Safari let's signal the same sample duration for all samples
  14056. // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS
  14057. // set this constant duration as being the avg delta between consecutive DTS.
  14058. if (isSafari) {
  14059. mp4SampleDuration = Math.round((lastDTS - firstDTS) / (inputSamples.length - 1));
  14060. }
  14061. var nbNalu = 0, naluLen = 0;
  14062. for (var i = 0; i < nbSamples; i++) {
  14063. // compute total/avc sample length and nb of NAL units
  14064. var sample_1 = inputSamples[i], units = sample_1.units, nbUnits = units.length, sampleLen = 0;
  14065. for (var j = 0; j < nbUnits; j++) {
  14066. sampleLen += units[j].data.length;
  14067. }
  14068. naluLen += sampleLen;
  14069. nbNalu += nbUnits;
  14070. sample_1.length = sampleLen;
  14071. // normalize PTS/DTS
  14072. if (isSafari) {
  14073. // sample DTS is computed using a constant decoding offset (mp4SampleDuration) between samples
  14074. sample_1.dts = firstDTS + i * mp4SampleDuration;
  14075. }
  14076. else {
  14077. // ensure sample monotonic DTS
  14078. sample_1.dts = Math.max(sample_1.dts, firstDTS);
  14079. }
  14080. // ensure that computed value is greater or equal than sample DTS
  14081. sample_1.pts = Math.max(sample_1.pts, sample_1.dts);
  14082. }
  14083. /* concatenate the video data and construct the mdat in place
  14084. (need 8 more bytes to fill length and mpdat type) */
  14085. var mdatSize = naluLen + (4 * nbNalu) + 8;
  14086. try {
  14087. mdat = new Uint8Array(mdatSize);
  14088. }
  14089. catch (err) {
  14090. this.observer.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MUX_ERROR, details: errors_1.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: "fail allocating video mdat " + mdatSize });
  14091. return;
  14092. }
  14093. var view = new DataView(mdat.buffer);
  14094. view.setUint32(0, mdatSize);
  14095. mdat.set(mp4_generator_1.default.types.mdat, 4);
  14096. for (var i = 0; i < nbSamples; i++) {
  14097. var avcSample = inputSamples[i], avcSampleUnits = avcSample.units, mp4SampleLength = 0, compositionTimeOffset = void 0;
  14098. // convert NALU bitstream to MP4 format (prepend NALU with size field)
  14099. for (var j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {
  14100. var unit = avcSampleUnits[j], unitData = unit.data, unitDataLen = unit.data.byteLength;
  14101. view.setUint32(offset, unitDataLen);
  14102. offset += 4;
  14103. mdat.set(unitData, offset);
  14104. offset += unitDataLen;
  14105. mp4SampleLength += 4 + unitDataLen;
  14106. }
  14107. if (!isSafari) {
  14108. // expected sample duration is the Decoding Timestamp diff of consecutive samples
  14109. if (i < nbSamples - 1) {
  14110. mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts;
  14111. }
  14112. else {
  14113. var config = this.config, lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i - 1 : i].dts;
  14114. if (config.stretchShortVideoTrack) {
  14115. // In some cases, a segment's audio track duration may exceed the video track duration.
  14116. // Since we've already remuxed audio, and we know how long the audio track is, we look to
  14117. // see if the delta to the next segment is longer than maxBufferHole.
  14118. // If so, playback would potentially get stuck, so we artificially inflate
  14119. // the duration of the last frame to minimize any potential gap between segments.
  14120. var maxBufferHole = config.maxBufferHole, gapTolerance = Math.floor(maxBufferHole * timeScale), deltaToFrameEnd = (audioTrackLength ? firstPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;
  14121. if (deltaToFrameEnd > gapTolerance) {
  14122. // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video
  14123. // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.
  14124. mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;
  14125. if (mp4SampleDuration < 0) {
  14126. mp4SampleDuration = lastFrameDuration;
  14127. }
  14128. logger_1.logger.log("It is approximately " + deltaToFrameEnd / 90 + " ms to the next segment; using duration " + mp4SampleDuration / 90 + " ms for the last video frame.");
  14129. }
  14130. else {
  14131. mp4SampleDuration = lastFrameDuration;
  14132. }
  14133. }
  14134. else {
  14135. mp4SampleDuration = lastFrameDuration;
  14136. }
  14137. }
  14138. compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);
  14139. }
  14140. else {
  14141. compositionTimeOffset = Math.max(0, mp4SampleDuration * Math.round((avcSample.pts - avcSample.dts) / mp4SampleDuration));
  14142. }
  14143. // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');
  14144. outputSamples.push({
  14145. size: mp4SampleLength,
  14146. // constant duration
  14147. duration: mp4SampleDuration,
  14148. cts: compositionTimeOffset,
  14149. flags: {
  14150. isLeading: 0,
  14151. isDependedOn: 0,
  14152. hasRedundancy: 0,
  14153. degradPrio: 0,
  14154. dependsOn: avcSample.key ? 2 : 1,
  14155. isNonSync: avcSample.key ? 0 : 1
  14156. }
  14157. });
  14158. }
  14159. // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)
  14160. this.nextAvcDts = lastDTS + mp4SampleDuration;
  14161. var dropped = track.dropped;
  14162. track.len = 0;
  14163. track.nbNalu = 0;
  14164. track.dropped = 0;
  14165. if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
  14166. var flags = outputSamples[0].flags;
  14167. // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue
  14168. // https://code.google.com/p/chromium/issues/detail?id=229412
  14169. flags.dependsOn = 2;
  14170. flags.isNonSync = 0;
  14171. }
  14172. track.samples = outputSamples;
  14173. moof = mp4_generator_1.default.moof(track.sequenceNumber++, firstDTS, track);
  14174. track.samples = [];
  14175. var data = {
  14176. data1: moof,
  14177. data2: mdat,
  14178. startPTS: firstPTS / timeScale,
  14179. endPTS: (lastPTS + mp4SampleDuration) / timeScale,
  14180. startDTS: firstDTS / timeScale,
  14181. endDTS: this.nextAvcDts / timeScale,
  14182. type: 'video',
  14183. hasAudio: false,
  14184. hasVideo: true,
  14185. nb: outputSamples.length,
  14186. dropped: dropped
  14187. };
  14188. this.observer.trigger(events_1.default.FRAG_PARSING_DATA, data);
  14189. return data;
  14190. };
  14191. MP4Remuxer.prototype.remuxAudio = function (track, timeOffset, contiguous, accurateTimeOffset) {
  14192. var inputTimeScale = track.inputTimeScale;
  14193. var mp4timeScale = track.timescale;
  14194. var scaleFactor = inputTimeScale / mp4timeScale;
  14195. var mp4SampleDuration = track.isAAC ? 1024 : 1152;
  14196. var inputSampleDuration = mp4SampleDuration * scaleFactor;
  14197. var ptsNormalize = this._PTSNormalize;
  14198. var initPTS = this._initPTS;
  14199. var rawMPEG = !track.isAAC && this.typeSupported.mpeg;
  14200. var offset, mp4Sample, fillFrame, mdat, moof, firstPTS, lastPTS, inputSamples = track.samples, outputSamples = [], nextAudioPts = this.nextAudioPts;
  14201. // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),
  14202. // for sake of clarity:
  14203. // consecutive fragments are frags with
  14204. // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR
  14205. // - less than 20 audio frames distance
  14206. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  14207. // this helps ensuring audio continuity
  14208. // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame
  14209. contiguous |= (inputSamples.length && nextAudioPts &&
  14210. ((accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1) ||
  14211. Math.abs((inputSamples[0].pts - nextAudioPts - initPTS)) < 20 * inputSampleDuration));
  14212. // compute normalized PTS
  14213. inputSamples.forEach(function (sample) {
  14214. sample.pts = sample.dts = ptsNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);
  14215. });
  14216. // filter out sample with negative PTS that are not playable anyway
  14217. // if we don't remove these negative samples, they will shift all audio samples forward.
  14218. // leading to audio overlap between current / next fragment
  14219. inputSamples = inputSamples.filter(function (sample) {
  14220. return sample.pts >= 0;
  14221. });
  14222. // in case all samples have negative PTS, and have been filtered out, return now
  14223. if (inputSamples.length === 0) {
  14224. return;
  14225. }
  14226. if (!contiguous) {
  14227. if (!accurateTimeOffset) {
  14228. // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS
  14229. nextAudioPts = inputSamples[0].pts;
  14230. }
  14231. else {
  14232. // if timeOffset is accurate, let's use it as predicted next audio PTS
  14233. nextAudioPts = timeOffset * inputTimeScale;
  14234. }
  14235. }
  14236. // If the audio track is missing samples, the frames seem to get "left-shifted" within the
  14237. // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.
  14238. // In an effort to prevent this from happening, we inject frames here where there are gaps.
  14239. // When possible, we inject a silent frame; when that's not possible, we duplicate the last
  14240. // frame.
  14241. if (track.isAAC) {
  14242. var maxAudioFramesDrift = this.config.maxAudioFramesDrift;
  14243. for (var i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {
  14244. // First, let's see how far off this frame is from where we expect it to be
  14245. var sample = inputSamples[i], delta;
  14246. var pts = sample.pts;
  14247. delta = pts - nextPts;
  14248. var duration = Math.abs(1000 * delta / inputTimeScale);
  14249. // If we're overlapping by more than a duration, drop this sample
  14250. if (delta <= -maxAudioFramesDrift * inputSampleDuration) {
  14251. logger_1.logger.warn("Dropping 1 audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(duration) + " ms overlap.");
  14252. inputSamples.splice(i, 1);
  14253. track.len -= sample.unit.length;
  14254. // Don't touch nextPtsNorm or i
  14255. } // eslint-disable-line brace-style
  14256. // Insert missing frames if:
  14257. // 1: We're more than maxAudioFramesDrift frame away
  14258. // 2: Not more than MAX_SILENT_FRAME_DURATION away
  14259. // 3: currentTime (aka nextPtsNorm) is not 0
  14260. else if (delta >= maxAudioFramesDrift * inputSampleDuration && duration < MAX_SILENT_FRAME_DURATION && nextPts) {
  14261. var missing = Math.round(delta / inputSampleDuration);
  14262. logger_1.logger.warn("Injecting " + missing + " audio frame @ " + (nextPts / inputTimeScale).toFixed(3) + "s due to " + Math.round(1000 * delta / inputTimeScale) + " ms gap.");
  14263. for (var j = 0; j < missing; j++) {
  14264. var newStamp = Math.max(nextPts, 0);
  14265. fillFrame = aac_helper_1.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  14266. if (!fillFrame) {
  14267. logger_1.logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');
  14268. fillFrame = sample.unit.subarray();
  14269. }
  14270. inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });
  14271. track.len += fillFrame.length;
  14272. nextPts += inputSampleDuration;
  14273. i++;
  14274. }
  14275. // Adjust sample to next expected pts
  14276. sample.pts = sample.dts = nextPts;
  14277. nextPts += inputSampleDuration;
  14278. i++;
  14279. }
  14280. else {
  14281. // Otherwise, just adjust pts
  14282. if (Math.abs(delta) > (0.1 * inputSampleDuration)) {
  14283. // logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);
  14284. }
  14285. sample.pts = sample.dts = nextPts;
  14286. nextPts += inputSampleDuration;
  14287. i++;
  14288. }
  14289. }
  14290. }
  14291. for (var j = 0, nbSamples_1 = inputSamples.length; j < nbSamples_1; j++) {
  14292. var audioSample = inputSamples[j];
  14293. var unit = audioSample.unit;
  14294. var pts = audioSample.pts;
  14295. // logger.log(`Audio/PTS:${Math.round(pts/90)}`);
  14296. // if not first sample
  14297. if (lastPTS !== undefined) {
  14298. mp4Sample.duration = Math.round((pts - lastPTS) / scaleFactor);
  14299. }
  14300. else {
  14301. var delta_1 = Math.round(1000 * (pts - nextAudioPts) / inputTimeScale), numMissingFrames = 0;
  14302. // if fragment are contiguous, detect hole/overlapping between fragments
  14303. // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)
  14304. if (contiguous && track.isAAC) {
  14305. // log delta
  14306. if (delta_1) {
  14307. if (delta_1 > 0 && delta_1 < MAX_SILENT_FRAME_DURATION) {
  14308. numMissingFrames = Math.round((pts - nextAudioPts) / inputSampleDuration);
  14309. logger_1.logger.log(delta_1 + " ms hole between AAC samples detected,filling it");
  14310. if (numMissingFrames > 0) {
  14311. fillFrame = aac_helper_1.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  14312. if (!fillFrame) {
  14313. fillFrame = unit.subarray();
  14314. }
  14315. track.len += numMissingFrames * fillFrame.length;
  14316. }
  14317. // if we have frame overlap, overlapping for more than half a frame duraion
  14318. }
  14319. else if (delta_1 < -12) {
  14320. // drop overlapping audio frames... browser will deal with it
  14321. logger_1.logger.log("drop overlapping AAC sample, expected/parsed/delta:" + (nextAudioPts / inputTimeScale).toFixed(3) + "s/" + (pts / inputTimeScale).toFixed(3) + "s/" + (-delta_1) + "ms");
  14322. track.len -= unit.byteLength;
  14323. continue;
  14324. }
  14325. // set PTS/DTS to expected PTS/DTS
  14326. pts = nextAudioPts;
  14327. }
  14328. }
  14329. // remember first PTS of our audioSamples
  14330. firstPTS = pts;
  14331. if (track.len > 0) {
  14332. /* concatenate the audio data and construct the mdat in place
  14333. (need 8 more bytes to fill length and mdat type) */
  14334. var mdatSize = rawMPEG ? track.len : track.len + 8;
  14335. offset = rawMPEG ? 0 : 8;
  14336. try {
  14337. mdat = new Uint8Array(mdatSize);
  14338. }
  14339. catch (err) {
  14340. this.observer.trigger(events_1.default.ERROR, { type: errors_1.ErrorTypes.MUX_ERROR, details: errors_1.ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: "fail allocating audio mdat " + mdatSize });
  14341. return;
  14342. }
  14343. if (!rawMPEG) {
  14344. var view = new DataView(mdat.buffer);
  14345. view.setUint32(0, mdatSize);
  14346. mdat.set(mp4_generator_1.default.types.mdat, 4);
  14347. }
  14348. }
  14349. else {
  14350. // no audio samples
  14351. return;
  14352. }
  14353. for (var i = 0; i < numMissingFrames; i++) {
  14354. fillFrame = aac_helper_1.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  14355. if (!fillFrame) {
  14356. logger_1.logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');
  14357. fillFrame = unit.subarray();
  14358. }
  14359. mdat.set(fillFrame, offset);
  14360. offset += fillFrame.byteLength;
  14361. mp4Sample = {
  14362. size: fillFrame.byteLength,
  14363. cts: 0,
  14364. duration: 1024,
  14365. flags: {
  14366. isLeading: 0,
  14367. isDependedOn: 0,
  14368. hasRedundancy: 0,
  14369. degradPrio: 0,
  14370. dependsOn: 1
  14371. }
  14372. };
  14373. outputSamples.push(mp4Sample);
  14374. }
  14375. }
  14376. mdat.set(unit, offset);
  14377. var unitLen = unit.byteLength;
  14378. offset += unitLen;
  14379. // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');
  14380. mp4Sample = {
  14381. size: unitLen,
  14382. cts: 0,
  14383. duration: 0,
  14384. flags: {
  14385. isLeading: 0,
  14386. isDependedOn: 0,
  14387. hasRedundancy: 0,
  14388. degradPrio: 0,
  14389. dependsOn: 1
  14390. }
  14391. };
  14392. outputSamples.push(mp4Sample);
  14393. lastPTS = pts;
  14394. }
  14395. var lastSampleDuration = 0;
  14396. var nbSamples = outputSamples.length;
  14397. // set last sample duration as being identical to previous sample
  14398. if (nbSamples >= 2) {
  14399. lastSampleDuration = outputSamples[nbSamples - 2].duration;
  14400. mp4Sample.duration = lastSampleDuration;
  14401. }
  14402. if (nbSamples) {
  14403. // next audio sample PTS should be equal to last sample PTS + duration
  14404. this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;
  14405. // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));
  14406. track.len = 0;
  14407. track.samples = outputSamples;
  14408. if (rawMPEG) {
  14409. moof = new Uint8Array();
  14410. }
  14411. else {
  14412. moof = mp4_generator_1.default.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);
  14413. }
  14414. track.samples = [];
  14415. var start = firstPTS / inputTimeScale;
  14416. var end = nextAudioPts / inputTimeScale;
  14417. var audioData = {
  14418. data1: moof,
  14419. data2: mdat,
  14420. startPTS: start,
  14421. endPTS: end,
  14422. startDTS: start,
  14423. endDTS: end,
  14424. type: 'audio',
  14425. hasAudio: true,
  14426. hasVideo: false,
  14427. nb: nbSamples
  14428. };
  14429. this.observer.trigger(events_1.default.FRAG_PARSING_DATA, audioData);
  14430. return audioData;
  14431. }
  14432. return null;
  14433. };
  14434. MP4Remuxer.prototype.remuxEmptyAudio = function (track, timeOffset, contiguous, videoData) {
  14435. var inputTimeScale = track.inputTimeScale, mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale, scaleFactor = inputTimeScale / mp4timeScale, nextAudioPts = this.nextAudioPts,
  14436. // sync with video's timestamp
  14437. startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS, endDTS = videoData.endDTS * inputTimeScale + this._initDTS,
  14438. // one sample's duration value
  14439. sampleDuration = 1024, frameDuration = scaleFactor * sampleDuration,
  14440. // samples count of this segment's duration
  14441. nbSamples = Math.ceil((endDTS - startDTS) / frameDuration),
  14442. // silent frame
  14443. silentFrame = aac_helper_1.default.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);
  14444. logger_1.logger.warn('remux empty Audio');
  14445. // Can't remux if we can't generate a silent frame...
  14446. if (!silentFrame) {
  14447. logger_1.logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');
  14448. return;
  14449. }
  14450. var samples = [];
  14451. for (var i = 0; i < nbSamples; i++) {
  14452. var stamp = startDTS + i * frameDuration;
  14453. samples.push({ unit: silentFrame, pts: stamp, dts: stamp });
  14454. track.len += silentFrame.length;
  14455. }
  14456. track.samples = samples;
  14457. this.remuxAudio(track, timeOffset, contiguous);
  14458. };
  14459. MP4Remuxer.prototype.remuxID3 = function (track) {
  14460. var length = track.samples.length, sample;
  14461. var inputTimeScale = track.inputTimeScale;
  14462. var initPTS = this._initPTS;
  14463. var initDTS = this._initDTS;
  14464. // consume samples
  14465. if (length) {
  14466. for (var index = 0; index < length; index++) {
  14467. sample = track.samples[index];
  14468. // setting id3 pts, dts to relative time
  14469. // using this._initPTS and this._initDTS to calculate relative time
  14470. sample.pts = ((sample.pts - initPTS) / inputTimeScale);
  14471. sample.dts = ((sample.dts - initDTS) / inputTimeScale);
  14472. }
  14473. this.observer.trigger(events_1.default.FRAG_PARSING_METADATA, {
  14474. samples: track.samples
  14475. });
  14476. }
  14477. track.samples = [];
  14478. };
  14479. MP4Remuxer.prototype.remuxText = function (track) {
  14480. track.samples.sort(function (a, b) {
  14481. return (a.pts - b.pts);
  14482. });
  14483. var length = track.samples.length, sample;
  14484. var inputTimeScale = track.inputTimeScale;
  14485. var initPTS = this._initPTS;
  14486. // consume samples
  14487. if (length) {
  14488. for (var index = 0; index < length; index++) {
  14489. sample = track.samples[index];
  14490. // setting text pts, dts to relative time
  14491. // using this._initPTS and this._initDTS to calculate relative time
  14492. sample.pts = ((sample.pts - initPTS) / inputTimeScale);
  14493. }
  14494. this.observer.trigger(events_1.default.FRAG_PARSING_USERDATA, {
  14495. samples: track.samples
  14496. });
  14497. }
  14498. track.samples = [];
  14499. };
  14500. MP4Remuxer.prototype._PTSNormalize = function (value, reference) {
  14501. var offset;
  14502. if (reference === undefined) {
  14503. return value;
  14504. }
  14505. if (reference < value) {
  14506. // - 2^33
  14507. offset = -8589934592;
  14508. }
  14509. else {
  14510. // + 2^33
  14511. offset = 8589934592;
  14512. }
  14513. /* PTS is 33bit (from 0 to 2^33 -1)
  14514. if diff between value and reference is bigger than half of the amplitude (2^32) then it means that
  14515. PTS looping occured. fill the gap */
  14516. while (Math.abs(value - reference) > 4294967296) {
  14517. value += offset;
  14518. }
  14519. return value;
  14520. };
  14521. return MP4Remuxer;
  14522. }());
  14523. exports.default = MP4Remuxer;
  14524. /***/ }),
  14525. /***/ "./src/remux/passthrough-remuxer.js":
  14526. /*!******************************************!*\
  14527. !*** ./src/remux/passthrough-remuxer.js ***!
  14528. \******************************************/
  14529. /*! no static exports found */
  14530. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  14531. /***/ (function(module, exports, __webpack_require__) {
  14532. "use strict";
  14533. Object.defineProperty(exports, "__esModule", { value: true });
  14534. /**
  14535. * passthrough remuxer
  14536. */
  14537. var events_1 = __webpack_require__(/*! ../events */ "./src/events.js");
  14538. var PassThroughRemuxer = /** @class */ (function () {
  14539. function PassThroughRemuxer(observer) {
  14540. this.observer = observer;
  14541. }
  14542. PassThroughRemuxer.prototype.destroy = function () {
  14543. };
  14544. PassThroughRemuxer.prototype.resetTimeStamp = function () {
  14545. };
  14546. PassThroughRemuxer.prototype.resetInitSegment = function () {
  14547. };
  14548. PassThroughRemuxer.prototype.remux = function (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {
  14549. var observer = this.observer;
  14550. var streamType = '';
  14551. if (audioTrack) {
  14552. streamType += 'audio';
  14553. }
  14554. if (videoTrack) {
  14555. streamType += 'video';
  14556. }
  14557. observer.trigger(events_1.default.FRAG_PARSING_DATA, {
  14558. data1: rawData,
  14559. startPTS: timeOffset,
  14560. startDTS: timeOffset,
  14561. type: streamType,
  14562. hasAudio: !!audioTrack,
  14563. hasVideo: !!videoTrack,
  14564. nb: 1,
  14565. dropped: 0
  14566. });
  14567. // notify end of parsing
  14568. observer.trigger(events_1.default.FRAG_PARSED);
  14569. };
  14570. return PassThroughRemuxer;
  14571. }());
  14572. exports.default = PassThroughRemuxer;
  14573. /***/ }),
  14574. /***/ "./src/task-loop.js":
  14575. /*!**************************!*\
  14576. !*** ./src/task-loop.js ***!
  14577. \**************************/
  14578. /*! no static exports found */
  14579. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  14580. /***/ (function(module, exports, __webpack_require__) {
  14581. "use strict";
  14582. var __extends = (this && this.__extends) || (function () {
  14583. var extendStatics = Object.setPrototypeOf ||
  14584. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  14585. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  14586. return function (d, b) {
  14587. extendStatics(d, b);
  14588. function __() { this.constructor = d; }
  14589. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  14590. };
  14591. })();
  14592. Object.defineProperty(exports, "__esModule", { value: true });
  14593. var event_handler_1 = __webpack_require__(/*! ./event-handler */ "./src/event-handler.js");
  14594. /**
  14595. * Sub-class specialization of EventHandler base class.
  14596. *
  14597. * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,
  14598. * scheduled asynchroneously, avoiding recursive calls in the same tick.
  14599. *
  14600. * The task itself is implemented in `doTick`. It can be requested and called for single execution
  14601. * using the `tick` method.
  14602. *
  14603. * It will be assured that the task execution method (`tick`) only gets called once per main loop "tick",
  14604. * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.
  14605. *
  14606. * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,
  14607. * and cancelled with `clearNextTick`.
  14608. *
  14609. * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).
  14610. *
  14611. * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.
  14612. *
  14613. * Further explanations:
  14614. *
  14615. * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously
  14616. * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.
  14617. *
  14618. * When the task execution (`tick` method) is called in re-entrant way this is detected and
  14619. * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further
  14620. * task processing on the next main loop iteration (also known as "next tick" in the Node/JS runtime lingo).
  14621. */
  14622. var TaskLoop = /** @class */ (function (_super) {
  14623. __extends(TaskLoop, _super);
  14624. function TaskLoop(hls) {
  14625. var events = [];
  14626. for (var _i = 1; _i < arguments.length; _i++) {
  14627. events[_i - 1] = arguments[_i];
  14628. }
  14629. var _this = _super.apply(this, [hls].concat(events)) || this;
  14630. _this._tickInterval = null;
  14631. _this._tickTimer = null;
  14632. _this._tickCallCount = 0;
  14633. _this._boundTick = _this.tick.bind(_this);
  14634. return _this;
  14635. }
  14636. /**
  14637. * @override
  14638. */
  14639. TaskLoop.prototype.onHandlerDestroying = function () {
  14640. // clear all timers before unregistering from event bus
  14641. this.clearNextTick();
  14642. this.clearInterval();
  14643. };
  14644. /**
  14645. * @returns {boolean}
  14646. */
  14647. TaskLoop.prototype.hasInterval = function () {
  14648. return !!this._tickInterval;
  14649. };
  14650. /**
  14651. * @returns {boolean}
  14652. */
  14653. TaskLoop.prototype.hasNextTick = function () {
  14654. return !!this._tickTimer;
  14655. };
  14656. /**
  14657. * @param {number} millis Interval time (ms)
  14658. * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)
  14659. */
  14660. TaskLoop.prototype.setInterval = function (millis) {
  14661. if (!this._tickInterval) {
  14662. this._tickInterval = setInterval(this._boundTick, millis);
  14663. return true;
  14664. }
  14665. return false;
  14666. };
  14667. /**
  14668. * @returns {boolean} True when interval was cleared, false when none was set (no effect)
  14669. */
  14670. TaskLoop.prototype.clearInterval = function () {
  14671. if (this._tickInterval) {
  14672. clearInterval(this._tickInterval);
  14673. this._tickInterval = null;
  14674. return true;
  14675. }
  14676. return false;
  14677. };
  14678. /**
  14679. * @returns {boolean} True when timeout was cleared, false when none was set (no effect)
  14680. */
  14681. TaskLoop.prototype.clearNextTick = function () {
  14682. if (this._tickTimer) {
  14683. clearTimeout(this._tickTimer);
  14684. this._tickTimer = null;
  14685. return true;
  14686. }
  14687. return false;
  14688. };
  14689. /**
  14690. * Will call the subclass doTick implementation in this main loop tick
  14691. * or in the next one (via setTimeout(,0)) in case it has already been called
  14692. * in this tick (in case this is a re-entrant call).
  14693. */
  14694. TaskLoop.prototype.tick = function () {
  14695. this._tickCallCount++;
  14696. if (this._tickCallCount === 1) {
  14697. this.doTick();
  14698. // re-entrant call to tick from previous doTick call stack
  14699. // -> schedule a call on the next main loop iteration to process this task processing request
  14700. if (this._tickCallCount > 1) {
  14701. // make sure only one timer exists at any time at max
  14702. this.clearNextTick();
  14703. this._tickTimer = setTimeout(this._boundTick, 0);
  14704. }
  14705. this._tickCallCount = 0;
  14706. }
  14707. };
  14708. /**
  14709. * For subclass to implement task logic
  14710. * @abstract
  14711. */
  14712. TaskLoop.prototype.doTick = function () { };
  14713. return TaskLoop;
  14714. }(event_handler_1.default));
  14715. exports.default = TaskLoop;
  14716. /***/ }),
  14717. /***/ "./src/utils/attr-list.js":
  14718. /*!********************************!*\
  14719. !*** ./src/utils/attr-list.js ***!
  14720. \********************************/
  14721. /*! no static exports found */
  14722. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  14723. /***/ (function(module, exports, __webpack_require__) {
  14724. "use strict";
  14725. /* WEBPACK VAR INJECTION */(function(Number) {
  14726. Object.defineProperty(exports, "__esModule", { value: true });
  14727. var DECIMAL_RESOLUTION_REGEX = /^(\d+)x(\d+)$/; // eslint-disable-line no-useless-escape
  14728. var ATTR_LIST_REGEX = /\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape
  14729. // adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js
  14730. var AttrList = /** @class */ (function () {
  14731. function AttrList(attrs) {
  14732. if (typeof attrs === 'string') {
  14733. attrs = AttrList.parseAttrList(attrs);
  14734. }
  14735. for (var attr in attrs) {
  14736. if (attrs.hasOwnProperty(attr)) {
  14737. this[attr] = attrs[attr];
  14738. }
  14739. }
  14740. }
  14741. AttrList.prototype.decimalInteger = function (attrName) {
  14742. var intValue = parseInt(this[attrName], 10);
  14743. if (intValue > Number.MAX_SAFE_INTEGER) {
  14744. return Infinity;
  14745. }
  14746. return intValue;
  14747. };
  14748. AttrList.prototype.hexadecimalInteger = function (attrName) {
  14749. if (this[attrName]) {
  14750. var stringValue = (this[attrName] || '0x').slice(2);
  14751. stringValue = ((stringValue.length & 1) ? '0' : '') + stringValue;
  14752. var value = new Uint8Array(stringValue.length / 2);
  14753. for (var i = 0; i < stringValue.length / 2; i++) {
  14754. value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);
  14755. }
  14756. return value;
  14757. }
  14758. else {
  14759. return null;
  14760. }
  14761. };
  14762. AttrList.prototype.hexadecimalIntegerAsNumber = function (attrName) {
  14763. var intValue = parseInt(this[attrName], 16);
  14764. if (intValue > Number.MAX_SAFE_INTEGER) {
  14765. return Infinity;
  14766. }
  14767. return intValue;
  14768. };
  14769. AttrList.prototype.decimalFloatingPoint = function (attrName) {
  14770. return parseFloat(this[attrName]);
  14771. };
  14772. AttrList.prototype.enumeratedString = function (attrName) {
  14773. return this[attrName];
  14774. };
  14775. AttrList.prototype.decimalResolution = function (attrName) {
  14776. var res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);
  14777. if (res === null) {
  14778. return undefined;
  14779. }
  14780. return {
  14781. width: parseInt(res[1], 10),
  14782. height: parseInt(res[2], 10)
  14783. };
  14784. };
  14785. AttrList.parseAttrList = function (input) {
  14786. var match, attrs = {};
  14787. ATTR_LIST_REGEX.lastIndex = 0;
  14788. while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {
  14789. var value = match[2], quote = '"';
  14790. if (value.indexOf(quote) === 0 &&
  14791. value.lastIndexOf(quote) === (value.length - 1)) {
  14792. value = value.slice(1, -1);
  14793. }
  14794. attrs[match[1]] = value;
  14795. }
  14796. return attrs;
  14797. };
  14798. return AttrList;
  14799. }());
  14800. exports.default = AttrList;
  14801. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  14802. /***/ }),
  14803. /***/ "./src/utils/binary-search.js":
  14804. /*!************************************!*\
  14805. !*** ./src/utils/binary-search.js ***!
  14806. \************************************/
  14807. /*! no static exports found */
  14808. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  14809. /***/ (function(module, exports, __webpack_require__) {
  14810. "use strict";
  14811. Object.defineProperty(exports, "__esModule", { value: true });
  14812. var BinarySearch = {
  14813. /**
  14814. * Searches for an item in an array which matches a certain condition.
  14815. * This requires the condition to only match one item in the array,
  14816. * and for the array to be ordered.
  14817. *
  14818. * @param {Array} list The array to search.
  14819. * @param {Function} comparisonFunction
  14820. * Called and provided a candidate item as the first argument.
  14821. * Should return:
  14822. * > -1 if the item should be located at a lower index than the provided item.
  14823. * > 1 if the item should be located at a higher index than the provided item.
  14824. * > 0 if the item is the item you're looking for.
  14825. *
  14826. * @return {*} The object if it is found or null otherwise.
  14827. */
  14828. search: function (list, comparisonFunction) {
  14829. var minIndex = 0;
  14830. var maxIndex = list.length - 1;
  14831. var currentIndex = null;
  14832. var currentElement = null;
  14833. while (minIndex <= maxIndex) {
  14834. currentIndex = (minIndex + maxIndex) / 2 | 0;
  14835. currentElement = list[currentIndex];
  14836. var comparisonResult = comparisonFunction(currentElement);
  14837. if (comparisonResult > 0) {
  14838. minIndex = currentIndex + 1;
  14839. }
  14840. else if (comparisonResult < 0) {
  14841. maxIndex = currentIndex - 1;
  14842. }
  14843. else {
  14844. return currentElement;
  14845. }
  14846. }
  14847. return null;
  14848. }
  14849. };
  14850. exports.default = BinarySearch;
  14851. /***/ }),
  14852. /***/ "./src/utils/buffer-helper.js":
  14853. /*!************************************!*\
  14854. !*** ./src/utils/buffer-helper.js ***!
  14855. \************************************/
  14856. /*! no static exports found */
  14857. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  14858. /***/ (function(module, exports, __webpack_require__) {
  14859. "use strict";
  14860. /**
  14861. * @module BufferHelper
  14862. *
  14863. * Providing methods dealing with buffer length retrieval for example.
  14864. *
  14865. * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.
  14866. *
  14867. * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered
  14868. */
  14869. Object.defineProperty(exports, "__esModule", { value: true });
  14870. var BufferHelper = /** @class */ (function () {
  14871. function BufferHelper() {
  14872. }
  14873. /**
  14874. * Return true if `media`'s buffered include `position`
  14875. * @param {HTMLMediaElement|SourceBuffer} media
  14876. * @param {number} position
  14877. * @returns {boolean}
  14878. */
  14879. BufferHelper.isBuffered = function (media, position) {
  14880. try {
  14881. if (media) {
  14882. var buffered = media.buffered;
  14883. for (var i = 0; i < buffered.length; i++) {
  14884. if (position >= buffered.start(i) && position <= buffered.end(i)) {
  14885. return true;
  14886. }
  14887. }
  14888. }
  14889. }
  14890. catch (error) {
  14891. // this is to catch
  14892. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  14893. // This SourceBuffer has been removed from the parent media source
  14894. }
  14895. return false;
  14896. };
  14897. BufferHelper.bufferInfo = function (media, pos, maxHoleDuration) {
  14898. try {
  14899. if (media) {
  14900. var vbuffered = media.buffered, buffered = [], i = void 0;
  14901. for (i = 0; i < vbuffered.length; i++) {
  14902. buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });
  14903. }
  14904. return this.bufferedInfo(buffered, pos, maxHoleDuration);
  14905. }
  14906. }
  14907. catch (error) {
  14908. // this is to catch
  14909. // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':
  14910. // This SourceBuffer has been removed from the parent media source
  14911. }
  14912. return { len: 0, start: pos, end: pos, nextStart: undefined };
  14913. };
  14914. BufferHelper.bufferedInfo = function (buffered, pos, maxHoleDuration) {
  14915. var buffered2 = [],
  14916. // bufferStart and bufferEnd are buffer boundaries around current video position
  14917. bufferLen, bufferStart, bufferEnd, bufferStartNext, i;
  14918. // sort on buffer.start/smaller end (IE does not always return sorted buffered range)
  14919. buffered.sort(function (a, b) {
  14920. var diff = a.start - b.start;
  14921. if (diff) {
  14922. return diff;
  14923. }
  14924. else {
  14925. return b.end - a.end;
  14926. }
  14927. });
  14928. // there might be some small holes between buffer time range
  14929. // consider that holes smaller than maxHoleDuration are irrelevant and build another
  14930. // buffer time range representations that discards those holes
  14931. for (i = 0; i < buffered.length; i++) {
  14932. var buf2len = buffered2.length;
  14933. if (buf2len) {
  14934. var buf2end = buffered2[buf2len - 1].end;
  14935. // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)
  14936. if ((buffered[i].start - buf2end) < maxHoleDuration) {
  14937. // merge overlapping time ranges
  14938. // update lastRange.end only if smaller than item.end
  14939. // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)
  14940. // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])
  14941. if (buffered[i].end > buf2end) {
  14942. buffered2[buf2len - 1].end = buffered[i].end;
  14943. }
  14944. }
  14945. else {
  14946. // big hole
  14947. buffered2.push(buffered[i]);
  14948. }
  14949. }
  14950. else {
  14951. // first value
  14952. buffered2.push(buffered[i]);
  14953. }
  14954. }
  14955. for (i = 0, bufferLen = 0, bufferStart = bufferEnd = pos; i < buffered2.length; i++) {
  14956. var start = buffered2[i].start, end = buffered2[i].end;
  14957. // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));
  14958. if ((pos + maxHoleDuration) >= start && pos < end) {
  14959. // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length
  14960. bufferStart = start;
  14961. bufferEnd = end;
  14962. bufferLen = bufferEnd - pos;
  14963. }
  14964. else if ((pos + maxHoleDuration) < start) {
  14965. bufferStartNext = start;
  14966. break;
  14967. }
  14968. }
  14969. return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };
  14970. };
  14971. return BufferHelper;
  14972. }());
  14973. exports.BufferHelper = BufferHelper;
  14974. /***/ }),
  14975. /***/ "./src/utils/cea-608-parser.js":
  14976. /*!*************************************!*\
  14977. !*** ./src/utils/cea-608-parser.js ***!
  14978. \*************************************/
  14979. /*! no static exports found */
  14980. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  14981. /***/ (function(module, exports, __webpack_require__) {
  14982. "use strict";
  14983. /**
  14984. *
  14985. * This code was ported from the dash.js project at:
  14986. * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js
  14987. * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2
  14988. *
  14989. * The original copyright appears below:
  14990. *
  14991. * The copyright in this software is being made available under the BSD License,
  14992. * included below. This software may be subject to other third party and contributor
  14993. * rights, including patent rights, and no such rights are granted under this license.
  14994. *
  14995. * Copyright (c) 2015-2016, DASH Industry Forum.
  14996. * All rights reserved.
  14997. *
  14998. * Redistribution and use in source and binary forms, with or without modification,
  14999. * are permitted provided that the following conditions are met:
  15000. * 1. Redistributions of source code must retain the above copyright notice, this
  15001. * list of conditions and the following disclaimer.
  15002. * * Redistributions in binary form must reproduce the above copyright notice,
  15003. * this list of conditions and the following disclaimer in the documentation and/or
  15004. * other materials provided with the distribution.
  15005. * 2. Neither the name of Dash Industry Forum nor the names of its
  15006. * contributors may be used to endorse or promote products derived from this software
  15007. * without specific prior written permission.
  15008. *
  15009. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY
  15010. * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  15011. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  15012. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
  15013. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  15014. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  15015. * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  15016. * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  15017. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  15018. * POSSIBILITY OF SUCH DAMAGE.
  15019. */
  15020. /**
  15021. * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes
  15022. */
  15023. Object.defineProperty(exports, "__esModule", { value: true });
  15024. var specialCea608CharsCodes = {
  15025. 0x2a: 0xe1,
  15026. 0x5c: 0xe9,
  15027. 0x5e: 0xed,
  15028. 0x5f: 0xf3,
  15029. 0x60: 0xfa,
  15030. 0x7b: 0xe7,
  15031. 0x7c: 0xf7,
  15032. 0x7d: 0xd1,
  15033. 0x7e: 0xf1,
  15034. 0x7f: 0x2588,
  15035. // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  15036. // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F
  15037. // THIS MEANS THAT \x50 MUST BE ADDED TO THE VALUES
  15038. 0x80: 0xae,
  15039. 0x81: 0xb0,
  15040. 0x82: 0xbd,
  15041. 0x83: 0xbf,
  15042. 0x84: 0x2122,
  15043. 0x85: 0xa2,
  15044. 0x86: 0xa3,
  15045. 0x87: 0x266a,
  15046. 0x88: 0xe0,
  15047. 0x89: 0x20,
  15048. 0x8a: 0xe8,
  15049. 0x8b: 0xe2,
  15050. 0x8c: 0xea,
  15051. 0x8d: 0xee,
  15052. 0x8e: 0xf4,
  15053. 0x8f: 0xfb,
  15054. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  15055. // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F
  15056. 0x90: 0xc1,
  15057. 0x91: 0xc9,
  15058. 0x92: 0xd3,
  15059. 0x93: 0xda,
  15060. 0x94: 0xdc,
  15061. 0x95: 0xfc,
  15062. 0x96: 0x2018,
  15063. 0x97: 0xa1,
  15064. 0x98: 0x2a,
  15065. 0x99: 0x2019,
  15066. 0x9a: 0x2501,
  15067. 0x9b: 0xa9,
  15068. 0x9c: 0x2120,
  15069. 0x9d: 0x2022,
  15070. 0x9e: 0x201c,
  15071. 0x9f: 0x201d,
  15072. 0xa0: 0xc0,
  15073. 0xa1: 0xc2,
  15074. 0xa2: 0xc7,
  15075. 0xa3: 0xc8,
  15076. 0xa4: 0xca,
  15077. 0xa5: 0xcb,
  15078. 0xa6: 0xeb,
  15079. 0xa7: 0xce,
  15080. 0xa8: 0xcf,
  15081. 0xa9: 0xef,
  15082. 0xaa: 0xd4,
  15083. 0xab: 0xd9,
  15084. 0xac: 0xf9,
  15085. 0xad: 0xdb,
  15086. 0xae: 0xab,
  15087. 0xaf: 0xbb,
  15088. // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS
  15089. // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F
  15090. 0xb0: 0xc3,
  15091. 0xb1: 0xe3,
  15092. 0xb2: 0xcd,
  15093. 0xb3: 0xcc,
  15094. 0xb4: 0xec,
  15095. 0xb5: 0xd2,
  15096. 0xb6: 0xf2,
  15097. 0xb7: 0xd5,
  15098. 0xb8: 0xf5,
  15099. 0xb9: 0x7b,
  15100. 0xba: 0x7d,
  15101. 0xbb: 0x5c,
  15102. 0xbc: 0x5e,
  15103. 0xbd: 0x5f,
  15104. 0xbe: 0x7c,
  15105. 0xbf: 0x223c,
  15106. 0xc0: 0xc4,
  15107. 0xc1: 0xe4,
  15108. 0xc2: 0xd6,
  15109. 0xc3: 0xf6,
  15110. 0xc4: 0xdf,
  15111. 0xc5: 0xa5,
  15112. 0xc6: 0xa4,
  15113. 0xc7: 0x2503,
  15114. 0xc8: 0xc5,
  15115. 0xc9: 0xe5,
  15116. 0xca: 0xd8,
  15117. 0xcb: 0xf8,
  15118. 0xcc: 0x250f,
  15119. 0xcd: 0x2513,
  15120. 0xce: 0x2517,
  15121. 0xcf: 0x251b // Box drawings heavy up and left
  15122. };
  15123. /**
  15124. * Utils
  15125. */
  15126. var getCharForByte = function (byte) {
  15127. var charCode = byte;
  15128. if (specialCea608CharsCodes.hasOwnProperty(byte)) {
  15129. charCode = specialCea608CharsCodes[byte];
  15130. }
  15131. return String.fromCharCode(charCode);
  15132. };
  15133. var NR_ROWS = 15, NR_COLS = 100;
  15134. // Tables to look up row from PAC data
  15135. var rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };
  15136. var rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };
  15137. var rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };
  15138. var rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };
  15139. var backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];
  15140. /**
  15141. * Simple logger class to be able to write with time-stamps and filter on level.
  15142. */
  15143. var logger = {
  15144. verboseFilter: { 'DATA': 3, 'DEBUG': 3, 'INFO': 2, 'WARNING': 2, 'TEXT': 1, 'ERROR': 0 },
  15145. time: null,
  15146. verboseLevel: 0,
  15147. setTime: function (newTime) {
  15148. this.time = newTime;
  15149. },
  15150. log: function (severity, msg) {
  15151. var minLevel = this.verboseFilter[severity];
  15152. if (this.verboseLevel >= minLevel) {
  15153. // console.log(this.time + ' [' + severity + '] ' + msg);
  15154. }
  15155. }
  15156. };
  15157. var numArrayToHexArray = function (numArray) {
  15158. var hexArray = [];
  15159. for (var j = 0; j < numArray.length; j++) {
  15160. hexArray.push(numArray[j].toString(16));
  15161. }
  15162. return hexArray;
  15163. };
  15164. var PenState = /** @class */ (function () {
  15165. function PenState(foreground, underline, italics, background, flash) {
  15166. this.foreground = foreground || 'white';
  15167. this.underline = underline || false;
  15168. this.italics = italics || false;
  15169. this.background = background || 'black';
  15170. this.flash = flash || false;
  15171. }
  15172. PenState.prototype.reset = function () {
  15173. this.foreground = 'white';
  15174. this.underline = false;
  15175. this.italics = false;
  15176. this.background = 'black';
  15177. this.flash = false;
  15178. };
  15179. PenState.prototype.setStyles = function (styles) {
  15180. var attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];
  15181. for (var i = 0; i < attribs.length; i++) {
  15182. var style = attribs[i];
  15183. if (styles.hasOwnProperty(style)) {
  15184. this[style] = styles[style];
  15185. }
  15186. }
  15187. };
  15188. PenState.prototype.isDefault = function () {
  15189. return (this.foreground === 'white' && !this.underline && !this.italics &&
  15190. this.background === 'black' && !this.flash);
  15191. };
  15192. PenState.prototype.equals = function (other) {
  15193. return ((this.foreground === other.foreground) &&
  15194. (this.underline === other.underline) &&
  15195. (this.italics === other.italics) &&
  15196. (this.background === other.background) &&
  15197. (this.flash === other.flash));
  15198. };
  15199. PenState.prototype.copy = function (newPenState) {
  15200. this.foreground = newPenState.foreground;
  15201. this.underline = newPenState.underline;
  15202. this.italics = newPenState.italics;
  15203. this.background = newPenState.background;
  15204. this.flash = newPenState.flash;
  15205. };
  15206. PenState.prototype.toString = function () {
  15207. return ('color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics +
  15208. ', background=' + this.background + ', flash=' + this.flash);
  15209. };
  15210. return PenState;
  15211. }());
  15212. /**
  15213. * Unicode character with styling and background.
  15214. * @constructor
  15215. */
  15216. var StyledUnicodeChar = /** @class */ (function () {
  15217. function StyledUnicodeChar(uchar, foreground, underline, italics, background, flash) {
  15218. this.uchar = uchar || ' '; // unicode character
  15219. this.penState = new PenState(foreground, underline, italics, background, flash);
  15220. }
  15221. StyledUnicodeChar.prototype.reset = function () {
  15222. this.uchar = ' ';
  15223. this.penState.reset();
  15224. };
  15225. StyledUnicodeChar.prototype.setChar = function (uchar, newPenState) {
  15226. this.uchar = uchar;
  15227. this.penState.copy(newPenState);
  15228. };
  15229. StyledUnicodeChar.prototype.setPenState = function (newPenState) {
  15230. this.penState.copy(newPenState);
  15231. };
  15232. StyledUnicodeChar.prototype.equals = function (other) {
  15233. return this.uchar === other.uchar && this.penState.equals(other.penState);
  15234. };
  15235. StyledUnicodeChar.prototype.copy = function (newChar) {
  15236. this.uchar = newChar.uchar;
  15237. this.penState.copy(newChar.penState);
  15238. };
  15239. StyledUnicodeChar.prototype.isEmpty = function () {
  15240. return this.uchar === ' ' && this.penState.isDefault();
  15241. };
  15242. return StyledUnicodeChar;
  15243. }());
  15244. /**
  15245. * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.
  15246. * @constructor
  15247. */
  15248. var Row = /** @class */ (function () {
  15249. function Row() {
  15250. this.chars = [];
  15251. for (var i = 0; i < NR_COLS; i++) {
  15252. this.chars.push(new StyledUnicodeChar());
  15253. }
  15254. this.pos = 0;
  15255. this.currPenState = new PenState();
  15256. }
  15257. Row.prototype.equals = function (other) {
  15258. var equal = true;
  15259. for (var i = 0; i < NR_COLS; i++) {
  15260. if (!this.chars[i].equals(other.chars[i])) {
  15261. equal = false;
  15262. break;
  15263. }
  15264. }
  15265. return equal;
  15266. };
  15267. Row.prototype.copy = function (other) {
  15268. for (var i = 0; i < NR_COLS; i++) {
  15269. this.chars[i].copy(other.chars[i]);
  15270. }
  15271. };
  15272. Row.prototype.isEmpty = function () {
  15273. var empty = true;
  15274. for (var i = 0; i < NR_COLS; i++) {
  15275. if (!this.chars[i].isEmpty()) {
  15276. empty = false;
  15277. break;
  15278. }
  15279. }
  15280. return empty;
  15281. };
  15282. /**
  15283. * Set the cursor to a valid column.
  15284. */
  15285. Row.prototype.setCursor = function (absPos) {
  15286. if (this.pos !== absPos) {
  15287. this.pos = absPos;
  15288. }
  15289. if (this.pos < 0) {
  15290. logger.log('ERROR', 'Negative cursor position ' + this.pos);
  15291. this.pos = 0;
  15292. }
  15293. else if (this.pos > NR_COLS) {
  15294. logger.log('ERROR', 'Too large cursor position ' + this.pos);
  15295. this.pos = NR_COLS;
  15296. }
  15297. };
  15298. /**
  15299. * Move the cursor relative to current position.
  15300. */
  15301. Row.prototype.moveCursor = function (relPos) {
  15302. var newPos = this.pos + relPos;
  15303. if (relPos > 1) {
  15304. for (var i = this.pos + 1; i < newPos + 1; i++) {
  15305. this.chars[i].setPenState(this.currPenState);
  15306. }
  15307. }
  15308. this.setCursor(newPos);
  15309. };
  15310. /**
  15311. * Backspace, move one step back and clear character.
  15312. */
  15313. Row.prototype.backSpace = function () {
  15314. this.moveCursor(-1);
  15315. this.chars[this.pos].setChar(' ', this.currPenState);
  15316. };
  15317. Row.prototype.insertChar = function (byte) {
  15318. if (byte >= 0x90) { // Extended char
  15319. this.backSpace();
  15320. }
  15321. var char = getCharForByte(byte);
  15322. if (this.pos >= NR_COLS) {
  15323. logger.log('ERROR', 'Cannot insert ' + byte.toString(16) +
  15324. ' (' + char + ') at position ' + this.pos + '. Skipping it!');
  15325. return;
  15326. }
  15327. this.chars[this.pos].setChar(char, this.currPenState);
  15328. this.moveCursor(1);
  15329. };
  15330. Row.prototype.clearFromPos = function (startPos) {
  15331. var i;
  15332. for (i = startPos; i < NR_COLS; i++) {
  15333. this.chars[i].reset();
  15334. }
  15335. };
  15336. Row.prototype.clear = function () {
  15337. this.clearFromPos(0);
  15338. this.pos = 0;
  15339. this.currPenState.reset();
  15340. };
  15341. Row.prototype.clearToEndOfRow = function () {
  15342. this.clearFromPos(this.pos);
  15343. };
  15344. Row.prototype.getTextString = function () {
  15345. var chars = [];
  15346. var empty = true;
  15347. for (var i = 0; i < NR_COLS; i++) {
  15348. var char = this.chars[i].uchar;
  15349. if (char !== ' ') {
  15350. empty = false;
  15351. }
  15352. chars.push(char);
  15353. }
  15354. if (empty) {
  15355. return '';
  15356. }
  15357. else {
  15358. return chars.join('');
  15359. }
  15360. };
  15361. Row.prototype.setPenStyles = function (styles) {
  15362. this.currPenState.setStyles(styles);
  15363. var currChar = this.chars[this.pos];
  15364. currChar.setPenState(this.currPenState);
  15365. };
  15366. return Row;
  15367. }());
  15368. /**
  15369. * Keep a CEA-608 screen of 32x15 styled characters
  15370. * @constructor
  15371. */
  15372. var CaptionScreen = /** @class */ (function () {
  15373. function CaptionScreen() {
  15374. this.rows = [];
  15375. for (var i = 0; i < NR_ROWS; i++) {
  15376. this.rows.push(new Row());
  15377. } // Note that we use zero-based numbering (0-14)
  15378. this.currRow = NR_ROWS - 1;
  15379. this.nrRollUpRows = null;
  15380. this.reset();
  15381. }
  15382. CaptionScreen.prototype.reset = function () {
  15383. for (var i = 0; i < NR_ROWS; i++) {
  15384. this.rows[i].clear();
  15385. }
  15386. this.currRow = NR_ROWS - 1;
  15387. };
  15388. CaptionScreen.prototype.equals = function (other) {
  15389. var equal = true;
  15390. for (var i = 0; i < NR_ROWS; i++) {
  15391. if (!this.rows[i].equals(other.rows[i])) {
  15392. equal = false;
  15393. break;
  15394. }
  15395. }
  15396. return equal;
  15397. };
  15398. CaptionScreen.prototype.copy = function (other) {
  15399. for (var i = 0; i < NR_ROWS; i++) {
  15400. this.rows[i].copy(other.rows[i]);
  15401. }
  15402. };
  15403. CaptionScreen.prototype.isEmpty = function () {
  15404. var empty = true;
  15405. for (var i = 0; i < NR_ROWS; i++) {
  15406. if (!this.rows[i].isEmpty()) {
  15407. empty = false;
  15408. break;
  15409. }
  15410. }
  15411. return empty;
  15412. };
  15413. CaptionScreen.prototype.backSpace = function () {
  15414. var row = this.rows[this.currRow];
  15415. row.backSpace();
  15416. };
  15417. CaptionScreen.prototype.clearToEndOfRow = function () {
  15418. var row = this.rows[this.currRow];
  15419. row.clearToEndOfRow();
  15420. };
  15421. /**
  15422. * Insert a character (without styling) in the current row.
  15423. */
  15424. CaptionScreen.prototype.insertChar = function (char) {
  15425. var row = this.rows[this.currRow];
  15426. row.insertChar(char);
  15427. };
  15428. CaptionScreen.prototype.setPen = function (styles) {
  15429. var row = this.rows[this.currRow];
  15430. row.setPenStyles(styles);
  15431. };
  15432. CaptionScreen.prototype.moveCursor = function (relPos) {
  15433. var row = this.rows[this.currRow];
  15434. row.moveCursor(relPos);
  15435. };
  15436. CaptionScreen.prototype.setCursor = function (absPos) {
  15437. logger.log('INFO', 'setCursor: ' + absPos);
  15438. var row = this.rows[this.currRow];
  15439. row.setCursor(absPos);
  15440. };
  15441. CaptionScreen.prototype.setPAC = function (pacData) {
  15442. logger.log('INFO', 'pacData = ' + JSON.stringify(pacData));
  15443. var newRow = pacData.row - 1;
  15444. if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {
  15445. newRow = this.nrRollUpRows - 1;
  15446. }
  15447. // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows
  15448. if (this.nrRollUpRows && this.currRow !== newRow) {
  15449. // clear all rows first
  15450. for (var i = 0; i < NR_ROWS; i++) {
  15451. this.rows[i].clear();
  15452. }
  15453. // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location
  15454. // topRowIndex - the start of rows to copy (inclusive index)
  15455. var topRowIndex = this.currRow + 1 - (this.nrRollUpRows);
  15456. // We only copy if the last position was already shown.
  15457. // We use the cueStartTime value to check this.
  15458. var lastOutputScreen = this.lastOutputScreen;
  15459. if (lastOutputScreen) {
  15460. var prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;
  15461. if (prevLineTime && prevLineTime < logger.time) {
  15462. for (var i = 0; i < this.nrRollUpRows; i++) {
  15463. this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);
  15464. }
  15465. }
  15466. }
  15467. }
  15468. this.currRow = newRow;
  15469. var row = this.rows[this.currRow];
  15470. if (pacData.indent !== null) {
  15471. var indent = pacData.indent;
  15472. var prevPos = Math.max(indent - 1, 0);
  15473. row.setCursor(pacData.indent);
  15474. pacData.color = row.chars[prevPos].penState.foreground;
  15475. }
  15476. var styles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };
  15477. this.setPen(styles);
  15478. };
  15479. /**
  15480. * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).
  15481. */
  15482. CaptionScreen.prototype.setBkgData = function (bkgData) {
  15483. logger.log('INFO', 'bkgData = ' + JSON.stringify(bkgData));
  15484. this.backSpace();
  15485. this.setPen(bkgData);
  15486. this.insertChar(0x20); // Space
  15487. };
  15488. CaptionScreen.prototype.setRollUpRows = function (nrRows) {
  15489. this.nrRollUpRows = nrRows;
  15490. };
  15491. CaptionScreen.prototype.rollUp = function () {
  15492. if (this.nrRollUpRows === null) {
  15493. logger.log('DEBUG', 'roll_up but nrRollUpRows not set yet');
  15494. return; // Not properly setup
  15495. }
  15496. logger.log('TEXT', this.getDisplayText());
  15497. var topRowIndex = this.currRow + 1 - this.nrRollUpRows;
  15498. var topRow = this.rows.splice(topRowIndex, 1)[0];
  15499. topRow.clear();
  15500. this.rows.splice(this.currRow, 0, topRow);
  15501. logger.log('INFO', 'Rolling up');
  15502. // logger.log('TEXT', this.get_display_text())
  15503. };
  15504. /**
  15505. * Get all non-empty rows with as unicode text.
  15506. */
  15507. CaptionScreen.prototype.getDisplayText = function (asOneRow) {
  15508. asOneRow = asOneRow || false;
  15509. var displayText = [];
  15510. var text = '';
  15511. var rowNr = -1;
  15512. for (var i = 0; i < NR_ROWS; i++) {
  15513. var rowText = this.rows[i].getTextString();
  15514. if (rowText) {
  15515. rowNr = i + 1;
  15516. if (asOneRow) {
  15517. displayText.push('Row ' + rowNr + ': \'' + rowText + '\'');
  15518. }
  15519. else {
  15520. displayText.push(rowText.trim());
  15521. }
  15522. }
  15523. }
  15524. if (displayText.length > 0) {
  15525. if (asOneRow) {
  15526. text = '[' + displayText.join(' | ') + ']';
  15527. }
  15528. else {
  15529. text = displayText.join('\n');
  15530. }
  15531. }
  15532. return text;
  15533. };
  15534. CaptionScreen.prototype.getTextAndFormat = function () {
  15535. return this.rows;
  15536. };
  15537. return CaptionScreen;
  15538. }());
  15539. // var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];
  15540. var Cea608Channel = /** @class */ (function () {
  15541. function Cea608Channel(channelNumber, outputFilter) {
  15542. this.chNr = channelNumber;
  15543. this.outputFilter = outputFilter;
  15544. this.mode = null;
  15545. this.verbose = 0;
  15546. this.displayedMemory = new CaptionScreen();
  15547. this.nonDisplayedMemory = new CaptionScreen();
  15548. this.lastOutputScreen = new CaptionScreen();
  15549. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  15550. this.writeScreen = this.displayedMemory;
  15551. this.mode = null;
  15552. this.cueStartTime = null; // Keeps track of where a cue started.
  15553. }
  15554. Cea608Channel.prototype.reset = function () {
  15555. this.mode = null;
  15556. this.displayedMemory.reset();
  15557. this.nonDisplayedMemory.reset();
  15558. this.lastOutputScreen.reset();
  15559. this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];
  15560. this.writeScreen = this.displayedMemory;
  15561. this.mode = null;
  15562. this.cueStartTime = null;
  15563. this.lastCueEndTime = null;
  15564. };
  15565. Cea608Channel.prototype.getHandler = function () {
  15566. return this.outputFilter;
  15567. };
  15568. Cea608Channel.prototype.setHandler = function (newHandler) {
  15569. this.outputFilter = newHandler;
  15570. };
  15571. Cea608Channel.prototype.setPAC = function (pacData) {
  15572. this.writeScreen.setPAC(pacData);
  15573. };
  15574. Cea608Channel.prototype.setBkgData = function (bkgData) {
  15575. this.writeScreen.setBkgData(bkgData);
  15576. };
  15577. Cea608Channel.prototype.setMode = function (newMode) {
  15578. if (newMode === this.mode) {
  15579. return;
  15580. }
  15581. this.mode = newMode;
  15582. logger.log('INFO', 'MODE=' + newMode);
  15583. if (this.mode === 'MODE_POP-ON') {
  15584. this.writeScreen = this.nonDisplayedMemory;
  15585. }
  15586. else {
  15587. this.writeScreen = this.displayedMemory;
  15588. this.writeScreen.reset();
  15589. }
  15590. if (this.mode !== 'MODE_ROLL-UP') {
  15591. this.displayedMemory.nrRollUpRows = null;
  15592. this.nonDisplayedMemory.nrRollUpRows = null;
  15593. }
  15594. this.mode = newMode;
  15595. };
  15596. Cea608Channel.prototype.insertChars = function (chars) {
  15597. for (var i = 0; i < chars.length; i++) {
  15598. this.writeScreen.insertChar(chars[i]);
  15599. }
  15600. var screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';
  15601. logger.log('INFO', screen + ': ' + this.writeScreen.getDisplayText(true));
  15602. if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {
  15603. logger.log('TEXT', 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));
  15604. this.outputDataUpdate();
  15605. }
  15606. };
  15607. Cea608Channel.prototype.ccRCL = function () {
  15608. logger.log('INFO', 'RCL - Resume Caption Loading');
  15609. this.setMode('MODE_POP-ON');
  15610. };
  15611. Cea608Channel.prototype.ccBS = function () {
  15612. logger.log('INFO', 'BS - BackSpace');
  15613. if (this.mode === 'MODE_TEXT') {
  15614. return;
  15615. }
  15616. this.writeScreen.backSpace();
  15617. if (this.writeScreen === this.displayedMemory) {
  15618. this.outputDataUpdate();
  15619. }
  15620. };
  15621. Cea608Channel.prototype.ccAOF = function () {
  15622. };
  15623. Cea608Channel.prototype.ccAON = function () {
  15624. };
  15625. Cea608Channel.prototype.ccDER = function () {
  15626. logger.log('INFO', 'DER- Delete to End of Row');
  15627. this.writeScreen.clearToEndOfRow();
  15628. this.outputDataUpdate();
  15629. };
  15630. Cea608Channel.prototype.ccRU = function (nrRows) {
  15631. logger.log('INFO', 'RU(' + nrRows + ') - Roll Up');
  15632. this.writeScreen = this.displayedMemory;
  15633. this.setMode('MODE_ROLL-UP');
  15634. this.writeScreen.setRollUpRows(nrRows);
  15635. };
  15636. Cea608Channel.prototype.ccFON = function () {
  15637. logger.log('INFO', 'FON - Flash On');
  15638. this.writeScreen.setPen({ flash: true });
  15639. };
  15640. Cea608Channel.prototype.ccRDC = function () {
  15641. logger.log('INFO', 'RDC - Resume Direct Captioning');
  15642. this.setMode('MODE_PAINT-ON');
  15643. };
  15644. Cea608Channel.prototype.ccTR = function () {
  15645. logger.log('INFO', 'TR');
  15646. this.setMode('MODE_TEXT');
  15647. };
  15648. Cea608Channel.prototype.ccRTD = function () {
  15649. logger.log('INFO', 'RTD');
  15650. this.setMode('MODE_TEXT');
  15651. };
  15652. Cea608Channel.prototype.ccEDM = function () {
  15653. logger.log('INFO', 'EDM - Erase Displayed Memory');
  15654. this.displayedMemory.reset();
  15655. this.outputDataUpdate(true);
  15656. };
  15657. Cea608Channel.prototype.ccCR = function () {
  15658. logger.log('CR - Carriage Return');
  15659. this.writeScreen.rollUp();
  15660. this.outputDataUpdate(true);
  15661. };
  15662. Cea608Channel.prototype.ccENM = function () {
  15663. logger.log('INFO', 'ENM - Erase Non-displayed Memory');
  15664. this.nonDisplayedMemory.reset();
  15665. };
  15666. Cea608Channel.prototype.ccEOC = function () {
  15667. logger.log('INFO', 'EOC - End Of Caption');
  15668. if (this.mode === 'MODE_POP-ON') {
  15669. var tmp = this.displayedMemory;
  15670. this.displayedMemory = this.nonDisplayedMemory;
  15671. this.nonDisplayedMemory = tmp;
  15672. this.writeScreen = this.nonDisplayedMemory;
  15673. logger.log('TEXT', 'DISP: ' + this.displayedMemory.getDisplayText());
  15674. }
  15675. this.outputDataUpdate(true);
  15676. };
  15677. Cea608Channel.prototype.ccTO = function (nrCols) {
  15678. logger.log('INFO', 'TO(' + nrCols + ') - Tab Offset');
  15679. this.writeScreen.moveCursor(nrCols);
  15680. };
  15681. Cea608Channel.prototype.ccMIDROW = function (secondByte) {
  15682. var styles = { flash: false };
  15683. styles.underline = secondByte % 2 === 1;
  15684. styles.italics = secondByte >= 0x2e;
  15685. if (!styles.italics) {
  15686. var colorIndex = Math.floor(secondByte / 2) - 0x10;
  15687. var colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];
  15688. styles.foreground = colors[colorIndex];
  15689. }
  15690. else {
  15691. styles.foreground = 'white';
  15692. }
  15693. logger.log('INFO', 'MIDROW: ' + JSON.stringify(styles));
  15694. this.writeScreen.setPen(styles);
  15695. };
  15696. Cea608Channel.prototype.outputDataUpdate = function (dispatch) {
  15697. if (dispatch === void 0) { dispatch = false; }
  15698. var t = logger.time;
  15699. if (t === null) {
  15700. return;
  15701. }
  15702. if (this.outputFilter) {
  15703. if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { // Start of a new cue
  15704. this.cueStartTime = t;
  15705. }
  15706. else {
  15707. if (!this.displayedMemory.equals(this.lastOutputScreen)) {
  15708. if (this.outputFilter.newCue) {
  15709. this.outputFilter.newCue(this.cueStartTime, t, this.lastOutputScreen);
  15710. if (dispatch === true && this.outputFilter.dispatchCue) {
  15711. this.outputFilter.dispatchCue();
  15712. }
  15713. }
  15714. this.cueStartTime = this.displayedMemory.isEmpty() ? null : t;
  15715. }
  15716. }
  15717. this.lastOutputScreen.copy(this.displayedMemory);
  15718. }
  15719. };
  15720. Cea608Channel.prototype.cueSplitAtTime = function (t) {
  15721. if (this.outputFilter) {
  15722. if (!this.displayedMemory.isEmpty()) {
  15723. if (this.outputFilter.newCue) {
  15724. this.outputFilter.newCue(this.cueStartTime, t, this.displayedMemory);
  15725. }
  15726. this.cueStartTime = t;
  15727. }
  15728. }
  15729. };
  15730. return Cea608Channel;
  15731. }());
  15732. var Cea608Parser = /** @class */ (function () {
  15733. function Cea608Parser(field, out1, out2) {
  15734. this.field = field || 1;
  15735. this.outputs = [out1, out2];
  15736. this.channels = [new Cea608Channel(1, out1), new Cea608Channel(2, out2)];
  15737. this.currChNr = -1; // Will be 1 or 2
  15738. this.lastCmdA = null; // First byte of last command
  15739. this.lastCmdB = null; // Second byte of last command
  15740. this.bufferedData = [];
  15741. this.startTime = null;
  15742. this.lastTime = null;
  15743. this.dataCounters = { 'padding': 0, 'char': 0, 'cmd': 0, 'other': 0 };
  15744. }
  15745. Cea608Parser.prototype.getHandler = function (index) {
  15746. return this.channels[index].getHandler();
  15747. };
  15748. Cea608Parser.prototype.setHandler = function (index, newHandler) {
  15749. this.channels[index].setHandler(newHandler);
  15750. };
  15751. /**
  15752. * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.
  15753. */
  15754. Cea608Parser.prototype.addData = function (t, byteList) {
  15755. var cmdFound, a, b, charsFound = false;
  15756. this.lastTime = t;
  15757. logger.setTime(t);
  15758. for (var i = 0; i < byteList.length; i += 2) {
  15759. a = byteList[i] & 0x7f;
  15760. b = byteList[i + 1] & 0x7f;
  15761. if (a === 0 && b === 0) {
  15762. this.dataCounters.padding += 2;
  15763. continue;
  15764. }
  15765. else {
  15766. logger.log('DATA', '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');
  15767. }
  15768. cmdFound = this.parseCmd(a, b);
  15769. if (!cmdFound) {
  15770. cmdFound = this.parseMidrow(a, b);
  15771. }
  15772. if (!cmdFound) {
  15773. cmdFound = this.parsePAC(a, b);
  15774. }
  15775. if (!cmdFound) {
  15776. cmdFound = this.parseBackgroundAttributes(a, b);
  15777. }
  15778. if (!cmdFound) {
  15779. charsFound = this.parseChars(a, b);
  15780. if (charsFound) {
  15781. if (this.currChNr && this.currChNr >= 0) {
  15782. var channel = this.channels[this.currChNr - 1];
  15783. channel.insertChars(charsFound);
  15784. }
  15785. else {
  15786. logger.log('WARNING', 'No channel found yet. TEXT-MODE?');
  15787. }
  15788. }
  15789. }
  15790. if (cmdFound) {
  15791. this.dataCounters.cmd += 2;
  15792. }
  15793. else if (charsFound) {
  15794. this.dataCounters.char += 2;
  15795. }
  15796. else {
  15797. this.dataCounters.other += 2;
  15798. logger.log('WARNING', 'Couldn\'t parse cleaned data ' + numArrayToHexArray([a, b]) +
  15799. ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));
  15800. }
  15801. }
  15802. };
  15803. /**
  15804. * Parse Command.
  15805. * @returns {Boolean} Tells if a command was found
  15806. */
  15807. Cea608Parser.prototype.parseCmd = function (a, b) {
  15808. var chNr = null;
  15809. var cond1 = (a === 0x14 || a === 0x1C) && (b >= 0x20 && b <= 0x2F);
  15810. var cond2 = (a === 0x17 || a === 0x1F) && (b >= 0x21 && b <= 0x23);
  15811. if (!(cond1 || cond2)) {
  15812. return false;
  15813. }
  15814. if (a === this.lastCmdA && b === this.lastCmdB) {
  15815. this.lastCmdA = null;
  15816. this.lastCmdB = null; // Repeated commands are dropped (once)
  15817. logger.log('DEBUG', 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');
  15818. return true;
  15819. }
  15820. if (a === 0x14 || a === 0x17) {
  15821. chNr = 1;
  15822. }
  15823. else {
  15824. chNr = 2;
  15825. } // (a === 0x1C || a=== 0x1f)
  15826. var channel = this.channels[chNr - 1];
  15827. if (a === 0x14 || a === 0x1C) {
  15828. if (b === 0x20) {
  15829. channel.ccRCL();
  15830. }
  15831. else if (b === 0x21) {
  15832. channel.ccBS();
  15833. }
  15834. else if (b === 0x22) {
  15835. channel.ccAOF();
  15836. }
  15837. else if (b === 0x23) {
  15838. channel.ccAON();
  15839. }
  15840. else if (b === 0x24) {
  15841. channel.ccDER();
  15842. }
  15843. else if (b === 0x25) {
  15844. channel.ccRU(2);
  15845. }
  15846. else if (b === 0x26) {
  15847. channel.ccRU(3);
  15848. }
  15849. else if (b === 0x27) {
  15850. channel.ccRU(4);
  15851. }
  15852. else if (b === 0x28) {
  15853. channel.ccFON();
  15854. }
  15855. else if (b === 0x29) {
  15856. channel.ccRDC();
  15857. }
  15858. else if (b === 0x2A) {
  15859. channel.ccTR();
  15860. }
  15861. else if (b === 0x2B) {
  15862. channel.ccRTD();
  15863. }
  15864. else if (b === 0x2C) {
  15865. channel.ccEDM();
  15866. }
  15867. else if (b === 0x2D) {
  15868. channel.ccCR();
  15869. }
  15870. else if (b === 0x2E) {
  15871. channel.ccENM();
  15872. }
  15873. else if (b === 0x2F) {
  15874. channel.ccEOC();
  15875. }
  15876. }
  15877. else { // a == 0x17 || a == 0x1F
  15878. channel.ccTO(b - 0x20);
  15879. }
  15880. this.lastCmdA = a;
  15881. this.lastCmdB = b;
  15882. this.currChNr = chNr;
  15883. return true;
  15884. };
  15885. /**
  15886. * Parse midrow styling command
  15887. * @returns {Boolean}
  15888. */
  15889. Cea608Parser.prototype.parseMidrow = function (a, b) {
  15890. var chNr = null;
  15891. if (((a === 0x11) || (a === 0x19)) && b >= 0x20 && b <= 0x2f) {
  15892. if (a === 0x11) {
  15893. chNr = 1;
  15894. }
  15895. else {
  15896. chNr = 2;
  15897. }
  15898. if (chNr !== this.currChNr) {
  15899. logger.log('ERROR', 'Mismatch channel in midrow parsing');
  15900. return false;
  15901. }
  15902. var channel = this.channels[chNr - 1];
  15903. channel.ccMIDROW(b);
  15904. logger.log('DEBUG', 'MIDROW (' + numArrayToHexArray([a, b]) + ')');
  15905. return true;
  15906. }
  15907. return false;
  15908. };
  15909. /**
  15910. * Parse Preable Access Codes (Table 53).
  15911. * @returns {Boolean} Tells if PAC found
  15912. */
  15913. Cea608Parser.prototype.parsePAC = function (a, b) {
  15914. var chNr = null;
  15915. var row = null;
  15916. var case1 = ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1F)) && (b >= 0x40 && b <= 0x7F);
  15917. var case2 = (a === 0x10 || a === 0x18) && (b >= 0x40 && b <= 0x5F);
  15918. if (!(case1 || case2)) {
  15919. return false;
  15920. }
  15921. if (a === this.lastCmdA && b === this.lastCmdB) {
  15922. this.lastCmdA = null;
  15923. this.lastCmdB = null;
  15924. return true; // Repeated commands are dropped (once)
  15925. }
  15926. chNr = (a <= 0x17) ? 1 : 2;
  15927. if (b >= 0x40 && b <= 0x5F) {
  15928. row = (chNr === 1) ? rowsLowCh1[a] : rowsLowCh2[a];
  15929. }
  15930. else { // 0x60 <= b <= 0x7F
  15931. row = (chNr === 1) ? rowsHighCh1[a] : rowsHighCh2[a];
  15932. }
  15933. var pacData = this.interpretPAC(row, b);
  15934. var channel = this.channels[chNr - 1];
  15935. channel.setPAC(pacData);
  15936. this.lastCmdA = a;
  15937. this.lastCmdB = b;
  15938. this.currChNr = chNr;
  15939. return true;
  15940. };
  15941. /**
  15942. * Interpret the second byte of the pac, and return the information.
  15943. * @returns {Object} pacData with style parameters.
  15944. */
  15945. Cea608Parser.prototype.interpretPAC = function (row, byte) {
  15946. var pacIndex = byte;
  15947. var pacData = { color: null, italics: false, indent: null, underline: false, row: row };
  15948. if (byte > 0x5F) {
  15949. pacIndex = byte - 0x60;
  15950. }
  15951. else {
  15952. pacIndex = byte - 0x40;
  15953. }
  15954. pacData.underline = (pacIndex & 1) === 1;
  15955. if (pacIndex <= 0xd) {
  15956. pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];
  15957. }
  15958. else if (pacIndex <= 0xf) {
  15959. pacData.italics = true;
  15960. pacData.color = 'white';
  15961. }
  15962. else {
  15963. pacData.indent = (Math.floor((pacIndex - 0x10) / 2)) * 4;
  15964. }
  15965. return pacData; // Note that row has zero offset. The spec uses 1.
  15966. };
  15967. /**
  15968. * Parse characters.
  15969. * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.
  15970. */
  15971. Cea608Parser.prototype.parseChars = function (a, b) {
  15972. var channelNr = null, charCodes = null, charCode1 = null;
  15973. if (a >= 0x19) {
  15974. channelNr = 2;
  15975. charCode1 = a - 8;
  15976. }
  15977. else {
  15978. channelNr = 1;
  15979. charCode1 = a;
  15980. }
  15981. if (charCode1 >= 0x11 && charCode1 <= 0x13) {
  15982. // Special character
  15983. var oneCode = b;
  15984. if (charCode1 === 0x11) {
  15985. oneCode = b + 0x50;
  15986. }
  15987. else if (charCode1 === 0x12) {
  15988. oneCode = b + 0x70;
  15989. }
  15990. else {
  15991. oneCode = b + 0x90;
  15992. }
  15993. logger.log('INFO', 'Special char \'' + getCharForByte(oneCode) + '\' in channel ' + channelNr);
  15994. charCodes = [oneCode];
  15995. }
  15996. else if (a >= 0x20 && a <= 0x7f) {
  15997. charCodes = (b === 0) ? [a] : [a, b];
  15998. }
  15999. if (charCodes) {
  16000. var hexCodes = numArrayToHexArray(charCodes);
  16001. logger.log('DEBUG', 'Char codes = ' + hexCodes.join(','));
  16002. this.lastCmdA = null;
  16003. this.lastCmdB = null;
  16004. }
  16005. return charCodes;
  16006. };
  16007. /**
  16008. * Parse extended background attributes as well as new foreground color black.
  16009. * @returns{Boolean} Tells if background attributes are found
  16010. */
  16011. Cea608Parser.prototype.parseBackgroundAttributes = function (a, b) {
  16012. var bkgData, index, chNr, channel;
  16013. var case1 = (a === 0x10 || a === 0x18) && (b >= 0x20 && b <= 0x2f);
  16014. var case2 = (a === 0x17 || a === 0x1f) && (b >= 0x2d && b <= 0x2f);
  16015. if (!(case1 || case2)) {
  16016. return false;
  16017. }
  16018. bkgData = {};
  16019. if (a === 0x10 || a === 0x18) {
  16020. index = Math.floor((b - 0x20) / 2);
  16021. bkgData.background = backgroundColors[index];
  16022. if (b % 2 === 1) {
  16023. bkgData.background = bkgData.background + '_semi';
  16024. }
  16025. }
  16026. else if (b === 0x2d) {
  16027. bkgData.background = 'transparent';
  16028. }
  16029. else {
  16030. bkgData.foreground = 'black';
  16031. if (b === 0x2f) {
  16032. bkgData.underline = true;
  16033. }
  16034. }
  16035. chNr = (a < 0x18) ? 1 : 2;
  16036. channel = this.channels[chNr - 1];
  16037. channel.setBkgData(bkgData);
  16038. this.lastCmdA = null;
  16039. this.lastCmdB = null;
  16040. return true;
  16041. };
  16042. /**
  16043. * Reset state of parser and its channels.
  16044. */
  16045. Cea608Parser.prototype.reset = function () {
  16046. for (var i = 0; i < this.channels.length; i++) {
  16047. if (this.channels[i]) {
  16048. this.channels[i].reset();
  16049. }
  16050. }
  16051. this.lastCmdA = null;
  16052. this.lastCmdB = null;
  16053. };
  16054. /**
  16055. * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.
  16056. */
  16057. Cea608Parser.prototype.cueSplitAtTime = function (t) {
  16058. for (var i = 0; i < this.channels.length; i++) {
  16059. if (this.channels[i]) {
  16060. this.channels[i].cueSplitAtTime(t);
  16061. }
  16062. }
  16063. };
  16064. return Cea608Parser;
  16065. }());
  16066. exports.default = Cea608Parser;
  16067. /***/ }),
  16068. /***/ "./src/utils/codecs.js":
  16069. /*!*****************************!*\
  16070. !*** ./src/utils/codecs.js ***!
  16071. \*****************************/
  16072. /*! no static exports found */
  16073. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16074. /***/ (function(module, exports, __webpack_require__) {
  16075. "use strict";
  16076. Object.defineProperty(exports, "__esModule", { value: true });
  16077. // from http://mp4ra.org/codecs.html
  16078. var sampleEntryCodesISO = {
  16079. audio: {
  16080. 'a3ds': true,
  16081. 'ac-3': true,
  16082. 'ac-4': true,
  16083. 'alac': true,
  16084. 'alaw': true,
  16085. 'dra1': true,
  16086. 'dts+': true,
  16087. 'dts-': true,
  16088. 'dtsc': true,
  16089. 'dtse': true,
  16090. 'dtsh': true,
  16091. 'ec-3': true,
  16092. 'enca': true,
  16093. 'g719': true,
  16094. 'g726': true,
  16095. 'm4ae': true,
  16096. 'mha1': true,
  16097. 'mha2': true,
  16098. 'mhm1': true,
  16099. 'mhm2': true,
  16100. 'mlpa': true,
  16101. 'mp4a': true,
  16102. 'raw ': true,
  16103. 'Opus': true,
  16104. 'samr': true,
  16105. 'sawb': true,
  16106. 'sawp': true,
  16107. 'sevc': true,
  16108. 'sqcp': true,
  16109. 'ssmv': true,
  16110. 'twos': true,
  16111. 'ulaw': true
  16112. },
  16113. video: {
  16114. 'avc1': true,
  16115. 'avc2': true,
  16116. 'avc3': true,
  16117. 'avc4': true,
  16118. 'avcp': true,
  16119. 'drac': true,
  16120. 'dvav': true,
  16121. 'dvhe': true,
  16122. 'encv': true,
  16123. 'hev1': true,
  16124. 'hvc1': true,
  16125. 'mjp2': true,
  16126. 'mp4v': true,
  16127. 'mvc1': true,
  16128. 'mvc2': true,
  16129. 'mvc3': true,
  16130. 'mvc4': true,
  16131. 'resv': true,
  16132. 'rv60': true,
  16133. 's263': true,
  16134. 'svc1': true,
  16135. 'svc2': true,
  16136. 'vc-1': true,
  16137. 'vp08': true,
  16138. 'vp09': true
  16139. }
  16140. };
  16141. function isCodecType(codec, type) {
  16142. var typeCodes = sampleEntryCodesISO[type];
  16143. return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;
  16144. }
  16145. exports.isCodecType = isCodecType;
  16146. function isCodecSupportedInMp4(codec, type) {
  16147. return window.MediaSource.isTypeSupported((type || 'video') + "/mp4;codecs=\"" + codec + "\"");
  16148. }
  16149. exports.isCodecSupportedInMp4 = isCodecSupportedInMp4;
  16150. /***/ }),
  16151. /***/ "./src/utils/cues.js":
  16152. /*!***************************!*\
  16153. !*** ./src/utils/cues.js ***!
  16154. \***************************/
  16155. /*! no static exports found */
  16156. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16157. /***/ (function(module, exports, __webpack_require__) {
  16158. "use strict";
  16159. Object.defineProperty(exports, "__esModule", { value: true });
  16160. var vttparser_1 = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.js");
  16161. function newCue(track, startTime, endTime, captionScreen) {
  16162. var row;
  16163. var cue;
  16164. var indenting;
  16165. var indent;
  16166. var text;
  16167. var VTTCue = window.VTTCue || window.TextTrackCue;
  16168. for (var r = 0; r < captionScreen.rows.length; r++) {
  16169. row = captionScreen.rows[r];
  16170. indenting = true;
  16171. indent = 0;
  16172. text = '';
  16173. if (!row.isEmpty()) {
  16174. for (var c = 0; c < row.chars.length; c++) {
  16175. if (row.chars[c].uchar.match(/\s/) && indenting) {
  16176. indent++;
  16177. }
  16178. else {
  16179. text += row.chars[c].uchar;
  16180. indenting = false;
  16181. }
  16182. }
  16183. // To be used for cleaning-up orphaned roll-up captions
  16184. row.cueStartTime = startTime;
  16185. // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE
  16186. if (startTime === endTime) {
  16187. endTime += 0.0001;
  16188. }
  16189. cue = new VTTCue(startTime, endTime, vttparser_1.fixLineBreaks(text.trim()));
  16190. if (indent >= 16) {
  16191. indent--;
  16192. }
  16193. else {
  16194. indent++;
  16195. }
  16196. // VTTCue.line get's flakey when using controls, so let's now include line 13&14
  16197. // also, drop line 1 since it's to close to the top
  16198. if (navigator.userAgent.match(/Firefox\//)) {
  16199. cue.line = r + 1;
  16200. }
  16201. else {
  16202. cue.line = (r > 7 ? r - 2 : r + 1);
  16203. }
  16204. cue.align = 'left';
  16205. // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break
  16206. cue.position = Math.max(0, Math.min(100, 100 * (indent / 32) + (navigator.userAgent.match(/Firefox\//) ? 50 : 0)));
  16207. track.addCue(cue);
  16208. }
  16209. }
  16210. }
  16211. exports.newCue = newCue;
  16212. /***/ }),
  16213. /***/ "./src/utils/discontinuities.js":
  16214. /*!**************************************!*\
  16215. !*** ./src/utils/discontinuities.js ***!
  16216. \**************************************/
  16217. /*! no static exports found */
  16218. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16219. /***/ (function(module, exports, __webpack_require__) {
  16220. "use strict";
  16221. /* WEBPACK VAR INJECTION */(function(Number) {
  16222. Object.defineProperty(exports, "__esModule", { value: true });
  16223. var binary_search_1 = __webpack_require__(/*! ./binary-search */ "./src/utils/binary-search.js");
  16224. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  16225. function findFirstFragWithCC(fragments, cc) {
  16226. var firstFrag = null;
  16227. for (var i = 0; i < fragments.length; i += 1) {
  16228. var currentFrag = fragments[i];
  16229. if (currentFrag && currentFrag.cc === cc) {
  16230. firstFrag = currentFrag;
  16231. break;
  16232. }
  16233. }
  16234. return firstFrag;
  16235. }
  16236. exports.findFirstFragWithCC = findFirstFragWithCC;
  16237. function findFragWithCC(fragments, CC) {
  16238. return binary_search_1.default.search(fragments, function (candidate) {
  16239. if (candidate.cc < CC) {
  16240. return 1;
  16241. }
  16242. else if (candidate.cc > CC) {
  16243. return -1;
  16244. }
  16245. else {
  16246. return 0;
  16247. }
  16248. });
  16249. }
  16250. exports.findFragWithCC = findFragWithCC;
  16251. function shouldAlignOnDiscontinuities(lastFrag, lastLevel, details) {
  16252. var shouldAlign = false;
  16253. if (lastLevel && lastLevel.details && details) {
  16254. if (details.endCC > details.startCC || (lastFrag && lastFrag.cc < details.startCC)) {
  16255. shouldAlign = true;
  16256. }
  16257. }
  16258. return shouldAlign;
  16259. }
  16260. exports.shouldAlignOnDiscontinuities = shouldAlignOnDiscontinuities;
  16261. // Find the first frag in the previous level which matches the CC of the first frag of the new level
  16262. function findDiscontinuousReferenceFrag(prevDetails, curDetails) {
  16263. var prevFrags = prevDetails.fragments;
  16264. var curFrags = curDetails.fragments;
  16265. if (!curFrags.length || !prevFrags.length) {
  16266. logger_1.logger.log('No fragments to align');
  16267. return;
  16268. }
  16269. var prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);
  16270. if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {
  16271. logger_1.logger.log('No frag in previous level to align on');
  16272. return;
  16273. }
  16274. return prevStartFrag;
  16275. }
  16276. exports.findDiscontinuousReferenceFrag = findDiscontinuousReferenceFrag;
  16277. function adjustPts(sliding, details) {
  16278. details.fragments.forEach(function (frag) {
  16279. if (frag) {
  16280. var start = frag.start + sliding;
  16281. frag.start = frag.startPTS = start;
  16282. frag.endPTS = start + frag.duration;
  16283. }
  16284. });
  16285. details.PTSKnown = true;
  16286. }
  16287. exports.adjustPts = adjustPts;
  16288. /**
  16289. * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a
  16290. * contiguous stream with the last fragments.
  16291. * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to
  16292. * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time
  16293. * and an extra download.
  16294. * @param lastFrag
  16295. * @param lastLevel
  16296. * @param details
  16297. */
  16298. function alignStream(lastFrag, lastLevel, details) {
  16299. alignDiscontinuities(lastFrag, details, lastLevel);
  16300. if (!details.PTSKnown && lastLevel) {
  16301. // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.
  16302. // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same
  16303. // discontinuity sequence.
  16304. alignPDT(details, lastLevel.details);
  16305. }
  16306. }
  16307. exports.alignStream = alignStream;
  16308. /**
  16309. * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same
  16310. * discontinuity sequence.
  16311. * @param lastLevel - The details of the last loaded level
  16312. * @param details - The details of the new level
  16313. */
  16314. function alignDiscontinuities(lastFrag, details, lastLevel) {
  16315. if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {
  16316. var referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);
  16317. if (referenceFrag) {
  16318. logger_1.logger.log('Adjusting PTS using last level due to CC increase within current level');
  16319. adjustPts(referenceFrag.start, details);
  16320. }
  16321. }
  16322. }
  16323. exports.alignDiscontinuities = alignDiscontinuities;
  16324. /**
  16325. * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.
  16326. * @param details - The details of the new level
  16327. * @param lastDetails - The details of the last loaded level
  16328. */
  16329. function alignPDT(details, lastDetails) {
  16330. if (lastDetails && lastDetails.fragments.length) {
  16331. if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {
  16332. return;
  16333. }
  16334. // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM
  16335. // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM
  16336. // then we can deduce that playlist B sliding is 1000+8 = 1008s
  16337. var lastPDT = lastDetails.fragments[0].programDateTime;
  16338. var newPDT = details.fragments[0].programDateTime;
  16339. // date diff is in ms. frag.start is in seconds
  16340. var sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;
  16341. if (Number.isFinite(sliding)) {
  16342. logger_1.logger.log("adjusting PTS using programDateTime delta, sliding:" + sliding.toFixed(3));
  16343. adjustPts(sliding, details);
  16344. }
  16345. }
  16346. }
  16347. exports.alignPDT = alignPDT;
  16348. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  16349. /***/ }),
  16350. /***/ "./src/utils/ewma-bandwidth-estimator.js":
  16351. /*!***********************************************!*\
  16352. !*** ./src/utils/ewma-bandwidth-estimator.js ***!
  16353. \***********************************************/
  16354. /*! no static exports found */
  16355. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16356. /***/ (function(module, exports, __webpack_require__) {
  16357. "use strict";
  16358. /*
  16359. * EWMA Bandwidth Estimator
  16360. * - heavily inspired from shaka-player
  16361. * Tracks bandwidth samples and estimates available bandwidth.
  16362. * Based on the minimum of two exponentially-weighted moving averages with
  16363. * different half-lives.
  16364. */
  16365. Object.defineProperty(exports, "__esModule", { value: true });
  16366. var ewma_1 = __webpack_require__(/*! ../utils/ewma */ "./src/utils/ewma.js");
  16367. var EwmaBandWidthEstimator = /** @class */ (function () {
  16368. function EwmaBandWidthEstimator(hls, slow, fast, defaultEstimate) {
  16369. this.hls = hls;
  16370. this.defaultEstimate_ = defaultEstimate;
  16371. this.minWeight_ = 0.001;
  16372. this.minDelayMs_ = 50;
  16373. this.slow_ = new ewma_1.default(slow);
  16374. this.fast_ = new ewma_1.default(fast);
  16375. }
  16376. EwmaBandWidthEstimator.prototype.sample = function (durationMs, numBytes) {
  16377. durationMs = Math.max(durationMs, this.minDelayMs_);
  16378. var bandwidth = 8000 * numBytes / durationMs,
  16379. // console.log('instant bw:'+ Math.round(bandwidth));
  16380. // we weight sample using loading duration....
  16381. weight = durationMs / 1000;
  16382. this.fast_.sample(weight, bandwidth);
  16383. this.slow_.sample(weight, bandwidth);
  16384. };
  16385. EwmaBandWidthEstimator.prototype.canEstimate = function () {
  16386. var fast = this.fast_;
  16387. return (fast && fast.getTotalWeight() >= this.minWeight_);
  16388. };
  16389. EwmaBandWidthEstimator.prototype.getEstimate = function () {
  16390. if (this.canEstimate()) {
  16391. // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));
  16392. // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));
  16393. // Take the minimum of these two estimates. This should have the effect of
  16394. // adapting down quickly, but up more slowly.
  16395. return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());
  16396. }
  16397. else {
  16398. return this.defaultEstimate_;
  16399. }
  16400. };
  16401. EwmaBandWidthEstimator.prototype.destroy = function () {
  16402. };
  16403. return EwmaBandWidthEstimator;
  16404. }());
  16405. exports.default = EwmaBandWidthEstimator;
  16406. /***/ }),
  16407. /***/ "./src/utils/ewma.js":
  16408. /*!***************************!*\
  16409. !*** ./src/utils/ewma.js ***!
  16410. \***************************/
  16411. /*! no static exports found */
  16412. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16413. /***/ (function(module, exports, __webpack_require__) {
  16414. "use strict";
  16415. /*
  16416. * compute an Exponential Weighted moving average
  16417. * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
  16418. * - heavily inspired from shaka-player
  16419. */
  16420. Object.defineProperty(exports, "__esModule", { value: true });
  16421. var EWMA = /** @class */ (function () {
  16422. // About half of the estimated value will be from the last |halfLife| samples by weight.
  16423. function EWMA(halfLife) {
  16424. // Larger values of alpha expire historical data more slowly.
  16425. this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
  16426. this.estimate_ = 0;
  16427. this.totalWeight_ = 0;
  16428. }
  16429. EWMA.prototype.sample = function (weight, value) {
  16430. var adjAlpha = Math.pow(this.alpha_, weight);
  16431. this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
  16432. this.totalWeight_ += weight;
  16433. };
  16434. EWMA.prototype.getTotalWeight = function () {
  16435. return this.totalWeight_;
  16436. };
  16437. EWMA.prototype.getEstimate = function () {
  16438. if (this.alpha_) {
  16439. var zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
  16440. return this.estimate_ / zeroFactor;
  16441. }
  16442. else {
  16443. return this.estimate_;
  16444. }
  16445. };
  16446. return EWMA;
  16447. }());
  16448. exports.default = EWMA;
  16449. /***/ }),
  16450. /***/ "./src/utils/get-self-scope.js":
  16451. /*!*************************************!*\
  16452. !*** ./src/utils/get-self-scope.js ***!
  16453. \*************************************/
  16454. /*! no static exports found */
  16455. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16456. /***/ (function(module, exports, __webpack_require__) {
  16457. "use strict";
  16458. Object.defineProperty(exports, "__esModule", { value: true });
  16459. function getSelfScope() {
  16460. // see https://stackoverflow.com/a/11237259/589493
  16461. if (typeof window === 'undefined') {
  16462. /* eslint-disable-next-line no-undef */
  16463. return self;
  16464. }
  16465. else {
  16466. return window;
  16467. }
  16468. }
  16469. exports.getSelfScope = getSelfScope;
  16470. /***/ }),
  16471. /***/ "./src/utils/logger.js":
  16472. /*!*****************************!*\
  16473. !*** ./src/utils/logger.js ***!
  16474. \*****************************/
  16475. /*! no static exports found */
  16476. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16477. /***/ (function(module, exports, __webpack_require__) {
  16478. "use strict";
  16479. Object.defineProperty(exports, "__esModule", { value: true });
  16480. var get_self_scope_1 = __webpack_require__(/*! ./get-self-scope */ "./src/utils/get-self-scope.js");
  16481. function noop() { }
  16482. var fakeLogger = {
  16483. trace: noop,
  16484. debug: noop,
  16485. log: noop,
  16486. warn: noop,
  16487. info: noop,
  16488. error: noop
  16489. };
  16490. var exportedLogger = fakeLogger;
  16491. // let lastCallTime;
  16492. // function formatMsgWithTimeInfo(type, msg) {
  16493. // const now = Date.now();
  16494. // const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';
  16495. // lastCallTime = now;
  16496. // msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';
  16497. // return msg;
  16498. // }
  16499. function formatMsg(type, msg) {
  16500. msg = '[' + type + '] > ' + msg;
  16501. return msg;
  16502. }
  16503. var global = get_self_scope_1.getSelfScope();
  16504. function consolePrintFn(type) {
  16505. var func = global.console[type];
  16506. if (func) {
  16507. return function () {
  16508. var args = [];
  16509. for (var _i = 0; _i < arguments.length; _i++) {
  16510. args[_i] = arguments[_i];
  16511. }
  16512. if (args[0]) {
  16513. args[0] = formatMsg(type, args[0]);
  16514. }
  16515. func.apply(global.console, args);
  16516. };
  16517. }
  16518. return noop;
  16519. }
  16520. function exportLoggerFunctions(debugConfig) {
  16521. var functions = [];
  16522. for (var _i = 1; _i < arguments.length; _i++) {
  16523. functions[_i - 1] = arguments[_i];
  16524. }
  16525. functions.forEach(function (type) {
  16526. exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);
  16527. });
  16528. }
  16529. exports.enableLogs = function (debugConfig) {
  16530. if (debugConfig === true || typeof debugConfig === 'object') {
  16531. exportLoggerFunctions(debugConfig,
  16532. // Remove out from list here to hard-disable a log-level
  16533. // 'trace',
  16534. 'debug', 'log', 'info', 'warn', 'error');
  16535. // Some browsers don't allow to use bind on console object anyway
  16536. // fallback to default if needed
  16537. try {
  16538. exportedLogger.log();
  16539. }
  16540. catch (e) {
  16541. exportedLogger = fakeLogger;
  16542. }
  16543. }
  16544. else {
  16545. exportedLogger = fakeLogger;
  16546. }
  16547. };
  16548. exports.logger = exportedLogger;
  16549. /***/ }),
  16550. /***/ "./src/utils/mediakeys-helper.js":
  16551. /*!***************************************!*\
  16552. !*** ./src/utils/mediakeys-helper.js ***!
  16553. \***************************************/
  16554. /*! no static exports found */
  16555. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16556. /***/ (function(module, exports, __webpack_require__) {
  16557. "use strict";
  16558. Object.defineProperty(exports, "__esModule", { value: true });
  16559. var requestMediaKeySystemAccess = (function () {
  16560. if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {
  16561. return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);
  16562. }
  16563. else {
  16564. return null;
  16565. }
  16566. })();
  16567. exports.requestMediaKeySystemAccess = requestMediaKeySystemAccess;
  16568. /***/ }),
  16569. /***/ "./src/utils/mediasource-helper.js":
  16570. /*!*****************************************!*\
  16571. !*** ./src/utils/mediasource-helper.js ***!
  16572. \*****************************************/
  16573. /*! no static exports found */
  16574. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16575. /***/ (function(module, exports, __webpack_require__) {
  16576. "use strict";
  16577. /**
  16578. * MediaSource helper
  16579. */
  16580. Object.defineProperty(exports, "__esModule", { value: true });
  16581. function getMediaSource() {
  16582. if (typeof window !== 'undefined') {
  16583. return window.MediaSource || window.WebKitMediaSource;
  16584. }
  16585. }
  16586. exports.getMediaSource = getMediaSource;
  16587. /***/ }),
  16588. /***/ "./src/utils/output-filter.js":
  16589. /*!************************************!*\
  16590. !*** ./src/utils/output-filter.js ***!
  16591. \************************************/
  16592. /*! no static exports found */
  16593. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16594. /***/ (function(module, exports, __webpack_require__) {
  16595. "use strict";
  16596. Object.defineProperty(exports, "__esModule", { value: true });
  16597. var OutputFilter = /** @class */ (function () {
  16598. function OutputFilter(timelineController, trackName) {
  16599. this.timelineController = timelineController;
  16600. this.trackName = trackName;
  16601. this.startTime = null;
  16602. this.endTime = null;
  16603. this.screen = null;
  16604. }
  16605. OutputFilter.prototype.dispatchCue = function () {
  16606. if (this.startTime === null) {
  16607. return;
  16608. }
  16609. this.timelineController.addCues(this.trackName, this.startTime, this.endTime, this.screen);
  16610. this.startTime = null;
  16611. };
  16612. OutputFilter.prototype.newCue = function (startTime, endTime, screen) {
  16613. if (this.startTime === null || this.startTime > startTime) {
  16614. this.startTime = startTime;
  16615. }
  16616. this.endTime = endTime;
  16617. this.screen = screen;
  16618. this.timelineController.createCaptionsTrack(this.trackName);
  16619. };
  16620. return OutputFilter;
  16621. }());
  16622. exports.default = OutputFilter;
  16623. /***/ }),
  16624. /***/ "./src/utils/texttrack-utils.js":
  16625. /*!**************************************!*\
  16626. !*** ./src/utils/texttrack-utils.js ***!
  16627. \**************************************/
  16628. /*! no static exports found */
  16629. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16630. /***/ (function(module, exports, __webpack_require__) {
  16631. "use strict";
  16632. Object.defineProperty(exports, "__esModule", { value: true });
  16633. function sendAddTrackEvent(track, videoEl) {
  16634. var event = null;
  16635. try {
  16636. event = new window.Event('addtrack');
  16637. }
  16638. catch (err) {
  16639. // for IE11
  16640. event = document.createEvent('Event');
  16641. event.initEvent('addtrack', false, false);
  16642. }
  16643. event.track = track;
  16644. videoEl.dispatchEvent(event);
  16645. }
  16646. exports.sendAddTrackEvent = sendAddTrackEvent;
  16647. function clearCurrentCues(track) {
  16648. if (track && track.cues) {
  16649. while (track.cues.length > 0) {
  16650. track.removeCue(track.cues[0]);
  16651. }
  16652. }
  16653. }
  16654. exports.clearCurrentCues = clearCurrentCues;
  16655. /***/ }),
  16656. /***/ "./src/utils/time-ranges.js":
  16657. /*!**********************************!*\
  16658. !*** ./src/utils/time-ranges.js ***!
  16659. \**********************************/
  16660. /*! no static exports found */
  16661. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16662. /***/ (function(module, exports, __webpack_require__) {
  16663. "use strict";
  16664. /**
  16665. * TimeRanges to string helper
  16666. */
  16667. Object.defineProperty(exports, "__esModule", { value: true });
  16668. var TimeRanges = {
  16669. toString: function (r) {
  16670. var log = '', len = r.length;
  16671. for (var i = 0; i < len; i++) {
  16672. log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';
  16673. }
  16674. return log;
  16675. }
  16676. };
  16677. exports.default = TimeRanges;
  16678. /***/ }),
  16679. /***/ "./src/utils/vttcue.js":
  16680. /*!*****************************!*\
  16681. !*** ./src/utils/vttcue.js ***!
  16682. \*****************************/
  16683. /*! no static exports found */
  16684. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16685. /***/ (function(module, exports, __webpack_require__) {
  16686. "use strict";
  16687. /**
  16688. * Copyright 2013 vtt.js Contributors
  16689. *
  16690. * Licensed under the Apache License, Version 2.0 (the "License");
  16691. * you may not use this file except in compliance with the License.
  16692. * You may obtain a copy of the License at
  16693. *
  16694. * http://www.apache.org/licenses/LICENSE-2.0
  16695. *
  16696. * Unless required by applicable law or agreed to in writing, software
  16697. * distributed under the License is distributed on an "AS IS" BASIS,
  16698. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16699. * See the License for the specific language governing permissions and
  16700. * limitations under the License.
  16701. */
  16702. Object.defineProperty(exports, "__esModule", { value: true });
  16703. exports.default = (function () {
  16704. if (typeof window !== 'undefined' && window.VTTCue) {
  16705. return window.VTTCue;
  16706. }
  16707. var autoKeyword = 'auto';
  16708. var directionSetting = {
  16709. '': true,
  16710. lr: true,
  16711. rl: true
  16712. };
  16713. var alignSetting = {
  16714. start: true,
  16715. middle: true,
  16716. end: true,
  16717. left: true,
  16718. right: true
  16719. };
  16720. function findDirectionSetting(value) {
  16721. if (typeof value !== 'string') {
  16722. return false;
  16723. }
  16724. var dir = directionSetting[value.toLowerCase()];
  16725. return dir ? value.toLowerCase() : false;
  16726. }
  16727. function findAlignSetting(value) {
  16728. if (typeof value !== 'string') {
  16729. return false;
  16730. }
  16731. var align = alignSetting[value.toLowerCase()];
  16732. return align ? value.toLowerCase() : false;
  16733. }
  16734. function extend(obj) {
  16735. var i = 1;
  16736. for (; i < arguments.length; i++) {
  16737. var cobj = arguments[i];
  16738. for (var p in cobj) {
  16739. obj[p] = cobj[p];
  16740. }
  16741. }
  16742. return obj;
  16743. }
  16744. function VTTCue(startTime, endTime, text) {
  16745. var cue = this;
  16746. var isIE8 = (function () {
  16747. if (typeof navigator === 'undefined') {
  16748. return;
  16749. }
  16750. return (/MSIE\s8\.0/).test(navigator.userAgent);
  16751. })();
  16752. var baseObj = {};
  16753. if (isIE8) {
  16754. cue = document.createElement('custom');
  16755. }
  16756. else {
  16757. baseObj.enumerable = true;
  16758. }
  16759. /**
  16760. * Shim implementation specific properties. These properties are not in
  16761. * the spec.
  16762. */
  16763. // Lets us know when the VTTCue's data has changed in such a way that we need
  16764. // to recompute its display state. This lets us compute its display state
  16765. // lazily.
  16766. cue.hasBeenReset = false;
  16767. /**
  16768. * VTTCue and TextTrackCue properties
  16769. * http://dev.w3.org/html5/webvtt/#vttcue-interface
  16770. */
  16771. var _id = '';
  16772. var _pauseOnExit = false;
  16773. var _startTime = startTime;
  16774. var _endTime = endTime;
  16775. var _text = text;
  16776. var _region = null;
  16777. var _vertical = '';
  16778. var _snapToLines = true;
  16779. var _line = 'auto';
  16780. var _lineAlign = 'start';
  16781. var _position = 50;
  16782. var _positionAlign = 'middle';
  16783. var _size = 50;
  16784. var _align = 'middle';
  16785. Object.defineProperty(cue, 'id', extend({}, baseObj, {
  16786. get: function () {
  16787. return _id;
  16788. },
  16789. set: function (value) {
  16790. _id = '' + value;
  16791. }
  16792. }));
  16793. Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {
  16794. get: function () {
  16795. return _pauseOnExit;
  16796. },
  16797. set: function (value) {
  16798. _pauseOnExit = !!value;
  16799. }
  16800. }));
  16801. Object.defineProperty(cue, 'startTime', extend({}, baseObj, {
  16802. get: function () {
  16803. return _startTime;
  16804. },
  16805. set: function (value) {
  16806. if (typeof value !== 'number') {
  16807. throw new TypeError('Start time must be set to a number.');
  16808. }
  16809. _startTime = value;
  16810. this.hasBeenReset = true;
  16811. }
  16812. }));
  16813. Object.defineProperty(cue, 'endTime', extend({}, baseObj, {
  16814. get: function () {
  16815. return _endTime;
  16816. },
  16817. set: function (value) {
  16818. if (typeof value !== 'number') {
  16819. throw new TypeError('End time must be set to a number.');
  16820. }
  16821. _endTime = value;
  16822. this.hasBeenReset = true;
  16823. }
  16824. }));
  16825. Object.defineProperty(cue, 'text', extend({}, baseObj, {
  16826. get: function () {
  16827. return _text;
  16828. },
  16829. set: function (value) {
  16830. _text = '' + value;
  16831. this.hasBeenReset = true;
  16832. }
  16833. }));
  16834. Object.defineProperty(cue, 'region', extend({}, baseObj, {
  16835. get: function () {
  16836. return _region;
  16837. },
  16838. set: function (value) {
  16839. _region = value;
  16840. this.hasBeenReset = true;
  16841. }
  16842. }));
  16843. Object.defineProperty(cue, 'vertical', extend({}, baseObj, {
  16844. get: function () {
  16845. return _vertical;
  16846. },
  16847. set: function (value) {
  16848. var setting = findDirectionSetting(value);
  16849. // Have to check for false because the setting an be an empty string.
  16850. if (setting === false) {
  16851. throw new SyntaxError('An invalid or illegal string was specified.');
  16852. }
  16853. _vertical = setting;
  16854. this.hasBeenReset = true;
  16855. }
  16856. }));
  16857. Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {
  16858. get: function () {
  16859. return _snapToLines;
  16860. },
  16861. set: function (value) {
  16862. _snapToLines = !!value;
  16863. this.hasBeenReset = true;
  16864. }
  16865. }));
  16866. Object.defineProperty(cue, 'line', extend({}, baseObj, {
  16867. get: function () {
  16868. return _line;
  16869. },
  16870. set: function (value) {
  16871. if (typeof value !== 'number' && value !== autoKeyword) {
  16872. throw new SyntaxError('An invalid number or illegal string was specified.');
  16873. }
  16874. _line = value;
  16875. this.hasBeenReset = true;
  16876. }
  16877. }));
  16878. Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {
  16879. get: function () {
  16880. return _lineAlign;
  16881. },
  16882. set: function (value) {
  16883. var setting = findAlignSetting(value);
  16884. if (!setting) {
  16885. throw new SyntaxError('An invalid or illegal string was specified.');
  16886. }
  16887. _lineAlign = setting;
  16888. this.hasBeenReset = true;
  16889. }
  16890. }));
  16891. Object.defineProperty(cue, 'position', extend({}, baseObj, {
  16892. get: function () {
  16893. return _position;
  16894. },
  16895. set: function (value) {
  16896. if (value < 0 || value > 100) {
  16897. throw new Error('Position must be between 0 and 100.');
  16898. }
  16899. _position = value;
  16900. this.hasBeenReset = true;
  16901. }
  16902. }));
  16903. Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {
  16904. get: function () {
  16905. return _positionAlign;
  16906. },
  16907. set: function (value) {
  16908. var setting = findAlignSetting(value);
  16909. if (!setting) {
  16910. throw new SyntaxError('An invalid or illegal string was specified.');
  16911. }
  16912. _positionAlign = setting;
  16913. this.hasBeenReset = true;
  16914. }
  16915. }));
  16916. Object.defineProperty(cue, 'size', extend({}, baseObj, {
  16917. get: function () {
  16918. return _size;
  16919. },
  16920. set: function (value) {
  16921. if (value < 0 || value > 100) {
  16922. throw new Error('Size must be between 0 and 100.');
  16923. }
  16924. _size = value;
  16925. this.hasBeenReset = true;
  16926. }
  16927. }));
  16928. Object.defineProperty(cue, 'align', extend({}, baseObj, {
  16929. get: function () {
  16930. return _align;
  16931. },
  16932. set: function (value) {
  16933. var setting = findAlignSetting(value);
  16934. if (!setting) {
  16935. throw new SyntaxError('An invalid or illegal string was specified.');
  16936. }
  16937. _align = setting;
  16938. this.hasBeenReset = true;
  16939. }
  16940. }));
  16941. /**
  16942. * Other <track> spec defined properties
  16943. */
  16944. // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state
  16945. cue.displayState = undefined;
  16946. if (isIE8) {
  16947. return cue;
  16948. }
  16949. }
  16950. /**
  16951. * VTTCue methods
  16952. */
  16953. VTTCue.prototype.getCueAsHTML = function () {
  16954. // Assume WebVTT.convertCueToDOMTree is on the global.
  16955. var WebVTT = window.WebVTT;
  16956. return WebVTT.convertCueToDOMTree(window, this.text);
  16957. };
  16958. return VTTCue;
  16959. })();
  16960. /***/ }),
  16961. /***/ "./src/utils/vttparser.js":
  16962. /*!********************************!*\
  16963. !*** ./src/utils/vttparser.js ***!
  16964. \********************************/
  16965. /*! no static exports found */
  16966. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  16967. /***/ (function(module, exports, __webpack_require__) {
  16968. "use strict";
  16969. /*
  16970. * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716
  16971. */
  16972. Object.defineProperty(exports, "__esModule", { value: true });
  16973. var vttcue_1 = __webpack_require__(/*! ./vttcue */ "./src/utils/vttcue.js");
  16974. var StringDecoder = function StringDecoder() {
  16975. return {
  16976. decode: function (data) {
  16977. if (!data) {
  16978. return '';
  16979. }
  16980. if (typeof data !== 'string') {
  16981. throw new Error('Error - expected string data.');
  16982. }
  16983. return decodeURIComponent(encodeURIComponent(data));
  16984. }
  16985. };
  16986. };
  16987. function VTTParser() {
  16988. this.window = window;
  16989. this.state = 'INITIAL';
  16990. this.buffer = '';
  16991. this.decoder = new StringDecoder();
  16992. this.regionList = [];
  16993. }
  16994. // Try to parse input as a time stamp.
  16995. function parseTimeStamp(input) {
  16996. function computeSeconds(h, m, s, f) {
  16997. return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;
  16998. }
  16999. var m = input.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);
  17000. if (!m) {
  17001. return null;
  17002. }
  17003. if (m[3]) {
  17004. // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]
  17005. return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);
  17006. }
  17007. else if (m[1] > 59) {
  17008. // Timestamp takes the form of [hours]:[minutes].[milliseconds]
  17009. // First position is hours as it's over 59.
  17010. return computeSeconds(m[1], m[2], 0, m[4]);
  17011. }
  17012. else {
  17013. // Timestamp takes the form of [minutes]:[seconds].[milliseconds]
  17014. return computeSeconds(0, m[1], m[2], m[4]);
  17015. }
  17016. }
  17017. // A settings object holds key/value pairs and will ignore anything but the first
  17018. // assignment to a specific key.
  17019. function Settings() {
  17020. this.values = Object.create(null);
  17021. }
  17022. Settings.prototype = {
  17023. // Only accept the first assignment to any key.
  17024. set: function (k, v) {
  17025. if (!this.get(k) && v !== '') {
  17026. this.values[k] = v;
  17027. }
  17028. },
  17029. // Return the value for a key, or a default value.
  17030. // If 'defaultKey' is passed then 'dflt' is assumed to be an object with
  17031. // a number of possible default values as properties where 'defaultKey' is
  17032. // the key of the property that will be chosen; otherwise it's assumed to be
  17033. // a single value.
  17034. get: function (k, dflt, defaultKey) {
  17035. if (defaultKey) {
  17036. return this.has(k) ? this.values[k] : dflt[defaultKey];
  17037. }
  17038. return this.has(k) ? this.values[k] : dflt;
  17039. },
  17040. // Check whether we have a value for a key.
  17041. has: function (k) {
  17042. return k in this.values;
  17043. },
  17044. // Accept a setting if its one of the given alternatives.
  17045. alt: function (k, v, a) {
  17046. for (var n = 0; n < a.length; ++n) {
  17047. if (v === a[n]) {
  17048. this.set(k, v);
  17049. break;
  17050. }
  17051. }
  17052. },
  17053. // Accept a setting if its a valid (signed) integer.
  17054. integer: function (k, v) {
  17055. if (/^-?\d+$/.test(v)) { // integer
  17056. this.set(k, parseInt(v, 10));
  17057. }
  17058. },
  17059. // Accept a setting if its a valid percentage.
  17060. percent: function (k, v) {
  17061. var m;
  17062. if ((m = v.match(/^([\d]{1,3})(\.[\d]*)?%$/))) {
  17063. v = parseFloat(v);
  17064. if (v >= 0 && v <= 100) {
  17065. this.set(k, v);
  17066. return true;
  17067. }
  17068. }
  17069. return false;
  17070. }
  17071. };
  17072. // Helper function to parse input into groups separated by 'groupDelim', and
  17073. // interprete each group as a key/value pair separated by 'keyValueDelim'.
  17074. function parseOptions(input, callback, keyValueDelim, groupDelim) {
  17075. var groups = groupDelim ? input.split(groupDelim) : [input];
  17076. for (var i in groups) {
  17077. if (typeof groups[i] !== 'string') {
  17078. continue;
  17079. }
  17080. var kv = groups[i].split(keyValueDelim);
  17081. if (kv.length !== 2) {
  17082. continue;
  17083. }
  17084. var k = kv[0];
  17085. var v = kv[1];
  17086. callback(k, v);
  17087. }
  17088. }
  17089. var defaults = new vttcue_1.default(0, 0, 0);
  17090. // 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244
  17091. // Safari doesn't yet support this change, but FF and Chrome do.
  17092. var center = defaults.align === 'middle' ? 'middle' : 'center';
  17093. function parseCue(input, cue, regionList) {
  17094. // Remember the original input if we need to throw an error.
  17095. var oInput = input;
  17096. // 4.1 WebVTT timestamp
  17097. function consumeTimeStamp() {
  17098. var ts = parseTimeStamp(input);
  17099. if (ts === null) {
  17100. throw new Error('Malformed timestamp: ' + oInput);
  17101. }
  17102. // Remove time stamp from input.
  17103. input = input.replace(/^[^\sa-zA-Z-]+/, '');
  17104. return ts;
  17105. }
  17106. // 4.4.2 WebVTT cue settings
  17107. function consumeCueSettings(input, cue) {
  17108. var settings = new Settings();
  17109. parseOptions(input, function (k, v) {
  17110. switch (k) {
  17111. case 'region':
  17112. // Find the last region we parsed with the same region id.
  17113. for (var i = regionList.length - 1; i >= 0; i--) {
  17114. if (regionList[i].id === v) {
  17115. settings.set(k, regionList[i].region);
  17116. break;
  17117. }
  17118. }
  17119. break;
  17120. case 'vertical':
  17121. settings.alt(k, v, ['rl', 'lr']);
  17122. break;
  17123. case 'line':
  17124. var vals = v.split(','), vals0 = vals[0];
  17125. settings.integer(k, vals0);
  17126. if (settings.percent(k, vals0)) {
  17127. settings.set('snapToLines', false);
  17128. }
  17129. settings.alt(k, vals0, ['auto']);
  17130. if (vals.length === 2) {
  17131. settings.alt('lineAlign', vals[1], ['start', center, 'end']);
  17132. }
  17133. break;
  17134. case 'position':
  17135. vals = v.split(',');
  17136. settings.percent(k, vals[0]);
  17137. if (vals.length === 2) {
  17138. settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);
  17139. }
  17140. break;
  17141. case 'size':
  17142. settings.percent(k, v);
  17143. break;
  17144. case 'align':
  17145. settings.alt(k, v, ['start', center, 'end', 'left', 'right']);
  17146. break;
  17147. }
  17148. }, /:/, /\s/);
  17149. // Apply default values for any missing fields.
  17150. cue.region = settings.get('region', null);
  17151. cue.vertical = settings.get('vertical', '');
  17152. var line = settings.get('line', 'auto');
  17153. if (line === 'auto' && defaults.line === -1) {
  17154. // set numeric line number for Safari
  17155. line = -1;
  17156. }
  17157. cue.line = line;
  17158. cue.lineAlign = settings.get('lineAlign', 'start');
  17159. cue.snapToLines = settings.get('snapToLines', true);
  17160. cue.size = settings.get('size', 100);
  17161. cue.align = settings.get('align', center);
  17162. var position = settings.get('position', 'auto');
  17163. if (position === 'auto' && defaults.position === 50) {
  17164. // set numeric position for Safari
  17165. position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;
  17166. }
  17167. cue.position = position;
  17168. }
  17169. function skipWhitespace() {
  17170. input = input.replace(/^\s+/, '');
  17171. }
  17172. // 4.1 WebVTT cue timings.
  17173. skipWhitespace();
  17174. cue.startTime = consumeTimeStamp(); // (1) collect cue start time
  17175. skipWhitespace();
  17176. if (input.substr(0, 3) !== '-->') { // (3) next characters must match '-->'
  17177. throw new Error('Malformed time stamp (time stamps must be separated by \'-->\'): ' +
  17178. oInput);
  17179. }
  17180. input = input.substr(3);
  17181. skipWhitespace();
  17182. cue.endTime = consumeTimeStamp(); // (5) collect cue end time
  17183. // 4.1 WebVTT cue settings list.
  17184. skipWhitespace();
  17185. consumeCueSettings(input, cue);
  17186. }
  17187. function fixLineBreaks(input) {
  17188. return input.replace(/<br(?: \/)?>/gi, '\n');
  17189. }
  17190. exports.fixLineBreaks = fixLineBreaks;
  17191. VTTParser.prototype = {
  17192. parse: function (data) {
  17193. var self = this;
  17194. // If there is no data then we won't decode it, but will just try to parse
  17195. // whatever is in buffer already. This may occur in circumstances, for
  17196. // example when flush() is called.
  17197. if (data) {
  17198. // Try to decode the data that we received.
  17199. self.buffer += self.decoder.decode(data, { stream: true });
  17200. }
  17201. function collectNextLine() {
  17202. var buffer = self.buffer;
  17203. var pos = 0;
  17204. buffer = fixLineBreaks(buffer);
  17205. while (pos < buffer.length && buffer[pos] !== '\r' && buffer[pos] !== '\n') {
  17206. ++pos;
  17207. }
  17208. var line = buffer.substr(0, pos);
  17209. // Advance the buffer early in case we fail below.
  17210. if (buffer[pos] === '\r') {
  17211. ++pos;
  17212. }
  17213. if (buffer[pos] === '\n') {
  17214. ++pos;
  17215. }
  17216. self.buffer = buffer.substr(pos);
  17217. return line;
  17218. }
  17219. // 3.2 WebVTT metadata header syntax
  17220. function parseHeader(input) {
  17221. parseOptions(input, function (k, v) {
  17222. switch (k) {
  17223. case 'Region':
  17224. // 3.3 WebVTT region metadata header syntax
  17225. // console.log('parse region', v);
  17226. // parseRegion(v);
  17227. break;
  17228. }
  17229. }, /:/);
  17230. }
  17231. // 5.1 WebVTT file parsing.
  17232. try {
  17233. var line = void 0;
  17234. if (self.state === 'INITIAL') {
  17235. // We can't start parsing until we have the first line.
  17236. if (!/\r\n|\n/.test(self.buffer)) {
  17237. return this;
  17238. }
  17239. line = collectNextLine();
  17240. // strip of UTF-8 BOM if any
  17241. // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8
  17242. var m = line.match(/^()?WEBVTT([ \t].*)?$/);
  17243. if (!m || !m[0]) {
  17244. throw new Error('Malformed WebVTT signature.');
  17245. }
  17246. self.state = 'HEADER';
  17247. }
  17248. var alreadyCollectedLine = false;
  17249. while (self.buffer) {
  17250. // We can't parse a line until we have the full line.
  17251. if (!/\r\n|\n/.test(self.buffer)) {
  17252. return this;
  17253. }
  17254. if (!alreadyCollectedLine) {
  17255. line = collectNextLine();
  17256. }
  17257. else {
  17258. alreadyCollectedLine = false;
  17259. }
  17260. switch (self.state) {
  17261. case 'HEADER':
  17262. // 13-18 - Allow a header (metadata) under the WEBVTT line.
  17263. if (/:/.test(line)) {
  17264. parseHeader(line);
  17265. }
  17266. else if (!line) {
  17267. // An empty line terminates the header and starts the body (cues).
  17268. self.state = 'ID';
  17269. }
  17270. continue;
  17271. case 'NOTE':
  17272. // Ignore NOTE blocks.
  17273. if (!line) {
  17274. self.state = 'ID';
  17275. }
  17276. continue;
  17277. case 'ID':
  17278. // Check for the start of NOTE blocks.
  17279. if (/^NOTE($|[ \t])/.test(line)) {
  17280. self.state = 'NOTE';
  17281. break;
  17282. }
  17283. // 19-29 - Allow any number of line terminators, then initialize new cue values.
  17284. if (!line) {
  17285. continue;
  17286. }
  17287. self.cue = new vttcue_1.default(0, 0, '');
  17288. self.state = 'CUE';
  17289. // 30-39 - Check if self line contains an optional identifier or timing data.
  17290. if (line.indexOf('-->') === -1) {
  17291. self.cue.id = line;
  17292. continue;
  17293. }
  17294. // Process line as start of a cue.
  17295. /* falls through */
  17296. case 'CUE':
  17297. // 40 - Collect cue timings and settings.
  17298. try {
  17299. parseCue(line, self.cue, self.regionList);
  17300. }
  17301. catch (e) {
  17302. // In case of an error ignore rest of the cue.
  17303. self.cue = null;
  17304. self.state = 'BADCUE';
  17305. continue;
  17306. }
  17307. self.state = 'CUETEXT';
  17308. continue;
  17309. case 'CUETEXT':
  17310. var hasSubstring = line.indexOf('-->') !== -1;
  17311. // 34 - If we have an empty line then report the cue.
  17312. // 35 - If we have the special substring '-->' then report the cue,
  17313. // but do not collect the line as we need to process the current
  17314. // one as a new cue.
  17315. if (!line || hasSubstring && (alreadyCollectedLine = true)) {
  17316. // We are done parsing self cue.
  17317. if (self.oncue) {
  17318. self.oncue(self.cue);
  17319. }
  17320. self.cue = null;
  17321. self.state = 'ID';
  17322. continue;
  17323. }
  17324. if (self.cue.text) {
  17325. self.cue.text += '\n';
  17326. }
  17327. self.cue.text += line;
  17328. continue;
  17329. case 'BADCUE': // BADCUE
  17330. // 54-62 - Collect and discard the remaining cue.
  17331. if (!line) {
  17332. self.state = 'ID';
  17333. }
  17334. continue;
  17335. }
  17336. }
  17337. }
  17338. catch (e) {
  17339. // If we are currently parsing a cue, report what we have.
  17340. if (self.state === 'CUETEXT' && self.cue && self.oncue) {
  17341. self.oncue(self.cue);
  17342. }
  17343. self.cue = null;
  17344. // Enter BADWEBVTT state if header was not parsed correctly otherwise
  17345. // another exception occurred so enter BADCUE state.
  17346. self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';
  17347. }
  17348. return this;
  17349. },
  17350. flush: function () {
  17351. var self = this;
  17352. try {
  17353. // Finish decoding the stream.
  17354. self.buffer += self.decoder.decode();
  17355. // Synthesize the end of the current cue or region.
  17356. if (self.cue || self.state === 'HEADER') {
  17357. self.buffer += '\n\n';
  17358. self.parse();
  17359. }
  17360. // If we've flushed, parsed, and we're still on the INITIAL state then
  17361. // that means we don't have enough of the stream to parse the first
  17362. // line.
  17363. if (self.state === 'INITIAL') {
  17364. throw new Error('Malformed WebVTT signature.');
  17365. }
  17366. }
  17367. catch (e) {
  17368. throw e;
  17369. }
  17370. if (self.onflush) {
  17371. self.onflush();
  17372. }
  17373. return this;
  17374. }
  17375. };
  17376. exports.default = VTTParser;
  17377. /***/ }),
  17378. /***/ "./src/utils/webvtt-parser.js":
  17379. /*!************************************!*\
  17380. !*** ./src/utils/webvtt-parser.js ***!
  17381. \************************************/
  17382. /*! no static exports found */
  17383. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  17384. /***/ (function(module, exports, __webpack_require__) {
  17385. "use strict";
  17386. /* WEBPACK VAR INJECTION */(function(Number) {
  17387. Object.defineProperty(exports, "__esModule", { value: true });
  17388. var vttparser_1 = __webpack_require__(/*! ./vttparser */ "./src/utils/vttparser.js");
  17389. var id3_1 = __webpack_require__(/*! ../demux/id3 */ "./src/demux/id3.js");
  17390. // String.prototype.startsWith is not supported in IE11
  17391. var startsWith = function (inputString, searchString, position) {
  17392. return inputString.substr(position || 0, searchString.length) === searchString;
  17393. };
  17394. var cueString2millis = function (timeString) {
  17395. var ts = parseInt(timeString.substr(-3));
  17396. var secs = parseInt(timeString.substr(-6, 2));
  17397. var mins = parseInt(timeString.substr(-9, 2));
  17398. var hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;
  17399. if (!Number.isFinite(ts) || !Number.isFinite(secs) || !Number.isFinite(mins) || !Number.isFinite(hours)) {
  17400. return -1;
  17401. }
  17402. ts += 1000 * secs;
  17403. ts += 60 * 1000 * mins;
  17404. ts += 60 * 60 * 1000 * hours;
  17405. return ts;
  17406. };
  17407. // From https://github.com/darkskyapp/string-hash
  17408. var hash = function (text) {
  17409. var hash = 5381;
  17410. var i = text.length;
  17411. while (i) {
  17412. hash = (hash * 33) ^ text.charCodeAt(--i);
  17413. }
  17414. return (hash >>> 0).toString();
  17415. };
  17416. var calculateOffset = function (vttCCs, cc, presentationTime) {
  17417. var currCC = vttCCs[cc];
  17418. var prevCC = vttCCs[currCC.prevCC];
  17419. // This is the first discontinuity or cues have been processed since the last discontinuity
  17420. // Offset = current discontinuity time
  17421. if (!prevCC || (!prevCC.new && currCC.new)) {
  17422. vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;
  17423. currCC.new = false;
  17424. return;
  17425. }
  17426. // There have been discontinuities since cues were last parsed.
  17427. // Offset = time elapsed
  17428. while (prevCC && prevCC.new) {
  17429. vttCCs.ccOffset += currCC.start - prevCC.start;
  17430. currCC.new = false;
  17431. currCC = prevCC;
  17432. prevCC = vttCCs[currCC.prevCC];
  17433. }
  17434. vttCCs.presentationOffset = presentationTime;
  17435. };
  17436. var WebVTTParser = {
  17437. parse: function (vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {
  17438. // Convert byteArray into string, replacing any somewhat exotic linefeeds with "\n", then split on that character.
  17439. var re = /\r\n|\n\r|\n|\r/g;
  17440. // Uint8Array.prototype.reduce is not implemented in IE11
  17441. var vttLines = id3_1.utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(re, '\n').split('\n');
  17442. var cueTime = '00:00.000';
  17443. var mpegTs = 0;
  17444. var localTime = 0;
  17445. var presentationTime = 0;
  17446. var cues = [];
  17447. var parsingError;
  17448. var inHeader = true;
  17449. // let VTTCue = VTTCue || window.TextTrackCue;
  17450. // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.
  17451. var parser = new vttparser_1.default();
  17452. parser.oncue = function (cue) {
  17453. // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.
  17454. var currCC = vttCCs[cc];
  17455. var cueOffset = vttCCs.ccOffset;
  17456. // Update offsets for new discontinuities
  17457. if (currCC && currCC.new) {
  17458. if (localTime !== undefined) {
  17459. // When local time is provided, offset = discontinuity start time - local time
  17460. cueOffset = vttCCs.ccOffset = currCC.start;
  17461. }
  17462. else {
  17463. calculateOffset(vttCCs, cc, presentationTime);
  17464. }
  17465. }
  17466. if (presentationTime) {
  17467. // If we have MPEGTS, offset = presentation time + discontinuity offset
  17468. cueOffset = presentationTime - vttCCs.presentationOffset;
  17469. }
  17470. cue.startTime += cueOffset - localTime;
  17471. cue.endTime += cueOffset - localTime;
  17472. // Create a unique hash id for a cue based on start/end times and text.
  17473. // This helps timeline-controller to avoid showing repeated captions.
  17474. cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);
  17475. // Fix encoding of special characters. TODO: Test with all sorts of weird characters.
  17476. cue.text = decodeURIComponent(encodeURIComponent(cue.text));
  17477. if (cue.endTime > 0) {
  17478. cues.push(cue);
  17479. }
  17480. };
  17481. parser.onparsingerror = function (e) {
  17482. parsingError = e;
  17483. };
  17484. parser.onflush = function () {
  17485. if (parsingError && errorCallBack) {
  17486. errorCallBack(parsingError);
  17487. return;
  17488. }
  17489. callBack(cues);
  17490. };
  17491. // Go through contents line by line.
  17492. vttLines.forEach(function (line) {
  17493. if (inHeader) {
  17494. // Look for X-TIMESTAMP-MAP in header.
  17495. if (startsWith(line, 'X-TIMESTAMP-MAP=')) {
  17496. // Once found, no more are allowed anyway, so stop searching.
  17497. inHeader = false;
  17498. // Extract LOCAL and MPEGTS.
  17499. line.substr(16).split(',').forEach(function (timestamp) {
  17500. if (startsWith(timestamp, 'LOCAL:')) {
  17501. cueTime = timestamp.substr(6);
  17502. }
  17503. else if (startsWith(timestamp, 'MPEGTS:')) {
  17504. mpegTs = parseInt(timestamp.substr(7));
  17505. }
  17506. });
  17507. try {
  17508. // Calculate subtitle offset in milliseconds.
  17509. if (syncPTS + ((vttCCs[cc].start * 90000) || 0) < 0) {
  17510. syncPTS += 8589934592;
  17511. }
  17512. // Adjust MPEGTS by sync PTS.
  17513. mpegTs -= syncPTS;
  17514. // Convert cue time to seconds
  17515. localTime = cueString2millis(cueTime) / 1000;
  17516. // Convert MPEGTS to seconds from 90kHz.
  17517. presentationTime = mpegTs / 90000;
  17518. if (localTime === -1) {
  17519. parsingError = new Error("Malformed X-TIMESTAMP-MAP: " + line);
  17520. }
  17521. }
  17522. catch (e) {
  17523. parsingError = new Error("Malformed X-TIMESTAMP-MAP: " + line);
  17524. }
  17525. // Return without parsing X-TIMESTAMP-MAP line.
  17526. return;
  17527. }
  17528. else if (line === '') {
  17529. inHeader = false;
  17530. }
  17531. }
  17532. // Parse line by default.
  17533. parser.parse(line + '\n');
  17534. });
  17535. parser.flush();
  17536. }
  17537. };
  17538. exports.default = WebVTTParser;
  17539. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./src/polyfills/number */ "./src/polyfills/number.js")["Number"]))
  17540. /***/ }),
  17541. /***/ "./src/utils/xhr-loader.js":
  17542. /*!*********************************!*\
  17543. !*** ./src/utils/xhr-loader.js ***!
  17544. \*********************************/
  17545. /*! no static exports found */
  17546. /*! ModuleConcatenation bailout: Module is not an ECMAScript module */
  17547. /***/ (function(module, exports, __webpack_require__) {
  17548. "use strict";
  17549. /**
  17550. * XHR based logger
  17551. */
  17552. Object.defineProperty(exports, "__esModule", { value: true });
  17553. var logger_1 = __webpack_require__(/*! ../utils/logger */ "./src/utils/logger.js");
  17554. var performance = window.performance, XMLHttpRequest = window.XMLHttpRequest;
  17555. var XhrLoader = /** @class */ (function () {
  17556. function XhrLoader(config) {
  17557. if (config && config.xhrSetup) {
  17558. this.xhrSetup = config.xhrSetup;
  17559. }
  17560. }
  17561. XhrLoader.prototype.destroy = function () {
  17562. this.abort();
  17563. this.loader = null;
  17564. };
  17565. XhrLoader.prototype.abort = function () {
  17566. var loader = this.loader;
  17567. if (loader && loader.readyState !== 4) {
  17568. this.stats.aborted = true;
  17569. loader.abort();
  17570. }
  17571. window.clearTimeout(this.requestTimeout);
  17572. this.requestTimeout = null;
  17573. window.clearTimeout(this.retryTimeout);
  17574. this.retryTimeout = null;
  17575. };
  17576. XhrLoader.prototype.load = function (context, config, callbacks) {
  17577. this.context = context;
  17578. this.config = config;
  17579. this.callbacks = callbacks;
  17580. this.stats = { trequest: performance.now(), retry: 0 };
  17581. this.retryDelay = config.retryDelay;
  17582. this.loadInternal();
  17583. };
  17584. XhrLoader.prototype.loadInternal = function () {
  17585. var xhr, context = this.context;
  17586. xhr = this.loader = new XMLHttpRequest();
  17587. var stats = this.stats;
  17588. stats.tfirst = 0;
  17589. stats.loaded = 0;
  17590. var xhrSetup = this.xhrSetup;
  17591. try {
  17592. if (xhrSetup) {
  17593. try {
  17594. xhrSetup(xhr, context.url);
  17595. }
  17596. catch (e) {
  17597. // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader("Content-Language", "test");}
  17598. // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN
  17599. xhr.open('GET', context.url, true);
  17600. xhrSetup(xhr, context.url);
  17601. }
  17602. }
  17603. if (!xhr.readyState) {
  17604. xhr.open('GET', context.url, true);
  17605. }
  17606. }
  17607. catch (e) {
  17608. // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS
  17609. this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);
  17610. return;
  17611. }
  17612. if (context.rangeEnd) {
  17613. xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));
  17614. }
  17615. xhr.onreadystatechange = this.readystatechange.bind(this);
  17616. xhr.onprogress = this.loadprogress.bind(this);
  17617. xhr.responseType = context.responseType;
  17618. // setup timeout before we perform request
  17619. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);
  17620. xhr.send();
  17621. };
  17622. XhrLoader.prototype.readystatechange = function (event) {
  17623. var xhr = event.currentTarget, readyState = xhr.readyState, stats = this.stats, context = this.context, config = this.config;
  17624. // don't proceed if xhr has been aborted
  17625. if (stats.aborted) {
  17626. return;
  17627. }
  17628. // >= HEADERS_RECEIVED
  17629. if (readyState >= 2) {
  17630. // clear xhr timeout and rearm it if readyState less than 4
  17631. window.clearTimeout(this.requestTimeout);
  17632. if (stats.tfirst === 0) {
  17633. stats.tfirst = Math.max(performance.now(), stats.trequest);
  17634. }
  17635. if (readyState === 4) {
  17636. var status_1 = xhr.status;
  17637. // http status between 200 to 299 are all successful
  17638. if (status_1 >= 200 && status_1 < 300) {
  17639. stats.tload = Math.max(stats.tfirst, performance.now());
  17640. var data = void 0, len = void 0;
  17641. if (context.responseType === 'arraybuffer') {
  17642. data = xhr.response;
  17643. len = data.byteLength;
  17644. }
  17645. else {
  17646. data = xhr.responseText;
  17647. len = data.length;
  17648. }
  17649. stats.loaded = stats.total = len;
  17650. var response = { url: xhr.responseURL, data: data };
  17651. this.callbacks.onSuccess(response, stats, context, xhr);
  17652. }
  17653. else {
  17654. // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error
  17655. if (stats.retry >= config.maxRetry || (status_1 >= 400 && status_1 < 499)) {
  17656. logger_1.logger.error(status_1 + " while loading " + context.url);
  17657. this.callbacks.onError({ code: status_1, text: xhr.statusText }, context, xhr);
  17658. }
  17659. else {
  17660. // retry
  17661. logger_1.logger.warn(status_1 + " while loading " + context.url + ", retrying in " + this.retryDelay + "...");
  17662. // aborts and resets internal state
  17663. this.destroy();
  17664. // schedule retry
  17665. this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);
  17666. // set exponential backoff
  17667. this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);
  17668. stats.retry++;
  17669. }
  17670. }
  17671. }
  17672. else {
  17673. // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet
  17674. this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);
  17675. }
  17676. }
  17677. };
  17678. XhrLoader.prototype.loadtimeout = function () {
  17679. logger_1.logger.warn("timeout while loading " + this.context.url);
  17680. this.callbacks.onTimeout(this.stats, this.context, null);
  17681. };
  17682. XhrLoader.prototype.loadprogress = function (event) {
  17683. var xhr = event.currentTarget, stats = this.stats;
  17684. stats.loaded = event.loaded;
  17685. if (event.lengthComputable) {
  17686. stats.total = event.total;
  17687. }
  17688. var onProgress = this.callbacks.onProgress;
  17689. if (onProgress) {
  17690. // third arg is to provide on progress data
  17691. onProgress(stats, this.context, null, xhr);
  17692. }
  17693. };
  17694. return XhrLoader;
  17695. }());
  17696. exports.default = XhrLoader;
  17697. /***/ })
  17698. /******/ })["default"];
  17699. });
  17700. //# sourceMappingURL=hls.js.map