diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index ee24fe2323..c701a09137 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1,7 +1,7 @@ # These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] -patreon: # Replace with a single Patreon username +patreon: ossrs open_collective: srs-server ko_fi: # Replace with a single Ko-fi username tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md index 7bce38f63b..037369f123 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -7,6 +7,11 @@ assignees: '' --- +!!! Before submitting a new bug report, please ensure you have searched for any existing bugs and utilized +the `Ask AI` feature at https://ossrs.io or https://ossrs.net (for users in China). Duplicate issues or +questions that are overly simple or already addressed in the documentation will be removed without any +response. + **Describe the bug** A clear and concise description of what the bug is. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md index b07a11b29e..5eba3b916d 100644 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -7,6 +7,11 @@ assignees: '' --- +!!! Before submitting a new feature request, please ensure you have searched for any existing features and utilized +the `Ask AI` feature at https://ossrs.io or https://ossrs.net (for users in China). Duplicate issues or +questions that are overly simple or already addressed in the documentation will be removed without any +response. + **What is the business background? Please provide a description.** Who are the users? How do they utilize this feature? What problem does this feature address? diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index fc95ef5f72..4d18f236c5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -250,7 +250,7 @@ jobs: echo "SRS_TAG=${{ needs.envs.outputs.SRS_TAG }}" >> $GITHUB_ENV echo "SRS_VERSION=${{ needs.envs.outputs.SRS_VERSION }}" >> $GITHUB_ENV echo "SRS_MAJOR=${{ needs.envs.outputs.SRS_MAJOR }}" >> $GITHUB_ENV - echo "SRS_MAJOR=${{ needs.envs.outputs.SRS_XYZ }}" >> $GITHUB_ENV + echo "SRS_XYZ=${{ needs.envs.outputs.SRS_XYZ }}" >> $GITHUB_ENV ################################################################################################################## # Git checkout - name: Checkout repository @@ -276,7 +276,9 @@ jobs: echo "Release ossrs/srs:$SRS_TAG" docker buildx build --platform linux/arm/v7,linux/arm64/v8,linux/amd64 \ --output "type=image,push=true" \ - -t ossrs/srs:$SRS_TAG --build-arg SRS_AUTO_PACKAGER=$PACKAGER -f Dockerfile . + -t ossrs/srs:$SRS_TAG --build-arg SRS_AUTO_PACKAGER=$PACKAGER \ + --build-arg CONFARGS='--sanitizer=off --gb28181=on' \ + -f Dockerfile . # Docker alias images # TODO: FIXME: If stable, please set the latest from 5.0 to 6.0 - name: Docker alias images for ossrs/srs @@ -304,7 +306,7 @@ jobs: echo "SRS_TAG=${{ needs.envs.outputs.SRS_TAG }}" >> $GITHUB_ENV echo "SRS_VERSION=${{ needs.envs.outputs.SRS_VERSION }}" >> $GITHUB_ENV echo "SRS_MAJOR=${{ needs.envs.outputs.SRS_MAJOR }}" >> $GITHUB_ENV - echo "SRS_MAJOR=${{ needs.envs.outputs.SRS_XYZ }}" >> $GITHUB_ENV + echo "SRS_XYZ=${{ needs.envs.outputs.SRS_XYZ }}" >> $GITHUB_ENV # Aliyun ACR # TODO: FIXME: If stable, please set the latest from 5.0 to 6.0 - name: Login aliyun hub diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 53a114a6cf..6ea5e3c1f4 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -198,7 +198,7 @@ jobs: - name: Run SRS regression-test run: | docker run --rm srs:test bash -c './objs/srs -c conf/regression-test.conf && \ - cd 3rdparty/srs-bench && (./objs/srs_test -test.v || (cat ../../objs/srs.log && exit 1)) && cat ../../objs/srs.log && \ + cd 3rdparty/srs-bench && (./objs/srs_test -test.v || (cat ../../objs/srs.log && exit 1)) && \ ./objs/srs_gb28181_test -test.v' runs-on: ubuntu-20.04 diff --git a/Dockerfile b/Dockerfile index 953f60df27..bf301547ec 100644 --- a/Dockerfile +++ b/Dockerfile @@ -29,7 +29,7 @@ WORKDIR /srs/trunk # Build and install SRS. # Note that SRT is enabled by default, so we configure without --srt=on. # Note that we have copied all files by make install. -RUN ./configure --sanitizer=off --gb28181=on --h265=on ${CONFARGS} && make ${MAKEARGS} && make install +RUN ./configure ${CONFARGS} && make ${MAKEARGS} && make install ############################################################ # dist diff --git a/LICENSE b/LICENSE index 2ce38816d0..4391c39244 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2013-2023 The SRS Authors +Copyright (c) 2013-2024 The SRS Authors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in diff --git a/README.md b/README.md index 458259592a..f45d8e36b7 100755 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ [![](https://badgen.net/badge/srs/stackoverflow/orange?icon=terminal)](https://stackoverflow.com/questions/tagged/simple-realtime-server) [![](https://opencollective.com/srs-server/tiers/badge.svg)](https://opencollective.com/srs-server) [![](https://img.shields.io/docker/pulls/ossrs/srs)](https://hub.docker.com/r/ossrs/srs/tags) -[![](https://ossrs.net/wiki/images/do-btn-srs-125x20.svg)](https://cloud.digitalocean.com/droplets/new?appId=133468816&size=s-2vcpu-2gb®ion=sgp1&image=ossrs-srs&type=applications) +[![](https://ossrs.net/wiki/images/do-btn-srs-125x20.svg)](https://marketplace.digitalocean.com/apps/srs) [![](https://api.securityscorecards.dev/projects/github.com/ossrs/srs/badge)](https://api.securityscorecards.dev/projects/github.com/ossrs/srs) [![](https://bestpractices.coreinfrastructure.org/projects/5619/badge)](https://bestpractices.coreinfrastructure.org/projects/5619) @@ -130,6 +130,7 @@ distributed under their [licenses](https://ossrs.io/lts/en-us/license). * 2023-09-28, [Release v6.0-d2](https://github.com/ossrs/srs/releases/tag/v6.0-d2), v6.0-d2, 6.0 dev2, v6.0.85, 167509 lines. * 2023-08-31, [Release v6.0-d1](https://github.com/ossrs/srs/releases/tag/v6.0-d1), v6.0-d1, 6.0 dev1, v6.0.72, 167135 lines. * 2023-07-09, [Release v6.0-d0](https://github.com/ossrs/srs/releases/tag/v6.0-d0), v6.0-d0, 6.0 dev0, v6.0.59, 166739 lines. +* 2023-12-30, [Release v5.0-r0](https://github.com/ossrs/srs/releases/tag/v5.0-r0), v5.0-r0, 5.0 release0, v5.0.205, 163363 lines. * 2023-11-19, [Release v5.0-b7](https://github.com/ossrs/srs/releases/tag/v5.0-b7), v5.0-b7, 5.0 beta7, v5.0.200, 163305 lines. * 2023-10-25, [Release v5.0-b6](https://github.com/ossrs/srs/releases/tag/v5.0-b6), v5.0-b6, 5.0 beta6, v5.0.195, 163303 lines. * 2023-09-28, [Release v5.0-b5](https://github.com/ossrs/srs/releases/tag/v5.0-b5), v5.0-b5, 5.0 beta5, v5.0.185, 163254 lines. diff --git a/trunk/3rdparty/st-srs/tools/backtrace/backtrace.c b/trunk/3rdparty/st-srs/tools/backtrace/backtrace.c index 61480b7cc0..0af24cfaf6 100644 --- a/trunk/3rdparty/st-srs/tools/backtrace/backtrace.c +++ b/trunk/3rdparty/st-srs/tools/backtrace/backtrace.c @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: MIT */ -/* Copyright (c) 2013-2023 Winlin */ +/* Copyright (c) 2013-2024 The SRS Authors */ #ifdef __linux__ #define _GNU_SOURCE diff --git a/trunk/3rdparty/st-srs/tools/helloworld/helloworld.c b/trunk/3rdparty/st-srs/tools/helloworld/helloworld.c index 316a438c03..5c30d690b8 100644 --- a/trunk/3rdparty/st-srs/tools/helloworld/helloworld.c +++ b/trunk/3rdparty/st-srs/tools/helloworld/helloworld.c @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: MIT */ -/* Copyright (c) 2013-2023 Winlin */ +/* Copyright (c) 2013-2024 The SRS Authors */ #include diff --git a/trunk/3rdparty/st-srs/tools/porting/porting.c b/trunk/3rdparty/st-srs/tools/porting/porting.c index 3e1479fb8c..7267ac7a72 100644 --- a/trunk/3rdparty/st-srs/tools/porting/porting.c +++ b/trunk/3rdparty/st-srs/tools/porting/porting.c @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: MIT */ -/* Copyright (c) 2013-2023 Winlin */ +/* Copyright (c) 2013-2024 The SRS Authors */ #include #include diff --git a/trunk/3rdparty/st-srs/tools/verify/verify.c b/trunk/3rdparty/st-srs/tools/verify/verify.c index 4a1ae1c386..ea96e233b7 100644 --- a/trunk/3rdparty/st-srs/tools/verify/verify.c +++ b/trunk/3rdparty/st-srs/tools/verify/verify.c @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: MIT */ -/* Copyright (c) 2013-2023 Winlin */ +/* Copyright (c) 2013-2024 The SRS Authors */ #include diff --git a/trunk/3rdparty/st-srs/utest/st_utest.cpp b/trunk/3rdparty/st-srs/utest/st_utest.cpp index 325d3cf52f..4571bfbb3a 100644 --- a/trunk/3rdparty/st-srs/utest/st_utest.cpp +++ b/trunk/3rdparty/st-srs/utest/st_utest.cpp @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: MIT */ -/* Copyright (c) 2013-2023 Winlin */ +/* Copyright (c) 2013-2024 The SRS Authors */ #include diff --git a/trunk/3rdparty/st-srs/utest/st_utest.hpp b/trunk/3rdparty/st-srs/utest/st_utest.hpp index ff1c5f6ceb..470b9ed2af 100644 --- a/trunk/3rdparty/st-srs/utest/st_utest.hpp +++ b/trunk/3rdparty/st-srs/utest/st_utest.hpp @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: MIT */ -/* Copyright (c) 2013-2023 Winlin */ +/* Copyright (c) 2013-2024 The SRS Authors */ #ifndef ST_UTEST_PUBLIC_HPP #define ST_UTEST_PUBLIC_HPP diff --git a/trunk/3rdparty/st-srs/utest/st_utest_coroutines.cpp b/trunk/3rdparty/st-srs/utest/st_utest_coroutines.cpp index 5628cd76f8..fe57aa7261 100644 --- a/trunk/3rdparty/st-srs/utest/st_utest_coroutines.cpp +++ b/trunk/3rdparty/st-srs/utest/st_utest_coroutines.cpp @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: MIT */ -/* Copyright (c) 2013-2023 Winlin */ +/* Copyright (c) 2013-2024 The SRS Authors */ #include diff --git a/trunk/3rdparty/st-srs/utest/st_utest_tcp.cpp b/trunk/3rdparty/st-srs/utest/st_utest_tcp.cpp index 82c9f83856..ecbd839e0d 100644 --- a/trunk/3rdparty/st-srs/utest/st_utest_tcp.cpp +++ b/trunk/3rdparty/st-srs/utest/st_utest_tcp.cpp @@ -1,5 +1,5 @@ /* SPDX-License-Identifier: MIT */ -/* Copyright (c) 2013-2023 Winlin */ +/* Copyright (c) 2013-2024 The SRS Authors */ #include diff --git a/trunk/Dockerfile.test b/trunk/Dockerfile.test index 30222976bf..aae3f09180 100644 --- a/trunk/Dockerfile.test +++ b/trunk/Dockerfile.test @@ -16,7 +16,8 @@ COPY . /srs WORKDIR /srs/trunk # Note that we must enable the gcc7 or link failed. -# Note that we must disable the build-cache, or it will failed, but donot know why. +# Please note that we must disable the ffmpeg-opus, as it negatively impacts performance. We may consider +# enabling it in the future when support for multi-threading transcoding is available. RUN ./configure --srt=on --gb28181=on --srt=on --apm=on --h265=on --utest=on --ffmpeg-opus=off --build-cache=on RUN make utest ${MAKEARGS} diff --git a/trunk/auto/options.sh b/trunk/auto/options.sh index ef879547ee..5d5e9aa299 100755 --- a/trunk/auto/options.sh +++ b/trunk/auto/options.sh @@ -6,7 +6,7 @@ help=no SRS_HDS=NO SRS_SRT=YES SRS_RTC=YES -SRS_H265=NO +SRS_H265=YES SRS_GB28181=NO SRS_CXX11=YES SRS_CXX14=NO @@ -446,7 +446,7 @@ function parse_user_option_to_value_and_option() { case "$option" in -*=*) value=`echo "$option" | sed -e 's|[-_a-zA-Z0-9/]*=||'` - option=`echo "$option" | sed -e 's|=[,-_a-zA-Z0-9/. +]*||'` + option=`echo "$option" | sed -e 's|=[-_a-zA-Z0-9/. +,=]*||'` ;; *) value="" ;; esac diff --git a/trunk/conf/full.conf b/trunk/conf/full.conf index 1082dad671..1f9da26b20 100644 --- a/trunk/conf/full.conf +++ b/trunk/conf/full.conf @@ -434,6 +434,10 @@ rtc_server { # * Retrieve server IP automatically, from all network interfaces. # $CANDIDATE Read the IP from ENV variable, use * if not set. # x.x.x.x A specified IP address or DNS name, use * if 0.0.0.0. + # You can also set the candidate by the query string eip, note that you can also set the UDP port, + # for example: + # http://locahost:1985/rtc/v1/whip/?app=live&stream=livestream&eip=192.168.3.11 + # http://locahost:1985/rtc/v1/whip/?app=live&stream=livestream&eip=192.168.3.11:18000 # @remark For Firefox, the candidate MUST be IP, MUST NOT be DNS name, see https://bugzilla.mozilla.org/show_bug.cgi?id=1239006 # @see https://ossrs.net/lts/zh-cn/docs/v4/doc/webrtc#config-candidate # Overwrite by env SRS_RTC_SERVER_CANDIDATE diff --git a/trunk/configure b/trunk/configure index 471a7eac1c..24fe192c96 100755 --- a/trunk/configure +++ b/trunk/configure @@ -648,9 +648,8 @@ install: @mkdir -p \$(__REAL_INSTALL) @echo "Now make the http root dir" @mkdir -p \$(__REAL_INSTALL)/objs/nginx/html - @cp -f research/api-server/static-dir/index.html \$(__REAL_INSTALL)/objs/nginx/html - @cp -f research/players/crossdomain.xml \$(__REAL_INSTALL)/objs/nginx/html - @cp -f research/api-server/static-dir/favicon.ico \$(__REAL_INSTALL)/objs/nginx/html + @cp -f research/index.html \$(__REAL_INSTALL)/objs/nginx/html + @cp -f research/favicon.ico \$(__REAL_INSTALL)/objs/nginx/html @cp -Rf research/players \$(__REAL_INSTALL)/objs/nginx/html/ @cp -Rf research/console \$(__REAL_INSTALL)/objs/nginx/html/ @cp -Rf 3rdparty/signaling/www/demos \$(__REAL_INSTALL)/objs/nginx/html/ @@ -846,6 +845,12 @@ if [[ $SRS_VALGRIND == YES ]]; then else echo -e "${GREEN}Note: The valgrind is disabled.${BLACK}" fi +if [[ $SRS_SANITIZER == YES ]]; then + echo -e "${GREEN}The sanitizer is enabled.${BLACK}" +else + echo -e "${GREEN}Note: The sanitizer is disabled.${BLACK}" +fi + # add each modules for application for SRS_MODULE in ${SRS_MODULES[*]}; do echo -e "${GREEN}Enable module: $SRS_MODULE${BLACK}" diff --git a/trunk/doc/CHANGELOG.md b/trunk/doc/CHANGELOG.md index 21165b223f..34e358167b 100644 --- a/trunk/doc/CHANGELOG.md +++ b/trunk/doc/CHANGELOG.md @@ -7,6 +7,17 @@ The changelog for SRS. ## SRS 6.0 Changelog +* v6.0, 2024-02-06, Merge [#3920](https://github.com/ossrs/srs/pull/3920): WHIP: Fix bug for converting WHIP to RTMP/HLS. v6.0.113 (#3920) +* v6.0, 2024-02-05, Merge [#3924](https://github.com/ossrs/srs/pull/3924): Upgrade hls.js and set in low latency mode. v6.0.112 (#3924) +* v6.0, 2024-02-05, Merge [#3925](https://github.com/ossrs/srs/pull/3925): RTC: Fix video and audio track pt_ is not change in player before publisher. v6.0.111 (#3925) +* v6.0, 2024-02-05, Merge [#3923](https://github.com/ossrs/srs/pull/3923): Configure: print enabled/disable sanitizer. v6.0.110 (#3923) +* v6.0, 2023-12-30, Merge [#3916](https://github.com/ossrs/srs/pull/3916): Enhancing the compatibility of options.sh. v6.0.108 (#3916) +* v6.0, 2023-12-30, Merge [#3914](https://github.com/ossrs/srs/pull/3914): Forward: when unpublish crash caused by uninitialized forward connection. v6.0.107 (#3914) +* v6.0, 2023-12-15, Merge [#3854](https://github.com/ossrs/srs/pull/3854): Typo: line 263 - srs_app_srt_conn.cpp. v6.0.106 (#3854) +* v6.0, 2023-12-14, Merge [#3910](https://github.com/ossrs/srs/pull/3910): RTC: Support OPUS stereo SDP option. v6.0.105 (#3910) +* v6.0, 2023-12-14, Merge [#3902](https://github.com/ossrs/srs/pull/3902): Security: Support IP whitelist for HTTP-FLV, HLS, WebRTC, and SRT. v6.0.104 (#3902) +* v6.0, 2023-11-22, Merge [#3891](https://github.com/ossrs/srs/pull/3891): fix 'sed' error in options.sh. v6.0.103 (#3891) +* v6.0, 2023-11-22, Merge [#3883](https://github.com/ossrs/srs/pull/3883): Fix opus delay options, use ffmpeg-opus in docker test. v6.0.102 (#3883) * v6.0, 2023-11-19, Merge [#3886](https://github.com/ossrs/srs/pull/3886): Change the hls_aof_ratio to 2.1. v6.0.101 (#3886) * v6.0, 2023-11-16, Merge [#3868](https://github.com/ossrs/srs/pull/3868): Fix the test fail when enable ffmpeg-opus. v6.0.100 (#3868) * v6.0, 2023-11-15, Merge [#3879](https://github.com/ossrs/srs/pull/3879): Add --extra-ldflags. v6.0.99 (#3879) @@ -113,6 +124,13 @@ The changelog for SRS. ## SRS 5.0 Changelog +* v5.0, 2024-02-06, Merge [#3920](https://github.com/ossrs/srs/pull/3920): WHIP: Fix bug for converting WHIP to RTMP/HLS. v5.0.208 (#3920) +* v5.0, 2024-02-05, Merge [#3925](https://github.com/ossrs/srs/pull/3925): RTC: Fix video and audio track pt_ is not change in player before publisher. v5.0.207 (#3925) +* v5.0, 2024-02-05, Merge [#3923](https://github.com/ossrs/srs/pull/3923): Configure: print enabled/disable sanitizer. v5.0.206 (#3923) +* v5.0, 2023-12-30, Merge [#3916](https://github.com/ossrs/srs/pull/3916): Enhancing the compatibility of options.sh. v5.0.204 (#3916) +* v5.0, 2023-12-14, Merge [#3910](https://github.com/ossrs/srs/pull/3910): RTC: Support OPUS stereo SDP option. v5.0.203 (#3910) +* v5.0, 2023-12-14, Merge [#3902](https://github.com/ossrs/srs/pull/3902): Security: Support IP whitelist for HTTP-FLV, HLS, WebRTC, and SRT. v5.0.202 (#3902) +* v5.0, 2023-11-22, Merge [#3891](https://github.com/ossrs/srs/pull/3891): fix 'sed' error in options.sh. v5.0.201 (#3891) * v5.0, 2023-11-19, Merge [#3886](https://github.com/ossrs/srs/pull/3886): Change the hls_aof_ratio to 2.1. v5.0.200 (#3886) * v5.0, 2023-11-15, Merge [#3879](https://github.com/ossrs/srs/pull/3879): Add --extra-ldflags. v5.0.199 (#3879) * v5.0, 2023-11-06, Merge [#3851](https://github.com/ossrs/srs/pull/3851): donot compile libopus when enable sys-ffmpeg. v5.0.198 (#3851) diff --git a/trunk/research/api-server/static-dir/favicon.ico b/trunk/research/api-server/static-dir/favicon.ico deleted file mode 100644 index 8c68afab84..0000000000 Binary files a/trunk/research/api-server/static-dir/favicon.ico and /dev/null differ diff --git a/trunk/research/api-server/static-dir/favicon.ico b/trunk/research/api-server/static-dir/favicon.ico new file mode 120000 index 0000000000..251568d4d1 --- /dev/null +++ b/trunk/research/api-server/static-dir/favicon.ico @@ -0,0 +1 @@ +../../favicon.ico \ No newline at end of file diff --git a/trunk/research/api-server/static-dir/index.html b/trunk/research/api-server/static-dir/index.html deleted file mode 100755 index 8d92fc12cc..0000000000 --- a/trunk/research/api-server/static-dir/index.html +++ /dev/null @@ -1,72 +0,0 @@ - - - - SRS - - - - -
-

SRS works!

-

- Click here to enter SRS console.
- 点击进入SRS控制台 -

-

- Publish stream by FFmpeg or OBS:
- 请使用工具FFmpeg或者OBS推流到下面地址: -


-        

-

- Click here to start SRS player.
- 点击进入SRS播放器 -

-

SRS Team © 2022

-
- - diff --git a/trunk/research/api-server/static-dir/index.html b/trunk/research/api-server/static-dir/index.html new file mode 120000 index 0000000000..c90ed45dd3 --- /dev/null +++ b/trunk/research/api-server/static-dir/index.html @@ -0,0 +1 @@ +../../index.html \ No newline at end of file diff --git a/trunk/research/favicon.ico b/trunk/research/favicon.ico new file mode 100644 index 0000000000..8c68afab84 Binary files /dev/null and b/trunk/research/favicon.ico differ diff --git a/trunk/research/index.html b/trunk/research/index.html new file mode 100755 index 0000000000..c76a99e526 --- /dev/null +++ b/trunk/research/index.html @@ -0,0 +1,103 @@ + + + + SRS + + + + +
+

Status

+

Congratulations! SRS works!

+
+

English

+

+ 1. Please publish stream by: +

    +
  • + Recommend OBS, set Service to Custom, + set Server to + and Stream Key to +
  • +
  • + You can also use FFmpeg: + +
  • +
  • + Or use WHIP to publish stream, please click SRS Player link below. +
  • +
+

+

2. Choose SRS player to play the stream in different protocols.

+

3. (Optional) Click here to enter SRS console.

+
+

简体中文

+

+ 1. 请选择推流方式: +

    +
  • + 推荐OBS,设置服务为 自定义, + 设置推流地址(服务器)为 , + 设置推流密钥(串流密钥)为 +
  • +
  • + 或者用FFmpeg推流到地址: + +
  • +
  • + 或者使用WHIP推流,请点击下面的 SRS播放器 链接。 +
  • +
+

+

2. 点击选择 SRS播放器

+

3. 点击进入 SRS控制台 (可选)

+
+

SRS Team © 2013~2024

+
+ + diff --git a/trunk/research/players/js/hls-0.14.17.min.js b/trunk/research/players/js/hls-0.14.17.min.js deleted file mode 100644 index 9d47ba41d7..0000000000 --- a/trunk/research/players/js/hls-0.14.17.min.js +++ /dev/null @@ -1,2 +0,0 @@ -"undefined"!=typeof window&&function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Hls=t():e.Hls=t()}(this,(function(){return function(e){var t={};function r(i){if(t[i])return t[i].exports;var a=t[i]={i:i,l:!1,exports:{}};return e[i].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=e,r.c=t,r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},r.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},r.t=function(e,t){if(1&t&&(e=r(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)r.d(i,a,function(t){return e[t]}.bind(null,a));return i},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/dist/",r(r.s=13)}([function(e,t,r){"use strict";r.d(t,"a",(function(){return u})),r.d(t,"b",(function(){return c}));var i=r(5);function a(){}var n={trace:a,debug:a,log:a,warn:a,info:a,error:a},s=n;function o(e,t){return t="["+e+"] > "+t}var l=Object(i.a)();function d(e){var t=l.console[e];return t?function(){for(var r=arguments.length,i=new Array(r),a=0;a1?t-1:0),i=1;i0)return t.subarray(i,i+a)},e._readSize=function(e,t){var r=0;return r=(127&e[t])<<21,r|=(127&e[t+1])<<14,r|=(127&e[t+2])<<7,r|=127&e[t+3]},e.getTimeStamp=function(t){for(var r=e.getID3Frames(t),i=0;i>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(n);break;case 12:case 13:o=e[c++],u+=String.fromCharCode((31&n)<<6|63&o);break;case 14:o=e[c++],l=e[c++],u+=String.fromCharCode((15&n)<<12|(63&o)<<6|(63&l)<<0)}}return u},e}();function s(){var e=Object(a.a)();return i||void 0===e.TextDecoder||(i=new e.TextDecoder("utf-8")),i}var o=n._utf8ArrayToStr;t.a=n},function(e,t,r){"use strict";function i(){return"undefined"==typeof window?self:window}r.d(t,"a",(function(){return i}))},function(e,t,r){var i,a,n,s,o;i=/^((?:[a-zA-Z0-9+\-.]+:)?)(\/\/[^\/?#]*)?((?:[^\/?#]*\/)*[^;?#]*)?(;[^?#]*)?(\?[^#]*)?(#.*)?$/,a=/^([^\/?#]*)(.*)$/,n=/(?:\/|^)\.(?=\/)/g,s=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,r){if(r=r||{},e=e.trim(),!(t=t.trim())){if(!r.alwaysNormalize)return e;var i=o.parseURL(e);if(!i)throw new Error("Error trying to parse base URL.");return i.path=o.normalizePath(i.path),o.buildURLFromParts(i)}var n=o.parseURL(t);if(!n)throw new Error("Error trying to parse relative URL.");if(n.scheme)return r.alwaysNormalize?(n.path=o.normalizePath(n.path),o.buildURLFromParts(n)):t;var s=o.parseURL(e);if(!s)throw new Error("Error trying to parse base URL.");if(!s.netLoc&&s.path&&"/"!==s.path[0]){var l=a.exec(s.path);s.netLoc=l[1],s.path=l[2]}s.netLoc&&!s.path&&(s.path="/");var d={scheme:s.scheme,netLoc:n.netLoc,path:null,params:n.params,query:n.query,fragment:n.fragment};if(!n.netLoc&&(d.netLoc=s.netLoc,"/"!==n.path[0]))if(n.path){var u=s.path,c=u.substring(0,u.lastIndexOf("/")+1)+n.path;d.path=o.normalizePath(c)}else d.path=s.path,n.params||(d.params=s.params,n.query||(d.query=s.query));return null===d.path&&(d.path=r.alwaysNormalize?o.normalizePath(n.path):n.path),o.buildURLFromParts(d)},parseURL:function(e){var t=i.exec(e);return t?{scheme:t[1]||"",netLoc:t[2]||"",path:t[3]||"",params:t[4]||"",query:t[5]||"",fragment:t[6]||""}:null},normalizePath:function(e){for(e=e.split("").reverse().join("").replace(n,"");e.length!==(e=e.replace(s,"")).length;);return e.split("").reverse().join("")},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}},e.exports=o},function(e,t,r){"use strict";var i=function(){function e(e,t){this.subtle=e,this.aesIV=t}return e.prototype.decrypt=function(e,t){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e)},e}(),a=function(){function e(e,t){this.subtle=e,this.key=t}return e.prototype.expandKey=function(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])},e}();var n=function(){function e(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.initTable()}var t=e.prototype;return t.uint8ArrayToUint32Array_=function(e){for(var t=new DataView(e),r=new Uint32Array(4),i=0;i<4;i++)r[i]=t.getUint32(4*i);return r},t.initTable=function(){var e=this.sBox,t=this.invSBox,r=this.subMix,i=r[0],a=r[1],n=r[2],s=r[3],o=this.invSubMix,l=o[0],d=o[1],u=o[2],c=o[3],h=new Uint32Array(256),f=0,g=0,p=0;for(p=0;p<256;p++)h[p]=p<128?p<<1:p<<1^283;for(p=0;p<256;p++){var v=g^g<<1^g<<2^g<<3^g<<4;v=v>>>8^255&v^99,e[f]=v,t[v]=f;var m=h[f],y=h[m],b=h[y],T=257*h[v]^16843008*v;i[f]=T<<24|T>>>8,a[f]=T<<16|T>>>16,n[f]=T<<8|T>>>24,s[f]=T,T=16843009*b^65537*y^257*m^16843008*f,l[v]=T<<24|T>>>8,d[v]=T<<16|T>>>16,u[v]=T<<8|T>>>24,c[v]=T,f?(f=m^h[h[h[b^m]]],g^=h[h[g]]):f=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i>>5}function h(e,t){return!!(t+1=e.length)return!1;var i=c(e,t);if(i<=r)return!1;var a=t+i;if(a===e.length||a+1>>6),!((l=(60&t[r+2])>>>2)>g.length-1))return u=(1&t[r+2])<<2,u|=(192&t[r+3])>>>6,o.b.log("manifest codec:"+n+",ADTS data:type:"+s+",sampleingIndex:"+l+"["+g[l]+"Hz],channelConfig:"+u),/firefox/i.test(h)?l>=6?(s=5,c=new Array(4),d=l-3):(s=2,c=new Array(2),d=l):-1!==h.indexOf("android")?(s=2,c=new Array(2),d=l):(s=5,c=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&l>=6?d=l-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(l>=6&&1===u||/vivaldi/i.test(h))||!n&&1===u)&&(s=2,c=new Array(2)),d=l)),c[0]=s<<3,c[0]|=(14&l)>>1,c[1]|=(1&l)<<7,c[1]|=u<<3,5===s&&(c[1]|=(14&d)>>1,c[2]=(1&d)<<7,c[2]|=8,c[3]=0),{config:c,samplerate:g[l],channelCount:u,codec:"mp4a.40."+s,manifestCodec:f};e.trigger(i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+l})}(t,r,n,s);e.config=l.config,e.samplerate=l.samplerate,e.channelCount=l.channelCount,e.codec=l.codec,e.manifestCodec=l.manifestCodec,o.b.log("parsed codec:"+e.codec+",rate:"+l.samplerate+",nb channel:"+l.channelCount)}}function p(e){return 9216e4/e}function v(e,t,r,i,a){var n=function(e,t,r,i,a){var n,s,o=e.length;if(n=u(e,t),s=c(e,t),(s-=n)>0&&t+n+s<=o)return{headerLength:n,frameLength:s,stamp:r+i*a}}(t,r,i,a,p(e.samplerate));if(n){var s=n.stamp,o=n.headerLength,l=n.frameLength,d={unit:t.subarray(r+o,r+o+l),pts:s,dts:s};return e.samples.push(d),{sample:d,length:l+o}}}var m=r(4),y=function(){function e(e,t,r){this.observer=e,this.config=r,this.remuxer=t}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._audioTrack={container:"audio/adts",type:"audio",id:0,sequenceNumber:0,isAAC:!0,samples:[],len:0,manifestCodec:t,duration:i,inputTimeScale:9e4}},t.resetTimeStamp=function(){},e.probe=function(e){if(!e)return!1;for(var t=(m.a.getID3Data(e,0)||[]).length,r=e.length;tt.length)){var n=this.parseHeader(t,r);if(n&&r+n.frameLength<=t.length){var s=i+a*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:t.subarray(r,r+n.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=n.channelCount,e.samplerate=n.sampleRate,e.samples.push(o),{sample:o,length:n.frameLength}}}},parseHeader:function(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,a=e[t+2]>>4&15,n=e[t+2]>>2&3,s=e[t+2]>>1&1;if(1!==r&&0!==a&&15!==a&&3!==n){var o=3===r?3-i:3===i?3:4,l=1e3*T.BitratesMap[14*o+a-1],d=3===r?0:2===r?1:2,u=T.SamplingRateMap[3*d+n],c=e[t+3]>>6==3?1:2,h=T.SamplesCoefficients[r][i],f=T.BytesInSlot[i],g=8*h*f;return{sampleRate:u,channelCount:c,frameLength:parseInt(h*l/u+s,10)*f,samplesPerFrame:g}}},isHeaderPattern:function(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])},isHeader:function(e,t){return!!(t+1e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,e-=(t=e>>3)>>3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)},t.readBits=function(e){var t=Math.min(this.bitsAvailable,e),r=this.word>>>32-t;return e>32&&o.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0?this.word<<=t:this.bytesAvailable>0&&this.loadWord(),(t=e-t)>0&&this.bitsAvailable?r<>>e))return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()},t.skipUEG=function(){this.skipBits(1+this.skipLZ())},t.skipEG=function(){this.skipBits(1+this.skipLZ())},t.readUEG=function(){var e=this.skipLZ();return this.readBits(e+1)-1},t.readEG=function(){var e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)},t.readBoolean=function(){return 1===this.readBits(1)},t.readUByte=function(){return this.readBits(8)},t.readUShort=function(){return this.readBits(16)},t.readUInt=function(){return this.readBits(32)},t.skipScalingList=function(e){var t,r=8,i=8;for(t=0;t=e.length)return void r();if(!(e[t].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(e,t,r,i),!i)return}}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,a=32;a<=e.length-16;a+=160,i+=16)r.set(e.subarray(a,a+16),i);return r},t.getAvcDecryptedUnit=function(e,t){t=new Uint8Array(t);for(var r=0,i=32;i<=e.length-16;i+=160,r+=16)e.set(t.subarray(r,r+16),i);return e},t.decryptAvcSample=function(e,t,r,i,a,n){var s=this.discardEPB(a.data),o=this.getAvcEncryptedData(s),l=this;this.decryptBuffer(o.buffer,(function(o){a.data=l.getAvcDecryptedUnit(s,o),n||l.decryptAvcSamples(e,t,r+1,i)}))},t.decryptAvcSamples=function(e,t,r,i){for(;;t++,r=0){if(t>=e.length)return void i();for(var a=e[t].units;!(r>=a.length);r++){var n=a[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(e,t,r,i,n,s),!s)return}}}},e}(),R={video:1,audio:2,id3:3,text:4},A=function(){function e(e,t,r,i){this.observer=e,this.config=r,this.typeSupported=i,this.remuxer=t,this.sampleAes=null,this.pmtUnknownTypes={}}var t=e.prototype;return t.setDecryptData=function(e){null!=e&&null!=e.key&&"SAMPLE-AES"===e.method?this.sampleAes=new _(this.observer,this.config,e,this.discardEPB):this.sampleAes=null},e.probe=function(t){var r=e._syncOffset(t);return!(r<0)&&(r&&o.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},e._syncOffset=function(e){for(var t=Math.min(1e3,e.length-564),r=0;r>4>1){if((c=l+5+t[l+4])===l+188)continue}else c=l+4;switch(u){case b:d&&(_&&(h=L(_))&&D(h,!1),_={data:[],size:0}),_&&(_.data.push(t.subarray(c,l+188)),_.size+=l+188-c);break;case T:d&&(R&&(h=L(R))&&(m.isAAC?O(h):C(h)),R={data:[],size:0}),R&&(R.data.push(t.subarray(c,l+188)),R.size+=l+188-c);break;case E:d&&(A&&(h=L(A))&&I(h),A={data:[],size:0}),A&&(A.data.push(t.subarray(c,l+188)),A.size+=l+188-c);break;case 0:d&&(c+=t[c]+1),S=this._pmtId=k(t,c);break;case S:d&&(c+=t[c]+1);var x=w(t,c,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,null!=this.sampleAes);(b=x.avc)>0&&(v.pid=b),(T=x.audio)>0&&(m.pid=T,m.isAAC=x.isAAC),(E=x.id3)>0&&(y.pid=E),g&&!p&&(o.b.log("reparse from beginning"),g=!1,l=P-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:g=!0}}else this.observer.trigger(i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});_&&(h=L(_))?(D(h,!0),v.pesData=null):v.pesData=_,R&&(h=L(R))?(m.isAAC?O(h):C(h),m.pesData=null):(R&&R.size&&o.b.log("last AAC PES packet truncated,might overlap between fragments"),m.pesData=R),A&&(h=L(A))?(I(h),y.pesData=null):y.pesData=A,null==this.sampleAes?this.remuxer.remux(m,v,y,this._txtTrack,r,n,s):this.decryptAndRemux(m,v,y,this._txtTrack,r,n,s)},t.decryptAndRemux=function(e,t,r,i,a,n,s){if(e.samples&&e.isAAC){var o=this;this.sampleAes.decryptAacSamples(e.samples,0,(function(){o.decryptAndRemuxAvc(e,t,r,i,a,n,s)}))}else this.decryptAndRemuxAvc(e,t,r,i,a,n,s)},t.decryptAndRemuxAvc=function(e,t,r,i,a,n,s){if(t.samples){var o=this;this.sampleAes.decryptAvcSamples(t.samples,0,0,(function(){o.remuxer.remux(e,t,r,i,a,n,s)}))}else this.remuxer.remux(e,t,r,i,a,n,s)},t.destroy=function(){this._initPTS=this._initDTS=void 0,this._duration=0},t._parsePAT=function(e,t){return(31&e[t+10])<<8|e[t+11]},t._trackUnknownPmt=function(e,t,r){var i=this.pmtUnknownTypes[e]||0;return 0===i&&(this.pmtUnknownTypes[e]=0,t.call(o.b,r)),this.pmtUnknownTypes[e]++,i},t._parsePMT=function(e,t,r,i){var a,n,s={audio:-1,avc:-1,id3:-1,isAAC:!0};for(a=t+3+((15&e[t+1])<<8|e[t+2])-4,t+=12+((15&e[t+10])<<8|e[t+11]);t1;){var h=new Uint8Array(c[0].length+c[1].length);h.set(c[0]),h.set(c[1],c[0].length),c[0]=h,c.splice(1,1)}if(1===((t=c[0])[0]<<16)+(t[1]<<8)+t[2]){if((i=(t[4]<<8)+t[5])&&i>e.size-6)return null;if(192&(r=t[7])&&(s=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,64&r?s-(l=536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2)>54e5&&(o.b.warn(Math.round((s-l)/9e4)+"s delta between PTS and DTS, align them"),s=l):l=s),d=(a=t[8])+9,e.size<=d)return null;e.size-=d,n=new Uint8Array(e.size);for(var f=0,g=c.length;fp){d-=p;continue}t=t.subarray(d),p-=d,d=0}n.set(t,u),u+=p}return i&&(i-=a+3),{data:n,pts:s,dts:l,len:i}}return null},t.pushAccesUnit=function(e,t){if(e.units.length&&e.frame){var r=t.samples,i=r.length;if(isNaN(e.pts)){if(!i)return void t.dropped++;var a=r[i-1];e.pts=a.pts,e.dts=a.dts}!this.config.forceKeyFrameOnDiscontinuity||!0===e.key||t.sps&&(i||this.contiguous)?(e.id=i,r.push(e)):t.dropped++}e.debug.length&&o.b.log(e.pts+"/"+e.dts+":"+e.debug)},t._parseAVCPES=function(e,t){var r,i,a,n=this,s=this._avcTrack,o=this._parseAVCNALu(e.data),l=this.avcSample,d=!1,u=this.pushAccesUnit.bind(this),c=function(e,t,r,i){return{key:e,pts:t,dts:r,units:[],debug:i}};e.data=null,l&&o.length&&!s.audFound&&(u(l,s),l=this.avcSample=c(!1,e.pts,e.dts,"")),o.forEach((function(t){switch(t.type){case 1:i=!0,l||(l=n.avcSample=c(!0,e.pts,e.dts,"")),l.frame=!0;var o=t.data;if(d&&o.length>4){var h=new S(o).readSliceType();2!==h&&4!==h&&7!==h&&9!==h||(l.key=!0)}break;case 5:i=!0,l||(l=n.avcSample=c(!0,e.pts,e.dts,"")),l.key=!0,l.frame=!0;break;case 6:i=!0,(r=new S(n.discardEPB(t.data))).readUByte();for(var f=0,g=0,p=!1,v=0;!p&&r.bytesAvailable>1;){f=0;do{f+=v=r.readUByte()}while(255===v);g=0;do{g+=v=r.readUByte()}while(255===v);if(4===f&&0!==r.bytesAvailable){if(p=!0,181===r.readUByte())if(49===r.readUShort())if(1195456820===r.readUInt())if(3===r.readUByte()){var y=r.readUByte(),b=31&y,T=[y,r.readUByte()];for(a=0;a16){var E=[];for(a=0;a<16;a++)E.push(r.readUByte().toString(16)),3!==a&&5!==a&&7!==a&&9!==a||E.push("-");var _=g-16,R=new Uint8Array(_);for(a=0;a<_;a++)R[a]=r.readUByte();n._insertSampleInOrder(n._txtTrack.samples,{pts:e.pts,payloadType:f,uuid:E.join(""),userDataBytes:R,userData:Object(m.b)(R.buffer)})}}else if(g0){if(t.pts>=e[r-1].pts)e.push(t);else for(var i=r-1;i>=0;i--)if(t.pts=0)i={data:e.subarray(c,n-l-1),type:a},u.push(i);else{var h=this._getLastNalUnit();if(h&&(d&&n<=4-d&&h.state&&(h.data=h.data.subarray(0,h.data.byteLength-d)),(r=n-l-1)>0)){var f=new Uint8Array(h.data.byteLength+r);f.set(h.data,0),f.set(e.subarray(0,r),h.data.byteLength),h.data=f}}n=0&&l>=0&&(i={data:e.subarray(c,s),type:a,state:l},u.push(i)),0===u.length){var g=this._getLastNalUnit();if(g){var p=new Uint8Array(g.data.byteLength+e.byteLength);p.set(g.data,0),p.set(e,g.data.byteLength),g.data=p}}return o.naluState=l,u},t.discardEPB=function(e){for(var t,r,i=e.byteLength,a=[],n=1;n1&&(o.b.log("AAC: align PTS for overlapping frames by "+Math.round((E-m)/90)),m=E)}for(;n>24&255,t[1]=i>>16&255,t[2]=i>>8&255,t[3]=255&i,t.set(e,4),a=0,i=8;a>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t.timescale,t.duration),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,255&t]))},e.minf=function(t){return"audio"===t.type?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(e.types.moof,e.mfhd(t),e.traf(i,r))},e.moov=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trak(t[r]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale,t[0].duration)].concat(i).concat(e.mvex(t)))},e.mvex=function(t){for(var r=t.length,i=[];r--;)i[r]=e.trex(t[r]);return e.box.apply(null,[e.types.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(L+1)),a=Math.floor(r%(L+1)),n=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,n)},e.sdtp=function(t){var r,i,a=t.samples||[],n=new Uint8Array(4+a.length);for(i=0;i>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(s))),l=t.width,d=t.height,u=t.pixelRatio[0],c=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,d>>8&255,255&d,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,255&u,c>>24,c>>16&255,c>>8&255,255&c])))},e.esds=function(e){var t=e.config.length;return new Uint8Array([0,0,0,0,3,23+t,0,1,0,4,15+t,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([t]).concat(e.config).concat([6,1,2]))},e.mp4a=function(t){var r=t.samplerate;return e.box(e.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),e.box(e.types.esds,e.esds(t)))},e.mp3=function(t){var r=t.samplerate;return e.box(e.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},e.stsd=function(t){return"audio"===t.type?t.isAAC||"mp3"!==t.codec?e.box(e.types.stsd,e.STSD,e.mp4a(t)):e.box(e.types.stsd,e.STSD,e.mp3(t)):e.box(e.types.stsd,e.STSD,e.avc1(t))},e.tkhd=function(t){var r=t.id,i=t.duration*t.timescale,a=t.width,n=t.height,s=Math.floor(i/(L+1)),o=Math.floor(i%(L+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,255&a,0,0,n>>8&255,255&n,0,0]))},e.traf=function(t,r){var i=e.sdtp(t),a=t.id,n=Math.floor(r/(L+1)),s=Math.floor(r%(L+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,n>>24,n>>16&255,n>>8&255,255&n,s>>24,s>>16&255,s>>8&255,255&s])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},e.trun=function(t,r){var i,a,n,s,o,l,d=t.samples||[],u=d.length,c=12+16*u,h=new Uint8Array(c);for(r+=8+c,h.set([0,0,15,1,u>>>24&255,u>>>16&255,u>>>8&255,255&u,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return e.box(e.types.trun,h)},e.initSegment=function(t){e.types||e.init();var r,i=e.moov(t);return(r=new Uint8Array(e.FTYP.byteLength+i.byteLength)).set(e.FTYP),r.set(i,e.FTYP.byteLength),r},e}();function O(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var a=e*t*r;return i?Math.round(a):a}function C(e,t){return void 0===t&&(t=!1),O(e,1e3,1/9e4,t)}function I(e,t){return void 0===t&&(t=1),O(e,9e4,1/t)}var P=I(10),x=I(.2),M=null;function F(e,t){var r;if(void 0===t)return e;for(r=t4294967296;)e+=r;return e}var U,N=function(){function e(e,t,r,i){if(this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,null===M){var a=navigator.userAgent.match(/Chrome\/(\d+)/i);M=a?parseInt(a[1]):0}}var t=e.prototype;return t.destroy=function(){},t.resetTimeStamp=function(e){this._initPTS=this._initDTS=e},t.resetInitSegment=function(){this.ISGenerated=!1},t.getVideoStartPts=function(e){var t=!1,r=e.reduce((function(e,r){var i=r.pts-e;return i<-4294967296?(t=!0,F(e,r.pts)):i>0?e:r.pts}),e[0].pts);return t&&o.b.debug("PTS rollover detected"),r},t.remux=function(e,t,r,a,n,s,l){if(this.ISGenerated||this.generateIS(e,t,n),this.ISGenerated){var d=e.samples.length,u=t.samples.length,c=n,h=n;if(d&&u){var f=this.getVideoStartPts(t.samples),g=(F(e.samples[0].pts,f)-f)/t.inputTimeScale;c+=Math.max(0,g),h+=Math.max(0,-g)}if(d){e.timescale||(o.b.warn("regenerate InitSegment as audio detected"),this.generateIS(e,t,n));var p,v=this.remuxAudio(e,c,s,l);if(u)v&&(p=v.endPTS-v.startPTS),t.timescale||(o.b.warn("regenerate InitSegment as video detected"),this.generateIS(e,t,n)),this.remuxVideo(t,h,s,p)}else if(u){var m=this.remuxVideo(t,h,s,0,l);m&&e.codec&&this.remuxEmptyAudio(e,c,s,m)}}r.samples.length&&this.remuxID3(r,n),a.samples.length&&this.remuxText(a,n),this.observer.trigger(i.a.FRAG_PARSED)},t.generateIS=function(e,t,r){var n,s,l=this.observer,d=e.samples,u=t.samples,c=this.typeSupported,h="audio/mp4",f={},g={tracks:f},p=void 0===this._initPTS;if(p&&(n=s=1/0),e.config&&d.length&&(e.timescale=e.samplerate,o.b.log("audio sampling rate : "+e.samplerate),e.isAAC||(c.mpeg?(h="audio/mpeg",e.codec=""):c.mp3&&(e.codec="mp3")),f.audio={container:h,codec:e.codec,initSegment:!e.isAAC&&c.mpeg?new Uint8Array:D.initSegment([e]),metadata:{channelCount:e.channelCount}},p&&(n=s=d[0].pts-Math.round(e.inputTimeScale*r))),t.sps&&t.pps&&u.length){var v=t.inputTimeScale;if(t.timescale=v,f.video={container:"video/mp4",codec:t.codec,initSegment:D.initSegment([t]),metadata:{width:t.width,height:t.height}},p){var m=this.getVideoStartPts(u),y=Math.round(v*r);s=Math.min(s,F(u[0].dts,m)-y),n=Math.min(n,m-y),this.observer.trigger(i.a.INIT_PTS_FOUND,{initPTS:n})}}else p&&f.audio&&this.observer.trigger(i.a.INIT_PTS_FOUND,{initPTS:n});Object.keys(f).length?(l.trigger(i.a.FRAG_PARSING_INIT_SEGMENT,g),this.ISGenerated=!0,p&&(this._initPTS=n,this._initDTS=s)):l.trigger(i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!1,reason:"no audio/video samples found"})},t.remuxVideo=function(e,t,r,n){var s,l,d,u,c,h=e.timescale,f=e.samples,g=[],p=f.length,v=this._initPTS,m=8,y=Number.POSITIVE_INFINITY,b=Number.NEGATIVE_INFINITY,T=0,E=!1,S=this.nextAvcDts;if(0!==p){if(!r)S=t*h-(f[0].pts-F(f[0].dts,f[0].pts));for(var _=0;_R.pts&&(T=Math.max(Math.min(T,R.pts-R.dts),-1*x)),R.dts0?_-1:_].dts&&(E=!0)}E&&f.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i||e.id-t.id})),u=f[0].dts,c=f[p-1].dts;var A=Math.round((c-u)/(p-1));if(T<0){if(T<-2*A){o.b.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+C(-A,!0)+" ms");for(var k=T,w=0;wA;if(I||O<-1){I?o.b.warn("AVC: "+C(O,!0)+" ms ("+O+"dts) hole between fragments detected, filling it"):o.b.warn("AVC: "+C(-O,!0)+" ms ("+O+"dts) overlapping between fragments detected"),u=S;var P=f[0].pts-O;f[0].dts=u,f[0].pts=P,o.b.log("Video: First PTS/DTS adjusted: "+C(P,!0)+"/"+C(u,!0)+", delta: "+C(O,!0)+" ms")}}M&&M<75&&(u=Math.max(0,u));for(var U=0,N=0,B=0;B0?q-1:q].dts;if(ie.stretchShortVideoTrack){var ne=ie.maxBufferHole,se=Math.floor(ne*h),oe=(n?y+n*h:this.nextAudioPts)-z.pts;oe>se?((s=oe-ae)<0&&(s=ae),o.b.log("It is approximately "+C(oe,!1)+" ms to the next segment; using duration "+C(s,!1)+" ms for the last video frame.")):s=ae}else s=ae}X=Math.round(z.pts-z.dts),g.push({size:$,duration:s,cts:X,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:z.key?2:1,isNonSync:z.key?0:1}})}this.nextAvcDts=c+s;var le=e.dropped;if(e.nbNalu=0,e.dropped=0,g.length&&navigator.userAgent.toLowerCase().indexOf("chrome")>-1){var de=g[0].flags;de.dependsOn=2,de.isNonSync=0}e.samples=g,d=D.moof(e.sequenceNumber++,u,e),e.samples=[];var ue={data1:d,data2:l,startPTS:y/h,endPTS:(b+s)/h,startDTS:u/h,endDTS:this.nextAvcDts/h,type:"video",hasAudio:!1,hasVideo:!0,nb:g.length,dropped:le};return this.observer.trigger(i.a.FRAG_PARSING_DATA,ue),ue}},t.remuxAudio=function(e,t,r,n){var s,l,d,u,c,h,f=e.inputTimeScale,g=e.timescale,p=f/g,v=(e.isAAC?1024:1152)*p,m=this._initPTS,y=!e.isAAC&&this.typeSupported.mpeg,b=y?0:8,T=e.samples,E=[],S=this.nextAudioPts;if(r|=T.length&&S&&(n&&Math.abs(t-S/f)<.1||Math.abs(T[0].pts-S-m)<20*v),T.forEach((function(e){e.pts=e.dts=F(e.pts-m,t*f)})),0!==(T=T.filter((function(e){return e.pts>=0}))).length){if(r||(S=n?Math.max(0,t*f):T[0].pts),e.isAAC)for(var _=this.config.maxAudioFramesDrift,R=0,A=S;R0?(o.b.warn("Dropping 1 audio frame @ "+C(A,!0)/1e3+"s due to "+C(O,!0)+" ms overlap."),T.splice(R,1)):(o.b.warn("Audio frame @ "+C(L,!0)/1e3+"s overlaps nextAudioPts by "+C(O,!0)+" ms."),A=L+v,R++);else if(O>=_*v&&O0&&V0&&((l=w.getSilentFrame(e.manifestCodec||e.codec,e.channelCount))||(l=j.subarray()),N+=Y*l.length);else if(V<-12){o.b.log("drop overlapping AAC sample, expected/parsed/delta: "+C(S,!0)+" ms / "+C(H,!0)+" ms / "+C(-V,!0)+" ms"),N-=j.byteLength;continue}H=S}if(c=H,!(N>0))return;N+=b;try{d=new Uint8Array(N)}catch(e){return void this.observer.trigger(i.a.ERROR,{type:a.b.MUX_ERROR,details:a.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:N,reason:"fail allocating audio mdat "+N})}y||(new DataView(d.buffer).setUint32(0,N),d.set(D.types.mdat,4));for(var W=0;W=2&&(X=E[U-2].duration,s.duration=X),U){this.nextAudioPts=S=h+p*X,e.samples=E,u=y?new Uint8Array:D.moof(e.sequenceNumber++,c/p,e),e.samples=[];var z=c/f,Q=S/f,$={data1:u,data2:d,startPTS:z,endPTS:Q,startDTS:z,endDTS:Q,type:"audio",hasAudio:!0,hasVideo:!1,nb:U};return this.observer.trigger(i.a.FRAG_PARSING_DATA,$),$}return null}},t.remuxEmptyAudio=function(e,t,r,i){var a=e.inputTimeScale,n=a/(e.samplerate?e.samplerate:a),s=this.nextAudioPts,l=(void 0!==s?s:i.startDTS*a)+this._initDTS,d=i.endDTS*a+this._initDTS,u=1024*n,c=Math.ceil((d-l)/u),h=w.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(o.b.warn("remux empty Audio"),h){for(var f=[],g=0;g0&&null!=t&&null!=t.key&&"AES-128"===t.method){var p=this.decrypter;null==p&&(p=this.decrypter=new n.a(this.observer,this.config));var v=U();p.decrypt(e,t.key.buffer,t.iv.buffer,(function(e){var n=U();g.observer.trigger(i.a.FRAG_DECRYPTED,{stats:{tstart:v,tdecrypt:n}}),g.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),a,s,o,l,d,u,c,h,f)}))}else this.pushDecrypted(new Uint8Array(e),t,new Uint8Array(r),a,s,o,l,d,u,c,h,f)},t.pushDecrypted=function(e,t,r,n,s,o,l,d,u,c,h,f){var g=this.demuxer,p=this.remuxer;if(!g||l||d){for(var v,m=this.observer,T=this.typeSupported,E=this.config,S=[{demux:A,remux:N},{demux:b.a,remux:B},{demux:y,remux:N},{demux:k,remux:N}],_=0,R=S.length;_0},e.bin2str=function(e){return String.fromCharCode.apply(null,e)},e.readUint16=function(e,t){e.data&&(t+=e.start,e=e.data);var r=e[t]<<8|e[t+1];return r<0?65536+r:r},e.readUint32=function(e,t){e.data&&(t+=e.start,e=e.data);var r=e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3];return r<0?4294967296+r:r},e.writeUint32=function(e,t,r){e.data&&(t+=e.start,e=e.data),e[t]=r>>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r},e.findBox=function(t,r){var i,a,n,s,o,l,d=[];if(t.data?(o=t.start,n=t.end,t=t.data):(o=0,n=t.byteLength),!r.length)return null;for(i=o;i1?i+a:n,e.bin2str(t.subarray(i+4,i+8))===r[0]&&(1===r.length?d.push({data:t,start:i+8,end:l}):(s=e.findBox({data:t,start:i+8,end:l},r.slice(1))).length&&(d=d.concat(s))),i=l;return d},e.parseSegmentIndex=function(t){var r,i=e.findBox(t,["moov"])[0],a=i?i.end:null,n=0,s=e.findBox(t,["sidx"]);if(!s||!s[0])return null;r=[];var o=(s=s[0]).data[0];n=0===o?8:16;var l=e.readUint32(s,n);n+=4;n+=0===o?8:16,n+=2;var d=s.end+0,u=e.readUint16(s,n);n+=2;for(var c=0;c>>31)return void console.warn("SIDX has hierarchical references (not supported)");var p=e.readUint32(s,h);h+=4,r.push({referenceSize:g,subsegmentDuration:p,info:{duration:p/l,start:d,end:d+g-1}}),d+=g,n=h+=4}return{earliestPresentationTime:0,timescale:l,version:o,referencesCount:u,references:r,moovEndOffset:a}},e.parseInitSegment=function(t){var r=[];return e.findBox(t,["moov","trak"]).forEach((function(t){var a=e.findBox(t,["tkhd"])[0];if(a){var n=a.data[a.start],s=0===n?12:20,o=e.readUint32(a,s),l=e.findBox(t,["mdia","mdhd"])[0];if(l){s=0===(n=l.data[l.start])?12:20;var d=e.readUint32(l,s),u=e.findBox(t,["mdia","hdlr"])[0];if(u){var c={soun:"audio",vide:"video"}[e.bin2str(u.data.subarray(u.start+8,u.start+12))];if(c){var h=e.findBox(t,["mdia","minf","stbl","stsd"]);if(h.length){h=h[0];var f=e.bin2str(h.data.subarray(h.start+12,h.start+16));i.b.log("MP4Demuxer:"+c+":"+f+" found")}r[o]={timescale:d,type:c},r[c]={timescale:d,id:o}}}}}})),r},e.getStartDTS=function(t,r){var i,a,n;return i=e.findBox(r,["moof","traf"]),a=[].concat.apply([],i.map((function(r){return e.findBox(r,["tfhd"]).map((function(i){var a,n;return a=e.readUint32(i,4),n=t[a].timescale||9e4,e.findBox(r,["tfdt"]).map((function(t){var r,i;return r=t.data[t.start],i=e.readUint32(t,4),1===r&&(i*=Math.pow(2,32),i+=e.readUint32(t,8)),i}))[0]/n}))}))),n=Math.min.apply(null,a),isFinite(n)?n:0},e.offsetStartDTS=function(t,r,i){e.findBox(r,["moof","traf"]).map((function(r){return e.findBox(r,["tfhd"]).map((function(a){var s=e.readUint32(a,4),o=t[s].timescale||9e4;e.findBox(r,["tfdt"]).map((function(t){var r=t.data[t.start],a=e.readUint32(t,4);if(0===r)e.writeUint32(t,4,a-i*o);else{a*=Math.pow(2,32),a+=e.readUint32(t,8),a-=i*o,a=Math.max(a,0);var s=Math.floor(a/(n+1)),l=Math.floor(a%(n+1));e.writeUint32(t,4,s),e.writeUint32(t,8,l)}}))}))}))},t.append=function(t,r,i,n){var s=this.initData;s||(this.resetInitSegment(t,this.audioCodec,this.videoCodec,!1),s=this.initData);var o,l=this.initPTS;if(void 0===l){var d=e.getStartDTS(s,t);this.initPTS=l=d-r,this.observer.trigger(a.a.INIT_PTS_FOUND,{initPTS:l})}e.offsetStartDTS(s,t,l),o=e.getStartDTS(s,t),this.remuxer.remux(s.audio,s.video,null,null,o,i,n,t)},t.destroy=function(){},e}();t.a=s},function(e,t,r){function i(e){var t={};function r(i){if(t[i])return t[i].exports;var a=t[i]={i:i,l:!1,exports:{}};return e[i].call(a.exports,a,a.exports,r),a.l=!0,a.exports}r.m=e,r.c=t,r.i=function(e){return e},r.d=function(e,t,i){r.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:i})},r.r=function(e){Object.defineProperty(e,"__esModule",{value:!0})},r.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(t,"a",t),t},r.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},r.p="/",r.oe=function(e){throw console.error(e),e};var i=r(r.s=ENTRY_MODULE);return i.default||i}function a(e){return(e+"").replace(/[.?*+^$[\]\\(){}|-]/g,"\\$&")}function n(e,t,i){var n={};n[i]=[];var s=t.toString(),o=s.match(/^function\s?\w*\(\w+,\s*\w+,\s*(\w+)\)/);if(!o)return n;for(var l,d=o[1],u=new RegExp("(\\\\n|\\W)"+a(d)+"\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)","g");l=u.exec(s);)"dll-reference"!==l[3]&&n[i].push(l[3]);for(u=new RegExp("\\("+a(d)+'\\("(dll-reference\\s([\\.|\\-|\\+|\\w|/|@]+))"\\)\\)\\(\\s*(/\\*.*?\\*/)?\\s*.*?([\\.|\\-|\\+|\\w|/|@]+).*?\\)',"g");l=u.exec(s);)e[l[2]]||(n[i].push(l[1]),e[l[2]]=r(l[1]).m),n[l[2]]=n[l[2]]||[],n[l[2]].push(l[4]);for(var c,h=Object.keys(n),f=0;f0}),!1)}e.exports=function(e,t){t=t||{};var a={main:r.m},o=t.all?{main:Object.keys(a.main)}:function(e,t){for(var r={main:[t]},i={main:[]},a={main:{}};s(r);)for(var o=Object.keys(r),l=0;l1?r-1:0),a=1;a1?r-1:0),a=1;a1?t-1:0),i=1;i>8*(15-r)&255;return t},a.setDecryptDataFromLevelKey=function(e,t){var r=e;return(null==e?void 0:e.method)&&e.uri&&!e.iv&&((r=new v(e.baseuri,e.reluri)).method=e.method,r.iv=this.createInitializationVector(t)),r},t=e,(r=[{key:"url",get:function(){return!this._url&&this.relurl&&(this._url=Object(s.buildAbsoluteURL)(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url},set:function(e){this._url=e}},{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var e=this.sn;"number"!=typeof e&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&u.b.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),e=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,e)}return this._decryptdata}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(l.a)(this.programDateTime))return null;var e=Object(l.a)(this.duration)?this.duration:0;return this.programDateTime+1e3*e}},{key:"encrypted",get:function(){return!(!this.decryptdata||null===this.decryptdata.uri||null!==this.decryptdata.key)}}])&&m(t.prototype,r),i&&m(t,i),e}();function b(e,t){for(var r=0;rNumber.MAX_SAFE_INTEGER?1/0:t},t.hexadecimalInteger=function(e){if(this[e]){var t=(this[e]||"0x").slice(2);t=(1&t.length?"0":"")+t;for(var r=new Uint8Array(t.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:t},t.decimalFloatingPoint=function(e){return parseFloat(this[e])},t.enumeratedString=function(e){return this[e]},t.decimalResolution=function(e){var t=E.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e){var t,r={};for(S.lastIndex=0;null!==(t=S.exec(e));){var i=t[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[t[1]]=i}return r},e}(),R={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0}};function A(e,t){return MediaSource.isTypeSupported((t||"video")+'/mp4;codecs="'+e+'"')}var k=/(?:#EXT-X-STREAM-INF:([^\n\r]*)[\r\n]+([^\r\n]+)|#EXT-X-SESSION-DATA:([^\n\r]*)[\r\n]+)/g,w=/#EXT-X-MEDIA:(.*)/g,L=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/|(?!#)([\S+ ?]+)/.source,/|#EXT-X-BYTERANGE:*(.+)/.source,/|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/|#.*/.source].join(""),"g"),D=/(?:(?:#(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?/,O=/\.(mp4|m4s|m4v|m4a)$/i,C=function(){function e(){}return e.findGroup=function(e,t){for(var r=0;r2?(t=r.shift()+".",t+=parseInt(r.shift()).toString(16),t+=("000"+parseInt(r.shift()).toString(16)).substr(-4)):t=e,t},e.resolve=function(e,t){return s.buildAbsoluteURL(t,e,{alwaysNormalize:!0})},e.parseMasterPlaylist=function(t,r){var i,a=[],n={},s=!1;function o(e,t){["video","audio"].forEach((function(r){var i=e.filter((function(e){return function(e,t){var r=R[t];return!!r&&!0===r[e.slice(0,4)]}(e,r)}));if(i.length){var a=i.filter((function(e){return 0===e.lastIndexOf("avc1",0)||0===e.lastIndexOf("mp4a",0)}));t[r+"Codec"]=a.length>0?a[0]:i[0],e=e.filter((function(e){return-1===i.indexOf(e)}))}})),t.unknownCodecs=e}for(k.lastIndex=0;null!=(i=k.exec(t));)if(i[1]){var l={},d=l.attrs=new _(i[1]);l.url=e.resolve(i[2],r);var u=d.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),l.bitrate=d.decimalInteger("AVERAGE-BANDWIDTH")||d.decimalInteger("BANDWIDTH"),l.name=d.NAME,o([].concat((d.CODECS||"").split(/[ ,]+/)),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=e.convertAVC1ToAVCOTI(l.videoCodec)),a.push(l)}else if(i[3]){var c=new _(i[3]);c["DATA-ID"]&&(s=!0,n[c["DATA-ID"]]=c)}return{levels:a,sessionData:s?n:null}},e.parseMasterPlaylistMedia=function(t,r,i,a){var n;void 0===a&&(a=[]);var s=[],o=0;for(w.lastIndex=0;null!==(n=w.exec(t));){var l=new _(n[1]);if(l.TYPE===i){var d={attrs:l,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE,type:i,default:"YES"===l.DEFAULT,autoselect:"YES"===l.AUTOSELECT,forced:"YES"===l.FORCED,lang:l.LANGUAGE};if(l.URI&&(d.url=e.resolve(l.URI,r)),a.length){var u=e.findGroup(a,d.groupId);d.audioCodec=u?u.codec:a[0].codec}s.push(d)}}return s},e.parseLevelPlaylist=function(e,t,r,i,a){var n,s,o,d=0,c=0,h=new T(t),f=0,g=null,p=new y,m=null;for(L.lastIndex=0;null!==(n=L.exec(e));){var b=n[1];if(b){p.duration=parseFloat(b);var E=(" "+n[2]).slice(1);p.title=E||null,p.tagList.push(E?["INF",b,E]:["INF",b])}else if(n[3]){if(Object(l.a)(p.duration)){var S=d++;p.type=i,p.start=c,o&&(p.levelkey=o),p.sn=S,p.level=r,p.cc=f,p.urlId=a,p.baseurl=t,p.relurl=(" "+n[3]).slice(1),I(p,g),h.fragments.push(p),g=p,c+=p.duration,p=new y}}else if(n[4]){var R=(" "+n[4]).slice(1);g?p.setByteRange(R,g):p.setByteRange(R)}else if(n[5])p.rawProgramDateTime=(" "+n[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),null===m&&(m=h.fragments.length);else{if(!(n=n[0].match(D))){u.b.warn("No matches on slow regex match for level playlist!");continue}for(s=1;s=0&&(o.method=C,o.key=null,o.iv=x));break;case"START":var M=new _(A).decimalFloatingPoint("TIME-OFFSET");Object(l.a)(M)&&(h.startTimeOffset=M);break;case"MAP":var F=new _(A);p.relurl=F.URI,F.BYTERANGE&&p.setByteRange(F.BYTERANGE),p.baseurl=t,p.level=r,p.type=i,p.sn="initSegment",h.initSegment=p,(p=new y).rawProgramDateTime=h.initSegment.rawProgramDateTime;break;default:u.b.warn("line parsed but not handled: "+n)}}}return(p=g)&&!p.relurl&&(h.fragments.pop(),c-=p.duration),h.totalduration=c,h.averagetargetduration=c/h.fragments.length,h.endSN=d-1,h.startCC=h.fragments[0]?h.fragments[0].cc:0,h.endCC=f,!h.initSegment&&h.fragments.length&&h.fragments.every((function(e){return O.test(e.relurl)}))&&(u.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(p=new y).relurl=h.fragments[0].relurl,p.baseurl=t,p.level=r,p.type=i,p.sn="initSegment",h.initSegment=p,h.needSidxRanges=!0),m&&function(e,t){for(var r=e[t],i=t-1;i>=0;i--){var a=e[i];a.programDateTime=r.programDateTime-1e3*a.duration,r=a}}(h.fragments,m),h},e}();function I(e,t){e.rawProgramDateTime?e.programDateTime=Date.parse(e.rawProgramDateTime):(null==t?void 0:t.programDateTime)&&(e.programDateTime=t.endProgramDateTime),Object(l.a)(e.programDateTime)||(e.programDateTime=null,e.rawProgramDateTime=null)}var P=window.performance,x=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,d.a.MANIFEST_LOADING,d.a.LEVEL_LOADING,d.a.AUDIO_TRACK_LOADING,d.a.SUBTITLE_TRACK_LOADING)||this).loaders={},r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,i.canHaveQualityLevels=function(e){return e!==a.AUDIO_TRACK&&e!==a.SUBTITLE_TRACK},i.mapContextToLevelType=function(e){switch(e.type){case a.AUDIO_TRACK:return n.AUDIO;case a.SUBTITLE_TRACK:return n.SUBTITLE;default:return n.MAIN}},i.getResponseUrl=function(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r};var s=i.prototype;return s.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,a=new(r||i)(t);return e.loader=a,this.loaders[e.type]=a,a},s.getInternalLoader=function(e){return this.loaders[e.type]},s.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},s.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},s.destroy=function(){this.destroyInternalLoaders(),e.prototype.destroy.call(this)},s.onManifestLoading=function(e){this.load({url:e.url,type:a.MANIFEST,level:0,id:null,responseType:"text"})},s.onLevelLoading=function(e){this.load({url:e.url,type:a.LEVEL,level:e.level,id:e.id,responseType:"text"})},s.onAudioTrackLoading=function(e){this.load({url:e.url,type:a.AUDIO_TRACK,level:null,id:e.id,responseType:"text"})},s.onSubtitleTrackLoading=function(e){this.load({url:e.url,type:a.SUBTITLE_TRACK,level:null,id:e.id,responseType:"text"})},s.load=function(e){var t=this.hls.config;u.b.debug("Loading playlist of type "+e.type+", level: "+e.level+", id: "+e.id);var r,i,n,s,o=this.getInternalLoader(e);if(o){var l=o.context;if(l&&l.url===e.url)return u.b.trace("playlist request ongoing"),!1;u.b.warn("aborting previous loader for type: "+e.type),o.abort()}switch(e.type){case a.MANIFEST:r=t.manifestLoadingMaxRetry,i=t.manifestLoadingTimeOut,n=t.manifestLoadingRetryDelay,s=t.manifestLoadingMaxRetryTimeout;break;case a.LEVEL:r=0,s=0,n=0,i=t.levelLoadingTimeOut;break;default:r=t.levelLoadingMaxRetry,i=t.levelLoadingTimeOut,n=t.levelLoadingRetryDelay,s=t.levelLoadingMaxRetryTimeout}o=this.createInternalLoader(e);var d={timeout:i,maxRetry:r,retryDelay:n,maxRetryDelay:s},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};return u.b.debug("Calling internal loader delegate for URL: "+e.url),o.load(e,d,c),!0},s.loadsuccess=function(e,t,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this._handleSidxRequest(e,r),void this._handlePlaylistLoaded(e,t,r,i);if(this.resetInternalLoader(r.type),"string"!=typeof e.data)throw new Error('expected responseType of "text" for PlaylistLoader');var a=e.data;t.tload=P.now(),0===a.indexOf("#EXTM3U")?a.indexOf("#EXTINF:")>0||a.indexOf("#EXT-X-TARGETDURATION:")>0?this._handleTrackOrLevelPlaylist(e,t,r,i):this._handleMasterPlaylist(e,t,r,i):this._handleManifestParsingError(e,r,"no EXTM3U delimiter",i)},s.loaderror=function(e,t,r){void 0===r&&(r=null),this._handleNetworkError(t,r,!1,e)},s.loadtimeout=function(e,t,r){void 0===r&&(r=null),this._handleNetworkError(t,r,!0)},s._handleMasterPlaylist=function(e,t,r,a){var n=this.hls,s=e.data,o=i.getResponseUrl(e,r),l=C.parseMasterPlaylist(s,o),c=l.levels,h=l.sessionData;if(c.length){var f=c.map((function(e){return{id:e.attrs.AUDIO,codec:e.audioCodec}})),g=C.parseMasterPlaylistMedia(s,o,"AUDIO",f),p=C.parseMasterPlaylistMedia(s,o,"SUBTITLES"),v=C.parseMasterPlaylistMedia(s,o,"CLOSED-CAPTIONS");if(g.length){var m=!1;g.forEach((function(e){e.url||(m=!0)})),!1===m&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(u.b.log("audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:{},url:""}))}n.trigger(d.a.MANIFEST_LOADED,{levels:c,audioTracks:g,subtitles:p,captions:v,url:o,stats:t,networkDetails:a,sessionData:h})}else this._handleManifestParsingError(e,r,"no level found in manifest",a)},s._handleTrackOrLevelPlaylist=function(e,t,r,n){var s=this.hls,u=r.id,c=r.level,h=r.type,f=i.getResponseUrl(e,r),g=Object(l.a)(u)?u:0,p=Object(l.a)(c)?c:g,v=i.mapContextToLevelType(r),m=C.parseLevelPlaylist(e.data,f,p,v,g);if(m.tload=t.tload,m.fragments.length){if(h===a.MANIFEST){var y={url:f,details:m};s.trigger(d.a.MANIFEST_LOADED,{levels:[y],audioTracks:[],url:f,stats:t,networkDetails:n,sessionData:null})}if(t.tparsed=P.now(),m.needSidxRanges){var b=m.initSegment.url;this.load({url:b,isSidxRequest:!0,type:h,level:c,levelDetails:m,id:u,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer"})}else r.levelDetails=m,this._handlePlaylistLoaded(e,t,r,n)}else s.trigger(d.a.ERROR,{type:o.b.NETWORK_ERROR,details:o.a.LEVEL_EMPTY_ERROR,fatal:!1,url:f,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},s._handleSidxRequest=function(e,t){if("string"==typeof e.data)throw new Error("sidx request must be made with responseType of array buffer");var r=f.a.parseSegmentIndex(new Uint8Array(e.data));if(r){var i=r.references,a=t.levelDetails;i.forEach((function(e,t){var r=e.info;if(a){var i=a.fragments[t];0===i.byteRange.length&&i.setByteRange(String(1+r.end-r.start)+"@"+String(r.start))}})),a&&a.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}},s._handleManifestParsingError=function(e,t,r,i){this.hls.trigger(d.a.ERROR,{type:o.b.NETWORK_ERROR,details:o.a.MANIFEST_PARSING_ERROR,fatal:!0,url:e.url,reason:r,networkDetails:i})},s._handleNetworkError=function(e,t,r,i){var n,s;void 0===r&&(r=!1),void 0===i&&(i=null),u.b.info("A network error occured while loading a "+e.type+"-type playlist");var l=this.getInternalLoader(e);switch(e.type){case a.MANIFEST:n=r?o.a.MANIFEST_LOAD_TIMEOUT:o.a.MANIFEST_LOAD_ERROR,s=!0;break;case a.LEVEL:n=r?o.a.LEVEL_LOAD_TIMEOUT:o.a.LEVEL_LOAD_ERROR,s=!1;break;case a.AUDIO_TRACK:n=r?o.a.AUDIO_TRACK_LOAD_TIMEOUT:o.a.AUDIO_TRACK_LOAD_ERROR,s=!1;break;default:s=!1}l&&(l.abort(),this.resetInternalLoader(e.type));var c={type:o.b.NETWORK_ERROR,details:n,fatal:s,url:e.url,loader:l,context:e,networkDetails:t};i&&(c.response=i),this.hls.trigger(d.a.ERROR,c)},s._handlePlaylistLoaded=function(e,t,r,n){var s=r.type,o=r.level,l=r.id,u=r.levelDetails;if(u&&u.targetduration)if(i.canHaveQualityLevels(r.type))this.hls.trigger(d.a.LEVEL_LOADED,{details:u,level:o||0,id:l||0,stats:t,networkDetails:n});else switch(s){case a.AUDIO_TRACK:this.hls.trigger(d.a.AUDIO_TRACK_LOADED,{details:u,id:l,stats:t,networkDetails:n});break;case a.SUBTITLE_TRACK:this.hls.trigger(d.a.SUBTITLE_TRACK_LOADED,{details:u,id:l,stats:t,networkDetails:n})}else this._handleManifestParsingError(e,r,"invalid target duration",n)},i}(h);var M=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,d.a.FRAG_LOADING)||this).loaders={},r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var a=i.prototype;return a.destroy=function(){var t=this.loaders;for(var r in t){var i=t[r];i&&i.destroy()}this.loaders={},e.prototype.destroy.call(this)},a.onFragLoading=function(e){var t=e.frag,r=t.type,i=this.loaders,a=this.hls.config,n=a.fLoader,s=a.loader;t.loaded=0;var o,d,c,h=i[r];h&&(u.b.warn("abort previous fragment loader for type: "+r),h.abort()),h=i[r]=t.loader=a.fLoader?new n(a):new s(a),o={url:t.url,frag:t,responseType:"arraybuffer",progressData:!1};var f=t.byteRangeStartOffset,g=t.byteRangeEndOffset;Object(l.a)(f)&&Object(l.a)(g)&&(o.rangeStart=f,o.rangeEnd=g),d={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout},c={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this),onProgress:this.loadprogress.bind(this)},h.load(o,d,c)},a.loadsuccess=function(e,t,r,i){void 0===i&&(i=null);var a=e.data,n=r.frag;n.loader=void 0,this.loaders[n.type]=void 0,this.hls.trigger(d.a.FRAG_LOADED,{payload:a,frag:n,stats:t,networkDetails:i})},a.loaderror=function(e,t,r){void 0===r&&(r=null);var i=t.frag,a=i.loader;a&&a.abort(),this.loaders[i.type]=void 0,this.hls.trigger(d.a.ERROR,{type:o.b.NETWORK_ERROR,details:o.a.FRAG_LOAD_ERROR,fatal:!1,frag:t.frag,response:e,networkDetails:r})},a.loadtimeout=function(e,t,r){void 0===r&&(r=null);var i=t.frag,a=i.loader;a&&a.abort(),this.loaders[i.type]=void 0,this.hls.trigger(d.a.ERROR,{type:o.b.NETWORK_ERROR,details:o.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t.frag,networkDetails:r})},a.loadprogress=function(e,t,r,i){void 0===i&&(i=null);var a=t.frag;a.loaded=e.loaded,this.hls.trigger(d.a.FRAG_LOAD_PROGRESS,{frag:a,stats:e,networkDetails:i})},i}(h);var F=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,d.a.KEY_LOADING)||this).loaders={},r.decryptkey=null,r.decrypturl=null,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var a=i.prototype;return a.destroy=function(){for(var t in this.loaders){var r=this.loaders[t];r&&r.destroy()}this.loaders={},e.prototype.destroy.call(this)},a.onKeyLoading=function(e){var t=e.frag,r=t.type,i=this.loaders[r];if(t.decryptdata){var a=t.decryptdata.uri;if(a!==this.decrypturl||null===this.decryptkey){var n=this.hls.config;if(i&&(u.b.warn("abort previous key loader for type:"+r),i.abort()),!a)return void u.b.warn("key uri is falsy");t.loader=this.loaders[r]=new n.loader(n),this.decrypturl=a,this.decryptkey=null;var s={url:a,frag:t,responseType:"arraybuffer"},o={timeout:n.fragLoadingTimeOut,maxRetry:0,retryDelay:n.fragLoadingRetryDelay,maxRetryDelay:n.fragLoadingMaxRetryTimeout},l={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};t.loader.load(s,o,l)}else this.decryptkey&&(t.decryptdata.key=this.decryptkey,this.hls.trigger(d.a.KEY_LOADED,{frag:t}))}else u.b.warn("Missing decryption data on fragment in onKeyLoading")},a.loadsuccess=function(e,t,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(e.data),i.loader=void 0,delete this.loaders[i.type],this.hls.trigger(d.a.KEY_LOADED,{frag:i})):u.b.error("after key load, decryptdata unset")},a.loaderror=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(d.a.ERROR,{type:o.b.NETWORK_ERROR,details:o.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:e})},a.loadtimeout=function(e,t){var r=t.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(d.a.ERROR,{type:o.b.NETWORK_ERROR,details:o.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},i}(h);var U="NOT_LOADED",N="APPENDING",B="PARTIAL",G="OK",K=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,d.a.BUFFER_APPENDED,d.a.FRAG_BUFFERED,d.a.FRAG_LOADED)||this).bufferPadding=.2,r.fragments=Object.create(null),r.timeRanges=Object.create(null),r.config=t.config,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var a=i.prototype;return a.destroy=function(){this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.config=null,h.prototype.destroy.call(this),e.prototype.destroy.call(this)},a.getBufferedFrag=function(e,t){var r=this.fragments,i=Object.keys(r).filter((function(i){var a=r[i];if(a.body.type!==t)return!1;if(!a.buffered)return!1;var n=a.body;return n.startPTS<=e&&e<=n.endPTS}));if(0===i.length)return null;var a=i.pop();return r[a].body},a.detectEvictedFragments=function(e,t){var r=this;Object.keys(this.fragments).forEach((function(i){var a=r.fragments[i];if(a&&a.buffered){var n=a.range[e];if(n)for(var s=n.time,o=0;o=i&&t<=a){n.push({startPTS:Math.max(e,r.start(o)),endPTS:Math.min(t,r.end(o))});break}if(ei)n.push({startPTS:Math.max(e,r.start(o)),endPTS:Math.min(t,r.end(o))}),s=!0;else if(t<=i)break}return{time:n,partial:s}},a.getFragmentKey=function(e){return e.type+"_"+e.level+"_"+e.urlId+"_"+e.sn},a.getPartialFragment=function(e){var t,r,i,a=this,n=null,s=0;return Object.keys(this.fragments).forEach((function(o){var l=a.fragments[o];a.isPartial(l)&&(r=l.body.startPTS-a.bufferPadding,i=l.body.endPTS+a.bufferPadding,e>=r&&e<=i&&(t=Math.min(e-r,i-e),s<=t&&(n=l.body,s=t)))})),n},a.getState=function(e){var t=this.getFragmentKey(e),r=this.fragments[t],i=U;return void 0!==r&&(i=r.buffered?!0===this.isPartial(r)?B:G:N),i},a.isPartial=function(e){return!0===e.buffered&&(void 0!==e.range.video&&!0===e.range.video.partial||void 0!==e.range.audio&&!0===e.range.audio.partial)},a.isTimeBuffered=function(e,t,r){for(var i,a,n=0;n=i&&t<=a)return!0;if(t<=i)return!1}return!1},a.onFragLoaded=function(e){var t=e.frag;Object(l.a)(t.sn)&&!t.bitrateTest&&(this.fragments[this.getFragmentKey(t)]={body:t,range:Object.create(null),buffered:!1})},a.onBufferAppended=function(e){var t=this;this.timeRanges=e.timeRanges,Object.keys(this.timeRanges).forEach((function(e){var r=t.timeRanges[e];t.detectEvictedFragments(e,r)}))},a.onFragBuffered=function(e){this.detectPartialFragments(e.frag)},a.hasFragment=function(e){var t=this.getFragmentKey(e);return void 0!==this.fragments[t]},a.removeFragment=function(e){var t=this.getFragmentKey(e);delete this.fragments[t]},a.removeAllFragments=function(){this.fragments=Object.create(null)},i}(h),j={search:function(e,t){for(var r=0,i=e.length-1,a=null,n=null;r<=i;){var s=t(n=e[a=(r+i)/2|0]);if(s>0)r=a+1;else{if(!(s<0))return n;i=a-1}}return null}},H=function(){function e(){}return e.isBuffered=function(e,t){try{if(e)for(var r=e.buffered,i=0;i=r.start(i)&&t<=r.end(i))return!0}catch(e){}return!1},e.bufferInfo=function(e,t,r){try{if(e){var i,a=e.buffered,n=[];for(i=0;is&&(i[n-1].end=e[a].end):i.push(e[a])}else i.push(e[a])}else i=e;for(var o,l=0,d=t,u=t,c=0;c=h&&t1?t-1:0),i=1;it?(i.duration=n-i.start,i.duration<0&&u.b.warn("negative duration computed for frag "+i.sn+",level "+i.level+", there should be some duration drift between playlist and fragment!")):(a.duration=i.start-n,a.duration<0&&u.b.warn("negative duration computed for frag "+a.sn+",level "+a.level+", there should be some duration drift between playlist and fragment!"));else if(r>t){var s=i.cc===a.cc;a.start=i.start+(s&&i.minEndPTS?i.minEndPTS-i.start:i.duration)}else a.start=Math.max(i.start-a.duration,0)}function te(e,t,r,i,a,n){var s=r,o=i;if(Object(l.a)(t.startPTS)){var d=Math.abs(t.startPTS-r);Object(l.a)(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,s=Math.max(r,t.startPTS),r=Math.min(r,t.startPTS),o=Math.min(i,t.endPTS),i=Math.max(i,t.endPTS),a=Math.min(a,t.startDTS),n=Math.max(n,t.endDTS)}var u=r-t.start;t.start=t.startPTS=r,t.maxStartPTS=s,t.endPTS=i,t.minEndPTS=o,t.startDTS=a,t.endDTS=n,t.duration=i-r;var c,h,f,g=t.sn;if(!e||ge.endSN)return 0;for(c=g-e.startSN,(h=e.fragments)[c]=t,f=c;f>0;f--)ee(h,f,f-1);for(f=c;fi.length)return;for(var n=0;nr.startCC||e&&e.cc=(e[e.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;ie&&r.start?-1:0}function ce(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}var he=function(){function e(e,t,r,i){this.config=e,this.media=t,this.fragmentTracker=r,this.hls=i,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1}var t=e.prototype;return t.poll=function(e){var t=this.config,r=this.media,i=this.stalled,a=r.currentTime,n=r.seeking,s=this.seeking&&!n,o=!this.seeking&&n;if(this.seeking=n,a===e){if((o||s)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&&r.buffered.length){var l=H.bufferInfo(r,a,0),d=l.len>0,c=l.nextStart||0;if(d||c){if(n){var h=l.len>2,f=!c||c-a>2&&!this.fragmentTracker.getPartialFragment(a);if(h||f)return;this.moved=!1}if(!this.moved&&this.stalled){var g=Math.max(c,l.start||0)-a;if(g>0&&g<=2)return void this._trySkipBufferHole(null)}var p=self.performance.now();if(null!==i){var v=p-i;!n&&v>=250&&this._reportStall(l.len);var m=H.bufferInfo(r,a,t.maxBufferHole);this._tryFixBufferStall(m,v)}else this.stalled=p}}}else if(this.moved=!0,null!==i){if(this.stallReported){var y=self.performance.now()-i;u.b.warn("playback not stuck anymore @"+a+", after "+Math.round(y)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},t._tryFixBufferStall=function(e,t){var r=this.config,i=this.fragmentTracker,a=this.media.currentTime,n=i.getPartialFragment(a);if(n&&this._trySkipBufferHole(n))return;e.len>r.maxBufferHole&&t>1e3*r.highBufferWatchdogPeriod&&(u.b.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},t._reportStall=function(e){var t=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,u.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+e+")"),t.trigger(d.a.ERROR,{type:o.b.MEDIA_ERROR,details:o.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:e}))},t._trySkipBufferHole=function(e){for(var t=this.config,r=this.hls,i=this.media,a=i.currentTime,n=0,s=0;s=n&&a1?i-1:0),n=1;n1&&(this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)),this._tickCallCount=0)},a.doTick=function(){},i}(h);var pe="STOPPED",ve="STARTING",me="IDLE",ye="PAUSED",be="KEY_LOADING",Te="FRAG_LOADING",Ee="FRAG_LOADING_WAITING_RETRY",Se="WAITING_TRACK",_e="PARSING",Re="PARSED",Ae="BUFFER_FLUSHING",ke="ENDED",we="ERROR",Le="WAITING_INIT_PTS",De="WAITING_LEVEL",Oe=function(e){var t,r;function i(){return e.apply(this,arguments)||this}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var a=i.prototype;return a.doTick=function(){},a.startLoad=function(){},a.stopLoad=function(){var e=this.fragCurrent;e&&(e.loader&&e.loader.abort(),this.fragmentTracker.removeFragment(e)),this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=pe},a._streamEnded=function(e,t){var r=this.fragCurrent,i=this.fragmentTracker;if(!t.live&&r&&!r.backtracked&&r.sn===t.endSN&&!e.nextStart){var a=i.getState(r);return a===B||a===G}return!1},a.onMediaSeeking=function(){var e=this.config,t=this.media,r=this.mediaBuffer,i=this.state,a=t?t.currentTime:null,n=H.bufferInfo(r||t,a,this.config.maxBufferHole);if(u.b.log("media seeking to "+(Object(l.a)(a)?a.toFixed(3):a)),i===Te){var s=this.fragCurrent;if(0===n.len&&s){var o=e.maxFragLookUpTolerance,d=s.start-o,c=s.start+s.duration+o;ac?(s.loader&&(u.b.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),s.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.state=me):u.b.log("seeking outside of buffer but within currently loaded fragment range")}}else i===ke&&(0===n.len&&(this.fragPrevious=null,this.fragCurrent=null),this.state=me);t&&(this.lastCurrentTime=a),this.loadedmetadata||(this.nextLoadPosition=this.startPosition=a),this.tick()},a.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},a.onHandlerDestroying=function(){this.stopLoad(),e.prototype.onHandlerDestroying.call(this)},a.onHandlerDestroyed=function(){this.state=pe,this.fragmentTracker=null},a.computeLivePosition=function(e,t){var r=void 0!==this.config.liveSyncDuration?this.config.liveSyncDuration:this.config.liveSyncDurationCount*t.targetduration;return e+Math.max(0,t.totalduration-r)},i}(ge);function Ce(e,t){for(var r=0;r0&&-1===e&&(u.b.log("override startPosition with lastCurrentTime @"+t.toFixed(3)),e=t),this.state=me,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this.forceStartLoad=!0,this.state=pe},h.stopLoad=function(){this.forceStartLoad=!1,e.prototype.stopLoad.call(this)},h.doTick=function(){switch(this.state){case Ae:this.fragLoadError=0;break;case me:this._doTickIdle();break;case De:var e=this.levels[this.level];e&&e.details&&(this.state=me);break;case Ee:var t=window.performance.now(),r=this.retryDate;(!r||t>=r||this.media&&this.media.seeking)&&(u.b.log("mediaController: retryDate reached, switch back to IDLE state"),this.state=me)}this._checkBuffer(),this._checkFragmentChanged()},h._doTickIdle=function(){var e=this.hls,t=e.config,r=this.media;if(void 0!==this.levelLastLoaded&&(r||!this.startFragRequested&&t.startFragPrefetch))if(this.altAudio&&this.audioOnly)this.demuxer.frag=null;else{var i;i=this.loadedmetadata?r.currentTime:this.nextLoadPosition;var a=e.nextLoadLevel,n=this.levels[a];if(n){var s,o=n.bitrate;s=o?Math.max(8*t.maxBufferSize/o,t.maxBufferLength):t.maxBufferLength,s=Math.min(s,t.maxMaxBufferLength);var l=i=s)){u.b.trace("buffer length of "+h.toFixed(3)+" is below max of "+s.toFixed(3)+". checking for more payload ..."),this.level=e.nextLoadLevel=a;var f=n.details;if(!f||f.live&&this.levelLastLoaded!==a)this.state=De;else{if(this._streamEnded(c,f)){var g={};return this.altAudio&&(g.type="video"),this.hls.trigger(d.a.BUFFER_EOS,g),void(this.state=ke)}this._fetchPayloadOrEos(i,c,f)}}}}},h._fetchPayloadOrEos=function(e,t,r){var i=this.fragPrevious,a=(this.level,r.fragments),n=a.length;if(0!==n){var s,o=a[0].start,l=a[n-1].start+a[n-1].duration,d=t.end;if(r.initSegment&&!r.initSegment.data)s=r.initSegment;else if(r.live){var c=this.config.initialLiveManifestSize;if(nh&&h>d.currentTime&&(u.b.log("buffer end: "+t.toFixed(3)+" is located too far from the end of live sliding playlist, reset currentTime to : "+h.toFixed(3)),d.currentTime=h),this.nextLoadPosition=h}if(e.PTSKnown&&t>i&&d&&d.readyState)return null;if(this.startFragRequested&&!e.PTSKnown&&a)if(e.hasProgramDateTime)u.b.log("live playlist, switching playlist, load frag with same PDT: "+a.programDateTime),s=le(n,a.endProgramDateTime,o.maxFragLookUpTolerance);else{var f=a.sn+1;if(f>=e.startSN&&f<=e.endSN){var g=n[f-e.startSN];a.cc===g.cc&&(s=g,u.b.log("live playlist, switching playlist, load frag with next SN: "+s.sn))}s||(s=j.search(n,(function(e){return a.cc-e.cc})))&&u.b.log("live playlist, switching playlist, load frag with same CC: "+s.sn)}return s},h._findFragment=function(e,t,r,i,a,n,s){var o,l=this.hls.config;an-l.maxFragLookUpTolerance?0:l.maxFragLookUpTolerance):o=i[r-1];if(o){var d=o.sn-s.startSN,c=t&&o.level===t.level,h=i[d-1],f=i[d+1];if(t&&o.sn===t.sn)if(c&&!o.backtracked)if(o.snl.maxBufferHole&&t.dropped&&d?(o=h,u.b.warn("Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this")):(o=f,this.fragmentTracker.getState(o)!==G&&u.b.log("Re-loading fragment with SN: "+o.sn))}else o=null;else o.backtracked&&(f&&f.backtracked?(u.b.warn("Already backtracked from fragment "+f.sn+", will not backtrack to fragment "+o.sn+". Loading fragment "+f.sn),o=f):(u.b.warn("Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe"),o.dropped=0,h?(o=h).backtracked=!0:d&&(o=null)))}return o},h._loadKey=function(e,t){u.b.log("Loading key for "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], level "+this.level),this.state=be,this.hls.trigger(d.a.KEY_LOADING,{frag:e})},h._loadFragment=function(e,t,r,i){var a=this.fragmentTracker.getState(e);this.fragCurrent=e,"initSegment"!==e.sn&&(this.startFragRequested=!0),Object(l.a)(e.sn)&&!e.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),e.backtracked||a===U||a===B?(e.autoLevel=this.hls.autoLevelEnabled,e.bitrateTest=this.bitrateTest,u.b.log("Loading "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], level "+this.level+", "+(this.loadedmetadata?"currentTime":"nextLoadPosition")+": "+parseFloat(r.toFixed(3))+", bufferEnd: "+parseFloat(i.toFixed(3))),this.hls.trigger(d.a.FRAG_LOADING,{frag:e}),this.demuxer||(this.demuxer=new J(this.hls,"main")),this.state=Te):a===N&&this._reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e)},h.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,n.MAIN)},h.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.endPTS+.5):null},h._checkFragmentChanged=function(){var e,t,r=this.media;if(r&&r.readyState&&!1===r.seeking&&((t=r.currentTime)>this.lastCurrentTime&&(this.lastCurrentTime=t),H.isBuffered(r,t)?e=this.getBufferedFrag(t):H.isBuffered(r,t+.1)&&(e=this.getBufferedFrag(t+.1)),e)){var i=e;if(i!==this.fragPlaying){this.hls.trigger(d.a.FRAG_CHANGED,{frag:i});var a=i.level;this.fragPlaying&&this.fragPlaying.level===a||this.hls.trigger(d.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=i}}},h.immediateLevelSwitch=function(){if(u.b.log("immediateLevelSwitch"),!this.immediateSwitch){this.immediateSwitch=!0;var e,t=this.media;t?(e=t.paused)||t.pause():e=!0,this.previouslyPaused=e}var r=this.fragCurrent;r&&r.loader&&r.loader.abort(),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},h.immediateLevelSwitchEnd=function(){var e=this.media;e&&e.buffered.length&&(this.immediateSwitch=!1,e.currentTime>0&&H.isBuffered(e,e.currentTime)&&(e.currentTime-=1e-4),this.previouslyPaused||e.play())},h.nextLevelSwitch=function(){var e=this.media;if(e&&e.readyState){var t,r=this.getBufferedFrag(e.currentTime);if(r&&r.startPTS>1&&this.flushMainBuffer(0,r.startPTS-1),e.paused)t=0;else{var i=this.hls.nextLoadLevel,a=this.levels[i],n=this.fragLastKbps;t=n&&this.fragCurrent?this.fragCurrent.duration*a.bitrate/(1e3*n)+1:0}var s=this.getBufferedFrag(e.currentTime+t);if(s){var o=this.followingBufferedFrag(s);if(o){var l=this.fragCurrent;l&&l.loader&&l.loader.abort(),this.fragCurrent=null;var d=Math.max(s.endPTS,o.maxStartPTS+Math.min(this.config.maxFragLookUpTolerance,o.duration));this.flushMainBuffer(d,Number.POSITIVE_INFINITY)}}}},h.flushMainBuffer=function(e,t){this.state=Ae;var r={startOffset:e,endOffset:t};this.altAudio&&(r.type="video"),this.hls.trigger(d.a.BUFFER_FLUSHING,r)},h.onMediaAttached=function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("seeked",this.onvseeked),t.addEventListener("ended",this.onvended);var r=this.config;this.levels&&r.autoStartLoad&&this.hls.startLoad(r.startPosition),this.gapController=new he(r,t,this.fragmentTracker,this.hls)},h.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(u.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0);var t=this.levels;t&&t.forEach((function(e){e.details&&e.details.fragments.forEach((function(e){e.backtracked=void 0}))})),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("seeked",this.onvseeked),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.fragmentTracker.removeAllFragments(),this.media=this.mediaBuffer=null,this.loadedmetadata=!1,this.stopLoad()},h.onMediaSeeked=function(){var e=this.media,t=e?e.currentTime:void 0;Object(l.a)(t)&&u.b.log("media seeked to "+t.toFixed(3)),this.tick()},h.onManifestLoading=function(){u.b.log("trigger BUFFER_RESET"),this.hls.trigger(d.a.BUFFER_RESET),this.fragmentTracker.removeAllFragments(),this.stalled=!1,this.startPosition=this.lastCurrentTime=0},h.onManifestParsed=function(e){var t,r=!1,i=!1;e.levels.forEach((function(e){(t=e.audioCodec)&&(-1!==t.indexOf("mp4a.40.2")&&(r=!0),-1!==t.indexOf("mp4a.40.5")&&(i=!0))})),this.audioCodecSwitch=r&&i,this.audioCodecSwitch&&u.b.log("both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.altAudio=e.altAudio,this.levels=e.levels,this.startFragRequested=!1;var a=this.config;(a.autoStartLoad||this.forceStartLoad)&&this.hls.startLoad(a.startPosition)},h.onLevelLoaded=function(e){var t=e.details,r=e.level,i=this.levels[this.levelLastLoaded],a=this.levels[r],n=t.totalduration,s=0;if(u.b.log("level "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+n),t.live||a.details&&a.details.live){var o=a.details;o&&t.fragments.length>0?(re(o,t),s=t.fragments[0].start,this.liveSyncPosition=this.computeLivePosition(s,o),t.PTSKnown&&Object(l.a)(s)?u.b.log("live playlist sliding:"+s.toFixed(3)):(u.b.log("live playlist - outdated PTS, unknown sliding"),oe(this.fragPrevious,i,t))):(u.b.log("live playlist - first load, unknown sliding"),t.PTSKnown=!1,oe(this.fragPrevious,i,t))}else t.PTSKnown=!1;if(a.details=t,this.levelLastLoaded=r,this.hls.trigger(d.a.LEVEL_UPDATED,{details:t,level:r}),!1===this.startFragRequested){if(-1===this.startPosition||-1===this.lastCurrentTime){var c=t.startTimeOffset;Object(l.a)(c)?(c<0&&(u.b.log("negative start time offset "+c+", count from end of last fragment"),c=s+n+c),u.b.log("start time offset found in playlist, adjust startPosition to "+c),this.startPosition=c):t.live?(this.startPosition=this.computeLivePosition(s,t),u.b.log("configure startPosition to "+this.startPosition)):this.startPosition=0,this.lastCurrentTime=this.startPosition}this.nextLoadPosition=this.startPosition}this.state===De&&(this.state=me),this.tick()},h.onKeyLoaded=function(){this.state===be&&(this.state=me,this.tick())},h.onFragLoaded=function(e){var t=this.fragCurrent,r=this.hls,i=this.levels,a=this.media,n=e.frag;if(this.state===Te&&t&&"main"===n.type&&n.level===t.level&&n.sn===t.sn){var s=e.stats,o=i[t.level],l=o.details;if(this.bitrateTest=!1,this.stats=s,u.b.log("Loaded "+t.sn+" of ["+l.startSN+" ,"+l.endSN+"],level "+t.level),n.bitrateTest&&r.nextLoadLevel)this.state=me,this.startFragRequested=!1,s.tparsed=s.tbuffered=window.performance.now(),r.trigger(d.a.FRAG_BUFFERED,{stats:s,frag:t,id:"main"}),this.tick();else if("initSegment"===n.sn)this.state=me,s.tparsed=s.tbuffered=window.performance.now(),l.initSegment.data=e.payload,r.trigger(d.a.FRAG_BUFFERED,{stats:s,frag:t,id:"main"}),this.tick();else{u.b.log("Parsing "+t.sn+" of ["+l.startSN+" ,"+l.endSN+"],level "+t.level+", cc "+t.cc),this.state=_e,this.pendingBuffering=!0,this.appended=!1,n.bitrateTest&&(n.bitrateTest=!1,this.fragmentTracker.onFragLoaded({frag:n}));var c=!(a&&a.seeking)&&(l.PTSKnown||!l.live),h=l.initSegment?l.initSegment.data:[],f=this._getAudioCodec(o);(this.demuxer=this.demuxer||new J(this.hls,"main")).push(e.payload,h,f,o.videoCodec,t,l.totalduration,c)}}this.fragLoadError=0},h.onFragParsingInitSegment=function(e){var t=this.fragCurrent,r=e.frag;if(t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===_e){var i,a,n=e.tracks;if(this.audioOnly=n.audio&&!n.video,this.altAudio&&!this.audioOnly&&delete n.audio,a=n.audio){var s=this.levels[this.level].audioCodec,o=navigator.userAgent.toLowerCase();s&&this.audioCodecSwap&&(u.b.log("swapping playlist audio codec"),s=-1!==s.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5"),this.audioCodecSwitch&&1!==a.metadata.channelCount&&-1===o.indexOf("firefox")&&(s="mp4a.40.5"),-1!==o.indexOf("android")&&"audio/mpeg"!==a.container&&(s="mp4a.40.2",u.b.log("Android: force audio codec to "+s)),a.levelCodec=s,a.id=e.id}for(i in(a=n.video)&&(a.levelCodec=this.levels[this.level].videoCodec,a.id=e.id),this.hls.trigger(d.a.BUFFER_CODECS,n),n){a=n[i],u.b.log("main track:"+i+",container:"+a.container+",codecs[level/parsed]=["+a.levelCodec+"/"+a.codec+"]");var l=a.initSegment;l&&(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(d.a.BUFFER_APPENDING,{type:i,data:l,parent:"main",content:"initSegment"}))}this.tick()}},h.onFragParsingData=function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"main"===e.id&&i.sn===r.sn&&i.level===r.level&&("audio"!==e.type||!this.altAudio)&&this.state===_e){var a=this.levels[this.level],n=r;if(Object(l.a)(e.endPTS)||(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),!0===e.hasAudio&&n.addElementaryStream(p.AUDIO),!0===e.hasVideo&&n.addElementaryStream(p.VIDEO),u.b.log("Parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb+",dropped:"+(e.dropped||0)),"video"===e.type)if(n.dropped=e.dropped,n.dropped)if(n.backtracked)u.b.warn("Already backtracked on this fragment, appending with the gap",n.sn);else{var s=a.details;if(!s||n.sn!==s.startSN)return u.b.warn("missing video frame(s), backtracking fragment",n.sn),this.fragmentTracker.removeFragment(n),n.backtracked=!0,this.nextLoadPosition=e.startPTS,this.state=me,this.fragPrevious=n,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),void this.tick();u.b.warn("missing video frame(s) on first frag, appending with gap",n.sn)}else n.backtracked=!1;var o=te(a.details,n,e.startPTS,e.endPTS,e.startDTS,e.endDTS),c=this.hls;c.trigger(d.a.LEVEL_PTS_UPDATED,{details:a.details,level:this.level,drift:o,type:e.type,start:e.startPTS,end:e.endPTS}),[e.data1,e.data2].forEach((function(r){r&&r.length&&t.state===_e&&(t.appended=!0,t.pendingBuffering=!0,c.trigger(d.a.BUFFER_APPENDING,{type:e.type,data:r,parent:"main",content:"data"}))})),this.tick()}},h.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"main"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===_e&&(this.stats.tparsed=window.performance.now(),this.state=Re,this._checkAppendedParsed())},h.onAudioTrackSwitching=function(e){var t=this.altAudio,r=!!e.url,i=e.id;if(!r){if(this.mediaBuffer!==this.media){u.b.log("switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var a=this.fragCurrent;a.loader&&(u.b.log("switching to main audio track, cancel main fragment load"),a.loader.abort()),this.fragCurrent=null,this.fragPrevious=null,this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),this.state=me}var n=this.hls;t&&n.trigger(d.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),n.trigger(d.a.AUDIO_TRACK_SWITCHED,{id:i})}},h.onAudioTrackSwitched=function(e){var t=e.id,r=!!this.hls.audioTracks[t].url;if(r){var i=this.videoBuffer;i&&this.mediaBuffer!==i&&(u.b.log("switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=i)}this.altAudio=r,this.tick()},h.onBufferCreated=function(e){var t,r,i=e.tracks,a=!1;for(var n in i){var s=i[n];"main"===s.id?(r=n,t=s,"video"===n&&(this.videoBuffer=i[n].buffer)):a=!0}a&&t?(u.b.log("alternate track found, use "+r+".buffered to schedule main fragment loading"),this.mediaBuffer=t.buffer):this.mediaBuffer=this.media},h.onBufferAppended=function(e){if("main"===e.parent){var t=this.state;t!==_e&&t!==Re||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},h._checkAppendedParsed=function(){if(!(this.state!==Re||this.appended&&this.pendingBuffering)){var e=this.fragCurrent;if(e){var t=this.mediaBuffer?this.mediaBuffer:this.media;u.b.log("main buffered : "+ne.toString(t.buffered)),this.fragPrevious=e;var r=this.stats;r.tbuffered=window.performance.now(),this.fragLastKbps=Math.round(8*r.total/(r.tbuffered-r.tfirst)),this.hls.trigger(d.a.FRAG_BUFFERED,{stats:r,frag:e,id:"main"}),this.state=me}(this.loadedmetadata||this.startPosition<=0)&&this.tick()}},h.onError=function(e){var t=e.frag||this.fragCurrent;if(!t||"main"===t.type){var r=!!this.media&&H.isBuffered(this.media,this.media.currentTime)&&H.isBuffered(this.media,this.media.currentTime+.5);switch(e.details){case o.a.FRAG_LOAD_ERROR:case o.a.FRAG_LOAD_TIMEOUT:case o.a.KEY_LOAD_ERROR:case o.a.KEY_LOAD_TIMEOUT:if(!e.fatal)if(this.fragLoadError+1<=this.config.fragLoadingMaxRetry){var i=Math.min(Math.pow(2,this.fragLoadError)*this.config.fragLoadingRetryDelay,this.config.fragLoadingMaxRetryTimeout);u.b.warn("mediaController: frag loading failed, retry in "+i+" ms"),this.retryDate=window.performance.now()+i,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.fragLoadError++,this.state=Ee}else u.b.error("mediaController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=we;break;case o.a.LEVEL_LOAD_ERROR:case o.a.LEVEL_LOAD_TIMEOUT:this.state!==we&&(e.fatal?(this.state=we,u.b.warn("streamController: "+e.details+",switch to "+this.state+" state ...")):e.levelRetry||this.state!==De||(this.state=me));break;case o.a.BUFFER_FULL_ERROR:"main"!==e.parent||this.state!==_e&&this.state!==Re||(r?(this._reduceMaxBufferLength(this.config.maxBufferLength),this.state=me):(u.b.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.fragCurrent=null,this.flushMainBuffer(0,Number.POSITIVE_INFINITY)))}}},h._reduceMaxBufferLength=function(e){var t=this.config;return t.maxMaxBufferLength>=e&&(t.maxMaxBufferLength/=2,u.b.warn("main:reduce max buffer length to "+t.maxMaxBufferLength+"s"),!0)},h._checkBuffer=function(){var e=this.media;if(e&&0!==e.readyState){var t=(this.mediaBuffer?this.mediaBuffer:e).buffered;!this.loadedmetadata&&t.length?(this.loadedmetadata=!0,this._seekToStartPos()):this.immediateSwitch?this.immediateLevelSwitchEnd():this.gapController.poll(this.lastCurrentTime,t)}},h.onFragLoadEmergencyAborted=function(){this.state=me,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},h.onBufferFlushed=function(){var e=this.mediaBuffer?this.mediaBuffer:this.media;if(e){var t=this.audioOnly?p.AUDIO:p.VIDEO;this.fragmentTracker.detectEvictedFragments(t,e.buffered)}this.state=me,this.fragPrevious=null},h.onLevelsUpdated=function(e){this.levels=e.levels},h.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},h._seekToStartPos=function(){var e=this.media,t=e.currentTime,r=this.startPosition;if(t!==r&&r>=0){if(e.seeking)return void u.b.log("could not seek to "+r+", already seeking at "+t);var i=(e.buffered.length?e.buffered.start(0):0)-r;i>0&&i"+e),this.hls.trigger(d.a.STREAM_STATE_TRANSITION,{previousState:t,nextState:e})}},get:function(){return this._state}},{key:"currentLevel",get:function(){var e=this.media;if(e){var t=this.getBufferedFrag(e.currentTime);if(t)return t.level}return-1}},{key:"nextBufferedFrag",get:function(){var e=this.media;return e?this.followingBufferedFrag(this.getBufferedFrag(e.currentTime)):null}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"liveSyncPosition",get:function(){return this._liveSyncPosition},set:function(e){this._liveSyncPosition=e}}])&&Ce(a.prototype,s),c&&Ce(a,c),i}(Oe);function xe(e,t){for(var r=0;r0){t=r[0].bitrate,r.sort((function(e,t){return e.bitrate-t.bitrate})),this._levels=r;for(var c=0;c=0&&e1&&c.loadError0){var t=this.currentLevelIndex,r=e.urlId,i=e.url[r];u.b.log("Attempt loading level index "+t+" with URL-id "+r),this.hls.trigger(d.a.LEVEL_LOADING,{url:i,level:t,id:r})}}},l.removeLevel=function(e,t){var r=this.levels.filter((function(r,i){return i!==e||r.url.length>1&&void 0!==t&&(r.url=r.url.filter((function(e,r){return r!==t})),r.urlId=0,!0)})).map((function(e,t){var r=e.details;return r&&r.fragments&&r.fragments.forEach((function(e){e.level=t})),e}));this._levels=r,this.hls.trigger(d.a.LEVELS_UPDATED,{levels:r})},a=i,(n=[{key:"levels",get:function(){return this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;t&&(e=Math.min(e,t.length-1),this.currentLevelIndex===e&&t[e].details||this.setLevelInternal(e))}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(e){this.manualLevelIndex=e,void 0===this._startLevel&&(this._startLevel=e),-1!==e&&(this.level=e)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(e){this._firstLevel=e}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var e=this.hls.config.startLevel;return void 0!==e?e:this._firstLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])&&xe(a.prototype,n),s&&xe(a,s),i}(h),Fe=r(4);function Ue(e,t){var r;try{r=new Event("addtrack")}catch(e){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function Ne(e){if(null==e?void 0:e.cues)for(;e.cues.length>0;)e.removeCue(e.cues[0])}var Be=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,d.a.MEDIA_ATTACHED,d.a.MEDIA_DETACHING,d.a.FRAG_PARSING_METADATA,d.a.LIVE_BACK_BUFFER_REACHED)||this).id3Track=void 0,r.media=void 0,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var a=i.prototype;return a.destroy=function(){h.prototype.destroy.call(this)},a.onMediaAttached=function(e){this.media=e.media,this.media},a.onMediaDetaching=function(){Ne(this.id3Track),this.id3Track=void 0,this.media=void 0},a.getID3Track=function(e){for(var t=0;te[e.length-1].endTime)return e[e.length-1];for(var r=0,i=e.length-1;r<=i;){var a=Math.floor((i+r)/2);if(te[a].endTime))return e[a];r=a+1}}return e[r].endTime-t=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.destroy=function(){},e}();function je(e,t){for(var r=0;r500*r.duration/s){var o=e.levels,l=Math.max(1,a.bw?a.bw/8:1e3*a.loaded/n),c=o[r.level];if(!c)return;var h=c.realBitrate?Math.max(c.realBitrate,c.bitrate):c.bitrate,f=a.total?a.total:Math.max(a.loaded,Math.round(r.duration*h/8)),g=t.currentTime,p=(f-a.loaded)/l,v=(H.bufferInfo(t,g,e.config.maxBufferHole).end-g)/s;if(v<2*r.duration/s&&p>v){var m,y=e.minAutoLevel;for(m=r.level-1;m>y;m--){var b=o[m].realBitrate?Math.max(o[m].realBitrate,o[m].bitrate):o[m].bitrate;if(r.duration*b/(6.4*l)=i;d--){var c=l[d];if(c){var h=c.details,f=h?h.totalduration/h.fragments.length:t,g=!!h&&h.live,p=void 0;p=d<=e?s*r:o*r;var v=l[d].realBitrate?Math.max(l[d].realBitrate,l[d].bitrate):l[d].bitrate,m=v*f/p;if(u.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+d+"/"+Math.round(p)+"/"+v+"/"+f+"/"+n+"/"+m),p>v&&(!m||g&&!this.bitrateTestDelay||m=0)return f;u.b.trace("rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering");var g=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay,p=i.abrBandWidthFactor,v=i.abrBandWidthUpFactor;if(0===h){var m=this.bitrateTestDelay;m&&(g=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-m,u.b.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*g)+" ms"),p=v=1)}return f=this._findBestLevel(s,o,c,a,t,h+g,p,v,r),Math.max(f,0)}}])&&je(a.prototype,n),s&&je(a,s),i}(h);var Ye=q(),We=function(e){var t,r;function i(t){var r;return(r=e.call(this,t,d.a.MEDIA_ATTACHING,d.a.MEDIA_DETACHING,d.a.MANIFEST_PARSED,d.a.BUFFER_RESET,d.a.BUFFER_APPENDING,d.a.BUFFER_CODECS,d.a.BUFFER_EOS,d.a.BUFFER_FLUSHING,d.a.LEVEL_PTS_UPDATED,d.a.LEVEL_UPDATED)||this)._msDuration=null,r._levelDuration=null,r._levelTargetDuration=10,r._live=null,r._objectUrl=null,r._needsFlush=!1,r._needsEos=!1,r.config=void 0,r.audioTimestampOffset=void 0,r.bufferCodecEventsExpected=0,r._bufferCodecEventsTotal=0,r.media=null,r.mediaSource=null,r.segments=[],r.parent=void 0,r.appending=!1,r.appended=0,r.appendError=0,r.flushBufferCounter=0,r.tracks={},r.pendingTracks={},r.sourceBuffer={},r.flushRange=[],r._onMediaSourceOpen=function(){u.b.log("media source opened"),r.hls.trigger(d.a.MEDIA_ATTACHED,{media:r.media});var e=r.mediaSource;e&&e.removeEventListener("sourceopen",r._onMediaSourceOpen),r.checkPendingTracks()},r._onMediaSourceClose=function(){u.b.log("media source closed")},r._onMediaSourceEnded=function(){u.b.log("media source ended")},r._onSBUpdateEnd=function(){if(r.audioTimestampOffset&&r.sourceBuffer.audio){var e=r.sourceBuffer.audio;u.b.warn("change mpeg audio timestamp offset from "+e.timestampOffset+" to "+r.audioTimestampOffset),e.timestampOffset=r.audioTimestampOffset,delete r.audioTimestampOffset}r._needsFlush&&r.doFlush(),r._needsEos&&r.checkEos(),r.appending=!1;var t=r.parent,i=r.segments.reduce((function(e,r){return r.parent===t?e+1:e}),0),a={},n=r.sourceBuffer;for(var s in n){var o=n[s];if(!o)throw Error("handling source buffer update end error: source buffer for "+s+" uninitilized and unable to update buffered TimeRanges.");a[s]=o.buffered}r.hls.trigger(d.a.BUFFER_APPENDED,{parent:t,pending:i,timeRanges:a}),r._needsFlush||r.doAppending(),r.updateMediaElementDuration(),0===i&&r.flushLiveBackBuffer()},r._onSBUpdateError=function(e){u.b.error("sourceBuffer error:",e),r.hls.trigger(d.a.ERROR,{type:o.b.MEDIA_ERROR,details:o.a.BUFFER_APPENDING_ERROR,fatal:!1})},r.config=t.config,r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var a=i.prototype;return a.destroy=function(){h.prototype.destroy.call(this)},a.onLevelPtsUpdated=function(e){var t=e.type,r=this.tracks.audio;if("audio"===t&&r&&"audio/mpeg"===r.container){var i=this.sourceBuffer.audio;if(!i)throw Error("Level PTS Updated and source buffer for audio uninitalized");if(Math.abs(i.timestampOffset-e.start)>.1){var a=i.updating;try{i.abort()}catch(e){u.b.warn("can not abort audio buffer: "+e)}a?this.audioTimestampOffset=e.start:(u.b.warn("change mpeg audio timestamp offset from "+i.timestampOffset+" to "+e.start),i.timestampOffset=e.start)}}},a.onManifestParsed=function(e){var t=2;(e.audio&&!e.video||!e.altAudio)&&(t=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=t,u.b.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},a.onMediaAttaching=function(e){var t=this.media=e.media;if(t&&Ye){var r=this.mediaSource=new Ye;r.addEventListener("sourceopen",this._onMediaSourceOpen),r.addEventListener("sourceended",this._onMediaSourceEnded),r.addEventListener("sourceclose",this._onMediaSourceClose),t.src=window.URL.createObjectURL(r),this._objectUrl=t.src}},a.onMediaDetaching=function(){u.b.log("media source detaching");var e=this.mediaSource;if(e){if("open"===e.readyState)try{e.endOfStream()}catch(e){u.b.warn("onMediaDetaching:"+e.message+" while calling endOfStream")}e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),this.media&&(this._objectUrl&&window.URL.revokeObjectURL(this._objectUrl),this.media.src===this._objectUrl?(this.media.removeAttribute("src"),this.media.load()):u.b.warn("media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={},this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0}this.hls.trigger(d.a.MEDIA_DETACHED)},a.checkPendingTracks=function(){var e=this.bufferCodecEventsExpected,t=this.pendingTracks,r=Object.keys(t).length;(r&&!e||2===r)&&(this.createSourceBuffers(t),this.pendingTracks={},this.doAppending())},a.onBufferReset=function(){var e=this.sourceBuffer;for(var t in e){var r=e[t];try{r&&(this.mediaSource&&this.mediaSource.removeSourceBuffer(r),r.removeEventListener("updateend",this._onSBUpdateEnd),r.removeEventListener("error",this._onSBUpdateError))}catch(e){}}this.sourceBuffer={},this.flushRange=[],this.segments=[],this.appended=0},a.onBufferCodecs=function(e){var t=this;Object.keys(this.sourceBuffer).length||(Object.keys(e).forEach((function(r){t.pendingTracks[r]=e[r]})),this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},a.createSourceBuffers=function(e){var t=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");for(var i in e)if(!t[i]){var a=e[i];if(!a)throw Error("source buffer exists for track "+i+", however track does not");var n=a.levelCodec||a.codec,s=a.container+";codecs="+n;u.b.log("creating sourceBuffer("+s+")");try{var l=t[i]=r.addSourceBuffer(s);l.addEventListener("updateend",this._onSBUpdateEnd),l.addEventListener("error",this._onSBUpdateError),this.tracks[i]={buffer:l,codec:n,id:a.id,container:a.container,levelCodec:a.levelCodec}}catch(e){u.b.error("error while trying to add sourceBuffer:"+e.message),this.hls.trigger(d.a.ERROR,{type:o.b.MEDIA_ERROR,details:o.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,err:e,mimeType:s})}}this.hls.trigger(d.a.BUFFER_CREATED,{tracks:this.tracks})},a.onBufferAppending=function(e){this._needsFlush||(this.segments?this.segments.push(e):this.segments=[e],this.doAppending())},a.onBufferEos=function(e){for(var t in this.sourceBuffer)if(!e.type||e.type===t){var r=this.sourceBuffer[t];r&&!r.ended&&(r.ended=!0,u.b.log(t+" sourceBuffer now EOS"))}this.checkEos()},a.checkEos=function(){var e=this.sourceBuffer,t=this.mediaSource;if(t&&"open"===t.readyState){for(var r in e){var i=e[r];if(i){if(!i.ended)return;if(i.updating)return void(this._needsEos=!0)}}u.b.log("all media data are available, signal endOfStream() to MediaSource and stop loading fragment");try{t.endOfStream()}catch(e){u.b.warn("exception while calling mediaSource.endOfStream()")}this._needsEos=!1}else this._needsEos=!1},a.onBufferFlushing=function(e){e.type?this.flushRange.push({start:e.startOffset,end:e.endOffset,type:e.type}):(this.flushRange.push({start:e.startOffset,end:e.endOffset,type:"video"}),this.flushRange.push({start:e.startOffset,end:e.endOffset,type:"audio"})),this.flushBufferCounter=0,this.doFlush()},a.flushLiveBackBuffer=function(){if(this._live){var e=this.config.liveBackBufferLength;if(isFinite(e)&&!(e<0))if(this.media)for(var t=this.media.currentTime,r=this.sourceBuffer,i=Object.keys(r),a=t-Math.max(e,this._levelTargetDuration),n=i.length-1;n>=0;n--){var s=i[n],o=r[s];if(o){var l=o.buffered;l.length>0&&a>l.start(0)&&this.removeBufferRange(s,o,0,a)&&this.hls.trigger(d.a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:a})}}else u.b.error("flushLiveBackBuffer called without attaching media")}},a.onLevelUpdated=function(e){var t=e.details;t.fragments.length>0&&(this._levelDuration=t.totalduration+t.fragments[0].start,this._levelTargetDuration=t.averagetargetduration||t.targetduration||10,this._live=t.live,this.updateMediaElementDuration())},a.updateMediaElementDuration=function(){var e,t=this.config;if(null!==this._levelDuration&&this.media&&this.mediaSource&&this.sourceBuffer&&0!==this.media.readyState&&"open"===this.mediaSource.readyState){for(var r in this.sourceBuffer){var i=this.sourceBuffer[r];if(i&&!0===i.updating)return}e=this.media.duration,null===this._msDuration&&(this._msDuration=this.mediaSource.duration),!0===this._live&&!0===t.liveDurationInfinity?(u.b.log("Media Source duration is set to Infinity"),this._msDuration=this.mediaSource.duration=1/0):(this._levelDuration>this._msDuration&&this._levelDuration>e||!Object(l.a)(e))&&(u.b.log("Updating Media Source duration to "+this._levelDuration.toFixed(3)),this._msDuration=this.mediaSource.duration=this._levelDuration)}},a.doFlush=function(){for(;this.flushRange.length;){var e=this.flushRange[0];if(!this.flushBuffer(e.start,e.end,e.type))return void(this._needsFlush=!0);this.flushRange.shift(),this.flushBufferCounter=0}if(0===this.flushRange.length){this._needsFlush=!1;var t=0,r=this.sourceBuffer;try{for(var i in r){var a=r[i];a&&(t+=a.buffered.length)}}catch(e){u.b.error("error while accessing sourceBuffer.buffered")}this.appended=t,this.hls.trigger(d.a.BUFFER_FLUSHED)}},a.doAppending=function(){var e=this.config,t=this.hls,r=this.segments,i=this.sourceBuffer;if(Object.keys(i).length){if(!this.media||this.media.error)return this.segments=[],void u.b.error("trying to append although a media error occured, flush segment and abort");if(!this.appending){var a=r.shift();if(a)try{var n=i[a.type];if(!n)return void this._onSBUpdateEnd();if(n.updating)return void r.unshift(a);n.ended=!1,this.parent=a.parent,n.appendBuffer(a.data),this.appendError=0,this.appended++,this.appending=!0}catch(i){u.b.error("error while trying to append buffer:"+i.message),r.unshift(a);var s={type:o.b.MEDIA_ERROR,parent:a.parent,details:"",fatal:!1};22===i.code?(this.segments=[],s.details=o.a.BUFFER_FULL_ERROR):(this.appendError++,s.details=o.a.BUFFER_APPEND_ERROR,this.appendError>e.appendErrorMaxRetry&&(u.b.log("fail "+e.appendErrorMaxRetry+" times to append segment in sourceBuffer"),this.segments=[],s.fatal=!0)),t.trigger(d.a.ERROR,s)}}}},a.flushBuffer=function(e,t,r){var i=this.sourceBuffer;if(!Object.keys(i).length)return!0;var a="null";if(this.media&&(a=this.media.currentTime.toFixed(3)),u.b.log("flushBuffer,pos/start/end: "+a+"/"+e+"/"+t),this.flushBufferCounter>=this.appended)return u.b.warn("abort flushing too many retries"),!0;var n=i[r];if(n){if(n.ended=!1,n.updating)return u.b.warn("cannot flush, sb updating in progress"),!1;if(this.removeBufferRange(r,n,e,t))return this.flushBufferCounter++,!1}return u.b.log("buffer flushed"),!0},a.removeBufferRange=function(e,t,r,i){try{for(var a=0;a.5){var d="null";return this.media&&(d=this.media.currentTime.toString()),u.b.log("sb remove "+e+" ["+o+","+l+"], of ["+n+","+s+"], pos:"+d),t.remove(o,l),!0}}}catch(e){u.b.warn("removeBufferRange failed",e)}return!1},i}(h);function qe(e,t){for(var r=0;rthis.autoLevelCapping&&t.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}},o.getMaxLevel=function(e){var t=this;if(!this.levels)return-1;var r=this.levels.filter((function(r,a){return i.isLevelAllowed(a,t.restrictedLevels)&&a<=e}));return this.clientRect=null,i.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)},o.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),clearInterval(this.timer),this.timer=setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},o.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=null,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(this.timer=clearInterval(this.timer),this.timer=null)},o.getDimensions=function(){if(this.clientRect)return this.clientRect;var e=this.media,t={width:0,height:0};if(e){var r=e.getBoundingClientRect();t.width=r.width,t.height=r.height,t.width||t.height||(t.width=r.right-r.left||e.width||0,t.height=r.bottom-r.top||e.height||0)}return this.clientRect=t,t},i.isLevelAllowed=function(e,t){return void 0===t&&(t=[]),-1===t.indexOf(e)},i.getMaxLevelByMediaSize=function(e,t,r){if(!e||e&&!e.length)return-1;for(var i,a,n=e.length-1,s=0;s=t||o.height>=r)&&(i=o,!(a=e[s+1])||i.width!==a.width||i.height!==a.height)){n=s;break}}return n},a=i,s=[{key:"contentScaleFactor",get:function(){var e=1;try{e=window.devicePixelRatio}catch(e){}return e}}],(n=[{key:"mediaWidth",get:function(){return this.getDimensions().width*i.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*i.contentScaleFactor}}])&&qe(a.prototype,n),s&&qe(a,s),i}(h);var ze=window.performance,Qe=function(e){var t,r;function i(t){return e.call(this,t,d.a.MEDIA_ATTACHING)||this}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var a=i.prototype;return a.destroy=function(){this.timer&&clearInterval(this.timer),this.isVideoPlaybackQualityAvailable=!1},a.onMediaAttaching=function(e){var t=this.hls.config;t.capLevelOnFPSDrop&&("function"==typeof(this.video=e.media instanceof window.HTMLVideoElement?e.media:null).getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),clearInterval(this.timer),this.timer=setInterval(this.checkFPSInterval.bind(this),t.fpsDroppedMonitoringPeriod))},a.checkFPS=function(e,t,r){var i=ze.now();if(t){if(this.lastTime){var a=i-this.lastTime,n=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*n/a,l=this.hls;if(l.trigger(d.a.FPS_DROP,{currentDropped:n,currentDecoded:s,totalDroppedFrames:r}),o>0&&n>l.config.fpsDroppedMonitoringThreshold*s){var c=l.currentLevel;u.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=c)&&(c-=1,l.trigger(d.a.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:l.currentLevel}),l.autoLevelCapping=c,l.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},a.checkFPSInterval=function(){var e=this.video;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},i}(h),$e=function(){function e(e){e&&e.xhrSetup&&(this.xhrSetup=e.xhrSetup)}var t=e.prototype;return t.destroy=function(){this.abort(),this.loader=null},t.abort=function(){var e=this.loader;e&&4!==e.readyState&&(this.stats.aborted=!0,e.abort()),window.clearTimeout(this.requestTimeout),this.requestTimeout=null,window.clearTimeout(this.retryTimeout),this.retryTimeout=null},t.load=function(e,t,r){this.context=e,this.config=t,this.callbacks=r,this.stats={trequest:window.performance.now(),retry:0},this.retryDelay=t.retryDelay,this.loadInternal()},t.loadInternal=function(){var e,t=this.context;e=this.loader=new window.XMLHttpRequest;var r=this.stats;r.tfirst=0,r.loaded=0;var i=this.xhrSetup;try{if(i)try{i(e,t.url)}catch(r){e.open("GET",t.url,!0),i(e,t.url)}e.readyState||e.open("GET",t.url,!0)}catch(r){return void this.callbacks.onError({code:e.status,text:r.message},t,e)}t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),this.config.timeout),e.send()},t.readystatechange=function(e){var t=e.currentTarget,r=t.readyState,i=this.stats,a=this.context,n=this.config;if(!i.aborted&&r>=2)if(window.clearTimeout(this.requestTimeout),0===i.tfirst&&(i.tfirst=Math.max(window.performance.now(),i.trequest)),4===r){var s=t.status;if(s>=200&&s<300){var o,l;i.tload=Math.max(i.tfirst,window.performance.now()),l="arraybuffer"===a.responseType?(o=t.response).byteLength:(o=t.responseText).length,i.loaded=i.total=l;var d={url:t.responseURL,data:o};this.callbacks.onSuccess(d,i,a,t)}else i.retry>=n.maxRetry||s>=400&&s<499?(u.b.error(s+" while loading "+a.url),this.callbacks.onError({code:s,text:t.statusText},a,t)):(u.b.warn(s+" while loading "+a.url+", retrying in "+this.retryDelay+"..."),this.destroy(),this.retryTimeout=window.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,n.maxRetryDelay),i.retry++)}else this.requestTimeout=window.setTimeout(this.loadtimeout.bind(this),n.timeout)},t.loadtimeout=function(){u.b.warn("timeout while loading "+this.context.url),this.callbacks.onTimeout(this.stats,this.context,null)},t.loadprogress=function(e){var t=e.currentTarget,r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total);var i=this.callbacks.onProgress;i&&i(r,this.context,null,t)},e}();function Je(e,t){for(var r=0;r=this.tracks.length)u.b.warn("Invalid audio track id:",e.id);else{if(u.b.log("audioTrack "+e.id+" loaded"),this.tracks[e.id].details=e.details,e.details.live&&!this.hasInterval()){var t=1e3*e.details.targetduration;this.setInterval(t)}!e.details.live&&this.hasInterval()&&this.clearInterval()}},l.onAudioTrackSwitched=function(e){var t=this.tracks[e.id].groupId;t&&this.audioGroupId!==t&&(this.audioGroupId=t)},l.onLevelLoaded=function(e){this._selectAudioGroup(e.level)},l.onError=function(e){e.type===o.b.NETWORK_ERROR&&(e.fatal&&this.clearInterval(),e.details===o.a.AUDIO_TRACK_LOAD_ERROR&&(u.b.warn("Network failure on audio-track id:",e.context.id),this._handleLoadError()))},l._setAudioTrack=function(e){if(this._trackId===e&&this.tracks[this._trackId].details)u.b.debug("Same id as current audio-track passed, and track details available -> no-op");else if(e<0||e>=this.tracks.length)u.b.warn("Invalid id passed to audio-track controller");else{var t=this.tracks[e];u.b.log("Now switching to audio-track index "+e),this.clearInterval(),this._trackId=e;var r=t.url,i=t.type,a=t.id;this.hls.trigger(d.a.AUDIO_TRACK_SWITCHING,{id:a,type:i,url:r}),this._loadTrackDetailsIfNeeded(t)}},l.doTick=function(){this._updateTrack(this._trackId)},l._selectAudioGroup=function(e){var t=this.hls.levels[e];if(t&&t.audioGroupIds){var r=t.audioGroupIds[t.urlId];this.audioGroupId!==r&&(this.audioGroupId=r,this._selectInitialAudioTrack())}},l._selectInitialAudioTrack=function(){var e=this,t=this.tracks;if(t.length){var r=this.tracks[this._trackId],i=null;if(r&&(i=r.name),this._selectDefaultTrack){var a=t.filter((function(e){return e.default}));a.length?t=a:u.b.warn("No default audio tracks defined")}var n=!1,s=function(){t.forEach((function(t){n||e.audioGroupId&&t.groupId!==e.audioGroupId||i&&i!==t.name||(e._setAudioTrack(t.id),n=!0)}))};s(),n||(i=null,s()),n||(u.b.error("No track found for running audio group-ID: "+this.audioGroupId),this.hls.trigger(d.a.ERROR,{type:o.b.MEDIA_ERROR,details:o.a.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))}},l._needsTrackLoading=function(e){var t=e.details,r=e.url;return!(t&&!t.live)&&!!r},l._loadTrackDetailsIfNeeded=function(e){if(this._needsTrackLoading(e)){var t=e.url,r=e.id;u.b.log("loading audio-track playlist for id: "+r),this.hls.trigger(d.a.AUDIO_TRACK_LOADING,{url:t,id:r})}},l._updateTrack=function(e){if(!(e<0||e>=this.tracks.length)){this.clearInterval(),this._trackId=e,u.b.log("trying to update audio-track "+e);var t=this.tracks[e];this._loadTrackDetailsIfNeeded(t)}},l._handleLoadError=function(){this.trackIdBlacklist[this._trackId]=!0;var e=this._trackId,t=this.tracks[e],r=t.name,i=t.language,a=t.groupId;u.b.warn("Loading failed on audio track id: "+e+", group-id: "+a+', name/language: "'+r+'" / "'+i+'"');for(var n=e,s=0;s0&&-1===e?(u.b.log("audio:override startPosition with lastCurrentTime @"+t.toFixed(3)),this.state=me):(this.lastCurrentTime=this.startPosition?this.startPosition:e,this.state=ve),this.nextLoadPosition=this.startPosition=this.lastCurrentTime,this.tick()}else this.startPosition=e,this.state=pe},c.doTick=function(){var e,t,r,i=this.hls,a=i.config;switch(this.state){case we:case ye:case Ae:break;case ve:this.state=Se,this.loadedmetadata=!1;break;case me:var n=this.tracks;if(!n)break;if(!this.media&&(this.startFragRequested||!a.startFragPrefetch))break;if(this.loadedmetadata)e=this.media.currentTime;else if(void 0===(e=this.nextLoadPosition))break;var s=this.mediaBuffer?this.mediaBuffer:this.media,o=this.videoBuffer?this.videoBuffer:this.media,c=eR||h.nextStart))return;u.b.log("alt audio track ahead of main track, seek to start of alt audio track"),this.media.currentTime=R+.05}if(r.initSegment&&!r.initSegment.data)E=r.initSegment;else if(p<=R){if(E=S[0],null!==this.videoTrackCC&&E.cc!==this.videoTrackCC&&(E=function(e,t){return j.search(e,(function(e){return e.cct?-1:0}))}(S,this.videoTrackCC)),r.live&&E.loadIdx&&E.loadIdx===this.fragLoadIdx){var k=h.nextStart?h.nextStart:R;return u.b.log("no alt audio available @currentTime:"+this.media.currentTime+", seeking @"+(k+.05)),void(this.media.currentTime=k+.05)}}else{var w,L=a.maxFragLookUpTolerance,D=v?S[v.sn-S[0].sn+1]:void 0;pA-L&&(L=0),w=D&&!ue(p,L,D)?D:j.search(S,(function(e){return ue(p,L,e)}))):w=S[_-1],w&&(E=w,R=w.start,v&&E.level===v.level&&E.sn===v.sn&&(E.sn=C||I)&&(u.b.log("audioStreamController: retryDate reached, switch back to IDLE state"),this.state=me);break;case Le:var P=this.waitingFragment;if(P){var x=P.frag.cc;if(void 0!==this.initPTS[x])this.waitingFragment=null,this.state=Te,this.onFragLoaded(P);else if(this.videoTrackCC!==this.waitingVideoCC)u.b.log("Waiting fragment cc ("+x+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var M=H.bufferInfo(this.mediaBuffer,this.media.currentTime,a.maxBufferHole);ue(M.end,a.maxFragLookUpTolerance,P.frag)<0&&(u.b.log("Waiting fragment cc ("+x+") @ "+P.frag.start+" cancelled because another fragment at "+M.end+" is needed"),this.clearWaitingFragment())}}else this.state=me}},c.clearWaitingFragment=function(){var e=this.waitingFragment;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingFragment=null,this.waitingVideoCC=null,this.state=me)},c.onMediaAttached=function(e){var t=this.media=this.mediaBuffer=e.media;this.onvseeking=this.onMediaSeeking.bind(this),this.onvended=this.onMediaEnded.bind(this),t.addEventListener("seeking",this.onvseeking),t.addEventListener("ended",this.onvended);var r=this.config;this.tracks&&r.autoStartLoad&&this.startLoad(r.startPosition)},c.onMediaDetaching=function(){var e=this.media;e&&e.ended&&(u.b.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),e&&(e.removeEventListener("seeking",this.onvseeking),e.removeEventListener("ended",this.onvended),this.onvseeking=this.onvseeked=this.onvended=null),this.media=this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()},c.onAudioTracksUpdated=function(e){u.b.log("audio tracks updated"),this.tracks=e.audioTracks},c.onAudioTrackSwitching=function(e){var t=!!e.url;this.trackId=e.id,this.fragCurrent=null,this.clearWaitingFragment(),this.state=ye,t?this.setInterval(100):this.demuxer&&(this.demuxer.destroy(),this.demuxer=null),t&&(this.audioSwitch=!0,this.state=me),this.tick()},c.onAudioTrackLoaded=function(e){var t=e.details,r=e.id,i=this.tracks[r],a=i.details,n=t.totalduration,s=0;if(u.b.log("track "+r+" loaded ["+t.startSN+","+t.endSN+"],duration:"+n),t.live||a&&a.live?a&&t.fragments.length>0?(re(a,t),s=t.fragments[0].start,t.PTSKnown?u.b.log("live audio playlist sliding:"+s.toFixed(3)):u.b.log("live audio playlist - outdated PTS, unknown sliding")):(t.PTSKnown=!1,u.b.log("live audio playlist - first load, unknown sliding")):t.PTSKnown=!1,i.details=t,!this.startFragRequested){if(-1===this.startPosition){var o=t.startTimeOffset;Object(l.a)(o)?(u.b.log("start time offset found in playlist, adjust startPosition to "+o),this.startPosition=o):t.live?(this.startPosition=this.computeLivePosition(s,t),u.b.log("compute startPosition for audio-track to "+this.startPosition)):this.startPosition=0}this.nextLoadPosition=this.startPosition}this.state===Se&&(this.state=me),this.tick()},c.onKeyLoaded=function(){this.state===be&&(this.state=me,this.tick())},c.onFragLoaded=function(e){var t=this.fragCurrent,r=e.frag;if(this.state===Te&&t&&"audio"===r.type&&r.level===t.level&&r.sn===t.sn){var i=this.tracks[this.trackId],a=i.details,n=a.totalduration,s=t.level,o=t.sn,l=t.cc,c=this.config.defaultAudioCodec||i.audioCodec||"mp4a.40.2",h=this.stats=e.stats;if("initSegment"===o)this.state=me,h.tparsed=h.tbuffered=tt.now(),a.initSegment.data=e.payload,this.hls.trigger(d.a.FRAG_BUFFERED,{stats:h,frag:t,id:"audio"}),this.tick();else{this.state=_e,this.appended=!1,this.demuxer||(this.demuxer=new J(this.hls,"audio"));var f=this.initPTS[l],g=a.initSegment?a.initSegment.data:[];if(void 0!==f){this.pendingBuffering=!0,u.b.log("Demuxing "+o+" of ["+a.startSN+" ,"+a.endSN+"],track "+s);this.demuxer.push(e.payload,g,c,null,t,n,!1,f)}else u.b.log("Unknown video PTS for cc "+l+", waiting for video PTS before demuxing audio frag "+o+" of ["+a.startSN+" ,"+a.endSN+"],track "+s),this.waitingFragment=e,this.waitingVideoCC=this.videoTrackCC,this.state=Le}}this.fragLoadError=0},c.onFragParsingInitSegment=function(e){var t=this.fragCurrent,r=e.frag;if(t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===_e){var i,a=e.tracks;if(a.video&&delete a.video,i=a.audio){i.levelCodec=i.codec,i.id=e.id,this.hls.trigger(d.a.BUFFER_CODECS,a),u.b.log("audio track:audio,container:"+i.container+",codecs[level/parsed]=["+i.levelCodec+"/"+i.codec+"]");var n=i.initSegment;if(n){var s={type:"audio",data:n,parent:"audio",content:"initSegment"};this.audioSwitch?this.pendingData=[s]:(this.appended=!0,this.pendingBuffering=!0,this.hls.trigger(d.a.BUFFER_APPENDING,s))}this.tick()}}},c.onFragParsingData=function(e){var t=this,r=this.fragCurrent,i=e.frag;if(r&&"audio"===e.id&&"audio"===e.type&&i.sn===r.sn&&i.level===r.level&&this.state===_e){var a=this.trackId,n=this.tracks[a],s=this.hls;Object(l.a)(e.endPTS)||(e.endPTS=e.startPTS+r.duration,e.endDTS=e.startDTS+r.duration),r.addElementaryStream(p.AUDIO),u.b.log("parsed "+e.type+",PTS:["+e.startPTS.toFixed(3)+","+e.endPTS.toFixed(3)+"],DTS:["+e.startDTS.toFixed(3)+"/"+e.endDTS.toFixed(3)+"],nb:"+e.nb),te(n.details,r,e.startPTS,e.endPTS);var c=this.media,h=!1;if(this.audioSwitch)if(c&&c.readyState){var f=c.currentTime;u.b.log("switching audio track : currentTime:"+f),f>=e.startPTS&&(u.b.log("switching audio track : flushing all audio"),this.state=Ae,s.trigger(d.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),h=!0,this.audioSwitch=!1,s.trigger(d.a.AUDIO_TRACK_SWITCHED,{id:a}))}else this.audioSwitch=!1,s.trigger(d.a.AUDIO_TRACK_SWITCHED,{id:a});var g=this.pendingData;if(!g)return u.b.warn("Apparently attempt to enqueue media payload without codec initialization data upfront"),void s.trigger(d.a.ERROR,{type:o.b.MEDIA_ERROR,details:null,fatal:!0});this.audioSwitch||([e.data1,e.data2].forEach((function(t){t&&t.length&&g.push({type:e.type,data:t,parent:"audio",content:"data"})})),!h&&g.length&&(g.forEach((function(e){t.state===_e&&(t.pendingBuffering=!0,t.hls.trigger(d.a.BUFFER_APPENDING,e))})),this.pendingData=[],this.appended=!0)),this.tick()}},c.onFragParsed=function(e){var t=this.fragCurrent,r=e.frag;t&&"audio"===e.id&&r.sn===t.sn&&r.level===t.level&&this.state===_e&&(this.stats.tparsed=tt.now(),this.state=Re,this._checkAppendedParsed())},c.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},c.onBufferCreated=function(e){var t=e.tracks.audio;t&&(this.mediaBuffer=t.buffer,this.loadedmetadata=!0),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer)},c.onBufferAppended=function(e){if("audio"===e.parent){var t=this.state;t!==_e&&t!==Re||(this.pendingBuffering=e.pending>0,this._checkAppendedParsed())}},c._checkAppendedParsed=function(){if(!(this.state!==Re||this.appended&&this.pendingBuffering)){var e=this.fragCurrent,t=this.stats,r=this.hls;if(e){this.fragPrevious=e,t.tbuffered=tt.now(),r.trigger(d.a.FRAG_BUFFERED,{stats:t,frag:e,id:"audio"});var i=this.mediaBuffer?this.mediaBuffer:this.media;i&&u.b.log("audio buffered : "+ne.toString(i.buffered)),this.audioSwitch&&this.appended&&(this.audioSwitch=!1,r.trigger(d.a.AUDIO_TRACK_SWITCHED,{id:this.trackId})),this.state=me}this.tick()}},c.onError=function(e){var t=e.frag;if(!t||"audio"===t.type)switch(e.details){case o.a.FRAG_LOAD_ERROR:case o.a.FRAG_LOAD_TIMEOUT:var r=e.frag;if(r&&"audio"!==r.type)break;if(!e.fatal){var i=this.fragLoadError;i?i++:i=1;var a=this.config;if(i<=a.fragLoadingMaxRetry){this.fragLoadError=i;var n=Math.min(Math.pow(2,i-1)*a.fragLoadingRetryDelay,a.fragLoadingMaxRetryTimeout);u.b.warn("AudioStreamController: frag loading failed, retry in "+n+" ms"),this.retryDate=tt.now()+n,this.state=Ee}else u.b.error("AudioStreamController: "+e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.state=we}break;case o.a.AUDIO_TRACK_LOAD_ERROR:case o.a.AUDIO_TRACK_LOAD_TIMEOUT:case o.a.KEY_LOAD_ERROR:case o.a.KEY_LOAD_TIMEOUT:this.state!==we&&(this.state=e.fatal?we:me,u.b.warn("AudioStreamController: "+e.details+" while loading frag, now switching to "+this.state+" state ..."));break;case o.a.BUFFER_FULL_ERROR:if("audio"===e.parent&&(this.state===_e||this.state===Re)){var s=this.mediaBuffer,l=this.media.currentTime;if(s&&H.isBuffered(s,l)&&H.isBuffered(s,l+.5)){var c=this.config;c.maxMaxBufferLength>=c.maxBufferLength&&(c.maxMaxBufferLength/=2,u.b.warn("AudioStreamController: reduce max buffer length to "+c.maxMaxBufferLength+"s")),this.state=me}else u.b.warn("AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,this.state=Ae,this.hls.trigger(d.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"})}}},c.onBufferFlushed=function(){var e=this,t=this.pendingData;t&&t.length?(u.b.log("AudioStreamController: appending pending audio data after buffer flushed"),t.forEach((function(t){e.hls.trigger(d.a.BUFFER_APPENDING,t)})),this.appended=!0,this.pendingData=[],this.state=Re):(this.state=me,this.fragPrevious=null,this.tick())},a=i,(n=[{key:"state",set:function(e){if(this.state!==e){var t=this.state;this._state=e,u.b.log("audio stream:"+t+"->"+e)}},get:function(){return this._state}}])&&et(a.prototype,n),s&&et(a,s),i}(Oe),it=function(){if("undefined"!=typeof window&&window.VTTCue)return window.VTTCue;var e={"":!0,lr:!0,rl:!0},t={start:!0,middle:!0,end:!0,left:!0,right:!0};function r(e){return"string"==typeof e&&(!!t[e.toLowerCase()]&&e.toLowerCase())}function i(e){for(var t=1;t100)throw new Error("Position must be between 0 and 100.");y=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"positionAlign",i({},o,{get:function(){return b},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");b=t,this.hasBeenReset=!0}})),Object.defineProperty(s,"size",i({},o,{get:function(){return T},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");T=e,this.hasBeenReset=!0}})),Object.defineProperty(s,"align",i({},o,{get:function(){return E},set:function(e){var t=r(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");E=t,this.hasBeenReset=!0}})),s.displayState=void 0}return a.prototype.getCueAsHTML=function(){return window.WebVTT.convertCueToDOMTree(window,this.text)},a}(),at=function(){return{decode:function(e){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}};function nt(){this.window=window,this.state="INITIAL",this.buffer="",this.decoder=new at,this.regionList=[]}function st(){this.values=Object.create(null)}function ot(e,t,r,i){var a=i?e.split(i):[e];for(var n in a)if("string"==typeof a[n]){var s=a[n].split(r);if(2===s.length)t(s[0],s[1])}}st.prototype={set:function(e,t){this.get(e)||""===t||(this.values[e]=t)},get:function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},has:function(e){return e in this.values},alt:function(e,t,r){for(var i=0;i=0&&t<=100)&&(this.set(e,t),!0)}};var lt=new it(0,0,0),dt="middle"===lt.align?"middle":"center";function ut(e,t,r){var i=e;function a(){var t=function(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+(0|i)/1e3}var r=e.match(/^(\d+):(\d{2})(:\d{2})?\.(\d{3})/);return r?r[3]?t(r[1],r[2],r[3].replace(":",""),r[4]):r[1]>59?t(r[1],r[2],0,r[4]):t(0,r[1],r[2],r[4]):null}(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function n(){e=e.replace(/^\s+/,"")}if(n(),t.startTime=a(),n(),"--\x3e"!==e.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.substr(3),n(),t.endTime=a(),n(),function(e,t){var i=new st;ot(e,(function(e,t){switch(e){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===t){i.set(e,r[a].region);break}break;case"vertical":i.alt(e,t,["rl","lr"]);break;case"line":var n=t.split(","),s=n[0];i.integer(e,s),i.percent(e,s)&&i.set("snapToLines",!1),i.alt(e,s,["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",dt,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",dt,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",dt,"end","left","right"])}}),/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var a=i.get("line","auto");"auto"===a&&-1===lt.line&&(a=-1),t.line=a,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",dt);var n=i.get("position","auto");"auto"===n&&50===lt.position&&(n="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=n}(e,t)}function ct(e){return e.replace(//gi,"\n")}nt.prototype={parse:function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=ct(e);r=16?o--:o++,navigator.userAgent.match(/Firefox\//)?n.line=c+1:n.line=c>7?c-2:c+1,n.align="left",n.position=Math.max(0,Math.min(100,o/32*100)),d.push(n),e&&e.addCue(n)}return d}var gt,pt={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},vt=function(e){var t=e;return pt.hasOwnProperty(e)&&(t=pt[e]),String.fromCharCode(t)},mt={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},yt={17:2,18:4,21:6,22:8,23:10,19:13,20:15},bt={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Tt={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Et=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];!function(e){e[e.ERROR=0]="ERROR",e[e.TEXT=1]="TEXT",e[e.WARNING=2]="WARNING",e[e.INFO=2]="INFO",e[e.DEBUG=3]="DEBUG",e[e.DATA=3]="DATA"}(gt||(gt={}));var St=function(){function e(){this.time=null,this.verboseLevel=gt.ERROR}return e.prototype.log=function(e,t){this.verboseLevel>=e&&u.b.log(this.time+" ["+e+"] "+t)},e}(),_t=function(e){for(var t=[],r=0;r100&&(this.logger.log(gt.DEBUG,"Too large cursor position "+this.pos),this.pos=100)},t.moveCursor=function(e){var t=this.pos+e;if(e>1)for(var r=this.pos+1;r=144&&this.backSpace();var t=vt(e);this.pos>=100?this.logger.log(gt.ERROR,"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t<100;t++)this.chars[t].reset()},t.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},t.clearToEndOfRow=function(){this.clearFromPos(this.pos)},t.getTextString=function(){for(var e=[],t=!0,r=0;r<100;r++){var i=this.chars[r].uchar;" "!==i&&(t=!1),e.push(i)}return t?"":e.join("")},t.setPenStyles=function(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)},e}(),wt=function(){function e(e){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(var t=0;t<15;t++)this.rows.push(new kt(e));this.logger=e,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}var t=e.prototype;return t.reset=function(){for(var e=0;e<15;e++)this.rows[e].clear();this.currRow=14},t.equals=function(e){for(var t=!0,r=0;r<15;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t},t.copy=function(e){for(var t=0;t<15;t++)this.rows[t].copy(e.rows[t])},t.isEmpty=function(){for(var e=!0,t=0;t<15;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e},t.backSpace=function(){this.rows[this.currRow].backSpace()},t.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},t.insertChar=function(e){this.rows[this.currRow].insertChar(e)},t.setPen=function(e){this.rows[this.currRow].setPenStyles(e)},t.moveCursor=function(e){this.rows[this.currRow].moveCursor(e)},t.setCursor=function(e){this.logger.log(gt.INFO,"setCursor: "+e),this.rows[this.currRow].setCursor(e)},t.setPAC=function(e){this.logger.log(gt.INFO,"pacData = "+JSON.stringify(e));var t=e.row-1;if(this.nrRollUpRows&&t0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},t.getTextAndFormat=function(){return this.rows},e}(),Lt=function(){function e(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new wt(r),this.nonDisplayedMemory=new wt(r),this.lastOutputScreen=new wt(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var t=e.prototype;return t.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},t.getHandler=function(){return this.outputFilter},t.setHandler=function(e){this.outputFilter=e},t.setPAC=function(e){this.writeScreen.setPAC(e)},t.setBkgData=function(e){this.writeScreen.setBkgData(e)},t.setMode=function(e){e!==this.mode&&(this.mode=e,this.logger.log(gt.INFO,"MODE="+e),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)},t.insertChars=function(e){for(var t=0;t=46,t.italics)t.foreground="white";else{var r=Math.floor(e/2)-16;t.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(gt.INFO,"MIDROW: "+JSON.stringify(t)),this.writeScreen.setPen(t)},t.outputDataUpdate=function(e){void 0===e&&(e=!1);var t=this.logger.time;null!==t&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t):this.cueStartTime=t,this.lastOutputScreen.copy(this.displayedMemory))},t.cueSplitAtTime=function(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))},e}();function Dt(e,t,r){r.a=e,r.b=t}function Ot(e,t,r){return r.a===e&&r.b===t}var Ct=function(){function e(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new St;this.channels=[null,new Lt(e,t,i),new Lt(e+1,r,i)],this.cmdHistory={a:null,b:null},this.logger=i}var t=e.prototype;return t.getHandler=function(e){return this.channels[e].getHandler()},t.setHandler=function(e,t){this.channels[e].setHandler(t)},t.addData=function(e,t){var r,i,a,n=!1;this.logger.time=e;for(var s=0;s ("+_t([i,a])+")"),(r=this.parseCmd(i,a))||(r=this.parseMidrow(i,a)),r||(r=this.parsePAC(i,a)),r||(r=this.parseBackgroundAttributes(i,a)),!r&&(n=this.parseChars(i,a))){var o=this.currentChannel;if(o&&o>0)this.channels[o].insertChars(n);else this.logger.log(gt.WARNING,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(gt.WARNING,"Couldn't parse cleaned data "+_t([i,a])+" orig: "+_t([t[s],t[s+1]]))}},t.parseCmd=function(e,t){var r=this.cmdHistory;if(!((20===e||28===e||21===e||29===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=33&&t<=35))return!1;if(Ot(e,t,r))return Dt(null,null,r),this.logger.log(gt.DEBUG,"Repeated command ("+_t([e,t])+") is dropped"),!0;var i=20===e||21===e||23===e?1:2,a=this.channels[i];return 20===e||21===e||28===e||29===e?32===t?a.ccRCL():33===t?a.ccBS():34===t?a.ccAOF():35===t?a.ccAON():36===t?a.ccDER():37===t?a.ccRU(2):38===t?a.ccRU(3):39===t?a.ccRU(4):40===t?a.ccFON():41===t?a.ccRDC():42===t?a.ccTR():43===t?a.ccRTD():44===t?a.ccEDM():45===t?a.ccCR():46===t?a.ccENM():47===t&&a.ccEOC():a.ccTO(t-32),Dt(e,t,r),this.currentChannel=i,!0},t.parseMidrow=function(e,t){var r=0;if((17===e||25===e)&&t>=32&&t<=47){if((r=17===e?1:2)!==this.currentChannel)return this.logger.log(gt.ERROR,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(gt.DEBUG,"MIDROW ("+_t([e,t])+")"),!0)}return!1},t.parsePAC=function(e,t){var r,i=this.cmdHistory;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127)&&!((16===e||24===e)&&t>=64&&t<=95))return!1;if(Ot(e,t,i))return Dt(null,null,i),!0;var a=e<=23?1:2;r=t>=64&&t<=95?1===a?mt[e]:bt[e]:1===a?yt[e]:Tt[e];var n=this.channels[a];return!!n&&(n.setPAC(this.interpretPAC(r,t)),Dt(e,t,i),this.currentChannel=a,!0)},t.interpretPAC=function(e,t){var r=t,i={color:null,italics:!1,indent:null,underline:!1,row:e};return r=t>95?t-96:t-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},t.parseChars=function(e,t){var r,i=null,a=null;if(e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19){var n=t;n=17===a?t+80:18===a?t+112:t+144,this.logger.log(gt.INFO,"Special char '"+vt(n)+"' in channel "+r),i=[n]}else e>=32&&e<=127&&(i=0===t?[e]:[e,t]);if(i){var s=_t(i);this.logger.log(gt.DEBUG,"Char codes = "+s.join(",")),Dt(e,t,this.cmdHistory)}return i},t.parseBackgroundAttributes=function(e,t){var r;if(!((16===e||24===e)&&t>=32&&t<=47)&&!((23===e||31===e)&&t>=45&&t<=47))return!1;var i={};16===e||24===e?(r=Math.floor((t-32)/2),i.background=Et[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var a=e<=23?1:2;return this.channels[a].setBkgData(i),Dt(e,t,this.cmdHistory),!0},t.reset=function(){for(var e=0;ee)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},t.reset=function(){this.cueRanges=[]},e}(),Pt=function(e,t,r){return e.substr(r||0,t.length)===t},xt=function(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()},Mt={parse:function(e,t,r,i,a,n){var s,o=Object(Fe.b)(new Uint8Array(e)).trim().replace(/\r\n|\n\r|\n|\r/g,"\n").split("\n"),d="00:00.000",u=0,c=0,h=0,f=[],g=!0,p=!1,v=new ht;v.oncue=function(e){var t=r[i],a=r.ccOffset;t&&t.new&&(void 0!==c?a=r.ccOffset=t.start:function(e,t,r){var i=e[t],a=e[i.prevCC];if(!a||!a.new&&i.new)return e.ccOffset=e.presentationOffset=i.start,void(i.new=!1);for(;a&&a.new;)e.ccOffset+=i.start-a.start,i.new=!1,a=e[(i=a).prevCC];e.presentationOffset=r}(r,i,h)),h&&(a=h-r.presentationOffset),p&&(e.startTime+=a-c,e.endTime+=a-c),e.id=xt(e.startTime.toString())+xt(e.endTime.toString())+xt(e.text),e.text=decodeURIComponent(encodeURIComponent(e.text)),e.endTime>0&&f.push(e)},v.onparsingerror=function(e){s=e},v.onflush=function(){s&&n?n(s):a(f)},o.forEach((function(e){if(g){if(Pt(e,"X-TIMESTAMP-MAP=")){g=!1,p=!0,e.substr(16).split(",").forEach((function(e){Pt(e,"LOCAL:")?d=e.substr(6):Pt(e,"MPEGTS:")&&(u=parseInt(e.substr(7)))}));try{t+(9e4*r[i].start||0)<0&&(t+=8589934592),u-=t,c=function(e){var t=parseInt(e.substr(-3)),r=parseInt(e.substr(-6,2)),i=parseInt(e.substr(-9,2)),a=e.length>9?parseInt(e.substr(0,e.indexOf(":"))):0;if(!(Object(l.a)(t)&&Object(l.a)(r)&&Object(l.a)(i)&&Object(l.a)(a)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*r,t+=6e4*i,t+=36e5*a}(d)/1e3,h=u/9e4}catch(e){p=!1,s=e}return}""===e&&(g=!1)}v.parse(e+"\n")})),v.flush()}};function Ft(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function Ut(e,t){return e&&e.label===t.name&&!(e.textTrack1||e.textTrack2)}var Nt=function(e){var t,r;function i(t){var r;if((r=e.call(this,t,d.a.MEDIA_ATTACHING,d.a.MEDIA_DETACHING,d.a.FRAG_PARSING_USERDATA,d.a.FRAG_DECRYPTED,d.a.MANIFEST_LOADING,d.a.MANIFEST_LOADED,d.a.FRAG_LOADED,d.a.INIT_PTS_FOUND)||this).media=null,r.config=void 0,r.enabled=!0,r.Cues=void 0,r.textTracks=[],r.tracks=[],r.initPTS=[],r.unparsedVttFrags=[],r.captionsTracks={},r.nonNativeCaptionsTracks={},r.captionsProperties=void 0,r.cea608Parser1=void 0,r.cea608Parser2=void 0,r.lastSn=-1,r.prevCC=-1,r.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!1}},r.hls=t,r.config=t.config,r.Cues=t.config.cueHandler,r.captionsProperties={textTrack1:{label:r.config.captionsTextTrack1Label,languageCode:r.config.captionsTextTrack1LanguageCode},textTrack2:{label:r.config.captionsTextTrack2Label,languageCode:r.config.captionsTextTrack2LanguageCode},textTrack3:{label:r.config.captionsTextTrack3Label,languageCode:r.config.captionsTextTrack3LanguageCode},textTrack4:{label:r.config.captionsTextTrack4Label,languageCode:r.config.captionsTextTrack4LanguageCode}},r.config.enableCEA708Captions){var i=new It(Ft(r),"textTrack1"),a=new It(Ft(r),"textTrack2"),n=new It(Ft(r),"textTrack3"),s=new It(Ft(r),"textTrack4");r.cea608Parser1=new Ct(1,i,a),r.cea608Parser2=new Ct(3,n,s)}return r}r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r;var a=i.prototype;return a.addCues=function(e,t,r,i,a){for(var n,s,o,l,u=!1,c=a.length;c--;){var h=a[c],f=(n=h[0],s=h[1],o=t,l=r,Math.min(s,l)-Math.max(n,o));if(f>=0&&(h[0]=Math.min(h[0],t),h[1]=Math.max(h[1],r),u=!0,f/(r-t)>.5))return}if(u||a.push([t,r]),this.config.renderTextTracksNatively)this.Cues.newCue(this.captionsTracks[e],t,r,i);else{var g=this.Cues.newCue(null,t,r,i);this.hls.trigger(d.a.CUES_PARSED,{type:"captions",cues:g,track:e})}},a.onInitPtsFound=function(e){var t=this,r=e.frag,i=e.id,a=e.initPTS,n=this.unparsedVttFrags;"main"===i&&(this.initPTS[r.cc]=a),n.length&&(this.unparsedVttFrags=[],n.forEach((function(e){t.onFragLoaded(e)})))},a.getExistingTrack=function(e){var t=this.media;if(t)for(var r=0;r=n.length||r!==a||!s||this.stopped)this._clearReloadTimer();else if(u.b.log("subtitle track "+r+" loaded"),i.live){var o=ae(s.details,i,e.stats.trequest);u.b.log("Reloading live subtitle playlist in "+o+"ms"),this.timer=setTimeout((function(){t._loadCurrentTrack()}),o)}else this._clearReloadTimer()},o.startLoad=function(){this.stopped=!1,this._loadCurrentTrack()},o.stopLoad=function(){this.stopped=!0,this._clearReloadTimer()},o._clearReloadTimer=function(){this.timer&&(clearTimeout(this.timer),this.timer=null)},o._loadCurrentTrack=function(){var e=this.trackId,t=this.tracks,r=this.hls,i=t[e];e<0||!i||i.details&&!i.details.live||(u.b.log("Loading subtitle track "+e),r.trigger(d.a.SUBTITLE_TRACK_LOADING,{url:i.url,id:e}))},o._toggleTrackModes=function(e){var t=this.media,r=this.subtitleDisplay,i=this.trackId;if(t){var a=Gt(t.textTracks);if(-1===e)[].slice.call(a).forEach((function(e){e.mode="disabled"}));else{var n=a[i];n&&(n.mode="disabled")}var s=a[e];s&&(s.mode=r?"showing":"hidden")}},o._setSubtitleTrackInternal=function(e){var t=this.hls,r=this.tracks;!Object(l.a)(e)||e<-1||e>=r.length||(this.trackId=e,u.b.log("Switching to subtitle track "+e),t.trigger(d.a.SUBTITLE_TRACK_SWITCH,{id:e}),this._loadCurrentTrack())},o._onTextTracksChanged=function(){if(this.media&&this.hls.config.renderTextTracksNatively){for(var e=-1,t=Gt(this.media.textTracks),r=0;r=i[s].start&&n<=i[s].end){a=i[s];break}var o=t.start+t.duration;a?a.end=o:(a={start:n,end:o},i.push(a))}}},a.onMediaAttached=function(e){var t=e.media;this.media=t,t.addEventListener("seeking",this._onMediaSeeking),this.state=me},a.onMediaDetaching=function(){var e=this;this.media&&(this.media.removeEventListener("seeking",this._onMediaSeeking),this.fragmentTracker.removeAllFragments(),this.currentTrackId=-1,this.tracks.forEach((function(t){e.tracksBuffered[t.id]=[]})),this.media=null,this.state=pe)},a.onError=function(e){var t=e.frag;t&&"subtitle"===t.type&&(this.fragCurrent&&this.fragCurrent.loader&&this.fragCurrent.loader.abort(),this.state=me)},a.onSubtitleTracksUpdated=function(e){var t=this;u.b.log("subtitle tracks updated"),this.tracksBuffered=[],this.tracks=e.subtitleTracks,this.tracks.forEach((function(e){t.tracksBuffered[e.id]=[]}))},a.onSubtitleTrackSwitch=function(e){if(this.currentTrackId=e.id,this.tracks&&this.tracks.length&&-1!==this.currentTrackId){var t=this.tracks[this.currentTrackId];t&&t.details&&this.setInterval(500)}else this.clearInterval()},a.onSubtitleTrackLoaded=function(e){var t=e.id,r=e.details,i=this.currentTrackId,a=this.tracks,n=a[i];t>=a.length||t!==i||!n||(r.live&&function(e,t,r){void 0===r&&(r=0);var i=-1;ie(e,t,(function(e,t,r){t.start=e.start,i=r}));var a=t.fragments;if(i<0)a.forEach((function(e){e.start+=r}));else for(var n=i+1;n0&&r&&r.key&&"AES-128"===r.method){var n=Vt.now();this.decrypter.decrypt(e.payload,r.key.buffer,r.iv.buffer,(function(e){var t=Vt.now();a.trigger(d.a.FRAG_DECRYPTED,{frag:i,payload:e,stats:{tstart:n,tdecrypt:t}})}))}},a.onLevelUpdated=function(e){var t=e.details.fragments;this.lastAVStart=t.length?t[0].start:0},a.doTick=function(){if(this.media)switch(this.state){case me:var e=this.config,t=this.currentTrackId,r=this.fragmentTracker,i=this.media,a=this.tracks;if(!a||!a[t]||!a[t].details)break;var n,s=e.maxBufferHole,o=e.maxFragLookUpTolerance,l=Math.min(e.maxBufferLength,e.maxMaxBufferLength),c=H.bufferedInfo(this._getBuffered(),i.currentTime,s),h=c.end,f=c.len,g=a[t].details,p=g.fragments,v=p.length,m=p[v-1].start+p[v-1].duration;if(f>l)return;var y=this.fragPrevious;hi)&&(this.fragCurrent.loader&&this.fragCurrent.loader.abort(),this.fragmentTracker.removeFragment(this.fragCurrent),this.fragCurrent=null,this.fragPrevious=null,this.state=me,this.tick())}},i}(Oe);!function(e){e.WIDEVINE="com.widevine.alpha",e.PLAYREADY="com.microsoft.playready"}(Ht||(Ht={}));var Wt="undefined"!=typeof window&&window.navigator&&window.navigator.requestMediaKeySystemAccess?window.navigator.requestMediaKeySystemAccess.bind(window.navigator):null;function qt(e,t){for(var r=0;r3)return void this.hls.trigger(d.a.ERROR,{type:o.b.KEY_SYSTEM_ERROR,details:o.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0});var a=3-this._requestLicenseFailureCount+1;u.b.warn("Retrying license request, "+a+" attempts left"),this._requestLicense(r,i)}}},l._generateLicenseRequestChallenge=function(e,t){switch(e.mediaKeySystemDomain){case Ht.WIDEVINE:return t}throw new Error("unsupported key-system: "+e.mediaKeySystemDomain)},l._requestLicense=function(e,t){u.b.log("Requesting content license for key-system");var r=this._mediaKeysList[0];if(!r)return u.b.error("Fatal error: Media is encrypted but no key-system access has been obtained yet"),void this.hls.trigger(d.a.ERROR,{type:o.b.KEY_SYSTEM_ERROR,details:o.a.KEY_SYSTEM_NO_ACCESS,fatal:!0});try{var i=this.getLicenseServerUrl(r.mediaKeySystemDomain),a=this._createLicenseXhr(i,e,t);u.b.log("Sending license request to URL: "+i);var n=this._generateLicenseRequestChallenge(r,e);a.send(n)}catch(e){u.b.error("Failure requesting DRM license: "+e),this.hls.trigger(d.a.ERROR,{type:o.b.KEY_SYSTEM_ERROR,details:o.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}},l.onMediaAttached=function(e){if(this._emeEnabled){var t=e.media;this._media=t,t.addEventListener("encrypted",this._onMediaEncrypted)}},l.onMediaDetached=function(){var e=this._media,t=this._mediaKeysList;e&&(e.removeEventListener("encrypted",this._onMediaEncrypted),this._media=null,this._mediaKeysList=[],Promise.all(t.map((function(e){if(e.mediaKeysSession)return e.mediaKeysSession.close().catch((function(){}))}))).then((function(){return e.setMediaKeys(null)})).catch((function(){})))},l.onManifestParsed=function(e){if(this._emeEnabled){var t=e.levels.map((function(e){return e.audioCodec})),r=e.levels.map((function(e){return e.videoCodec}));this._attemptKeySystemAccess(Ht.WIDEVINE,t,r)}},a=i,(n=[{key:"requestMediaKeySystemAccess",get:function(){if(!this._requestMediaKeySystemAccess)throw new Error("No requestMediaKeySystemAccess function configured");return this._requestMediaKeySystemAccess}}])&&qt(a.prototype,n),s&&qt(a,s),i}(h);function zt(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function Qt(e){for(var t=1;tt)return i}return 0}},{key:"maxAutoLevel",get:function(){var e=this.levels,t=this.autoLevelCapping;return-1===t&&e&&e.length?e.length-1:t}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(e){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,e)}},{key:"audioTracks",get:function(){var e=this.audioTrackController;return e?e.audioTracks:[]}},{key:"audioTrack",get:function(){var e=this.audioTrackController;return e?e.audioTrack:-1},set:function(e){var t=this.audioTrackController;t&&(t.audioTrack=e)}},{key:"liveSyncPosition",get:function(){return this.streamController.liveSyncPosition}},{key:"subtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var e=this.subtitleTrackController;return e?e.subtitleTrack:-1},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}}]),i}(z);nr.defaultConfig=void 0}]).default})); -//# sourceMappingURL=hls.min.js.map \ No newline at end of file diff --git a/trunk/research/players/js/hls-1.4.14.min.js b/trunk/research/players/js/hls-1.4.14.min.js new file mode 100644 index 0000000000..3e1958bb97 --- /dev/null +++ b/trunk/research/players/js/hls-1.4.14.min.js @@ -0,0 +1,2 @@ +!function t(e){var r,i;r=this,i=function(){"use strict";function r(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);e&&(i=i.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,i)}return r}function i(t){for(var e=1;et.length)&&(e=t.length);for(var r=0,i=new Array(e);r=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function m(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var r=t[Symbol.toPrimitive];if(void 0!==r){var i=r.call(t,e||"default");if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}function p(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var y={exports:{}};!function(t,e){var r,i,n,a,s;r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,n=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,s={buildAbsoluteURL:function(t,e,r){if(r=r||{},t=t.trim(),!(e=e.trim())){if(!r.alwaysNormalize)return t;var n=s.parseURL(t);if(!n)throw new Error("Error trying to parse base URL.");return n.path=s.normalizePath(n.path),s.buildURLFromParts(n)}var a=s.parseURL(e);if(!a)throw new Error("Error trying to parse relative URL.");if(a.scheme)return r.alwaysNormalize?(a.path=s.normalizePath(a.path),s.buildURLFromParts(a)):e;var o=s.parseURL(t);if(!o)throw new Error("Error trying to parse base URL.");if(!o.netLoc&&o.path&&"/"!==o.path[0]){var l=i.exec(o.path);o.netLoc=l[1],o.path=l[2]}o.netLoc&&!o.path&&(o.path="/");var u={scheme:o.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(u.netLoc=o.netLoc,"/"!==a.path[0]))if(a.path){var h=o.path,d=h.substring(0,h.lastIndexOf("/")+1)+a.path;u.path=s.normalizePath(d)}else u.path=o.path,a.params||(u.params=o.params,a.query||(u.query=o.query));return null===u.path&&(u.path=r.alwaysNormalize?s.normalizePath(a.path):a.path),s.buildURLFromParts(u)},parseURL:function(t){var e=r.exec(t);return e?{scheme:e[1]||"",netLoc:e[2]||"",path:e[3]||"",params:e[4]||"",query:e[5]||"",fragment:e[6]||""}:null},normalizePath:function(t){for(t=t.split("").reverse().join("").replace(n,"");t.length!==(t=t.replace(a,"")).length;);return t.split("").reverse().join("")},buildURLFromParts:function(t){return t.scheme+t.netLoc+t.path+t.params+t.query+t.fragment}},t.exports=s}(y);var T=y.exports,E=Number.isFinite||function(t){return"number"==typeof t&&isFinite(t)},S=Number.isSafeInteger||function(t){return"number"==typeof t&&Math.abs(t)<=L},L=Number.MAX_SAFE_INTEGER||9007199254740991,R=function(t){return t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached",t}({}),A=function(t){return t.NETWORK_ERROR="networkError",t.MEDIA_ERROR="mediaError",t.KEY_SYSTEM_ERROR="keySystemError",t.MUX_ERROR="muxError",t.OTHER_ERROR="otherError",t}({}),k=function(t){return t.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",t.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",t.KEY_SYSTEM_NO_SESSION="keySystemNoSession",t.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",t.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",t.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",t.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",t.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",t.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",t.MANIFEST_LOAD_ERROR="manifestLoadError",t.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",t.MANIFEST_PARSING_ERROR="manifestParsingError",t.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",t.LEVEL_EMPTY_ERROR="levelEmptyError",t.LEVEL_LOAD_ERROR="levelLoadError",t.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",t.LEVEL_PARSING_ERROR="levelParsingError",t.LEVEL_SWITCH_ERROR="levelSwitchError",t.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",t.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",t.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",t.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",t.FRAG_LOAD_ERROR="fragLoadError",t.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",t.FRAG_DECRYPT_ERROR="fragDecryptError",t.FRAG_PARSING_ERROR="fragParsingError",t.FRAG_GAP="fragGap",t.REMUX_ALLOC_ERROR="remuxAllocError",t.KEY_LOAD_ERROR="keyLoadError",t.KEY_LOAD_TIMEOUT="keyLoadTimeOut",t.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",t.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",t.BUFFER_APPEND_ERROR="bufferAppendError",t.BUFFER_APPENDING_ERROR="bufferAppendingError",t.BUFFER_STALLED_ERROR="bufferStalledError",t.BUFFER_FULL_ERROR="bufferFullError",t.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",t.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",t.INTERNAL_EXCEPTION="internalException",t.INTERNAL_ABORTED="aborted",t.UNKNOWN="unknown",t}({}),b=function(){},D={trace:b,debug:b,log:b,warn:b,info:b,error:b},I=D;function w(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):b}function C(t,e){if(self.console&&!0===t||"object"==typeof t){!function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;iNumber.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=P.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(x.lastIndex=0;null!==(e=x.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1].trim()]=i}return r},t}();function M(t){return"SCTE35-OUT"===t||"SCTE35-IN"===t}var O=function(){function t(t,e){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,e){var r=e.attr;for(var i in r)if(Object.prototype.hasOwnProperty.call(t,i)&&t[i]!==r[i]){_.warn('DATERANGE tag attribute: "'+i+'" does not match for tags with ID: "'+t.ID+'"'),this._badValueForSameId=i;break}t=o(new F({}),r,t)}if(this.attr=t,this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){var n=new Date(this.attr["END-DATE"]);E(n.getTime())&&(this._endDate=n)}}return a(t,[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){if(this._endDate)return this._endDate;var t=this.duration;return null!==t?new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var t=this.attr.decimalFloatingPoint("DURATION");if(E(t))return t}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}},{key:"plannedDuration",get:function(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}},{key:"endOnNext",get:function(){return this.attr.bool("END-ON-NEXT")}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&E(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)}}]),t}(),N=function(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}},U="audio",B="video",G="audiovideo",K=function(){function t(t){var e;this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams=((e={})[U]=null,e[B]=null,e[G]=null,e),this.baseurl=t}return t.prototype.setByteRange=function(t,e){var r=t.split("@",2),i=[];1===r.length?i[0]=e?e.byteRangeEndOffset:0:i[0]=parseInt(r[1]),i[1]=parseInt(r[0])+i[0],this._byteRange=i},a(t,[{key:"byteRange",get:function(){return this._byteRange?this._byteRange:[]}},{key:"byteRangeStartOffset",get:function(){return this.byteRange[0]}},{key:"byteRangeEndOffset",get:function(){return this.byteRange[1]}},{key:"url",get:function(){return!this._url&&this.baseurl&&this.relurl&&(this._url=T.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""},set:function(t){this._url=t}}]),t}(),H=function(t){function e(e,r){var i;return(i=t.call(this,r)||this)._decryptdata=null,i.rawProgramDateTime=null,i.programDateTime=null,i.tagList=[],i.duration=0,i.sn=0,i.levelkeys=void 0,i.type=void 0,i.loader=null,i.keyLoader=null,i.level=-1,i.cc=0,i.startPTS=void 0,i.endPTS=void 0,i.startDTS=void 0,i.endDTS=void 0,i.start=0,i.deltaPTS=void 0,i.maxStartPTS=void 0,i.minEndPTS=void 0,i.stats=new N,i.urlId=0,i.data=void 0,i.bitrateTest=!1,i.title=null,i.initSegment=null,i.endList=void 0,i.gap=void 0,i.type=e,i}l(e,t);var r=e.prototype;return r.setKeyFormat=function(t){if(this.levelkeys){var e=this.levelkeys[t];e&&!this._decryptdata&&(this._decryptdata=e.getDecryptData(this.sn))}},r.abortRequests=function(){var t,e;null==(t=this.loader)||t.abort(),null==(e=this.keyLoader)||e.abort()},r.setElementaryStreamInfo=function(t,e,r,i,n,a){void 0===a&&(a=!1);var s=this.elementaryStreams,o=s[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,n)):s[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:n,partial:a}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[U]=null,t[B]=null,t[G]=null},a(e,[{key:"decryptdata",get:function(){if(!this.levelkeys&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){var t=this.levelkeys.identity;if(t)this._decryptdata=t.getDecryptData(this.sn);else{var e=Object.keys(this.levelkeys);if(1===e.length)return this._decryptdata=this.levelkeys[e[0]].getDecryptData(this.sn)}}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!E(this.programDateTime))return null;var t=E(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;if(null!=(t=this._decryptdata)&&t.encrypted)return!0;if(this.levelkeys){var e=Object.keys(this.levelkeys),r=e.length;if(r>1||1===r&&this.levelkeys[e[0]].encrypted)return!0}return!1}}]),e}(K),V=function(t){function e(e,r,i,n,a){var s;(s=t.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new N,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=n;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return l(e,t),a(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(K),Y=function(){function t(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}return t.prototype.reloaded=function(t){if(!t)return this.advanced=!0,void(this.updated=!0);var e=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!e||!this.live,this.advanced=this.endSN>t.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},a(t,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&E(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!=(t=this.fragments)&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!=(t=this.partList)&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}]),t}();function W(t){return Uint8Array.from(atob(t),(function(t){return t.charCodeAt(0)}))}function j(t){var e,r,i=t.split(":"),n=null;if("data"===i[0]&&2===i.length){var a=i[1].split(";"),s=a[a.length-1].split(",");if(2===s.length){var o="base64"===s[0],l=s[1];o?(a.splice(-1,1),n=W(l)):(e=q(l).subarray(0,16),(r=new Uint8Array(16)).set(e,16-e.length),n=r)}}return n}function q(t){return Uint8Array.from(unescape(encodeURIComponent(t)),(function(t){return t.charCodeAt(0)}))}var X={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},z="org.w3.clearkey",Q="com.apple.streamingkeydelivery",$="com.microsoft.playready",J="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Z(t){switch(t){case Q:return X.FAIRPLAY;case $:return X.PLAYREADY;case J:return X.WIDEVINE;case z:return X.CLEARKEY}}var tt="edef8ba979d64acea3c827dcd51d21ed";function et(t){switch(t){case X.FAIRPLAY:return Q;case X.PLAYREADY:return $;case X.WIDEVINE:return J;case X.CLEARKEY:return z}}function rt(t){var e=t.drmSystems,r=t.widevineLicenseUrl,i=e?[X.FAIRPLAY,X.WIDEVINE,X.PLAYREADY,X.CLEARKEY].filter((function(t){return!!e[t]})):[];return!i[X.WIDEVINE]&&r&&i.push(X.WIDEVINE),i}var it="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function nt(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}var at,st=function(t,e){return e+10<=t.length&&73===t[e]&&68===t[e+1]&&51===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},ot=function(t,e){return e+10<=t.length&&51===t[e]&&68===t[e+1]&&73===t[e+2]&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128},lt=function(t,e){for(var r=e,i=0;st(t,e);)i+=10,i+=ut(t,e+6),ot(t,e+10)&&(i+=10),e+=i;if(i>0)return t.subarray(r,r+i)},ut=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},ht=function(t,e){return st(t,e)&&ut(t,e+6)+10<=t.length-e},dt=function(t){return t&&"PRIV"===t.key&&"com.apple.streaming.transportStreamTimestamp"===t.info},ct=function(t){var e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=ut(t,4);return{type:e,size:r,data:t.subarray(10,10+r)}},ft=function(t){for(var e=0,r=[];st(t,e);){for(var i=ut(t,e+6),n=(e+=10)+i;e+8>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(a);break;case 12:case 13:s=t[h++],u+=String.fromCharCode((31&a)<<6|63&s);break;case 14:s=t[h++],o=t[h++],u+=String.fromCharCode((15&a)<<12|(63&s)<<6|(63&o)<<0)}}return u};function Et(){if(!navigator.userAgent.includes("PlayStation 4"))return at||void 0===self.TextDecoder||(at=new self.TextDecoder("utf-8")),at}var St=function(t){for(var e="",r=0;r>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function Ct(t,e){var r=[];if(!e.length)return r;for(var i=t.byteLength,n=0;n1?n+a:i;if(kt(t.subarray(n+4,n+8))===e[0])if(1===e.length)r.push(t.subarray(n+8,s));else{var o=Ct(t.subarray(n+8,s),e.slice(1));o.length&&Rt.apply(r,o)}n=s}return r}function _t(t){var e=[],r=t[0],i=8,n=Dt(t,i);i+=4,i+=0===r?8:16,i+=2;var a=t.length+0,s=bt(t,i);i+=2;for(var o=0;o>>31)return _.warn("SIDX has hierarchical references (not supported)"),null;var d=Dt(t,l);l+=4,e.push({referenceSize:h,subsegmentDuration:d,info:{duration:d/n,start:a,end:a+h-1}}),a+=h,i=l+=4}return{earliestPresentationTime:0,timescale:n,version:r,referencesCount:s,references:e}}function Pt(t){for(var e=[],r=Ct(t,["moov","trak"]),i=0;i>1&63;return 39===r||40===r}return 6==(31&e)}function Ut(t,e,r,i){var n=Bt(t),a=0;a+=e;for(var s=0,o=0,l=!1,u=0;a=n.length)break;s+=u=n[a++]}while(255===u);o=0;do{if(a>=n.length)break;o+=u=n[a++]}while(255===u);var h=n.length-a;if(!l&&4===s&&a16){for(var T=[],E=0;E<16;E++){var S=n[a++].toString(16);T.push(1==S.length?"0"+S:S),3!==E&&5!==E&&7!==E&&9!==E||T.push("-")}for(var L=o-16,R=new Uint8Array(L),A=0;Ah)break}}function Bt(t){for(var e=t.byteLength,r=[],i=1;i0?(a=new Uint8Array(4),e.length>0&&new DataView(a.buffer).setUint32(0,e.length,!1)):a=new Uint8Array;var l=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(l.buffer).setUint32(0,r.byteLength,!1),function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(t,4),s=0,a=8;s>8*(15-r)&255;return e}(e);return new t(this.method,this.uri,"identity",this.keyFormatVersions,r)}var i=j(this.uri);if(i)switch(this.keyFormat){case J:this.pssh=i,i.length>=22&&(this.keyId=i.subarray(i.length-22,i.length-6));break;case $:var n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Gt(n,null,i);var a=new Uint16Array(i.buffer,i.byteOffset,i.byteLength/2),s=String.fromCharCode.apply(null,Array.from(a)),o=s.substring(s.indexOf("<"),s.length),l=(new DOMParser).parseFromString(o,"text/xml").getElementsByTagName("KID")[0];if(l){var u=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(u){var h=W(u).subarray(0,16);!function(t){var e=function(t,e,r){var i=t[e];t[e]=t[r],t[r]=i};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}(h),this.keyId=h}}break;default:var d=i.subarray(0,16);if(16!==d.length){var c=new Uint8Array(16);c.set(d,16-d.length),d=c}this.keyId=d}if(!this.keyId||16!==this.keyId.byteLength){var f=Kt[this.uri];if(!f){var g=Object.keys(Kt).length%Number.MAX_SAFE_INTEGER;f=new Uint8Array(16),new DataView(f.buffer,12,4).setUint32(0,g),Kt[this.uri]=f}this.keyId=f}return this},t}(),Vt=/\{\$([a-zA-Z0-9-_]+)\}/g;function Yt(t){return Vt.test(t)}function Wt(t,e,r){if(null!==t.variableList||t.hasVariableRefs)for(var i=r.length;i--;){var n=r[i],a=e[n];a&&(e[n]=jt(t,a))}}function jt(t,e){if(null!==t.variableList||t.hasVariableRefs){var r=t.variableList;return e.replace(Vt,(function(e){var i=e.substring(2,e.length-1),n=null==r?void 0:r[i];return void 0===n?(t.playlistParsingError||(t.playlistParsingError=new Error('Missing preceding EXT-X-DEFINE tag for Variable Reference: "'+i+'"')),e):n}))}return e}function qt(t,e,r){var i,n,a=t.variableList;if(a||(t.variableList=a={}),"QUERYPARAM"in e){i=e.QUERYPARAM;try{var s=new self.URL(r).searchParams;if(!s.has(i))throw new Error('"'+i+'" does not match any query parameter in URI: "'+r+'"');n=s.get(i)}catch(e){t.playlistParsingError||(t.playlistParsingError=new Error("EXT-X-DEFINE QUERYPARAM: "+e.message))}}else i=e.NAME,n=e.VALUE;i in a?t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE duplicate Variable Name declarations: "'+i+'"')):a[i]=n||""}function Xt(t,e,r){var i=e.IMPORT;if(r&&i in r){var n=t.variableList;n||(t.variableList=n={}),n[i]=r[i]}else t.playlistParsingError||(t.playlistParsingError=new Error('EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "'+i+'"'))}function zt(){if("undefined"!=typeof self)return self.MediaSource||self.WebKitMediaSource}var Qt={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dva1:!0,dvav:!0,dvh1:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}},$t=zt();function Jt(t,e){var r;return null!=(r=null==$t?void 0:$t.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"'))&&r}var Zt=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,te=/#EXT-X-MEDIA:(.*)/g,ee=/^#EXT(?:INF|-X-TARGETDURATION):/m,re=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),ie=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),ne=function(){function t(){}return t.findGroup=function(t,e){for(var r=0;r2){var r=e.shift()+".";return r+=parseInt(e.shift()).toString(16),r+=("000"+parseInt(e.shift()).toString(16)).slice(-4)}return t},t.resolve=function(t,e){return T.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.isMediaPlaylist=function(t){return ee.test(t)},t.parseMasterPlaylist=function(e,r){var i,n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:Yt(e)},a=[];for(Zt.lastIndex=0;null!=(i=Zt.exec(e));)if(i[1]){var s,o=new F(i[1]);Wt(n,o,["CODECS","SUPPLEMENTAL-CODECS","ALLOWED-CPC","PATHWAY-ID","STABLE-VARIANT-ID","AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS","NAME"]);var l=jt(n,i[2]),u={attrs:o,bitrate:o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),name:o.NAME,url:t.resolve(l,r)},h=o.decimalResolution("RESOLUTION");h&&(u.width=h.width,u.height=h.height),oe((o.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),u),u.videoCodec&&-1!==u.videoCodec.indexOf("avc1")&&(u.videoCodec=t.convertAVC1ToAVCOTI(u.videoCodec)),null!=(s=u.unknownCodecs)&&s.length||a.push(u),n.levels.push(u)}else if(i[3]){var d=i[3],c=i[4];switch(d){case"SESSION-DATA":var f=new F(c);Wt(n,f,["DATA-ID","LANGUAGE","VALUE","URI"]);var g=f["DATA-ID"];g&&(null===n.sessionData&&(n.sessionData={}),n.sessionData[g]=f);break;case"SESSION-KEY":var v=ae(c,r,n);v.encrypted&&v.isSupported()?(null===n.sessionKeys&&(n.sessionKeys=[]),n.sessionKeys.push(v)):_.warn('[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "'+c+'"');break;case"DEFINE":var m=new F(c);Wt(n,m,["NAME","VALUE","QUERYPARAM"]),qt(n,m,r);break;case"CONTENT-STEERING":var p=new F(c);Wt(n,p,["SERVER-URI","PATHWAY-ID"]),n.contentSteering={uri:t.resolve(p["SERVER-URI"],r),pathwayId:p["PATHWAY-ID"]||"."};break;case"START":n.startTimeOffset=se(c)}}var y=a.length>0&&a.length0&&W.bool("CAN-SKIP-DATERANGES"),h.partHoldBack=W.optionalFloat("PART-HOLD-BACK",0),h.holdBack=W.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var j=new F(D);h.partTarget=j.decimalFloatingPoint("PART-TARGET");break;case"PART":var q=h.partList;q||(q=h.partList=[]);var X=g>0?q[q.length-1]:void 0,z=g++,Q=new F(D);Wt(h,Q,["BYTERANGE","URI"]);var $=new V(Q,y,e,z,X);q.push($),y.duration+=$.duration;break;case"PRELOAD-HINT":var J=new F(D);Wt(h,J,["URI"]),h.preloadHint=J;break;case"RENDITION-REPORT":var Z=new F(D);Wt(h,Z,["URI"]),h.renditionReports=h.renditionReports||[],h.renditionReports.push(Z);break;default:_.warn("line parsed but not handled: "+s)}}}p&&!p.relurl?(d.pop(),v-=p.duration,h.partList&&(h.fragmentHint=p)):h.partList&&(ue(y,p),y.cc=m,h.fragmentHint=y,u&&de(y,u,h));var tt=d.length,et=d[0],rt=d[tt-1];if((v+=h.skippedSegments*h.targetduration)>0&&tt&&rt){h.averagetargetduration=v/tt;var it=rt.sn;h.endSN="initSegment"!==it?it:0,h.live||(rt.endList=!0),et&&(h.startCC=et.cc)}else h.endSN=0,h.startCC=0;return h.fragmentHint&&(v+=h.fragmentHint.duration),h.totalduration=v,h.endCC=m,T>0&&function(t,e){for(var r=t[e],i=e;i--;){var n=t[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(d,T),h},t}();function ae(t,e,r){var i,n,a=new F(t);Wt(r,a,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);var s=null!=(i=a.METHOD)?i:"",o=a.URI,l=a.hexadecimalInteger("IV"),u=a.KEYFORMATVERSIONS,h=null!=(n=a.KEYFORMAT)?n:"identity";o&&a.IV&&!l&&_.error("Invalid IV: "+a.IV);var d=o?ne.resolve(o,e):"",c=(u||"1").split("/").map(Number).filter(Number.isFinite);return new Ht(s,d,h,c,l)}function se(t){var e=new F(t).decimalFloatingPoint("TIME-OFFSET");return E(e)?e:null}function oe(t,e){["video","audio","text"].forEach((function(r){var i=t.filter((function(t){return function(t,e){var r=Qt[e];return!!r&&!0===r[t.slice(0,4)]}(t,r)}));if(i.length){var n=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));e[r+"Codec"]=n.length>0?n[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),e.unknownCodecs=t}function le(t,e,r){var i=e[r];i&&(t[r]=i)}function ue(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),E(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function he(t,e,r,i){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",i&&(t.levelkeys=i),t.initSegment=null}function de(t,e,r){t.levelkeys=e;var i=r.encryptedFragments;i.length&&i[i.length-1].levelkeys===e||!Object.keys(e).some((function(t){return e[t].isCommonEncryption}))||i.push(t)}var ce="manifest",fe="level",ge="audioTrack",ve="subtitleTrack",me="main",pe="audio",ye="subtitle";function Te(t){switch(t.type){case ge:return pe;case ve:return ye;default:return me}}function Ee(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}var Se=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=t,this.registerListeners()}var e=t.prototype;return e.startLoad=function(t){},e.stopLoad=function(){this.destroyInternalLoaders()},e.registerListeners=function(){var t=this.hls;t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.LEVEL_LOADING,this.onLevelLoading,this),t.on(R.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(R.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.LEVEL_LOADING,this.onLevelLoading,this),t.off(R.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(R.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,n=new(r||i)(e);return this.loaders[t.type]=n,n},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:ce,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,n=e.url,a=e.deliveryDirectives;this.load({id:r,level:i,responseType:"text",type:fe,url:n,deliveryDirectives:a})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,n=e.url,a=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:ge,url:n,deliveryDirectives:a})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,n=e.url,a=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:ve,url:n,deliveryDirectives:a})},e.load=function(t){var e,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(t);if(s){var l=s.context;if(l&&l.url===t.url)return void _.trace("[playlist-loader]: playlist request ongoing");_.log("[playlist-loader]: aborting previous loader for type: "+t.type),s.abort()}if(r=t.type===ce?a.manifestLoadPolicy.default:o({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(t),null!=(e=t.deliveryDirectives)&&e.part&&(t.type===fe&&null!==t.level?i=this.hls.levels[t.level].details:t.type===ge&&null!==t.id?i=this.hls.audioTracks[t.id].details:t.type===ve&&null!==t.id&&(i=this.hls.subtitleTracks[t.id].details),i)){var u=i.partTarget,h=i.targetduration;if(u&&h){var d=1e3*Math.max(3*u,.8*h);r=o({},r,{maxTimeToFirstByteMs:Math.min(d,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(d,r.maxTimeToFirstByteMs)})}}var c=r.errorRetry||r.timeoutRetry||{},f={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},g={onSuccess:function(t,e,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=t.data;0===s.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),ne.isMediaPlaylist(s)?n.handleTrackOrLevelPlaylist(t,e,r,i||null,a):n.handleMasterPlaylist(t,e,r,i)):n.handleManifestParsingError(t,r,new Error("no EXTM3U delimiter"),i||null,e)},onError:function(t,e,r,i){n.handleNetworkError(e,r,!1,t,i)},onTimeout:function(t,e,r){n.handleNetworkError(e,r,!0,void 0,t)}};s.load(t,f,g)},e.handleMasterPlaylist=function(t,e,r,i){var n=this.hls,a=t.data,s=Ee(t,r),o=ne.parseMasterPlaylist(a,s);if(o.playlistParsingError)this.handleManifestParsingError(t,r,o.playlistParsingError,i,e);else{var l=o.contentSteering,u=o.levels,h=o.sessionData,d=o.sessionKeys,c=o.startTimeOffset,f=o.variableList;this.variableList=f;var g=ne.parseMasterPlaylistMedia(a,s,o),v=g.AUDIO,m=void 0===v?[]:v,p=g.SUBTITLES,y=g["CLOSED-CAPTIONS"];m.length&&(m.some((function(t){return!t.url}))||!u[0].audioCodec||u[0].attrs.AUDIO||(_.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),m.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new F({}),bitrate:0,url:""}))),n.trigger(R.MANIFEST_LOADED,{levels:u,audioTracks:m,subtitles:p,captions:y,contentSteering:l,url:s,stats:e,networkDetails:i,sessionData:h,sessionKeys:d,startTimeOffset:c,variableList:f})}},e.handleTrackOrLevelPlaylist=function(t,e,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=Ee(t,r),h=E(s)?s:0,d=E(o)?o:h,c=Te(r),f=ne.parseLevelPlaylist(t.data,u,d,c,h,this.variableList);if(l===ce){var g={attrs:new F({}),bitrate:0,details:f,name:"",url:u};a.trigger(R.MANIFEST_LOADED,{levels:[g],audioTracks:[],url:u,stats:e,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}e.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,t,e,r,i,n)},e.handleManifestParsingError=function(t,e,r,i,n){this.hls.trigger(R.ERROR,{type:A.NETWORK_ERROR,details:k.MANIFEST_PARSING_ERROR,fatal:e.type===ce,url:t.url,err:r,error:r,reason:r.message,response:t,context:e,networkDetails:i,stats:n})},e.handleNetworkError=function(t,e,r,n,a){void 0===r&&(r=!1);var s="A network "+(r?"timeout":"error"+(n?" (status "+n.code+")":""))+" occurred while loading "+t.type;t.type===fe?s+=": "+t.level+" id: "+t.id:t.type!==ge&&t.type!==ve||(s+=" id: "+t.id+' group-id: "'+t.groupId+'"');var o=new Error(s);_.warn("[playlist-loader]: "+s);var l=k.UNKNOWN,u=!1,h=this.getInternalLoader(t);switch(t.type){case ce:l=r?k.MANIFEST_LOAD_TIMEOUT:k.MANIFEST_LOAD_ERROR,u=!0;break;case fe:l=r?k.LEVEL_LOAD_TIMEOUT:k.LEVEL_LOAD_ERROR,u=!1;break;case ge:l=r?k.AUDIO_TRACK_LOAD_TIMEOUT:k.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case ve:l=r?k.SUBTITLE_TRACK_LOAD_TIMEOUT:k.SUBTITLE_LOAD_ERROR,u=!1}h&&this.resetInternalLoader(t.type);var d={type:A.NETWORK_ERROR,details:l,fatal:u,url:t.url,loader:h,context:t,error:o,networkDetails:e,stats:a};if(n){var c=(null==e?void 0:e.url)||t.url;d.response=i({url:c,data:void 0},n)}this.hls.trigger(R.ERROR,d)},e.handlePlaylistLoaded=function(t,e,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.id,h=i.groupId,d=i.deliveryDirectives,c=Ee(e,i),f=Te(i),g="number"==typeof i.level&&f===me?l:void 0;if(t.fragments.length){t.targetduration||(t.playlistParsingError=new Error("Missing Target Duration"));var v=t.playlistParsingError;if(v)s.trigger(R.ERROR,{type:A.NETWORK_ERROR,details:k.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:v,reason:v.message,response:e,context:i,level:g,parent:f,networkDetails:n,stats:r});else switch(t.live&&a&&(a.getCacheAge&&(t.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(t.ageHeader)||(t.ageHeader=0)),o){case ce:case fe:s.trigger(R.LEVEL_LOADED,{details:t,level:g||0,id:u||0,stats:r,networkDetails:n,deliveryDirectives:d});break;case ge:s.trigger(R.AUDIO_TRACK_LOADED,{details:t,id:u||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:d});break;case ve:s.trigger(R.SUBTITLE_TRACK_LOADED,{details:t,id:u||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:d})}}else{var m=new Error("No Segments found in Playlist");s.trigger(R.ERROR,{type:A.NETWORK_ERROR,details:k.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:e,context:i,level:g,parent:f,networkDetails:n,stats:r})}},t}();function Le(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function Re(t,e){var r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(r){_.debug("[texttrack-utils]: "+r);try{var i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(t){_.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+t)}}"disabled"===r&&(t.mode=r)}function Ae(t){var e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues)for(var r=t.cues.length;r--;)t.removeCue(t.cues[r]);"disabled"===e&&(t.mode=e)}function ke(t,e,r,i){var n=t.mode;if("disabled"===n&&(t.mode="hidden"),t.cues&&t.cues.length>0)for(var a=function(t,e,r){var i=[],n=function(t,e){if(et[r].endTime)return-1;for(var i=0,n=r;i<=n;){var a=Math.floor((n+i)/2);if(et[a].startTime&&i-1)for(var a=n,s=t.length;a=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(t.cues,e,r),s=0;s_e&&(d=_e),d-h<=0&&(d=h+.25);for(var c=0;ce.startDate&&t.push(i),t}),[]).sort((function(t,e){return t.startDate.getTime()-e.startDate.getTime()}))[0];g&&(h=Pe(g.startDate,c),l=!0)}for(var m,p,y=Object.keys(e.attr),T=0;T.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,a)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(u,Math.max(1,h))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},e.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},e.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},a(t,[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,n=this.config,a=n.liveSyncDuration,s=n.liveSyncDurationCount,o=n.lowLatencyMode,l=this.hls.userConfig,u=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*i);var h=i;return u+Math.min(1*this.stallCount,h)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,n=t-e-this.edgeStalled,a=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return(r?t.buffered.end(r-1):e.edge)-this.currentTime}}]),t}(),Me=["NONE","TYPE-0","TYPE-1",null],Oe="",Ne="YES",Ue="v2",Be=function(){function t(t,e,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=t,this.part=e,this.skip=r}return t.prototype.addDirectives=function(t){var e=new self.URL(t);return void 0!==this.msn&&e.searchParams.set("_HLS_msn",this.msn.toString()),void 0!==this.part&&e.searchParams.set("_HLS_part",this.part.toString()),this.skip&&e.searchParams.set("_HLS_skip",this.skip),e.href},t}(),Ge=function(){function t(t){this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.videoCodec=void 0,this.width=void 0,this.unknownCodecs=void 0,this.audioGroupIds=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.textGroupIds=void 0,this.url=void 0,this._urlId=0,this.url=[t.url],this._attrs=[t.attrs],this.bitrate=t.bitrate,t.details&&(this.details=t.details),this.id=t.id||0,this.name=t.name,this.width=t.width||0,this.height=t.height||0,this.audioCodec=t.audioCodec,this.videoCodec=t.videoCodec,this.unknownCodecs=t.unknownCodecs,this.codecSet=[t.videoCodec,t.audioCodec].filter((function(t){return t})).join(",").replace(/\.[^.,]+/g,"")}return t.prototype.addFallback=function(t){this.url.push(t.url),this._attrs.push(t.attrs)},a(t,[{key:"maxBitrate",get:function(){return Math.max(this.realBitrate,this.bitrate)}},{key:"attrs",get:function(){return this._attrs[this._urlId]}},{key:"pathwayId",get:function(){return this.attrs["PATHWAY-ID"]||"."}},{key:"uri",get:function(){return this.url[this._urlId]||""}},{key:"urlId",get:function(){return this._urlId},set:function(t){var e=t%this.url.length;this._urlId!==e&&(this.fragmentError=0,this.loadError=0,this.details=void 0,this._urlId=e)}},{key:"audioGroupId",get:function(){var t;return null==(t=this.audioGroupIds)?void 0:t[this.urlId]}},{key:"textGroupId",get:function(){var t;return null==(t=this.textGroupIds)?void 0:t[this.urlId]}}]),t}();function Ke(t,e){var r=e.startPTS;if(E(r)){var i,n=0;e.sn>t.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration:e.start=Math.max(t.start-e.duration,0)}function He(t,e,r,i,n,a){i-r<=0&&(_.warn("Fragment should have a positive duration",e),i=r+e.duration,a=n+e.duration);var s=r,o=i,l=e.startPTS,u=e.endPTS;if(E(l)){var h=Math.abs(l-r);E(e.deltaPTS)?e.deltaPTS=Math.max(h,e.deltaPTS):e.deltaPTS=h,s=Math.max(r,l),r=Math.min(r,l),n=Math.min(n,e.startDTS),o=Math.min(i,u),i=Math.max(i,u),a=Math.max(a,e.endDTS)}var d=r-e.start;0!==e.start&&(e.start=r),e.duration=i-e.start,e.startPTS=r,e.maxStartPTS=s,e.startDTS=n,e.endPTS=i,e.minEndPTS=o,e.endDTS=a;var c,f=e.sn;if(!t||ft.endSN)return 0;var g=f-t.startSN,v=t.fragments;for(v[g]=e,c=g;c>0;c--)Ke(v[c],v[c-1]);for(c=g;c=0;n--){var a=i[n].initSegment;if(a){r=a;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;var s,l,u,h,d,c=0;if(function(t,e,r){for(var i=e.skippedSegments,n=Math.max(t.startSN,e.startSN)-e.startSN,a=(t.fragmentHint?1:0)+(i?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,s=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=n;u<=a;u++){var h=l[s+u],d=o[u];i&&!d&&u=i.length||We(e,i[r].start)}function We(t,e){if(e){for(var r=t.fragments,i=t.skippedSegments;i499)}(i)||!!r)}var Ze=function(t,e){for(var r=0,i=t.length-1,n=null,a=null;r<=i;){var s=e(a=t[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function tr(t,e,r,i){void 0===r&&(r=0),void 0===i&&(i=0);var n=null;if(t?n=e[t.sn-e[0].sn+1]||null:0===r&&0===e[0].start&&(n=e[0]),n&&0===er(r,i,n))return n;var a=Ze(e,er.bind(null,r,i));return!a||a===t&&n?n:a}function er(t,e,r){if(void 0===t&&(t=0),void 0===e&&(e=0),r.start<=t&&r.start+r.duration>t)return 0;var i=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=t?1:r.start-i>t&&r.start?-1:0}function rr(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}var ir,nr=3e5,ar=0,sr=2,or=5,lr=0,ur=1,hr=2,dr=function(){function t(t){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=t,this.log=_.log.bind(_,"[info]:"),this.warn=_.warn.bind(_,"[warning]:"),this.error=_.error.bind(_,"[error]:"),this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(R.ERROR,this.onError,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.LEVEL_UPDATED,this.onLevelUpdated,this)},e.unregisterListeners=function(){var t=this.hls;t&&(t.off(R.ERROR,this.onError,this),t.off(R.ERROR,this.onErrorOut,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.LEVEL_UPDATED,this.onLevelUpdated,this))},e.destroy=function(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}},e.startLoad=function(t){this.playlistError=0},e.stopLoad=function(){},e.getVariantLevelIndex=function(t){return(null==t?void 0:t.type)===me?t.level:this.hls.loadLevel},e.onManifestLoading=function(){this.playlistError=0,this.penalizedRenditions={}},e.onLevelUpdated=function(){this.playlistError=0},e.onError=function(t,e){var r,i;if(!e.fatal){var n=this.hls,a=e.context;switch(e.details){case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:return void(e.errorAction=this.getFragRetryOrSwitchAction(e));case k.FRAG_PARSING_ERROR:if(null!=(r=e.frag)&&r.gap)return void(e.errorAction={action:ar,flags:lr});case k.FRAG_GAP:case k.FRAG_DECRYPT_ERROR:return e.errorAction=this.getFragRetryOrSwitchAction(e),void(e.errorAction.action=sr);case k.LEVEL_EMPTY_ERROR:case k.LEVEL_PARSING_ERROR:var s,o,l=e.parent===me?e.level:n.loadLevel;return void(e.details===k.LEVEL_EMPTY_ERROR&&null!=(s=e.context)&&null!=(o=s.levelDetails)&&o.live?e.errorAction=this.getPlaylistRetryOrSwitchAction(e,l):(e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,l)));case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==a?void 0:a.level)&&(e.errorAction=this.getPlaylistRetryOrSwitchAction(e,a.level)));case k.AUDIO_TRACK_LOAD_ERROR:case k.AUDIO_TRACK_LOAD_TIMEOUT:case k.SUBTITLE_LOAD_ERROR:case k.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){var u=n.levels[n.loadLevel];if(u&&(a.type===ge&&a.groupId===u.audioGroupId||a.type===ve&&a.groupId===u.textGroupId))return e.errorAction=this.getPlaylistRetryOrSwitchAction(e,n.loadLevel),e.errorAction.action=sr,void(e.errorAction.flags=ur)}return;case k.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:var h=n.levels[n.loadLevel],d=null==h?void 0:h.attrs["HDCP-LEVEL"];return void(d&&(e.errorAction={action:sr,flags:hr,hdcpLevel:d}));case k.BUFFER_ADD_CODEC_ERROR:case k.REMUX_ALLOC_ERROR:return void(e.errorAction=this.getLevelSwitchAction(e,null!=(i=e.level)?i:n.loadLevel));case k.INTERNAL_EXCEPTION:case k.BUFFER_APPENDING_ERROR:case k.BUFFER_APPEND_ERROR:case k.BUFFER_FULL_ERROR:case k.LEVEL_SWITCH_ERROR:case k.BUFFER_STALLED_ERROR:case k.BUFFER_SEEK_OVER_HOLE:case k.BUFFER_NUDGE_ON_STALL:return void(e.errorAction={action:ar,flags:lr})}if(e.type===A.KEY_SYSTEM_ERROR){var c=this.getVariantLevelIndex(e.frag);return e.levelRetry=!1,void(e.errorAction=this.getLevelSwitchAction(e,c))}}},e.getPlaylistRetryOrSwitchAction=function(t,e){var r,i=ze(this.hls.config.playlistLoadPolicy,t),n=this.playlistError++,a=null==(r=t.response)?void 0:r.code;if(Je(i,n,Xe(t),a))return{action:or,flags:lr,retryConfig:i,retryCount:n};var s=this.getLevelSwitchAction(t,e);return i&&(s.retryConfig=i,s.retryCount=n),s},e.getFragRetryOrSwitchAction=function(t){var e=this.hls,r=this.getVariantLevelIndex(t.frag),i=e.levels[r],n=e.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=ze(t.details.startsWith("key")?s:a,t),l=e.levels.reduce((function(t,e){return t+e.fragmentError}),0);if(i){var u;t.details!==k.FRAG_GAP&&i.fragmentError++;var h=null==(u=t.response)?void 0:u.code;if(Je(o,l,Xe(t),h))return{action:or,flags:lr,retryConfig:o,retryCount:l}}var d=this.getLevelSwitchAction(t,r);return o&&(d.retryConfig=o,d.retryCount=l),d},e.getLevelSwitchAction=function(t,e){var r=this.hls;null==e&&(e=r.loadLevel);var i=this.hls.levels[e];if(i&&(i.loadError++,r.autoLevelEnabled)){for(var n,a,s=-1,o=r.levels,l=r.loadLevel,u=r.minAutoLevel,h=r.maxAutoLevel,d=null==(n=t.frag)?void 0:n.type,c=null!=(a=t.context)?a:{},f=c.type,g=c.groupId,v=o.length;v--;){var m=(v+l)%o.length;if(m!==l&&m>=u&&m<=h&&0===o[m].loadError){var p=o[m];if(t.details===k.FRAG_GAP&&t.frag){var y=o[m].details;if(y){var T=tr(t.frag,y.fragments,t.frag.start);if(null!=T&&T.gap)continue}}else{if(f===ge&&g===p.audioGroupId||f===ve&&g===p.textGroupId)continue;if(d===pe&&i.audioGroupId===p.audioGroupId||d===ye&&i.textGroupId===p.textGroupId)continue}s=m;break}}if(s>-1&&r.loadLevel!==s)return t.levelRetry=!0,this.playlistError=0,{action:sr,flags:lr,nextAutoLevel:s}}return{action:sr,flags:ur}},e.onErrorOut=function(t,e){var r;switch(null==(r=e.errorAction)?void 0:r.action){case ar:break;case sr:this.sendAlternateToPenaltyBox(e),e.errorAction.resolved||e.details===k.FRAG_GAP||(e.fatal=!0)}e.fatal&&this.hls.stopLoad()},e.sendAlternateToPenaltyBox=function(t){var e=this.hls,r=t.errorAction;if(r){var i=r.flags,n=r.hdcpLevel,a=r.nextAutoLevel;switch(i){case lr:this.switchLevel(t,a);break;case ur:r.resolved||(r.resolved=this.redundantFailover(t));break;case hr:n&&(e.maxHdcpLevel=Me[Me.indexOf(n)-1],r.resolved=!0),this.warn('Restricting playback to HDCP-LEVEL of "'+e.maxHdcpLevel+'" or lower')}r.resolved||this.switchLevel(t,a)}},e.switchLevel=function(t,e){void 0!==e&&t.errorAction&&(this.warn("switching to level "+e+" after "+t.details),this.hls.nextAutoLevel=e,t.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)},e.redundantFailover=function(t){var e=this,r=this.hls,i=this.penalizedRenditions,n=t.parent===me?t.level:r.loadLevel,a=r.levels[n],s=a.url.length,o=t.frag?t.frag.urlId:a.urlId;a.urlId!==o||t.frag&&!a.details||this.penalizeRendition(a,t);for(var l=function(){var l=(o+u)%s,h=i[l];if(!h||function(t,e,r){if(performance.now()-t.lastErrorPerfMs>nr)return!0;var i=t.details;if(e.details===k.FRAG_GAP&&i&&e.frag){var n=e.frag.start,a=tr(null,i.fragments,n);if(a&&!a.gap)return!0}if(r&&t.errors.length3*i.targetduration)return!0}return!1}(h,t,i[o]))return e.warn("Switching to Redundant Stream "+(l+1)+"/"+s+': "'+a.url[l]+'" after '+t.details),e.playlistError=0,r.levels.forEach((function(t){t.urlId=l})),r.nextLoadLevel=n,{v:!0}},u=1;u=0&&h>e.partTarget&&(u+=1)}return new Be(l,u>=0?u:void 0,Oe)}}},e.loadPlaylist=function(t){-1===this.requestScheduled&&(this.requestScheduled=self.performance.now())},e.shouldLoadPlaylist=function(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)},e.shouldReloadPlaylist=function(t){return-1===this.timer&&-1===this.requestScheduled&&this.shouldLoadPlaylist(t)},e.playlistLoaded=function(t,e,r){var i=this,n=e.details,a=e.stats,s=self.performance.now(),o=a.loading.first?Math.max(0,s-a.loading.first):0;if(n.advancedDateTime=Date.now()-o,n.live||null!=r&&r.live){if(n.reloaded(r),r&&this.log("live playlist "+t+" "+(n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED")),r&&n.fragments.length>0&&Ve(r,n),!this.canLoad||!n.live)return;var l,u=void 0,h=void 0;if(n.canBlockReload&&n.endSN&&n.advanced){var d=this.hls.config.lowLatencyMode,c=n.lastPartSn,f=n.endSN,g=n.lastPartIndex,v=c===f;-1!==g?(u=v?f+1:c,h=v?d?0:g:g+1):u=f+1;var m=n.age,p=m+n.ageHeader,y=Math.min(p-n.partTarget,1.5*n.targetduration);if(y>0){if(r&&y>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+y+" with playlist age: "+n.age),y=0;else{var T=Math.floor(y/n.targetduration);u+=T,void 0!==h&&(h+=Math.round(y%n.targetduration/n.partTarget)),this.log("CDN Tune-in age: "+n.ageHeader+"s last advanced "+m.toFixed(2)+"s goal: "+y+" skip sn "+T+" to part "+h)}n.tuneInGoal=y}if(l=this.getDeliveryDirectives(n,e.deliveryDirectives,u,h),d||!v)return void this.loadPlaylist(l)}else(n.canBlockReload||n.canSkipUntil)&&(l=this.getDeliveryDirectives(n,e.deliveryDirectives,u,h));var E=this.hls.mainForwardBufferInfo,S=E?E.end-E.len:0,L=function(t,e){void 0===e&&(e=1/0);var r=1e3*t.targetduration;if(t.updated){var i=t.fragments;if(i.length&&4*r>e){var n=1e3*i[i.length-1].duration;nthis.requestScheduled+L&&(this.requestScheduled=a.loading.start),void 0!==u&&n.canBlockReload?this.requestScheduled=a.loading.first+L-(1e3*n.partTarget||1e3):-1===this.requestScheduled||this.requestScheduled+L=u.maxNumRetry)return!1;if(i&&null!=(d=t.context)&&d.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var c=Qe(u,l);this.timer=self.setTimeout((function(){return e.loadPlaylist()}),c),this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" in '+c+"ms")}t.levelRetry=!0,n.resolved=!0}return h},t}(),fr=function(t){function e(e,r){var i;return(i=t.call(this,e,"[level-controller]")||this)._levels=[],i._firstLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}l(e,t);var r=e.prototype;return r._registerListeners=function(){var t=this.hls;t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(R.LEVEL_LOADED,this.onLevelLoaded,this),t.on(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(R.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(R.FRAG_LOADED,this.onFragLoaded,this),t.on(R.ERROR,this.onError,this)},r._unregisterListeners=function(){var t=this.hls;t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(R.LEVEL_LOADED,this.onLevelLoaded,this),t.off(R.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(R.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(R.FRAG_LOADED,this.onFragLoaded,this),t.off(R.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),t.prototype.destroy.call(this)},r.startLoad=function(){this._levels.forEach((function(t){t.loadError=0,t.fragmentError=0})),t.prototype.startLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[]},r.onManifestLoading=function(t,e){this.resetLevels()},r.onManifestLoaded=function(t,e){var r,i=[],n={};e.levels.forEach((function(t){var e,a=t.attrs;-1!==(null==(e=t.audioCodec)?void 0:e.indexOf("mp4a.40.34"))&&(ir||(ir=/chrome|firefox/i.test(navigator.userAgent)),ir&&(t.audioCodec=void 0));var s=a.AUDIO,o=a.CODECS,l=a["FRAME-RATE"],u=a["PATHWAY-ID"],h=a.RESOLUTION,d=a.SUBTITLES,c=(u||".")+"-"+t.bitrate+"-"+h+"-"+l+"-"+o;(r=n[c])?r.addFallback(t):(r=new Ge(t),n[c]=r,i.push(r)),gr(r,"audio",s),gr(r,"text",d)})),this.filterAndSortMediaOptions(i,e)},r.filterAndSortMediaOptions=function(t,e){var r=this,i=[],n=[],a=!1,s=!1,o=!1,l=t.filter((function(t){var e=t.audioCodec,r=t.videoCodec,i=t.width,n=t.height,l=t.unknownCodecs;return a||(a=!(!i||!n)),s||(s=!!r),o||(o=!!e),!(null!=l&&l.length)&&(!e||Jt(e,"audio"))&&(!r||Jt(r,"video"))}));if((a||s)&&o&&(l=l.filter((function(t){var e=t.videoCodec,r=t.width,i=t.height;return!!e||!(!r||!i)}))),0!==l.length){e.audioTracks&&vr(i=e.audioTracks.filter((function(t){return!t.audioCodec||Jt(t.audioCodec,"audio")}))),e.subtitles&&vr(n=e.subtitles);var u=l.slice(0);l.sort((function(t,e){return t.attrs["HDCP-LEVEL"]!==e.attrs["HDCP-LEVEL"]?(t.attrs["HDCP-LEVEL"]||"")>(e.attrs["HDCP-LEVEL"]||"")?1:-1:t.bitrate!==e.bitrate?t.bitrate-e.bitrate:t.attrs["FRAME-RATE"]!==e.attrs["FRAME-RATE"]?t.attrs.decimalFloatingPoint("FRAME-RATE")-e.attrs.decimalFloatingPoint("FRAME-RATE"):t.attrs.SCORE!==e.attrs.SCORE?t.attrs.decimalFloatingPoint("SCORE")-e.attrs.decimalFloatingPoint("SCORE"):a&&t.height!==e.height?t.height-e.height:0}));var h=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l)).length!==u.length)for(var d=0;d1&&void 0!==e?(n.url=n.url.filter(i),n.audioGroupIds&&(n.audioGroupIds=n.audioGroupIds.filter(i)),n.textGroupIds&&(n.textGroupIds=n.textGroupIds.filter(i)),n.urlId=0,!0):(r.steering&&r.steering.removeLevel(n),!1))}));this.hls.trigger(R.LEVELS_UPDATED,{levels:n})},r.onLevelsUpdated=function(t,e){var r=e.levels;r.forEach((function(t,e){var r=t.details;null!=r&&r.fragments&&r.fragments.forEach((function(t){t.level=e}))})),this._levels=r},a(e,[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e=this._levels;if(0!==e.length){if(t<0||t>=e.length){var r=new Error("invalid level idx"),i=t<0;if(this.hls.trigger(R.ERROR,{type:A.OTHER_ERROR,details:k.LEVEL_SWITCH_ERROR,level:t,fatal:i,error:r,reason:r.message}),i)return;t=Math.min(t,e.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,l=e[t],u=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,n!==t||!l.details||!a||s!==u){this.log("Switching to level "+t+(u?" with Pathway "+u:"")+" from level "+n+(s?" with Pathway "+s:""));var h=o({},l,{level:t,maxBitrate:l.maxBitrate,attrs:l.attrs,uri:l.uri,urlId:l.urlId});delete h._attrs,delete h._urlId,this.hls.trigger(R.LEVEL_SWITCHING,h);var d=l.details;if(!d||d.live){var c=this.switchParams(l.uri,null==a?void 0:a.details);this.loadPlaylist(c)}}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}]),e}(cr);function gr(t,e,r){r&&("audio"===e?(t.audioGroupIds||(t.audioGroupIds=[]),t.audioGroupIds[t.url.length-1]=r):"text"===e&&(t.textGroupIds||(t.textGroupIds=[]),t.textGroupIds[t.url.length-1]=r))}function vr(t){var e={};t.forEach((function(t){var r=t.groupId||"";t.id=e[r]=e[r]||0,e[r]++}))}var mr="NOT_LOADED",pr="APPENDING",yr="PARTIAL",Tr="OK",Er=function(){function t(t){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(R.BUFFER_APPENDED,this.onBufferAppended,this),t.on(R.FRAG_BUFFERED,this.onFragBuffered,this),t.on(R.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(R.BUFFER_APPENDED,this.onBufferAppended,this),t.off(R.FRAG_BUFFERED,this.onFragBuffered,this),t.off(R.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){var r=this.activePartLists[e];if(r)for(var i=r.length;i--;){var n=r[i];if(!n)break;var a=n.end;if(n.start<=t&&null!==a&&t<=a)return n}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),n=i.length;n--;){var a=r[i[n]];if((null==a?void 0:a.body.type)===e&&a.buffered){var s=a.body;if(s.start<=t&&t<=s.end)return s}}return null},e.detectEvictedFragments=function(t,e,r,i){var n=this;this.timeRanges&&(this.timeRanges[t]=e);var a=(null==i?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach((function(i){var s=n.fragments[i];if(s&&!(a>=s.body.sn))if(s.buffered||s.loaded){var o=s.range[t];o&&o.time.some((function(t){var r=!n.isTimeBuffered(t.startPTS,t.endPTS,e);return r&&n.removeFragment(s.body),r}))}else s.body.type===r&&n.removeFragment(s.body)}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,n=t.part;if(r&&"initSegment"!==i.sn){var a=Lr(i),s=this.fragments[a];if(!(!s||s.buffered&&i.gap)){var o=!i.relurl;Object.keys(r).forEach((function(t){var a=i.elementaryStreams[t];if(a){var l=r[t],u=o||!0===a.partial;s.range[t]=e.getBufferedTimes(i,n,u,l)}})),s.loaded=null,Object.keys(s.range).length?(s.buffered=!0,(s.body.endList=i.endList||s.body.endList)&&(this.endListFragments[s.body.type]=s),Sr(s)||this.removeParts(i.sn-1,i.type)):this.removeFragment(s.body)}}},e.removeParts=function(t,e){var r=this.activePartLists[e];r&&(this.activePartLists[e]=r.filter((function(e){return e.fragment.sn>=t})))},e.fragBuffered=function(t,e){var r=Lr(t),i=this.fragments[r];!i&&e&&(i=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)},e.getBufferedTimes=function(t,e,r,i){for(var n={time:[],partial:r},a=t.start,s=t.end,o=t.minEndPTS||s,l=t.maxStartPTS||a,u=0;u=h&&o<=d){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(ah)n.partial=!0,n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=h)break}return n},e.getPartialFragment=function(t){var e,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&Sr(u)&&(r=u.body.start-s,i=u.body.end+s,t>=r&&t<=i&&(e=Math.min(t-r,i-t),a<=e&&(n=u.body,a=e)))})),n},e.isEndListAppended=function(t){var e=this.endListFragments[t];return void 0!==e&&(e.buffered||Sr(e))},e.getState=function(t){var e=Lr(t),r=this.fragments[e];return r?r.buffered?Sr(r)?yr:Tr:pr:mr},e.isTimeBuffered=function(t,e,r){for(var i,n,a=0;a=i&&e<=n)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest){var n=i?null:e,a=Lr(r);this.fragments[a]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,n=e.part,a=e.timeRanges;if("initSegment"!==i.sn){var s=i.type;if(n){var o=this.activePartLists[s];o||(this.activePartLists[s]=o=[]),o.push(n)}this.timeRanges=a,Object.keys(a).forEach((function(t){var e=a[t];r.detectEvictedFragments(t,e,s,n)}))}},e.onFragBuffered=function(t,e){this.detectPartialFragments(e)},e.hasFragment=function(t){var e=Lr(t);return!!this.fragments[e]},e.hasParts=function(t){var e;return!(null==(e=this.activePartLists[t])||!e.length)},e.removeFragmentsInRange=function(t,e,r,i,n){var a=this;i&&!this.hasGaps||Object.keys(this.fragments).forEach((function(s){var o=a.fragments[s];if(o){var l=o.body;l.type!==r||i&&!l.gap||l.startt&&(o.buffered||n)&&a.removeFragment(l)}}))},e.removeFragment=function(t){var e=Lr(t);t.stats.loaded=0,t.clearElementaryStreamInfo();var r=this.activePartLists[t.type];if(r){var i=t.sn;this.activePartLists[t.type]=r.filter((function(t){return t.fragment.sn!==i}))}delete this.fragments[e],t.endList&&delete this.endListFragments[t.type]},e.removeAllFragments=function(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1},t}();function Sr(t){var e,r,i;return t.buffered&&(t.body.gap||(null==(e=t.range.video)?void 0:e.partial)||(null==(r=t.range.audio)?void 0:r.partial)||(null==(i=t.range.audiovideo)?void 0:i.partial))}function Lr(t){return t.type+"_"+t.level+"_"+t.urlId+"_"+t.sn}var Rr=Math.pow(2,17),Ar=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var r=this,n=t.url;if(!n)return Promise.reject(new Dr({type:A.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error("Fragment does not have a "+(n?"part list":"url")),networkDetails:null}));this.abort();var a=this.config,s=a.fLoader,o=a.loader;return new Promise((function(l,u){if(r.loader&&r.loader.destroy(),t.gap){if(t.tagList.some((function(t){return"GAP"===t[0]})))return void u(br(t));t.gap=!1}var h=r.loader=t.loader=s?new s(a):new o(a),d=kr(t),c=$e(a.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===t.sn?1/0:Rr};t.stats=h.stats,h.load(d,f,{onSuccess:function(e,i,n,a){r.resetLoader(t,h);var s=e.data;n.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),l({frag:t,part:null,payload:s,networkDetails:a})},onError:function(e,a,s,o){r.resetLoader(t,h),u(new Dr({type:A.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:i({url:n,data:void 0},e),error:new Error("HTTP Error "+e.code+" "+e.text),networkDetails:s,stats:o}))},onAbort:function(e,i,n){r.resetLoader(t,h),u(new Dr({type:A.NETWORK_ERROR,details:k.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:n,stats:e}))},onTimeout:function(e,i,n){r.resetLoader(t,h),u(new Dr({type:A.NETWORK_ERROR,details:k.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:n,stats:e}))},onProgress:function(r,i,n,a){e&&e({frag:t,part:null,payload:n,networkDetails:a})}})}))},e.loadPart=function(t,e,r){var n=this;this.abort();var a=this.config,s=a.fLoader,o=a.loader;return new Promise((function(l,u){if(n.loader&&n.loader.destroy(),t.gap||e.gap)u(br(t,e));else{var h=n.loader=t.loader=s?new s(a):new o(a),d=kr(t,e),c=$e(a.fragLoadPolicy.default),f={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Rr};e.stats=h.stats,h.load(d,f,{onSuccess:function(i,a,s,o){n.resetLoader(t,h),n.updateStatsFromPart(t,e);var u={frag:t,part:e,payload:i.data,networkDetails:o};r(u),l(u)},onError:function(r,a,s,o){n.resetLoader(t,h),u(new Dr({type:A.NETWORK_ERROR,details:k.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:i({url:d.url,data:void 0},r),error:new Error("HTTP Error "+r.code+" "+r.text),networkDetails:s,stats:o}))},onAbort:function(r,i,a){t.stats.aborted=e.stats.aborted,n.resetLoader(t,h),u(new Dr({type:A.NETWORK_ERROR,details:k.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,i,a){n.resetLoader(t,h),u(new Dr({type:A.NETWORK_ERROR,details:k.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:a,stats:r}))}})}}))},e.updateStatsFromPart=function(t,e){var r=t.stats,i=e.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(t.duration/e.duration),s=Math.min(Math.round(r.loaded/n),a),o=(a-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function kr(t,e){void 0===e&&(e=null);var r=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(E(n)&&E(a)){var s,o=n,l=a;if("initSegment"===t.sn&&"AES-128"===(null==(s=t.decryptdata)?void 0:s.method)){var u=a-n;u%16&&(l=a+(16-u%16)),0!==n&&(i.resetIV=!0,o=n-16)}i.rangeStart=o,i.rangeEnd=l}return i}function br(t,e){var r=new Error("GAP "+(t.gap?"tag":"attribute")+" found"),i={type:A.MEDIA_ERROR,details:k.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(i.part=e),(e||t).stats.aborted=!0,new Dr(i)}var Dr=function(t){function e(e){var r;return(r=t.call(this,e.error.message)||this).data=void 0,r.data=e,r}return l(e,t),e}(f(Error)),Ir=function(){function t(t){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=t}var e=t.prototype;return e.abort=function(t){for(var e in this.keyUriToKeyInfo){var r=this.keyUriToKeyInfo[e].loader;if(r){if(t&&t!==r.context.frag.type)return;r.abort()}}},e.detach=function(){for(var t in this.keyUriToKeyInfo){var e=this.keyUriToKeyInfo[t];(e.mediaKeySessionContext||e.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[t]}},e.destroy=function(){for(var t in this.detach(),this.keyUriToKeyInfo){var e=this.keyUriToKeyInfo[t].loader;e&&e.destroy()}this.keyUriToKeyInfo={}},e.createKeyLoadError=function(t,e,r,i,n){return void 0===e&&(e=k.KEY_LOAD_ERROR),new Dr({type:A.NETWORK_ERROR,details:e,fatal:!1,frag:t,response:n,error:r,networkDetails:i})},e.loadClear=function(t,e){var r=this;if(this.emeController&&this.config.emeEnabled)for(var i=t.sn,n=t.cc,a=function(){var t=e[s];if(n<=t.cc&&("initSegment"===i||"initSegment"===t.sn||i1&&this.tickImmediate(),this._tickCallCount=0)},e.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},e.doTick=function(){},t}(),Cr={length:0,start:function(){return 0},end:function(){return 0}},_r=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),n=0;n=i.start(n)&&r<=i.end(n))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var n,a=t.getBuffered(e),s=[];for(n=0;ns&&(i[a-1].end=t[n].end):i.push(t[n])}else i.push(t[n])}else i=t;for(var o,l=0,u=e,h=e,d=0;d=c&&er.startCC||t&&t.cc>>8^255&m^99,t[f]=m,e[m]=f;var p=c[f],y=c[p],T=c[y],E=257*c[m]^16843008*m;i[f]=E<<24|E>>>8,n[f]=E<<16|E>>>16,a[f]=E<<8|E>>>24,s[f]=E,E=16843009*T^65537*y^257*p^16843008*f,l[m]=E<<24|E>>>8,u[m]=E<<16|E>>>16,h[m]=E<<8|E>>>24,d[m]=E,f?(f=p^c[c[c[T^p]]],g^=c[c[g]]):f=g=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;is.end){var h=a>u;(a0&&a&&a.key&&a.iv&&"AES-128"===a.method){var s=self.performance.now();return r.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer).catch((function(e){throw i.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e})).then((function(r){var n=self.performance.now();return i.trigger(R.FRAG_DECRYPTED,{frag:t,payload:r,stats:{tstart:s,tdecrypt:n}}),e.payload=r,e}))}return e})).then((function(i){var n=r.fragCurrent,a=r.hls;if(!r.levels)throw new Error("init load aborted, missing levels");var s=t.stats;r.state=Yr,e.fragmentError=0,t.data=new Uint8Array(i.payload),s.parsing.start=s.buffering.start=self.performance.now(),s.parsing.end=s.buffering.end=self.performance.now(),i.frag===n&&a.trigger(R.FRAG_BUFFERED,{stats:s,frag:n,part:null,id:t.type}),r.tick()})).catch((function(e){r.state!==Vr&&r.state!==Jr&&(r.warn(e),r.resetFragmentLoading(t))}))},r.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId},r.fragBufferedComplete=function(t,e){var r,i,n,a,s=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+(this.playlistType===me?"level":"track")+" "+t.level+" (frag:["+(null!=(r=t.startPTS)?r:NaN).toFixed(3)+"-"+(null!=(i=t.endPTS)?i:NaN).toFixed(3)+"] > buffer:"+(s?Hr(_r.getBuffered(s)):"(detached)")+")"),this.state=Yr,s&&(!this.loadedmetadata&&t.type==me&&s.buffered.length&&(null==(n=this.fragCurrent)?void 0:n.sn)===(null==(a=this.fragPrevious)?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())},r.seekToStartPos=function(){},r._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,n=t.partsLoaded,a=!n||0===n.length||n.some((function(t){return!t})),s=new Pr(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a);e.flush(s)}},r._handleFragmentLoadProgress=function(t){},r._doFragLoad=function(t,e,r,i){var n,a=this;void 0===r&&(r=null);var s=null==e?void 0:e.details;if(!this.levels||!s)throw new Error("frag load aborted, missing level"+(s?"":" detail")+"s");var o=null;if(!t.encrypted||null!=(n=t.decryptdata)&&n.key?!t.encrypted&&s.encryptedFragments.length&&this.keyLoader.loadClear(t,s.encryptedFragments):(this.log("Loading key for "+t.sn+" of ["+s.startSN+"-"+s.endSN+"], "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level),this.state=Wr,this.fragCurrent=t,o=this.keyLoader.load(t).then((function(t){if(!a.fragContextChanged(t.frag))return a.hls.trigger(R.KEY_LOADED,t),a.state===Wr&&(a.state=Yr),t})),this.hls.trigger(R.KEY_LOADING,{frag:t}),null===this.fragCurrent&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))),r=Math.max(t.start,r||0),this.config.lowLatencyMode&&"initSegment"!==t.sn){var l=s.partList;if(l&&i){r>t.end&&s.fragmentHint&&(t=s.fragmentHint);var u=this.getNextPart(l,t,r);if(u>-1){var h,d=l[u];return this.log("Loading part sn: "+t.sn+" p: "+d.index+" cc: "+t.cc+" of playlist ["+s.startSN+"-"+s.endSN+"] parts [0-"+u+"-"+(l.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=d.start+d.duration,this.state=jr,h=o?o.then((function(r){return!r||a.fragContextChanged(r.frag)?null:a.doFragPartsLoad(t,d,e,i)})).catch((function(t){return a.handleFragLoadError(t)})):this.doFragPartsLoad(t,d,e,i).catch((function(t){return a.handleFragLoadError(t)})),this.hls.trigger(R.FRAG_LOADING,{frag:t,part:d,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):h}if(!t.url||this.loadedEndOfParts(l,r))return Promise.resolve(null)}}this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(s?"of ["+s.startSN+"-"+s.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),E(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=jr;var c,f=this.config.progressive;return c=f&&o?o.then((function(e){return!e||a.fragContextChanged(null==e?void 0:e.frag)?null:a.fragmentLoader.load(t,i)})).catch((function(t){return a.handleFragLoadError(t)})):Promise.all([this.fragmentLoader.load(t,f?i:void 0),o]).then((function(t){var e=t[0];return!f&&e&&i&&i(e),e})).catch((function(t){return a.handleFragLoadError(t)})),this.hls.trigger(R.FRAG_LOADING,{frag:t,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):c},r.doFragPartsLoad=function(t,e,r,i){var n=this;return new Promise((function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList;!function e(o){n.fragmentLoader.loadPart(t,o,i).then((function(i){l[o.index]=i;var s=i.part;n.hls.trigger(R.FRAG_LOADED,i);var h=je(r,t.sn,o.index+1)||qe(u,t.sn,o.index+1);if(!h)return a({frag:t,part:s,partsLoaded:l});e(h)})).catch(s)}(e)}))},r.handleFragLoadError=function(t){if("data"in t){var e=t.data;t.data&&e.details===k.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(R.ERROR,e)}else this.hls.trigger(R.ERROR,{type:A.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null},r._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===zr){var r=e.frag,i=e.part,n=e.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(r,i,n,t.partial)}else this.fragCurrent||this.state===Vr||this.state===Jr||(this.state=Yr)},r.getCurrentContext=function(t){var e=this.levels,r=this.fragCurrent,i=t.level,n=t.sn,a=t.part;if(null==e||!e[i])return this.warn("Levels object was unset while buffering fragment "+n+" of level "+i+". The current chunk will not be buffered."),null;var s=e[i],o=a>-1?je(s,n,a):null,l=o?o.fragment:function(t,e,r){if(null==t||!t.details)return null;var i=t.details,n=i.fragments[e-i.startSN];return n||((n=i.fragmentHint)&&n.sn===e?n:ea&&this.flushMainBuffer(s,t.start)}else this.flushMainBuffer(0,t.start)},r.getFwdBufferInfo=function(t,e){var r=this.getLoadPosition();return E(r)?this.getFwdBufferInfoAtPos(t,r,e):null},r.getFwdBufferInfoAtPos=function(t,e,r){var i=this.config.maxBufferHole,n=_r.bufferInfo(t,e,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(e,r);if(a&&n.nextStart=r&&(e.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},r.getAppendedFrag=function(t,e){var r=this.fragmentTracker.getAppendedFrag(t,me);return r&&"fragment"in r?r.fragment:r},r.getNextFragment=function(t,e){var r=e.fragments,i=r.length;if(!i)return null;var n,a=this.config,s=r[0].start;if(e.live){var o=a.initialLiveManifestSize;if(ie},r.getNextFragmentLoopLoading=function(t,e,r,i,n){var a=t.gap,s=this.getNextFragment(this.nextLoadPosition,e);if(null===s)return s;if(t=s,a&&t&&!t.gap&&r.nextStart){var o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i);if(null!==o&&r.len+o.len>=n)return this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+t.sn),null}return t},r.mapToInitFragWhenRequired=function(t){return null==t||!t.initSegment||null!=t&&t.initSegment.data||this.bitrateTest?t:t.initSegment},r.getNextPart=function(t,e,r){for(var i=-1,n=!1,a=!0,s=0,o=t.length;s-1&&rr.start&&r.loaded},r.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=function(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!E(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;i=t.startSN&&n<=t.endSN){var a=e[n-t.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(t,e){return Ze(t,(function(t){return t.cce?-1:0}))}(e,r.cc),i&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn))}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},r.getFragmentAtPosition=function(t,e,r){var i,n=this.config,a=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=n.maxFragLookUpTolerance,h=r.partList,d=!!(n.lowLatencyMode&&null!=h&&h.length&&l);if(d&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),i=te-u?0:u):s[s.length-1]){var c=i.sn-r.startSN,f=this.fragmentTracker.getState(i);if((f===Tr||f===yr&&i.gap)&&(a=i),a&&i.sn===a.sn&&(!d||h[0].fragment.sn>i.sn)&&a&&i.level===a.level){var g=s[c+1];i=i.sn=a-e.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n"+t.startSN+" prev-sn: "+(n?n.sn:"na")+" fragments: "+s),h}return o},r.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},r.setStartPosition=function(t,e){var r=this.startPosition;if(r "+(null==(n=this.fragCurrent)?void 0:n.url))}else{var a=e.details===k.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(i,!0);var s=e.errorAction,o=s||{},l=o.action,u=o.retryCount,h=void 0===u?0:u,d=o.retryConfig;if(s&&l===or&&d){var c;this.resetStartWhenNotLoaded(null!=(c=this.levelLastLoaded)?c:i.level);var f=Qe(d,h);this.warn("Fragment "+i.sn+" of "+t+" "+i.level+" errored with "+e.details+", retrying loading "+(h+1)+"/"+d.maxNumRetry+" in "+f+"ms"),s.resolved=!0,this.retryDate=self.performance.now()+f,this.state=qr}else d&&s?(this.resetFragmentErrors(t),h.5;i&&this.reduceMaxBufferLength(r.len);var n=!i;return n&&this.warn("Buffer full error while media.currentTime is not buffered, flush "+e+" buffer"),t.frag&&(this.fragmentTracker.removeFragment(t.frag),this.nextLoadPosition=t.frag.start),this.resetLoadingState(),n}return!1},r.resetFragmentErrors=function(t){t===pe&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Vr&&(this.state=Yr)},r.afterBufferFlushed=function(t,e,r){if(t){var i=_r.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,i,r),this.state===$r&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Yr},r.resetStartWhenNotLoaded=function(t){if(!this.loadedmetadata){this.startFragRequested=!1;var e=this.levels?this.levels[t].details:null;null!=e&&e.live?(this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},r.resetWhenMissingContext=function(t){var e;this.warn("The loading context changed while buffering fragment "+t.sn+" of level "+t.level+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(null!=(e=this.levelLastLoaded)?e:t.level),this.resetLoadingState()},r.removeUnbufferedFrags=function(t){void 0===t&&(t=0),this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(t,e,r,i){var n,a=this,s=r.details;if(s){if(Object.keys(t.elementaryStreams).reduce((function(e,n){var o=t.elementaryStreams[n];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return a.warn("Could not parse fragment "+t.sn+" "+n+" duration reliably ("+l+")"),e||!1;var u=i?0:He(s,t,o.startPTS,o.endPTS,o.startDTS,o.endDTS);return a.hls.trigger(R.LEVEL_PTS_UPDATED,{details:s,level:r,drift:u,type:n,frag:t,start:o.startPTS,end:o.endPTS}),!0}return e}),!1))r.fragmentError=0;else if(null===(null==(n=this.transmuxer)?void 0:n.error)){var o=new Error("Found no media in fragment "+t.sn+" of level "+t.level+" resetting transmuxer to fallback to playlist timing");if(0===r.fragmentError&&(r.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)),this.warn(o.message),this.hls.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:o,frag:t,reason:"Found no media in msn "+t.sn+' of level "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}this.state=Qr,this.hls.trigger(R.FRAG_PARSED,{frag:t,part:e})}else this.warn("level.details undefined")},r.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},r.recoverWorkerError=function(t){var e,r,i;"demuxerWorker"===t.event&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(null!=(e=null!=(r=this.levelLastLoaded)?r:null==(i=this.fragCurrent)?void 0:i.level)?e:0),this.resetLoadingState())},a(e,[{key:"state",get:function(){return this._state},set:function(t){var e=this._state;e!==t&&(this._state=t,this.log(e+"->"+t))}}]),e}(wr);function ri(){return self.SourceBuffer||self.WebKitSourceBuffer}function ii(t,e){return void 0===t&&(t=""),void 0===e&&(e=9e4),{type:t,id:-1,pid:-1,inputTimeScale:e,sequenceNumber:-1,samples:[],dropped:0}}var ni=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(t){this.initPTS=t,this.resetContiguity()},e.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,r){},e.demux=function(t,e){this.cachedData&&(t=Mt(this.cachedData,t),this.cachedData=null);var r,i=lt(t,0),n=i?i.length:0,a=this._audioTrack,s=this._id3Track,o=i?function(t){for(var e=ft(t),r=0;r0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:be,duration:Number.POSITIVE_INFINITY});n>>5}function ui(t,e){return e+1=t.length)return!1;var i=li(t,e);if(i<=r)return!1;var n=e+i;return n===t.length||ui(t,n)}return!1}function di(t,e,r,i,n){if(!t.samplerate){var a=function(t,e,r,i){var n,a,s,o,l=navigator.userAgent.toLowerCase(),u=i,h=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];n=1+((192&e[r+2])>>>6);var d=(60&e[r+2])>>>2;if(!(d>h.length-1))return s=(1&e[r+2])<<2,s|=(192&e[r+3])>>>6,_.log("manifest codec:"+i+", ADTS type:"+n+", samplingIndex:"+d),/firefox/i.test(l)?d>=6?(n=5,o=new Array(4),a=d-3):(n=2,o=new Array(2),a=d):-1!==l.indexOf("android")?(n=2,o=new Array(2),a=d):(n=5,o=new Array(4),i&&(-1!==i.indexOf("mp4a.40.29")||-1!==i.indexOf("mp4a.40.5"))||!i&&d>=6?a=d-3:((i&&-1!==i.indexOf("mp4a.40.2")&&(d>=6&&1===s||/vivaldi/i.test(l))||!i&&1===s)&&(n=2,o=new Array(2)),a=d)),o[0]=n<<3,o[0]|=(14&d)>>1,o[1]|=(1&d)<<7,o[1]|=s<<3,5===n&&(o[1]|=(14&a)>>1,o[2]=(1&a)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:h[d],channelCount:s,codec:"mp4a.40."+n,manifestCodec:u};t.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+d})}(e,r,i,n);if(!a)return;t.config=a.config,t.samplerate=a.samplerate,t.channelCount=a.channelCount,t.codec=a.codec,t.manifestCodec=a.manifestCodec,_.log("parsed codec:"+t.codec+", rate:"+a.samplerate+", channels:"+a.channelCount)}}function ci(t){return 9216e4/t}function fi(t,e,r,i,n){var a,s=i+n*ci(t.samplerate),o=function(t,e){var r=oi(t,e);if(e+r<=t.length){var i=li(t,e)-r;if(i>0)return{headerLength:r,frameLength:i}}}(e,r);if(o){var l=o.frameLength,u=o.headerLength,h=u+l,d=Math.max(0,r+h-e.length);d?(a=new Uint8Array(h-u)).set(e.subarray(r+u,e.length),0):a=e.subarray(r+u,r+h);var c={unit:a,pts:s};return d||t.samples.push(c),{sample:c,length:h,missing:d}}var f=e.length-r;return(a=new Uint8Array(f)).set(e.subarray(r,e.length),0),{sample:{unit:a,pts:s},length:f,missing:-1}}var gi=function(t){function e(e,r){var i;return(i=t.call(this)||this).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}l(e,t);var r=e.prototype;return r.resetInitSegment=function(e,r,i,n){t.prototype.resetInitSegment.call(this,e,r,i,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},e.probe=function(t){if(!t)return!1;for(var e=(lt(t,0)||[]).length,r=t.length;e16384?t.subarray(0,16384):t,["moof"]).length>0},e.demux=function(t,e){this.timeOffset=e;var r=t,i=this.videoTrack,n=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=Mt(this.remainderData,t));var a=function(t){var e={valid:null,remainder:null},r=Ct(t,["moof"]);if(!r)return e;if(r.length<2)return e.remainder=t,e;var i=r[r.length-1];return e.valid=nt(t,0,i.byteOffset-8),e.remainder=nt(t,i.byteOffset-8),e}(r);this.remainderData=a.remainder,i.samples=a.valid||new Uint8Array}else i.samples=r;var s=this.extractID3Track(i,e);return n.samples=Ot(e,i),{videoTrack:i,audioTrack:this.audioTrack,id3Track:s,textTrack:this.txtTrack}},e.flush=function(){var t=this.timeOffset,e=this.videoTrack,r=this.txtTrack;e.samples=this.remainderData||new Uint8Array,this.remainderData=null;var i=this.extractID3Track(e,this.timeOffset);return r.samples=Ot(t,e),{videoTrack:e,audioTrack:ii(),id3Track:i,textTrack:ii()}},e.extractID3Track=function(t,e){var r=this.id3Track;if(t.samples.length){var i=Ct(t.samples,["emsg"]);i&&i.forEach((function(t){var i=function(t){var e=t[0],r="",i="",n=0,a=0,s=0,o=0,l=0,u=0;if(0===e){for(;"\0"!==kt(t.subarray(u,u+1));)r+=kt(t.subarray(u,u+1)),u+=1;for(r+=kt(t.subarray(u,u+1)),u+=1;"\0"!==kt(t.subarray(u,u+1));)i+=kt(t.subarray(u,u+1)),u+=1;i+=kt(t.subarray(u,u+1)),u+=1,n=Dt(t,12),a=Dt(t,16),o=Dt(t,20),l=Dt(t,24),u=28}else if(1===e){n=Dt(t,u+=4);var h=Dt(t,u+=4),d=Dt(t,u+=4);for(u+=4,s=Math.pow(2,32)*h+d,S(s)||(s=Number.MAX_SAFE_INTEGER,_.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),o=Dt(t,u),l=Dt(t,u+=4),u+=4;"\0"!==kt(t.subarray(u,u+1));)r+=kt(t.subarray(u,u+1)),u+=1;for(r+=kt(t.subarray(u,u+1)),u+=1;"\0"!==kt(t.subarray(u,u+1));)i+=kt(t.subarray(u,u+1)),u+=1;i+=kt(t.subarray(u,u+1)),u+=1}return{schemeIdUri:r,value:i,timeScale:n,presentationTime:s,presentationTimeDelta:a,eventDuration:o,id:l,payload:t.subarray(u,t.byteLength)}}(t);if(vi.test(i.schemeIdUri)){var n=E(i.presentationTime)?i.presentationTime/i.timeScale:e+i.presentationTimeDelta/i.timeScale,a=4294967295===i.eventDuration?Number.POSITIVE_INFINITY:i.eventDuration/i.timeScale;a<=.001&&(a=Number.POSITIVE_INFINITY);var s=i.payload;r.samples.push({data:s,len:s.byteLength,dts:n,pts:n,type:Ie,duration:a})}}))}return r},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}(),pi=null,yi=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],Ti=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Ei=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Si=[0,1,1,4];function Li(t,e,r,i,n){if(!(r+24>e.length)){var a=Ri(e,r);if(a&&r+a.frameLength<=e.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:e.subarray(r,r+a.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=a.channelCount,t.samplerate=a.sampleRate,t.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function Ri(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,n=t[e+2]>>4&15,a=t[e+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*yi[14*(3===r?3-i:3===i?3:4)+n-1],u=Ti[3*(3===r?0:2===r?1:2)+a],h=3===o?1:2,d=Ei[r][i],c=Si[i],f=8*d*c,g=Math.floor(d*l/u+s)*c;if(null===pi){var v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);pi=v?parseInt(v[1]):0}return!!pi&&pi<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:h,frameLength:g,samplesPerFrame:f}}}function Ai(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function ki(t,e){return e+1t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)<<3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;if(t>32&&_.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0)this.word<<=e;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(e=t-e)>0&&this.bitsAvailable?r<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i=t.length)return void r();if(!(t[e].unit.length<32||(this.decryptAacSample(t,e,r),this.decrypter.isSync())))return}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,n=32;n=t.length)return void i();for(var n=t[e].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(t,e,r,i,a),this.decrypter.isSync())))return}}},t}(),wi=188,Ci=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=r}t.probe=function(e){var r=t.syncOffset(e);return r>0&&_.warn("MPEG2-TS detected but first sync word found @ offset "+r),-1!==r},t.syncOffset=function(t){for(var e=t.length,r=Math.min(940,t.length-wi)+1,i=0;i1&&(0===a&&s>2||o+wi>r))return a}i++}return-1},t.createTrack=function(t,e){return{container:"video"===t||"audio"===t?"video/mp2t":void 0,type:t,id:At[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===t?e:void 0}};var e=t.prototype;return e.resetInitSegment=function(e,r,i,n){this.pmtParsed=!1,this._pmtId=-1,this._avcTrack=t.createTrack("video"),this._audioTrack=t.createTrack("audio",n),this._id3Track=t.createTrack("id3"),this._txtTrack=t.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,this._duration=n},e.resetTimeStamp=function(){},e.resetContiguity=function(){var t=this._audioTrack,e=this._avcTrack,r=this._id3Track;t&&(t.pesData=null),e&&(e.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.avcSample=null,this.remainderData=null},e.demux=function(e,r,i,n){var a;void 0===i&&(i=!1),void 0===n&&(n=!1),i||(this.sampleAes=null);var s=this._avcTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack,h=s.pid,d=s.pesData,c=o.pid,f=l.pid,g=o.pesData,v=l.pesData,m=null,p=this.pmtParsed,y=this._pmtId,T=e.length;if(this.remainderData&&(T=(e=Mt(this.remainderData,e)).length,this.remainderData=null),T>4>1){if((I=L+5+e[L+4])===L+wi)continue}else I=L+4;switch(D){case h:b&&(d&&(a=Mi(d))&&this.parseAVCPES(s,u,a,!1),d={data:[],size:0}),d&&(d.data.push(e.subarray(I,L+wi)),d.size+=L+wi-I);break;case c:if(b){if(g&&(a=Mi(g)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,a);break;case"mp3":this.parseMPEGPES(o,a)}g={data:[],size:0}}g&&(g.data.push(e.subarray(I,L+wi)),g.size+=L+wi-I);break;case f:b&&(v&&(a=Mi(v))&&this.parseID3PES(l,a),v={data:[],size:0}),v&&(v.data.push(e.subarray(I,L+wi)),v.size+=L+wi-I);break;case 0:b&&(I+=e[I]+1),y=this._pmtId=xi(e,I);break;case y:b&&(I+=e[I]+1);var w=Fi(e,I,this.typeSupported,i);(h=w.avc)>0&&(s.pid=h),(c=w.audio)>0&&(o.pid=c,o.segmentCodec=w.segmentCodec),(f=w.id3)>0&&(l.pid=f),null===m||p||(_.warn("MPEG-TS PMT found at "+L+" after unknown PID '"+m+"'. Backtracking to sync byte @"+E+" to parse all TS packets."),m=null,L=E-188),p=this.pmtParsed=!0;break;case 17:case 8191:break;default:m=D}}else S++;if(S>0){var C=new Error("Found "+S+" TS packet/s that do not start with 0x47");this.observer.emit(R.ERROR,R.ERROR,{type:A.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:C,reason:C.message})}s.pesData=d,o.pesData=g,l.pesData=v;var P={audioTrack:o,videoTrack:s,id3Track:l,textTrack:u};return n&&this.extractRemainingSamples(P),P},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{videoTrack:this._avcTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.videoTrack,n=t.id3Track,a=t.textTrack,s=i.pesData,o=r.pesData,l=n.pesData;if(s&&(e=Mi(s))?(this.parseAVCPES(i,a,e,!0),i.pesData=null):i.pesData=s,o&&(e=Mi(o))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,e);break;case"mp3":this.parseMPEGPES(r,e)}r.pesData=null}else null!=o&&o.size&&_.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(e=Mi(l))?(this.parseID3PES(n,e),n.pesData=null):n.pesData=l},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),n=this.sampleAes=new Ii(this.observer,this.config,e);return this.decrypt(i,n)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,n=t.videoTrack;i.samples&&"aac"===i.segmentCodec?e.decryptAacSamples(i.samples,0,(function(){n.samples?e.decryptAvcSamples(n.samples,0,0,(function(){r(t)})):r(t)})):n.samples&&e.decryptAvcSamples(n.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._duration=0},e.parseAVCPES=function(t,e,r,i){var n,a=this,s=this.parseAVCNALu(t,r.data),o=this.avcSample,l=!1;r.data=null,o&&s.length&&!t.audFound&&(Oi(o,t),o=this.avcSample=_i(!1,r.pts,r.dts,"")),s.forEach((function(i){var s;switch(i.type){case 1:var u=!1;n=!0;var h,d=i.data;if(l&&d.length>4){var c=new Di(d).readSliceType();2!==c&&4!==c&&7!==c&&9!==c||(u=!0)}u&&null!=(h=o)&&h.frame&&!o.key&&(Oi(o,t),o=a.avcSample=null),o||(o=a.avcSample=_i(!0,r.pts,r.dts,"")),o.frame=!0,o.key=u;break;case 5:n=!0,null!=(s=o)&&s.frame&&!o.key&&(Oi(o,t),o=a.avcSample=null),o||(o=a.avcSample=_i(!0,r.pts,r.dts,"")),o.key=!0,o.frame=!0;break;case 6:n=!0,Ut(i.data,1,r.pts,e.samples);break;case 7:if(n=!0,l=!0,!t.sps){var f=i.data,g=new Di(f).readSPS();t.width=g.width,t.height=g.height,t.pixelRatio=g.pixelRatio,t.sps=[f],t.duration=a._duration;for(var v=f.subarray(1,4),m="avc1.",p=0;p<3;p++){var y=v[p].toString(16);y.length<2&&(y="0"+y),m+=y}t.codec=m}break;case 8:n=!0,t.pps||(t.pps=[i.data]);break;case 9:n=!1,t.audFound=!0,o&&Oi(o,t),o=a.avcSample=_i(!1,r.pts,r.dts,"");break;case 12:n=!0;break;default:n=!1,o&&(o.debug+="unknown NAL "+i.type+" ")}o&&n&&o.units.push(i)})),i&&o&&(Oi(o,t),this.avcSample=null)},e.getLastNalUnit=function(t){var e,r,i=this.avcSample;if(i&&0!==i.units.length||(i=t[t.length-1]),null!=(e=i)&&e.units){var n=i.units;r=n[n.length-1]}return r},e.parseAVCNALu=function(t,e){var r,i,n=e.byteLength,a=t.naluState||0,s=a,o=[],l=0,u=-1,h=0;for(-1===a&&(u=0,h=31&e[0],a=0,l=1);l=0){var d={data:e.subarray(u,l-a-1),type:h};o.push(d)}else{var c=this.getLastNalUnit(t.samples);if(c&&(s&&l<=4-s&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-s)),(i=l-a-1)>0)){var f=new Uint8Array(c.data.byteLength+i);f.set(c.data,0),f.set(e.subarray(0,i),c.data.byteLength),c.data=f,c.state=0}}l=0&&a>=0){var g={data:e.subarray(u,n),type:h,state:a};o.push(g)}if(0===o.length){var v=this.getLastNalUnit(t.samples);if(v){var m=new Uint8Array(v.data.byteLength+e.byteLength);m.set(v.data,0),m.set(e,v.data.byteLength),v.data=m}}return t.naluState=a,o},e.parseAACPES=function(t,e){var r,i,n,a=0,s=this.aacOverFlow,o=e.data;if(s){this.aacOverFlow=null;var l=s.missing,u=s.sample.unit.byteLength;if(-1===l){var h=new Uint8Array(u+o.byteLength);h.set(s.sample.unit,0),h.set(o,u),o=h}else{var d=u-l;s.sample.unit.set(o.subarray(0,l),d),t.samples.push(s.sample),a=s.missing}}for(r=a,i=o.length;r1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var u=e[7];192&u&&(n=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&u?n-(a=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(_.warn(Math.round((n-a)/9e4)+"s delta between PTS and DTS, align them"),n=a):a=n);var h=(i=e[8])+9;if(t.size<=h)return null;t.size-=h;for(var d=new Uint8Array(t.size),c=0,f=o.length;cg){h-=g;continue}e=e.subarray(h),g-=h,h=0}d.set(e,s),s+=g}return r&&(r-=i+3),{data:d,pts:n,dts:a,len:r}}return null}function Oi(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var n=r[i-1];t.pts=n.pts,t.dts=n.dts}e.samples.push(t)}t.debug.length&&_.log(t.pts+"/"+t.dts+":"+t.debug)}var Ni=function(t){function e(){return t.apply(this,arguments)||this}l(e,t);var r=e.prototype;return r.resetInitSegment=function(e,r,i,n){t.prototype.resetInitSegment.call(this,e,r,i,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:n,inputTimeScale:9e4,dropped:0}},e.probe=function(t){if(!t)return!1;for(var e=(lt(t,0)||[]).length,r=t.length;e1?r-1:0),n=1;n>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),a=0,e=8;a>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(Bi+1)),n=Math.floor(r%(Bi+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,a)},t.sdtp=function(e){var r,i,n=e.samples||[],a=new Uint8Array(4+n.length);for(r=0;r>>8&255),a.push(255&n),a=a.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&n),s=s.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|e.sps.length].concat(a).concat([e.pps.length]).concat(s))),l=e.width,u=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?"mp3"===e.segmentCodec&&"mp3"===e.codec?t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,n=e.width,a=e.height,s=Math.floor(i/(Bi+1)),o=Math.floor(i%(Bi+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,n>>8&255,255&n,0,0,a>>8&255,255&a,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),n=e.id,a=Math.floor(r/(Bi+1)),s=Math.floor(r%(Bi+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,255&a,s>>24,s>>16&255,s>>8&255,255&s])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,n,a,s,o,l,u=e.samples||[],h=u.length,d=12+16*h,c=new Uint8Array(d);for(r+=8+d,c.set(["video"===e.type?1:0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,a>>>16&255,a>>>8&255,255&a,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,c)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=new Uint8Array(t.FTYP.byteLength+r.byteLength);return i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();function Ki(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=t*e*r;return i?Math.round(n):n}function Hi(t,e){return void 0===e&&(e=!1),Ki(t,1e3,1/9e4,e)}Gi.types=void 0,Gi.HDLR_TYPES=void 0,Gi.STTS=void 0,Gi.STSC=void 0,Gi.STCO=void 0,Gi.STSZ=void 0,Gi.VMHD=void 0,Gi.SMHD=void 0,Gi.STSD=void 0,Gi.FTYP=void 0,Gi.DINF=void 0;var Vi=null,Yi=null,Wi=function(){function t(t,e,r,i){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.observer=t,this.config=e,this.typeSupported=r,this.ISGenerated=!1,null===Vi){var n=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Vi=n?parseInt(n[1]):0}if(null===Yi){var a=navigator.userAgent.match(/Safari\/(\d+)/i);Yi=a?parseInt(a[1]):0}}var e=t.prototype;return e.destroy=function(){},e.resetTimeStamp=function(t){_.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=t},e.resetNextTimestamp=function(){_.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},e.resetInitSegment=function(){_.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1},e.getVideoStartPts=function(t){var e=!1,r=t.reduce((function(t,r){var i=r.pts-t;return i<-4294967296?(e=!0,ji(t,r.pts)):i>0?t:r.pts}),t[0].pts);return e&&_.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,n,a,s,o){var l,u,h,d,c,f,g=n,v=n,m=t.pid>-1,p=e.pid>-1,y=e.samples.length,T=t.samples.length>0,E=s&&y>0||y>1;if((!m||T)&&(!p||E)||this.ISGenerated||s){this.ISGenerated||(h=this.generateIS(t,e,n,a));var S,L=this.isVideoContiguous,R=-1;if(E&&(R=function(t){for(var e=0;e0){_.warn("[mp4-remuxer]: Dropped "+R+" out of "+y+" video samples due to a missing keyframe");var A=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(R),e.dropped+=R,S=v+=(e.samples[0].pts-A)/e.inputTimeScale}else-1===R&&(_.warn("[mp4-remuxer]: No keyframe found out of "+y+" video samples"),f=!1);if(this.ISGenerated){if(T&&E){var k=this.getVideoStartPts(e.samples),b=(ji(t.samples[0].pts,k)-k)/e.inputTimeScale;g+=Math.max(0,b),v+=Math.max(0,-b)}if(T){if(t.samplerate||(_.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),h=this.generateIS(t,e,n,a)),u=this.remuxAudio(t,g,this.isAudioContiguous,a,p||E||o===pe?v:void 0),E){var D=u?u.endPTS-u.startPTS:0;e.inputTimeScale||(_.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),h=this.generateIS(t,e,n,a)),l=this.remuxVideo(e,v,L,D)}}else E&&(l=this.remuxVideo(e,v,L,0));l&&(l.firstKeyFrame=R,l.independent=-1!==R,l.firstKeyFramePTS=S)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=qi(r,n,this._initPTS,this._initDTS)),i.samples.length&&(d=Xi(i,n,this._initPTS))),{audio:u,video:l,initSegment:h,independent:f,text:d,id3:c}},e.generateIS=function(t,e,r,i){var n,a,s,o=t.samples,l=e.samples,u=this.typeSupported,h={},d=this._initPTS,c=!d||i,f="audio/mp4";if(c&&(n=a=1/0),t.config&&o.length&&(t.timescale=t.samplerate,"mp3"===t.segmentCodec&&(u.mpeg?(f="audio/mpeg",t.codec=""):u.mp3&&(t.codec="mp3")),h.audio={id:"audio",container:f,codec:t.codec,initSegment:"mp3"===t.segmentCodec&&u.mpeg?new Uint8Array(0):Gi.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(s=t.inputTimeScale,d&&s===d.timescale?c=!1:n=a=o[0].pts-Math.round(s*r))),e.sps&&e.pps&&l.length&&(e.timescale=e.inputTimeScale,h.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:Gi.initSegment([e]),metadata:{width:e.width,height:e.height}},c))if(s=e.inputTimeScale,d&&s===d.timescale)c=!1;else{var g=this.getVideoStartPts(l),v=Math.round(s*r);a=Math.min(a,ji(l[0].dts,g)-v),n=Math.min(n,g-v)}if(Object.keys(h).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:n,timescale:s},this._initDTS={baseTime:a,timescale:s}):n=s=void 0,{tracks:h,initPTS:n,timescale:s}},e.remuxVideo=function(t,e,r,i){var n,a,s=t.inputTimeScale,l=t.samples,u=[],h=l.length,d=this._initPTS,c=this.nextAvcDts,f=8,g=this.videoSampleDuration,v=Number.POSITIVE_INFINITY,m=Number.NEGATIVE_INFINITY,p=!1;r&&null!==c||(c=e*s-(l[0].pts-ji(l[0].dts,l[0].pts)));for(var y=d.baseTime*s/d.timescale,T=0;T0?T-1:T].dts&&(p=!0)}p&&l.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),n=l[0].dts;var S=(a=l[l.length-1].dts)-n,L=S?Math.round(S/(h-1)):g||t.inputTimeScale/30;if(r){var b=n-c,D=b>L,I=b<-1;if((D||I)&&(D?_.warn("AVC: "+Hi(b,!0)+" ms ("+b+"dts) hole between fragments detected, filling it"):_.warn("AVC: "+Hi(-b,!0)+" ms ("+b+"dts) overlapping between fragments detected"),!I||c>=l[0].pts)){n=c;var w=l[0].pts-b;l[0].dts=n,l[0].pts=w,_.log("Video: First PTS/DTS adjusted: "+Hi(w,!0)+"/"+Hi(n,!0)+", delta: "+Hi(b,!0)+" ms")}}n=Math.max(0,n);for(var C=0,P=0,x=0;x0?X.dts-l[q-1].dts:L;if(rt=q>0?X.pts-l[q-1].pts:L,it.stretchShortVideoTrack&&null!==this.nextAudioPts){var at=Math.floor(it.maxBufferHole*s),st=(i?v+i*s:this.nextAudioPts)-X.pts;st>at?((g=st-nt)<0?g=nt:H=!0,_.log("[mp4-remuxer]: It is approximately "+st/90+" ms to the next segment; using duration "+g/90+" ms for the last video frame.")):g=nt}else g=nt}var ot=Math.round(X.pts-X.dts);V=Math.min(V,g),W=Math.max(W,g),Y=Math.min(Y,rt),j=Math.max(j,rt),u.push(new Qi(X.key,g,Q,ot))}if(u.length)if(Vi){if(Vi<70){var lt=u[0].flags;lt.dependsOn=2,lt.isNonSync=0}}else if(Yi&&j-Y0&&(i&&Math.abs(p-m)<9e3||Math.abs(ji(g[0].pts-y,p)-m)<20*u),g.forEach((function(t){t.pts=ji(t.pts-y,p)})),!r||m<0){if(g=g.filter((function(t){return t.pts>=0})),!g.length)return;m=0===n?0:i&&!f?Math.max(0,p):g[0].pts}if("aac"===t.segmentCodec)for(var T=this.config.maxAudioFramesDrift,E=0,S=m;E=T*u&&I<1e4&&f){var w=Math.round(D/u);(S=b-w*u)<0&&(w--,S+=u),0===E&&(this.nextAudioPts=m=S),_.warn("[mp4-remuxer]: Injecting "+w+" audio frame @ "+(S/a).toFixed(3)+"s due to "+Math.round(1e3*D/a)+" ms gap.");for(var C=0;C0))return;N+=v;try{F=new Uint8Array(N)}catch(t){return void this.observer.emit(R.ERROR,R.ERROR,{type:A.MUX_ERROR,details:k.REMUX_ALLOC_ERROR,fatal:!1,error:t,bytes:N,reason:"fail allocating audio mdat "+N})}d||(new DataView(F.buffer).setUint32(0,N),F.set(Gi.types.mdat,4))}F.set(H,v);var Y=H.byteLength;v+=Y,c.push(new Qi(!0,l,Y,0)),O=V}var W=c.length;if(W){var j=c[c.length-1];this.nextAudioPts=m=O+s*j.duration;var q=d?new Uint8Array(0):Gi.moof(t.sequenceNumber++,M/s,o({},t,{samples:c}));t.samples=[];var X=M/a,z=m/a,Q={data1:q,data2:F,startPTS:X,endPTS:z,startDTS:X,endDTS:z,type:"audio",hasAudio:!0,hasVideo:!1,nb:W};return this.isAudioContiguous=!0,Q}},e.remuxEmptyAudio=function(t,e,r,i){var n=t.inputTimeScale,a=n/(t.samplerate?t.samplerate:n),s=this.nextAudioPts,o=this._initDTS,l=9e4*o.baseTime/o.timescale,u=(null!==s?s:i.startDTS*n)+l,h=i.endDTS*n+l,d=1024*a,c=Math.ceil((h-u)/d),f=Ui.getSilentFrame(t.manifestCodec||t.codec,t.channelCount);if(_.warn("[mp4-remuxer]: remux empty Audio"),f){for(var g=[],v=0;v4294967296;)t+=r;return t}function qi(t,e,r,i){var n=t.samples.length;if(n){for(var a=t.inputTimeScale,s=0;s0;n||(i=Ct(e,["encv"])),i.forEach((function(t){Ct(n?t.subarray(28):t.subarray(78),["sinf"]).forEach((function(t){var e=xt(t);if(e){var i=e.subarray(8,24);i.some((function(t){return 0!==t}))||(_.log("[eme] Patching keyId in 'enc"+(n?"a":"v")+">sinf>>tenc' box: "+St(i)+" -> "+St(r)),e.set(r,8))}}))}))})),t}(t,i)),this.emitInitSegment=!0},e.generateInitSegment=function(t){var e=this.audioCodec,r=this.videoCodec;if(null==t||!t.byteLength)return this.initTracks=void 0,void(this.initData=void 0);var i=this.initData=Pt(t);e||(e=Zi(i.audio,U)),r||(r=Zi(i.video,B));var n={};i.audio&&i.video?n.audiovideo={container:"video/mp4",codec:e+","+r,initSegment:t,id:"main"}:i.audio?n.audio={container:"audio/mp4",codec:e,initSegment:t,id:"audio"}:i.video?n.video={container:"video/mp4",codec:r,initSegment:t,id:"main"}:_.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=n},e.remux=function(t,e,r,i,n,a){var s,o,l=this.initPTS,u=this.lastEndTime,h={audio:void 0,video:void 0,text:i,id3:r,initSegment:void 0};E(u)||(u=this.lastEndTime=n||0);var d=e.samples;if(null==d||!d.length)return h;var c={initPTS:void 0,timescale:1},f=this.initData;if(null!=(s=f)&&s.length||(this.generateInitSegment(d),f=this.initData),null==(o=f)||!o.length)return _.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),h;this.emitInitSegment&&(c.tracks=this.initTracks,this.emitInitSegment=!1);var g=function(t,e){for(var r=0,i=0,n=0,a=Ct(t,["moof","traf"]),s=0;sn}(l,m,n,g)||c.timescale!==l.timescale&&a)&&(c.initPTS=m-n,l&&1===l.timescale&&_.warn("Adjusting initPTS by "+(c.initPTS-l.baseTime)),this.initPTS=l={baseTime:c.initPTS,timescale:1});var p=t?m-l.baseTime/l.timescale:u,y=p+g;!function(t,e,r){Ct(e,["moof","traf"]).forEach((function(e){Ct(e,["tfhd"]).forEach((function(i){var n=Dt(i,4),a=t[n];if(a){var s=a.timescale||9e4;Ct(e,["tfdt"]).forEach((function(t){var e=t[0],i=Dt(t,4);if(0===e)i-=r*s,wt(t,4,i=Math.max(i,0));else{i*=Math.pow(2,32),i+=Dt(t,8),i-=r*s,i=Math.max(i,0);var n=Math.floor(i/(Lt+1)),a=Math.floor(i%(Lt+1));wt(t,4,n),wt(t,8,a)}}))}}))}))}(f,d,l.baseTime/l.timescale),g>0?this.lastEndTime=y:(_.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var T=!!f.audio,S=!!f.video,L="";T&&(L+="audio"),S&&(L+="video");var R={data1:d,startPTS:p,startDTS:p,endPTS:y,endDTS:y,type:L,hasAudio:T,hasVideo:S,nb:1,dropped:0};return h.audio="audio"===R.type?R:void 0,h.video="audio"!==R.type?R:void 0,h.initSegment=c,h.id3=qi(r,n,l,l),i.samples.length&&(h.text=Xi(i,n,l)),h},t}();function Zi(t,e){var r=null==t?void 0:t.codec;return r&&r.length>4?r:"hvc1"===r||"hev1"===r?"hvc1.1.6.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||e===B?"avc1.42e01e":"mp4a.40.5"}try{zi=self.performance.now.bind(self.performance)}catch(t){_.debug("Unable to use Performance API on this environment"),zi="undefined"!=typeof self&&self.Date.now}var tn=[{demux:mi,remux:Ji},{demux:Ci,remux:Wi},{demux:gi,remux:Wi},{demux:Ni,remux:Wi}],en=function(){function t(t,e,r,i,n){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i,this.id=n}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,i){var n=this,a=r.transmuxing;a.executeStart=zi();var s=new Uint8Array(t),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,h=u.contiguous,d=u.discontinuity,c=u.trackSwitch,f=u.accurateTimeOffset,g=u.timeOffset,v=u.initSegmentChange,m=l.audioCodec,p=l.videoCodec,y=l.defaultInitPts,T=l.duration,E=l.initSegmentData,S=function(t,e){var r=null;return t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(r=e),r}(s,e);if(S&&"AES-128"===S.method){var L=this.getDecrypter();if(!L.isSync())return this.decryptionPromise=L.webCryptoDecrypt(s,S.key.buffer,S.iv.buffer).then((function(t){var e=n.push(t,null,r);return n.decryptionPromise=null,e})),this.decryptionPromise;var b=L.softwareDecrypt(s,S.key.buffer,S.iv.buffer);if(r.part>-1&&(b=L.flush()),!b)return a.executeEnd=zi(),rn(r);s=new Uint8Array(b)}var D=this.needsProbing(d,c);if(D){var I=this.configureTransmuxer(s);if(I)return _.warn("[transmuxer] "+I.message),this.observer.emit(R.ERROR,R.ERROR,{type:A.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),a.executeEnd=zi(),rn(r)}(d||c||v||D)&&this.resetInitSegment(E,m,p,T,e),(d||v||D)&&this.resetInitialTimestamp(y),h||this.resetContiguity();var w=this.transmux(s,S,g,f,r),C=this.currentTransmuxState;return C.contiguous=!0,C.discontinuity=!1,C.trackSwitch=!1,a.executeEnd=zi(),w},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=zi();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return a.then((function(){return e.flush(t)}));var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l,null,t))}var u=this.demuxer,h=this.remuxer;if(!u||!h)return r.executeEnd=zi(),[rn(t)];var d=u.flush(o);return nn(d)?d.then((function(r){return e.flushRemux(s,r,t),s})):(this.flushRemux(s,d,t),s)},e.flushRemux=function(t,e,r){var i=e.audioTrack,n=e.videoTrack,a=e.id3Track,s=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;_.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var h=this.remuxer.remux(i,n,a,s,u,l,!0,this.id);t.push({remuxResult:h,chunkMeta:r}),r.transmuxing.executeEnd=zi()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i,n){var a=this.demuxer,s=this.remuxer;a&&s&&(a.resetInitSegment(t,e,r,i),s.resetInitSegment(t,e,r,n))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,n){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,n):this.transmuxUnencrypted(t,r,i,n)},e.transmuxUnencrypted=function(t,e,r,i){var n=this.demuxer.demux(t,e,!1,!this.config.progressive),a=n.audioTrack,s=n.videoTrack,o=n.id3Track,l=n.textTrack;return{remuxResult:this.remuxer.remux(a,s,o,l,e,r,!1,this.id),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,n){var a=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:a.remuxer.remux(t.audioTrack,t.videoTrack,t.id3Track,t.textTrack,r,i,!1,a.id),chunkMeta:n}}))},e.configureTransmuxer=function(t){for(var e,r=this.config,i=this.observer,n=this.typeSupported,a=this.vendor,s=0,o=tn.length;s1&&l.id===(null==m?void 0:m.stats.chunkCount),L=!y&&(1===T||0===T&&(1===E||S&&E<=0)),R=self.performance.now();(y||T||0===n.stats.parsing.start)&&(n.stats.parsing.start=R),!a||!E&&L||(a.stats.parsing.start=R);var A=!(m&&(null==(h=n.initSegment)?void 0:h.url)===(null==(d=m.initSegment)?void 0:d.url)),k=new sn(p,L,o,y,g,A);if(!L||p||A){_.log("[transmuxer-interface, "+n.type+"]: Starting new transmux session for sn: "+l.sn+" p: "+l.part+" level: "+l.level+" id: "+l.id+"\n discontinuity: "+p+"\n trackSwitch: "+y+"\n contiguous: "+L+"\n accurateTimeOffset: "+o+"\n timeOffset: "+g+"\n initSegmentChange: "+A);var b=new an(r,i,e,s,u);this.configureTransmuxer(b)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:t,decryptdata:v,chunkMeta:l,state:k},t instanceof ArrayBuffer?[t]:[]);else if(f){var D=f.push(t,v,l,k);nn(D)?(f.async=!0,D.then((function(t){c.handleTransmuxComplete(t)})).catch((function(t){c.transmuxerError(t,l,"transmuxer-interface push error")}))):(f.async=!1,this.handleTransmuxComplete(D))}},r.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:t});else if(r){var i=r.flush(t);nn(i)||r.async?(nn(i)||(i=Promise.resolve(i)),i.then((function(r){e.handleFlushResult(r,t)})).catch((function(r){e.transmuxerError(r,t,"transmuxer-interface flush error")}))):this.handleFlushResult(i,t)}},r.transmuxerError=function(t,e,r){this.hls&&(this.error=t,this.hls.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.FRAG_PARSING_ERROR,chunkMeta:e,fatal:!1,error:t,err:t,reason:r}))},r.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},r.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":var i,n=null==(i=this.workerContext)?void 0:i.objectURL;n&&self.URL.revokeObjectURL(n);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;case"workerLog":_[e.data.logType]&&_[e.data.logType](e.data.message);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},r.configureTransmuxer=function(t){var e=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:t}):e&&e.configure(t)},r.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},e}(),gn=function(){function t(t,e,r,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=i}var e=t.prototype;return e.destroy=function(){this.media=null,this.hls=this.fragmentTracker=null},e.poll=function(t,e){var r=this.config,i=this.media,n=this.stalled;if(null!==i){var a=i.currentTime,s=i.seeking,o=this.seeking&&!s,l=!this.seeking&&s;if(this.seeking=s,a===t){if(l||o)this.stalled=null;else if(!(i.paused&&!s||i.ended||0===i.playbackRate)&&_r.getBuffered(i).length){var u=_r.bufferInfo(i,a,0),h=u.len>0,d=u.nextStart||0;if(h||d){if(s){var c=u.len>2,f=!d||e&&e.start<=a||d-a>2&&!this.fragmentTracker.getPartialFragment(a);if(c||f)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var g,v=Math.max(d,u.start||0)-a,m=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,p=(null==m||null==(g=m.details)?void 0:g.live)?2*m.details.targetduration:2,y=this.fragmentTracker.getPartialFragment(a);if(v>0&&(v<=p||y))return void this._trySkipBufferHole(y)}var T=self.performance.now();if(null!==n){var E=T-n;if(s||!(E>=250)||(this._reportStall(u),this.media)){var S=_r.bufferInfo(i,a,r.maxBufferHole);this._tryFixBufferStall(S,E)}}else this.stalled=T}}}else if(this.moved=!0,null!==n){if(this.stallReported){var L=self.performance.now()-n;_.warn("playback not stuck anymore @"+a+", after "+Math.round(L)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,n=this.media;if(null!==n){var a=n.currentTime,s=i.getPartialFragment(a);if(s&&(this._trySkipBufferHole(s)||!this.media))return;(t.len>r.maxBufferHole||t.nextStart&&t.nextStart-a1e3*r.highBufferWatchdogPeriod&&(_.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}},e._reportStall=function(t){var e=this.hls,r=this.media;if(!this.stallReported&&r){this.stallReported=!0;var i=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+JSON.stringify(t)+")");_.warn(i.message),e.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.BUFFER_STALLED_ERROR,fatal:!1,error:i,buffer:t.len})}},e._trySkipBufferHole=function(t){var e=this.config,r=this.hls,i=this.media;if(null===i)return 0;var n=i.currentTime,a=_r.bufferInfo(i,n,0),s=n0&&a.len<1&&i.readyState<3,u=s-n;if(u>0&&(o||l)){if(u>e.maxBufferHole){var h=this.fragmentTracker,d=!1;if(0===n){var c=h.getAppendedFrag(0,me);c&&s1?(i=0,this.bitrateTest=!0):i=r.nextAutoLevel),this.level=r.nextLoadLevel=i,this.loadedmetadata=!1}e>0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=Yr,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Vr},r.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case ti:var t,e=this.levels,r=this.level,i=null==e||null==(t=e[r])?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=Yr;break}if(this.hls.nextLoadLevel!==this.level){this.state=Yr;break}break;case qr:var n,a=self.performance.now(),s=this.retryDate;(!s||a>=s||null!=(n=this.media)&&n.seeking)&&(this.resetStartWhenNotLoaded(this.level),this.state=Yr)}this.state===Yr&&this.doTickIdle(),this.onTickEnd()},r.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},r.doTickIdle=function(){var t=this.hls,e=this.levelLastLoaded,r=this.levels,i=this.media,n=t.config,a=t.nextLoadLevel;if(null!==e&&(i||!this.startFragRequested&&n.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&null!=r&&r[a]){var s=r[a],o=this.getMainFwdBufferInfo();if(null!==o){var l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){var u={};return this.altAudio&&(u.type="video"),this.hls.trigger(R.BUFFER_EOS,u),void(this.state=$r)}t.loadLevel!==a&&-1===t.manualLevel&&this.log("Adapting to level "+a+" from level "+this.level),this.level=t.nextLoadLevel=a;var h=s.details;if(!h||this.state===ti||h.live&&this.levelLastLoaded!==a)return this.level=a,void(this.state=ti);var d=o.len,c=this.getMaxBufferLength(s.maxBitrate);if(!(d>=c)){this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);var f=this.backtrackFragment?this.backtrackFragment.start:o.end,g=this.getNextFragment(f,h);if(this.couldBacktrack&&!this.fragPrevious&&g&&"initSegment"!==g.sn&&this.fragmentTracker.getState(g)!==Tr){var v,m=(null!=(v=this.backtrackFragment)?v:g).sn-h.startSN,p=h.fragments[m-1];p&&g.cc===p.cc&&(g=p,this.fragmentTracker.removeFragment(p))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,f)){if(!g.gap){var y=this.audioOnly&&!this.altAudio?U:B,T=(y===B?this.videoBuffer:this.mediaBuffer)||this.media;T&&this.afterBufferFlushed(T,y,me)}g=this.getNextFragmentLoopLoading(g,h,o,me,c)}g&&(!g.initSegment||g.initSegment.data||this.bitrateTest||(g=g.initSegment),this.loadFragment(g,s,f))}}}},r.loadFragment=function(e,r,i){var n=this.fragmentTracker.getState(e);this.fragCurrent=e,n===mr||n===yr?"initSegment"===e.sn?this._loadInitSegment(e,r):this.bitrateTest?(this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e,r)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):this.clearTrackerIfNeeded(e)},r.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,me)},r.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},r.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},r.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);var n=this.getLevelDetails();if(null!=n&&n.live){var a=this.getMainFwdBufferInfo();if(!a||a.len<2*n.targetduration)return}if(!e.paused&&t){var s=t[this.hls.nextLoadLevel],o=this.fragLastKbps;r=o&&this.fragCurrent?this.fragCurrent.duration*s.maxBitrate/(1e3*o)+1:0}else r=0;var l=this.getBufferedFrag(e.currentTime+r);if(l){var u=this.followingBufferedFrag(l);if(u){this.abortCurrentFrag();var h=u.maxStartPTS?u.maxStartPTS:u.start,d=u.duration,c=Math.max(l.end,h+Math.min(Math.max(d-this.config.maxFragLookUpTolerance,.5*d),.75*d));this.flushMainBuffer(c,Number.POSITIVE_INFINITY)}}}},r.abortCurrentFrag=function(){var t=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Wr:case jr:case qr:case zr:case Qr:this.state=Yr}this.nextLoadPosition=this.getLoadPosition()},r.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},r.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new gn(this.config,i,this.fragmentTracker,this.hls)},r.onMediaDetaching=function(){var e=this.media;e&&this.onvplaying&&this.onvseeked&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},r.onMediaPlaying=function(){this.tick()},r.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;E(e)&&this.log("Media seeked to "+e.toFixed(3));var r=this.getMainFwdBufferInfo();null!==r&&0!==r.len?this.tick():this.warn('Main forward buffer length on "seeked" event '+(r?r.len:"empty")+")")},r.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(R.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.couldBacktrack=!1,this.startPosition=this.lastCurrentTime=0,this.levels=this.fragPlaying=this.backtrackFragment=null,this.altAudio=this.audioOnly=!1},r.onManifestParsed=function(t,e){var r,i,n,a=!1,s=!1;e.levels.forEach((function(t){(r=t.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(a=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=a&&s&&!("function"==typeof(null==(n=ri())||null==(i=n.prototype)?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},r.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===Yr){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(i.details))&&(this.state=ti)}},r.onLevelLoaded=function(t,e){var r,i=this.levels,n=e.level,a=e.details,s=a.totalduration;if(i){this.log("Level "+n+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+", cc ["+a.startCC+", "+a.endCC+"] duration:"+s);var o=i[n],l=this.fragCurrent;!l||this.state!==jr&&this.state!==qr||l.level===e.level&&l.urlId===o.urlId||!l.loader||this.abortCurrentFrag();var u=0;if(a.live||null!=(r=o.details)&&r.live){if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;u=this.alignPlaylists(a,o.details)}if(o.details=a,this.levelLastLoaded=n,this.hls.trigger(R.LEVEL_UPDATED,{details:a,level:n}),this.state===ti){if(this.waitForCdnTuneIn(a))return;this.state=Yr}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,u),this.tick()}else this.warn("Levels were reset while loading level "+n)},r._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,n=t.payload,a=this.levels;if(a){var s=a[r.level],o=s.details;if(!o)return this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset"),void this.fragmentTracker.removeFragment(r);var l=s.videoCodec,u=o.PTSKnown||!o.live,h=null==(e=r.initSegment)?void 0:e.data,d=this._getAudioCodec(s),c=this.transmuxer=this.transmuxer||new fn(this.hls,me,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,v=new Pr(r.level,r.sn,r.stats.chunkCount,n.byteLength,f,g),m=this.initPTS[r.cc];c.push(n,h,d,l,r,i,o.totalduration,u,v,m)}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r.onAudioTrackSwitching=function(t,e){var r=this.altAudio;if(!e.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var i=this.fragCurrent;i&&(this.log("Switching to main audio track, cancel main fragment load"),i.abortRequests(),this.fragmentTracker.removeFragment(i)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var n=this.hls;r&&(n.trigger(R.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),n.trigger(R.AUDIO_TRACK_SWITCHED,e)}},r.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=i,this.tick()},r.onBufferCreated=function(t,e){var r,i,n=e.tracks,a=!1;for(var s in n){var o=n[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=n[s];l&&(this.videoBuffer=l.buffer)}}else a=!0}a&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},r.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===me){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Qr&&(this.state=Yr));var n=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*n.total/(n.buffering.end-n.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},r.onError=function(t,e){var r;if(e.fatal)this.state=Jr;else switch(e.details){case k.FRAG_GAP:case k.FRAG_PARSING_ERROR:case k.FRAG_DECRYPT_ERROR:case k.FRAG_LOAD_ERROR:case k.FRAG_LOAD_TIMEOUT:case k.KEY_LOAD_ERROR:case k.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(me,e);break;case k.LEVEL_LOAD_ERROR:case k.LEVEL_LOAD_TIMEOUT:case k.LEVEL_PARSING_ERROR:e.levelRetry||this.state!==ti||(null==(r=e.context)?void 0:r.type)!==fe||(this.state=Yr);break;case k.BUFFER_FULL_ERROR:if(!e.parent||"main"!==e.parent)return;this.reduceLengthAndFlushBuffer(e)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case k.INTERNAL_EXCEPTION:this.recoverWorkerError(e)}},r.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){if(this.loadedmetadata||!_r.getBuffered(t).length){var r=this.state!==Yr?this.fragCurrent:null;e.poll(this.lastCurrentTime,r)}this.lastCurrentTime=t.currentTime}},r.onFragLoadEmergencyAborted=function(){this.state=Yr,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()},r.onBufferFlushed=function(t,e){var r=e.type;if(r!==U||this.audioOnly&&!this.altAudio){var i=(r===B?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r,me)}},r.onLevelsUpdated=function(t,e){this.levels=e.levels},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var t=this.media;if(t){var e=t.currentTime,r=this.startPosition;if(r>=0&&e0&&(nT.cc;if(!1!==n.independent){var A=h.startPTS,k=h.endPTS,b=h.startDTS,D=h.endDTS;if(l)l.elementaryStreams[h.type]={startPTS:A,endPTS:k,startDTS:b,endDTS:D};else if(h.firstKeyFrame&&h.independent&&1===a.id&&!L&&(this.couldBacktrack=!0),h.dropped&&h.independent){var I=this.getMainFwdBufferInfo(),w=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,C=h.firstKeyFramePTS?h.firstKeyFramePTS:A;if(!S&&w1&&!1===t.seeking){var r=t.currentTime;if(_r.isBuffered(t,r)?e=this.getAppendedFrag(r):_r.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){this.backtrackFragment=null;var i=this.fragPlaying,n=e.level;i&&e.sn===i.sn&&i.level===n&&e.urlId===i.urlId||(this.fragPlaying=e,this.hls.trigger(R.FRAG_CHANGED,{frag:e}),i&&i.level===n||this.hls.trigger(R.LEVEL_SWITCHED,{level:n}))}}},a(e,[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentFrag",get:function(){var t=this.media;return t?this.fragPlaying||this.getAppendedFrag(t.currentTime):null}},{key:"currentProgramDateTime",get:function(){var t=this.media;if(t){var e=t.currentTime,r=this.currentFrag;if(r&&E(e)&&E(r.programDateTime)){var i=r.programDateTime+1e3*(e-r.start);return new Date(i)}}return null}},{key:"currentLevel",get:function(){var t=this.currentFrag;return t?t.level:-1}},{key:"nextBufferedFrag",get:function(){var t=this.currentFrag;return t?this.followingBufferedFrag(t):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}]),e}(ei),mn=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),pn=function(){function t(t,e,r,i){void 0===i&&(i=100),this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new mn(t),this.fast_=new mn(e),this.defaultTTFB_=i,this.ttfb_=new mn(t)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==t&&(this.slow_=new mn(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.fast_=new mn(e,i.getEstimate(),i.getTotalWeight())),n.halfLife!==t&&(this.ttfb_=new mn(t,n.getEstimate(),n.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.sampleTTFB=function(t){var e=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(e,2)/2);this.ttfb_.sample(r,Math.max(t,5))},e.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},e.destroy=function(){},t}(),yn=function(){function t(t){this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=0,this._nextAutoLevel=-1,this.timer=-1,this.onCheck=this._abandonRulesCheck.bind(this),this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.bwEstimator=void 0,this.hls=t;var e=t.config;this.bwEstimator=new pn(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate),this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(R.FRAG_LOADING,this.onFragLoading,this),t.on(R.FRAG_LOADED,this.onFragLoaded,this),t.on(R.FRAG_BUFFERED,this.onFragBuffered,this),t.on(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(R.LEVEL_LOADED,this.onLevelLoaded,this)},e.unregisterListeners=function(){var t=this.hls;t.off(R.FRAG_LOADING,this.onFragLoading,this),t.off(R.FRAG_LOADED,this.onFragLoaded,this),t.off(R.FRAG_BUFFERED,this.onFragBuffered,this),t.off(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(R.LEVEL_LOADED,this.onLevelLoaded,this)},e.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this.onCheck=null,this.fragCurrent=this.partCurrent=null},e.onFragLoading=function(t,e){var r,i=e.frag;this.ignoreFragment(i)||(this.fragCurrent=i,this.partCurrent=null!=(r=e.part)?r:null,this.clearTimer(),this.timer=self.setInterval(this.onCheck,100))},e.onLevelSwitching=function(t,e){this.clearTimer()},e.getTimeToLoadFrag=function(t,e,r,i){return t+r/e+(i?this.lastLevelLoadSec:0)},e.onLevelLoaded=function(t,e){var r=this.hls.config,i=e.stats,n=i.total,a=i.bwEstimate;E(n)&&E(a)&&(this.lastLevelLoadSec=8*n/a),e.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD)},e._abandonRulesCheck=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.autoLevelEnabled,n=r.media;if(t&&n){var a=performance.now(),s=e?e.stats:t.stats,o=e?e.duration:t.duration,l=a-s.loading.start;if(s.aborted||s.loaded&&s.loaded===s.total||0===t.level)return this.clearTimer(),void(this._nextAutoLevel=-1);if(i&&!n.paused&&n.playbackRate&&n.readyState){var u=r.mainForwardBufferInfo;if(null!==u){var h=this.bwEstimator.getEstimateTTFB(),d=Math.abs(n.playbackRate);if(!(l<=Math.max(h,o/(2*d)*1e3))){var c=u.len/d;if(!(c>=2*o/d)){var f=s.loading.first?s.loading.first-s.loading.start:-1,g=s.loaded&&f>-1,v=this.bwEstimator.getEstimate(),m=r.levels,p=r.minAutoLevel,y=m[t.level],T=s.total||Math.max(s.loaded,Math.round(o*y.maxBitrate/8)),S=l-f;S<1&&g&&(S=Math.min(l,8*s.loaded/v));var L=g?1e3*s.loaded/S:0,A=L?(T-s.loaded)/L:8*T/v+h/1e3;if(!(A<=c)){var k,b=L?8*L:v,D=Number.POSITIVE_INFINITY;for(k=t.level-1;k>p;k--){var I=m[k].maxBitrate;if((D=this.getTimeToLoadFrag(h/1e3,b,o*I,!m[k].details))=A||D>10*o||(r.nextLoadLevel=k,g?this.bwEstimator.sample(l-Math.min(h,f),s.loaded):this.bwEstimator.sampleTTFB(l),this.clearTimer(),_.warn("[abr] Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" is loading too slowly;\n Time to underbuffer: "+c.toFixed(3)+" s\n Estimated load time for current fragment: "+A.toFixed(3)+" s\n Estimated load time for down switch fragment: "+D.toFixed(3)+" s\n TTFB estimate: "+f+"\n Current BW estimate: "+(E(v)?(v/1024).toFixed(3):"Unknown")+" Kb/s\n New BW estimate: "+(this.bwEstimator.getEstimate()/1024).toFixed(3)+" Kb/s\n Aborting and switching to level "+k),t.loader&&(this.fragCurrent=this.partCurrent=null,t.abortRequests()),r.trigger(R.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:s}))}}}}}}},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part,n=i?i.stats:r.stats;if(r.type===me&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var a=i?i.duration:r.duration,s=this.hls.levels[r.level],o=(s.loaded?s.loaded.bytes:0)+n.loaded,l=(s.loaded?s.loaded.duration:0)+a;s.loaded={bytes:o,duration:l},s.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){var u={stats:n,frag:r,part:i,id:r.type};this.onFragBuffered(R.FRAG_BUFFERED,u),r.bitrateTest=!1}}},e.onFragBuffered=function(t,e){var r=e.frag,i=e.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=n.parsing.end-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}},e.ignoreFragment=function(t){return t.type!==me||"initSegment"===t.sn},e.clearTimer=function(){self.clearInterval(this.timer)},e.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=r.media,o=e?e.duration:t?t.duration:0,l=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,u=this.bwEstimator?this.bwEstimator.getEstimate():n.abrEwmaDefaultEstimate,h=r.mainForwardBufferInfo,d=(h?h.len:0)/l,c=this.findBestLevel(u,a,i,d,n.abrBandWidthFactor,n.abrBandWidthUpFactor);if(c>=0)return c;_.trace("[abr] "+(d?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var f=o?Math.min(o,n.maxStarvationDelay):n.maxStarvationDelay,g=n.abrBandWidthFactor,v=n.abrBandWidthUpFactor;if(!d){var m=this.bitrateTestDelay;m&&(f=(o?Math.min(o,n.maxLoadingDelay):n.maxLoadingDelay)-m,_.trace("[abr] bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*f)+" ms"),g=v=1)}return c=this.findBestLevel(u,a,i,d+f,g,v),Math.max(c,0)},e.findBestLevel=function(t,e,r,i,n,a){for(var s,o=this.fragCurrent,l=this.partCurrent,u=this.lastLoadedFragLevel,h=this.hls.levels,d=h[u],c=!(null==d||null==(s=d.details)||!s.live),f=null==d?void 0:d.codecSet,g=l?l.duration:o?o.duration:0,v=this.bwEstimator.getEstimateTTFB()/1e3,m=e,p=-1,y=r;y>=e;y--){var T=h[y];if(!T||f&&T.codecSet!==f)T&&(m=Math.min(y,m),p=Math.max(y,p));else{-1!==p&&_.trace("[abr] Skipped level(s) "+m+"-"+p+' with CODECS:"'+h[p].attrs.CODECS+'"; not compatible with "'+d.attrs.CODECS+'"');var S=T.details,L=(l?null==S?void 0:S.partTarget:null==S?void 0:S.averagetargetduration)||g,R=void 0;R=y<=u?n*t:a*t;var A=h[y].maxBitrate,k=this.getTimeToLoadFrag(v,R,A*L,void 0===S);if(_.trace("[abr] level:"+y+" adjustedbw-bitrate:"+Math.round(R-A)+" avgDuration:"+L.toFixed(1)+" maxFetchDuration:"+i.toFixed(1)+" fetchDuration:"+k.toFixed(1)),R>A&&(0===k||!E(k)||c&&!this.bitrateTestDelay||kMath.max(t,r)&&i[t].loadError<=i[r].loadError)return t}return-1!==t&&(r=Math.min(t,r)),r},set:function(t){this._nextAutoLevel=t}}]),t}(),Tn=function(){function t(){this.chunks=[],this.dataLength=0}var e=t.prototype;return e.push=function(t){this.chunks.push(t),this.dataLength+=t.length},e.flush=function(){var t,e=this.chunks,r=this.dataLength;return e.length?(t=1===e.length?e[0]:function(t,e){for(var r=new Uint8Array(e),i=0,n=0;n0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e,this.state=Yr):(this.loadedmetadata=!1,this.state=Xr),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()},r.doTick=function(){switch(this.state){case Yr:this.doTickIdle();break;case Xr:var e,r=this.levels,i=this.trackId,n=null==r||null==(e=r[i])?void 0:e.details;if(n){if(this.waitForCdnTuneIn(n))break;this.state=Zr}break;case qr:var a,s=performance.now(),o=this.retryDate;(!o||s>=o||null!=(a=this.media)&&a.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded(this.trackId),this.state=Yr);break;case Zr:var l=this.waitingData;if(l){var u=l.frag,h=l.part,d=l.cache,c=l.complete;if(void 0!==this.initPTS[u.cc]){this.waitingData=null,this.waitingVideoCC=-1,this.state=jr;var f={frag:u,part:h,payload:d.flush(),networkDetails:null};this._handleFragmentLoadProgress(f),c&&t.prototype._handleFragmentLoadComplete.call(this,f)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log("Waiting fragment cc ("+u.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var g=this.getLoadPosition(),v=_r.bufferInfo(this.mediaBuffer,g,this.config.maxBufferHole);er(v.end,this.config.maxFragLookUpTolerance,u)<0&&(this.log("Waiting fragment cc ("+u.cc+") @ "+u.start+" cancelled because another fragment at "+v.end+" is needed"),this.clearWaitingFragment())}}else this.state=Yr}this.onTickEnd()},r.clearWaitingFragment=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Yr)},r.resetLoadingState=function(){this.clearWaitingFragment(),t.prototype.resetLoadingState.call(this)},r.onTickEnd=function(){var t=this.media;null!=t&&t.readyState&&(this.lastCurrentTime=t.currentTime)},r.doTickIdle=function(){var t=this.hls,e=this.levels,r=this.media,i=this.trackId,n=t.config;if(null!=e&&e[i]&&(r||!this.startFragRequested&&n.startFragPrefetch)){var a=e[i],s=a.details;if(!s||s.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(s))this.state=Xr;else{var o=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&o&&(this.bufferFlushed=!1,this.afterBufferFlushed(o,U,pe));var l=this.getFwdBufferInfo(o,pe);if(null!==l){var u=this.bufferedTrack,h=this.switchingTrack;if(!h&&this._streamEnded(l,s))return t.trigger(R.BUFFER_EOS,{type:"audio"}),void(this.state=$r);var d=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,me),c=l.len,f=this.getMaxBufferLength(null==d?void 0:d.len);if(!(c>=f)||h){var g=s.fragments[0].start,v=l.end;if(h&&r){var m=this.getLoadPosition();u&&h.attrs!==u.attrs&&(v=m),s.PTSKnown&&mg||l.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),r.currentTime=g+.05)}var p=this.getNextFragment(v,s),y=!1;if(p&&this.isLoopLoading(p,v)&&(y=!!p.gap,p=this.getNextFragmentLoopLoading(p,s,l,me,f)),p){var T=d&&p.start>d.end+s.targetduration;if(T||(null==d||!d.len)&&l.len){var E=this.getAppendedFrag(p.start,me);if(null===E)return;if(y||(y=!!E.gap||!!T&&0===d.len),T&&!y||y&&l.nextStart&&l.nextStart=e.length)this.warn("Invalid id passed to audio-track controller");else{this.clearTimer();var r=this.currentTrack;e[this.trackId];var n=e[t],a=n.groupId,s=n.name;if(this.log("Switching to audio-track "+t+' "'+s+'" lang:'+n.lang+" group:"+a),this.trackId=t,this.currentTrack=n,this.selectDefaultTrack=!1,this.hls.trigger(R.AUDIO_TRACK_SWITCHING,i({},n)),!n.details||n.details.live){var o=this.switchParams(n.url,null==r?void 0:r.details);this.loadPlaylist(o)}}},r.selectInitialTrack=function(){var t=this.tracksInGroup,e=this.findTrackId(this.currentTrack)|this.findTrackId(null);if(-1!==e)this.setAudioTrack(e);else{var r=new Error("No track found for running audio group-ID: "+this.groupId+" track count: "+t.length);this.warn(r.message),this.hls.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:r})}},r.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=n[o].start&&s<=n[o].end){a=n[o];break}var l=r.start+r.duration;a?a.end=l:(a={start:s,end:l},n.push(a)),this.fragmentTracker.fragBuffered(r)}}},r.onBufferFlushing=function(t,e){var r=e.startOffset,i=e.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;e.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach((function(t){for(var e=0;e=s.length||n!==a)&&o){this.mediaBuffer=this.mediaBufferTimeRanges;var l=0;if(i.live||null!=(r=o.details)&&r.live){var u=this.mainDetails;if(i.deltaUpdateFailed||!u)return;var h=u.fragments[0];o.details?0===(l=this.alignPlaylists(i,o.details))&&h&&We(i,l=h.start):i.hasProgramDateTime&&u.hasProgramDateTime?(Nr(i,u),l=i.fragments[0].start):h&&We(i,l=h.start)}o.details=i,this.levelLastLoaded=n,this.startFragRequested||!this.mainDetails&&i.live||this.setStartPosition(o.details,l),this.tick(),i.live&&!this.fragCurrent&&this.media&&this.state===Yr&&(tr(null,i.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),o.details=void 0))}}},r._handleFragmentLoadComplete=function(t){var e=this,r=t.frag,i=t.payload,n=r.decryptdata,a=this.hls;if(!this.fragContextChanged(r)&&i&&i.byteLength>0&&n&&n.key&&n.iv&&"AES-128"===n.method){var s=performance.now();this.decrypter.decrypt(new Uint8Array(i),n.key.buffer,n.iv.buffer).catch((function(t){throw a.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.FRAG_DECRYPT_ERROR,fatal:!1,error:t,reason:t.message,frag:r}),t})).then((function(t){var e=performance.now();a.trigger(R.FRAG_DECRYPTED,{frag:r,payload:t,stats:{tstart:s,tdecrypt:e}})})).catch((function(t){e.warn(t.name+": "+t.message),e.state=Yr}))}},r.doTick=function(){if(this.media){if(this.state===Yr){var t=this.currentTrackId,e=this.levels,r=e[t];if(!e.length||!r||!r.details)return;var i=this.config,n=this.getLoadPosition(),a=_r.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],n,i.maxBufferHole),s=a.end,o=a.len,l=this.getFwdBufferInfo(this.media,me),u=r.details;if(o>this.getMaxBufferLength(null==l?void 0:l.len)+u.levelTargetDuration)return;var h=u.fragments,d=h.length,c=u.edge,f=null,g=this.fragPrevious;if(sc-v?0:v;!(f=tr(g,h,Math.max(h[0].start,s),m))&&g&&g.start>>=0)>i-1)throw new DOMException("Failed to execute '"+e+"' on 'TimeRanges': The index provided ("+r+") is greater than the maximum bound ("+i+")");return t[r][e]};this.buffered={get length(){return t.length},end:function(r){return e("end",r,t.length)},start:function(r){return e("start",r,t.length)}}},bn=function(t){function e(e){var r;return(r=t.call(this,e,"[subtitle-track-controller]")||this).media=null,r.tracks=[],r.groupId=null,r.tracksInGroup=[],r.trackId=-1,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.trackChangeListener=function(){return r.onTextTracksChanged()},r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.registerListeners(),r}l(e,t);var r=e.prototype;return r.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.trackChangeListener=this.asyncPollTrackChange=null,t.prototype.destroy.call(this)},r.registerListeners=function(){var t=this.hls;t.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_PARSED,this.onManifestParsed,this),t.on(R.LEVEL_LOADING,this.onLevelLoading,this),t.on(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(R.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(R.ERROR,this.onError,this)},r.unregisterListeners=function(){var t=this.hls;t.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_PARSED,this.onManifestParsed,this),t.off(R.LEVEL_LOADING,this.onLevelLoading,this),t.off(R.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(R.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(R.ERROR,this.onError,this)},r.onMediaAttached=function(t,e){this.media=e.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))},r.pollTrackChange=function(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.trackChangeListener,t)},r.onMediaDetaching=function(){this.media&&(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Dn(this.media.textTracks).forEach((function(t){Ae(t)})),this.subtitleTrack=-1,this.media=null)},r.onManifestLoading=function(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0},r.onManifestParsed=function(t,e){this.tracks=e.subtitleTracks},r.onSubtitleTrackLoaded=function(t,e){var r=e.id,i=e.details,n=this.trackId,a=this.tracksInGroup[n];if(a){var s=a.details;a.details=e.details,this.log("subtitle track "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&this.playlistLoaded(r,e,s)}else this.warn("Invalid subtitle track id "+r)},r.onLevelLoading=function(t,e){this.switchLevel(e.level)},r.onLevelSwitching=function(t,e){this.switchLevel(e.level)},r.switchLevel=function(t){var e=this.hls.levels[t];if(null!=e&&e.textGroupIds){var r=e.textGroupIds[e.urlId],i=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;if(this.groupId!==r){var n=this.tracks.filter((function(t){return!r||t.groupId===r}));this.tracksInGroup=n;var a=this.findTrackId(null==i?void 0:i.name)||this.findTrackId();this.groupId=r||null;var s={subtitleTracks:n};this.log("Updating subtitle tracks, "+n.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(R.SUBTITLE_TRACKS_UPDATED,s),-1!==a&&this.setSubtitleTrack(a,i)}else this.shouldReloadPlaylist(i)&&this.setSubtitleTrack(this.trackId,i)}},r.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=i.length)){this.clearTimer();var n=i[t];if(this.log("Switching to subtitle-track "+t+(n?' "'+n.name+'" lang:'+n.lang+" group:"+n.groupId:"")),this.trackId=t,n){var a=n.id,s=n.groupId,o=void 0===s?"":s,l=n.name,u=n.type,h=n.url;this.hls.trigger(R.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:h});var d=this.switchParams(n.url,null==e?void 0:e.details);this.loadPlaylist(d)}else this.hls.trigger(R.SUBTITLE_TRACK_SWITCH,{id:t})}}else this.queuedDefaultTrack=t},r.onTextTracksChanged=function(){if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),this.media&&this.hls.config.renderTextTracksNatively){for(var t=-1,e=Dn(this.media.textTracks),r=0;r-1&&this.toggleTrackModes(this.trackId)}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(t){this.selectDefaultTrack=!1;var e=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0;this.setSubtitleTrack(t,e)}}]),e}(cr);function Dn(t){for(var e=[],r=0;r "+t.src+")")},this.hls=t,this._initSourceBuffer(),this.registerListeners()}var e=t.prototype;return e.hasSourceTypes=function(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null},e.registerListeners=function(){var t=this.hls;t.on(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_PARSED,this.onManifestParsed,this),t.on(R.BUFFER_RESET,this.onBufferReset,this),t.on(R.BUFFER_APPENDING,this.onBufferAppending,this),t.on(R.BUFFER_CODECS,this.onBufferCodecs,this),t.on(R.BUFFER_EOS,this.onBufferEos,this),t.on(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(R.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(R.FRAG_PARSED,this.onFragParsed,this),t.on(R.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_PARSED,this.onManifestParsed,this),t.off(R.BUFFER_RESET,this.onBufferReset,this),t.off(R.BUFFER_APPENDING,this.onBufferAppending,this),t.off(R.BUFFER_CODECS,this.onBufferCodecs,this),t.off(R.BUFFER_EOS,this.onBufferEos,this),t.off(R.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(R.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(R.FRAG_PARSED,this.onFragParsed,this),t.off(R.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new In(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.lastMpegAudioChunk=null},e.onManifestLoading=function(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,_.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media;if(r&&wn){var i=this.mediaSource=new wn;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src,r.addEventListener("emptied",this._onMediaEmptied)}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(_.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){_.warn("[buffer-controller]: onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(t.removeEventListener("emptied",this._onMediaEmptied),r&&self.URL.revokeObjectURL(r),t.src===r?(t.removeAttribute("src"),t.load()):_.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(R.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this;this.getSourceBufferTypes().forEach((function(e){var r=t.sourceBuffer[e];try{r&&(t.removeBufferListeners(e),t.mediaSource&&t.mediaSource.removeSourceBuffer(r),t.sourceBuffer[e]=void 0)}catch(t){_.warn("[buffer-controller]: Failed to reset the "+e+" buffer",t)}})),this._initSourceBuffer()},e.onBufferCodecs=function(t,e){var r=this,i=this.getSourceBufferTypes().length;Object.keys(e).forEach((function(t){if(i){var n=r.tracks[t];if(n&&"function"==typeof n.buffer.changeType){var a=e[t],s=a.id,o=a.codec,l=a.levelCodec,u=a.container,h=a.metadata,d=(n.levelCodec||n.codec).replace(Cn,"$1"),c=(l||o).replace(Cn,"$1");if(d!==c){var f=u+";codecs="+(l||o);r.appendChangeType(t,f),_.log("[buffer-controller]: switching codec "+d+" to "+c),r.tracks[t]={buffer:n.buffer,codec:o,container:u,levelCodec:l,metadata:h,id:s}}}}else r.pendingTracks[t]=e[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,n={execute:function(){var n=r.sourceBuffer[t];n&&(_.log("[buffer-controller]: changing "+t+" sourceBuffer type to "+e),n.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){_.warn("[buffer-controller]: Failed to change "+t+" SourceBuffer type",e)}};i.append(n,t)},e.onBufferAppending=function(t,e){var r=this,i=this.hls,n=this.operationQueue,a=this.tracks,s=e.data,o=e.type,l=e.frag,u=e.part,h=e.chunkMeta,d=h.buffering[o],c=self.performance.now();d.start=c;var f=l.stats.buffering,g=u?u.stats.buffering:null;0===f.start&&(f.start=c),g&&0===g.start&&(g.start=c);var v=a.audio,m=!1;"audio"===o&&"audio/mpeg"===(null==v?void 0:v.container)&&(m=!this.lastMpegAudioChunk||1===h.id||this.lastMpegAudioChunk.sn!==h.sn,this.lastMpegAudioChunk=h);var p=l.start,y={execute:function(){if(d.executeStart=self.performance.now(),m){var t=r.sourceBuffer[o];if(t){var e=p-t.timestampOffset;Math.abs(e)>=.1&&(_.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+p+" (delta: "+e+") sn: "+l.sn+")"),t.timestampOffset=p)}}r.appendExecutor(s,o)},onStart:function(){},onComplete:function(){var t=self.performance.now();d.executeEnd=d.end=t,0===f.first&&(f.first=t),g&&0===g.first&&(g.first=t);var e=r.sourceBuffer,i={};for(var n in e)i[n]=_r.getBuffered(e[n]);r.appendError=0,r.hls.trigger(R.BUFFER_APPENDED,{type:o,frag:l,part:u,chunkMeta:h,parent:l.type,timeRanges:i})},onError:function(t){_.error("[buffer-controller]: Error encountered while trying to append to the "+o+" SourceBuffer",t);var e={type:A.MEDIA_ERROR,parent:l.type,details:k.BUFFER_APPEND_ERROR,frag:l,part:u,chunkMeta:h,error:t,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=k.BUFFER_FULL_ERROR:(r.appendError++,e.details=k.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(_.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),e.fatal=!0)),i.trigger(R.ERROR,e)}};n.append(y,o)},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,n=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(R.BUFFER_FLUSHED,{type:t})},onError:function(e){_.warn("[buffer-controller]: Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(n(e.type),e.type):this.getSourceBufferTypes().forEach((function(t){i.append(n(t),t)}))},e.onFragParsed=function(t,e){var r=this,i=e.frag,n=e.part,a=[],s=n?n.elementaryStreams:i.elementaryStreams;s[G]?a.push("audiovideo"):(s[U]&&a.push("audio"),s[B]&&a.push("video")),0===a.length&&_.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,n&&(n.stats.buffering.end=t);var e=n?n.stats:i.stats;r.hls.trigger(R.FRAG_BUFFERED,{frag:i,part:n,stats:e,id:i.type})}),a)},e.onFragChanged=function(t,e){this.flushBackBuffer()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var n=r.sourceBuffer[i];return!n||e.type&&e.type!==i||(n.ending=!0,n.ended||(n.ended=!0,_.log("[buffer-controller]: "+i+" sourceBuffer now EOS"))),t&&!(n&&!n.ended)}),!0)&&(_.log("[buffer-controller]: Queueing mediaSource.endOfStream()"),this.blockBuffers((function(){r.getSourceBufferTypes().forEach((function(t){var e=r.sourceBuffer[t];e&&(e.ending=!1)}));var t=r.mediaSource;t&&"open"===t.readyState?(_.log("[buffer-controller]: Calling mediaSource.endOfStream()"),t.endOfStream()):t&&_.info("[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: "+t.readyState)})))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function(){var t=this.hls,e=this.details,r=this.media,i=this.sourceBuffer;if(r&&null!==e){var n=this.getSourceBufferTypes();if(n.length){var a=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(E(a)&&!(a<0)){var s=r.currentTime,o=e.levelTargetDuration,l=Math.max(a,o),u=Math.floor(s/o)*o-l;n.forEach((function(r){var n=i[r];if(n){var a=_r.getBuffered(n);if(a.length>0&&u>a.start(0)){if(t.trigger(R.BACK_BUFFER_REACHED,{bufferEnd:u}),e.live)t.trigger(R.LIVE_BACK_BUFFER_REACHED,{bufferEnd:u});else if(n.ended&&a.end(a.length-1)-s<2*o)return void _.info("[buffer-controller]: Cannot flush "+r+" back buffer while SourceBuffer is in ended state");t.trigger(R.BUFFER_FLUSHING,{startOffset:0,endOffset:u,type:r})}}}))}}}},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,i=this.mediaSource,n=t.fragments[0].start+t.totalduration,a=r.duration,s=E(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(_.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(t)):(n>s&&n>a||!E(a))&&(_.log("[buffer-controller]: Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),n=Math.max(i,i+t.totalduration);e.setLiveSeekableRange(i,n)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!t||2===i){this.createSourceBuffers(r),this.pendingTracks={};var n=this.getSourceBufferTypes();if(n.length)this.hls.trigger(R.BUFFER_CREATED,{tracks:this.tracks}),n.forEach((function(t){e.executeNext(t)}));else{var a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}},e.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");for(var i in t)if(!e[i]){var n=t[i];if(!n)throw Error("source buffer exists for track "+i+", however track does not");var a=n.levelCodec||n.codec,s=n.container+";codecs="+a;_.log("[buffer-controller]: creating sourceBuffer("+s+")");try{var o=e[i]=r.addSourceBuffer(s),l=i;this.addBufferListener(l,"updatestart",this._onSBUpdateStart),this.addBufferListener(l,"updateend",this._onSBUpdateEnd),this.addBufferListener(l,"error",this._onSBUpdateError),this.tracks[i]={buffer:o,codec:a,container:n.container,levelCodec:n.levelCodec,metadata:n.metadata,id:n.id}}catch(t){_.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:s})}}},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e=this.operationQueue;e.current(t).onComplete(),e.shiftAndExecuteNext(t)},e._onSBUpdateError=function(t,e){var r=new Error(t+" SourceBuffer error");_.error("[buffer-controller]: "+r,e),this.hls.trigger(R.ERROR,{type:A.MEDIA_ERROR,details:k.BUFFER_APPENDING_ERROR,error:r,fatal:!1});var i=this.operationQueue.current(t);i&&i.onError(e)},e.removeExecutor=function(t,e,r){var i=this.media,n=this.mediaSource,a=this.operationQueue,s=this.sourceBuffer[t];if(!i||!n||!s)return _.warn("[buffer-controller]: Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void a.shiftAndExecuteNext(t);var o=E(i.duration)?i.duration:1/0,l=E(n.duration)?n.duration:1/0,u=Math.max(0,e),h=Math.min(r,o,l);h>u&&!s.ending?(s.ended=!1,_.log("[buffer-controller]: Removing ["+u+","+h+"] from the "+t+" SourceBuffer"),s.remove(u,h)):a.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.operationQueue,i=this.sourceBuffer[e];if(!i)return _.warn("[buffer-controller]: Attempting to append to the "+e+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return _.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve().then(t);var i=this.operationQueue,n=e.map((function(t){return i.appendBlocker(t)}));Promise.all(n).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];null!=e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var n=r.bind(this,t);this.listeners[t].push({event:e,listener:n}),i.addEventListener(e,n)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},t}(),Pn={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},xn=function(t){var e=t;return Pn.hasOwnProperty(t)&&(e=Pn[t]),String.fromCharCode(e)},Fn=15,Mn=100,On={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Nn={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Un={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Bn={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Gn=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],Kn=function(){function t(){this.time=null,this.verboseLevel=0}return t.prototype.log=function(t,e){if(this.verboseLevel>=t){var r="function"==typeof e?e():e;_.log(this.time+" ["+t+"] "+r)}},t}(),Hn=function(t){for(var e=[],r=0;rMn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Mn)},e.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var r=this.pos+1;r=144&&this.backSpace();var r=xn(t);this.pos>=Mn?this.logger.log(0,(function(){return"Cannot insert "+t.toString(16)+" ("+r+") at position "+e.pos+". Skipping it!"})):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))},e.clearFromPos=function(t){var e;for(e=t;e0&&(r=t?"["+e.join(" | ")+"]":e.join("\n")),r},e.getTextAndFormat=function(){return this.rows},t}(),qn=function(){function t(t,e,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new jn(r),this.nonDisplayedMemory=new jn(r),this.lastOutputScreen=new jn(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var e=t.prototype;return e.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},e.getHandler=function(){return this.outputFilter},e.setHandler=function(t){this.outputFilter=t},e.setPAC=function(t){this.writeScreen.setPAC(t)},e.setBkgData=function(t){this.writeScreen.setBkgData(t)},e.setMode=function(t){t!==this.mode&&(this.mode=t,this.logger.log(2,(function(){return"MODE="+t})),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)},e.insertChars=function(t){for(var e=this,r=0;r=46,e.italics)e.foreground="white";else{var r=Math.floor(t/2)-16;e.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(2,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)},e.outputDataUpdate=function(t){void 0===t&&(t=!1);var e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))},e.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}(),Xn=function(){function t(t,e,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new Kn;this.channels=[null,new qn(t,e,i),new qn(t+1,r,i)],this.cmdHistory={a:null,b:null},this.logger=i}var e=t.prototype;return e.getHandler=function(t){return this.channels[t].getHandler()},e.setHandler=function(t,e){this.channels[t].setHandler(e)},e.addData=function(t,e){var r,i,n,a=!1;this.logger.time=t;for(var s=0;s ("+Hn([i,n])+")"),(r=this.parseCmd(i,n))||(r=this.parseMidrow(i,n)),r||(r=this.parsePAC(i,n)),r||(r=this.parseBackgroundAttributes(i,n)),!r&&(a=this.parseChars(i,n))){var o=this.currentChannel;o&&o>0?this.channels[o].insertChars(a):this.logger.log(2,"No channel found yet. TEXT-MODE?")}r||a||this.logger.log(2,"Couldn't parse cleaned data "+Hn([i,n])+" orig: "+Hn([e[s],e[s+1]]))}},e.parseCmd=function(t,e){var r=this.cmdHistory;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=33&&e<=35))return!1;if(Qn(t,e,r))return zn(null,null,r),this.logger.log(3,"Repeated command ("+Hn([t,e])+") is dropped"),!0;var i=20===t||21===t||23===t?1:2,n=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?n.ccRCL():33===e?n.ccBS():34===e?n.ccAOF():35===e?n.ccAON():36===e?n.ccDER():37===e?n.ccRU(2):38===e?n.ccRU(3):39===e?n.ccRU(4):40===e?n.ccFON():41===e?n.ccRDC():42===e?n.ccTR():43===e?n.ccRTD():44===e?n.ccEDM():45===e?n.ccCR():46===e?n.ccENM():47===e&&n.ccEOC():n.ccTO(e-32),zn(t,e,r),this.currentChannel=i,!0},e.parseMidrow=function(t,e){var r=0;if((17===t||25===t)&&e>=32&&e<=47){if((r=17===t?1:2)!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(e),this.logger.log(3,"MIDROW ("+Hn([t,e])+")"),!0)}return!1},e.parsePAC=function(t,e){var r,i=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127||(16===t||24===t)&&e>=64&&e<=95))return!1;if(Qn(t,e,i))return zn(null,null,i),!0;var n=t<=23?1:2;r=e>=64&&e<=95?1===n?On[t]:Un[t]:1===n?Nn[t]:Bn[t];var a=this.channels[n];return!!a&&(a.setPAC(this.interpretPAC(r,e)),zn(t,e,i),this.currentChannel=n,!0)},e.interpretPAC=function(t,e){var r,i={color:null,italics:!1,indent:null,underline:!1,row:t};return r=e>95?e-96:e-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},e.parseChars=function(t,e){var r,i,n=null,a=null;if(t>=25?(r=2,a=t-8):(r=1,a=t),a>=17&&a<=19?(i=17===a?e+80:18===a?e+112:e+144,this.logger.log(2,"Special char '"+xn(i)+"' in channel "+r),n=[i]):t>=32&&t<=127&&(n=0===e?[t]:[t,e]),n){var s=Hn(n);this.logger.log(3,"Char codes = "+s.join(",")),zn(t,e,this.cmdHistory)}return n},e.parseBackgroundAttributes=function(t,e){var r;if(!((16===t||24===t)&&e>=32&&e<=47||(23===t||31===t)&&e>=45&&e<=47))return!1;var i={};16===t||24===t?(r=Math.floor((e-32)/2),i.background=Gn[r],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));var n=t<=23?1:2;return this.channels[n].setBkgData(i),zn(t,e,this.cmdHistory),!0},e.reset=function(){for(var t=0;tt)&&(this.startTime=t),this.endTime=e,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function(){this.cueRanges=[],this.startTime=null},t}(),Jn=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;var t=["","lr","rl"],e=["start","middle","end","left","right"];function r(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;var r=e.toLowerCase();return!!~t.indexOf(r)&&r}function i(t){return r(e,t)}function n(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return E},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return S},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");S=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return L},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");L=e,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),Zn=function(){function t(){}return t.prototype.decode=function(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))},t}();function ta(t){function e(t,e,r,i){return 3600*(0|t)+60*(0|e)+(0|r)+parseFloat(i||0)}var r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}var ea=function(){function t(){this.values=Object.create(null)}var e=t.prototype;return e.set=function(t,e){this.get(t)||""===e||(this.values[t]=e)},e.get=function(t,e,r){return r?this.has(t)?this.values[t]:e[r]:this.has(t)?this.values[t]:e},e.has=function(t){return t in this.values},e.alt=function(t,e,r){for(var i=0;i=0&&r<=100)return this.set(t,r),!0}return!1},t}();function ra(t,e,r,i){var n=i?t.split(i):[t];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);2===s.length&&e(s[0],s[1])}}var ia=new Jn(0,0,""),na="middle"===ia.align?"middle":"center";function aa(t,e,r){var i=t;function n(){var e=ta(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=n(),a(),"--\x3e"!==t.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.slice(3),a(),e.endTime=n(),a(),function(t,e){var i=new ea;ra(t,(function(t,e){var n;switch(t){case"region":for(var a=r.length-1;a>=0;a--)if(r[a].id===e){i.set(t,r[a].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":n=e.split(","),i.integer(t,n[0]),i.percent(t,n[0])&&i.set("snapToLines",!1),i.alt(t,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",na,"end"]);break;case"position":n=e.split(","),i.percent(t,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",na,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",na,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===ia.line&&(n=-1),e.line=n,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",na);var a=i.get("position","auto");"auto"===a&&50===ia.position&&(a="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=a}(t,e)}function sa(t){return t.replace(//gi,"\n")}var oa=function(){function t(){this.state="INITIAL",this.buffer="",this.decoder=new Zn,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=t.prototype;return e.parse=function(t){var e=this;function r(){var t=e.buffer,r=0;for(t=sa(t);r>>0).toString()};function da(t,e,r){return ha(t.toString())+ha(e.toString())+ha(r)}function ca(t,e,r,i,n,a,s){var o,l,u,h=new oa,d=Tt(new Uint8Array(t)).trim().replace(la,"\n").split("\n"),c=[],f=e?(o=e.baseTime,void 0===(l=e.timescale)&&(l=1),Ki(o,9e4,1/l)):0,g="00:00.000",v=0,m=0,p=!0;h.oncue=function(t){var a=r[i],s=r.ccOffset,o=(v-f)/9e4;if(null!=a&&a.new&&(void 0!==m?s=r.ccOffset=a.start:function(t,e,r){var i=t[e],n=t[i.prevCC];if(!n||!n.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!=(a=n)&&a.new;){var a;t.ccOffset+=i.start-n.start,i.new=!1,n=t[(i=n).prevCC]}t.presentationOffset=r}(r,i,o)),o){if(!e)return void(u=new Error("Missing initPTS for VTT MPEGTS"));s=o-r.presentationOffset}var l=t.endTime-t.startTime,h=ji(9e4*(t.startTime+s-m),9e4*n)/9e4;t.startTime=Math.max(h,0),t.endTime=Math.max(h+l,0);var d=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(d)),t.id||(t.id=da(t.startTime,t.endTime,d)),t.endTime>0&&c.push(t)},h.onparsingerror=function(t){u=t},h.onflush=function(){u?s(u):a(c)},d.forEach((function(t){if(p){if(ua(t,"X-TIMESTAMP-MAP=")){p=!1,t.slice(16).split(",").forEach((function(t){ua(t,"LOCAL:")?g=t.slice(6):ua(t,"MPEGTS:")&&(v=parseInt(t.slice(7)))}));try{m=function(t){var e=parseInt(t.slice(-3)),r=parseInt(t.slice(-6,-4)),i=parseInt(t.slice(-9,-7)),n=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!(E(e)&&E(r)&&E(i)&&E(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*r,(e+=6e4*i)+36e5*n}(g)/1e3}catch(t){u=t}return}""===t&&(p=!1)}h.parse(t+"\n")})),h.flush()}var fa="stpp.ttml.im1t",ga=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,va=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,ma={left:"start",center:"center",right:"end",start:"start",end:"end"};function pa(t,e,r,i){var n=Ct(new Uint8Array(t),["mdat"]);if(0!==n.length){var a,s,l,u,h=n.map((function(t){return Tt(t)})),d=(a=e.baseTime,s=1,void 0===(l=e.timescale)&&(l=1),void 0===u&&(u=!1),Ki(a,s,1/l,u));try{h.forEach((function(t){return r(function(t,e){var r=(new DOMParser).parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");var i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},n=Object.keys(i).reduce((function(t,e){return t[e]=r.getAttribute("ttp:"+e)||i[e],t}),{}),a="preserve"!==r.getAttribute("xml:space"),s=Ta(ya(r,"styling","style")),l=Ta(ya(r,"layout","region")),u=ya(r,"body","[begin]");return[].map.call(u,(function(t){var r=Ea(t,a);if(!r||!t.hasAttribute("begin"))return null;var i=Ra(t.getAttribute("begin"),n),u=Ra(t.getAttribute("dur"),n),h=Ra(t.getAttribute("end"),n);if(null===i)throw La(t);if(null===h){if(null===u)throw La(t);h=i+u}var d=new Jn(i-e,h-e,r);d.id=da(d.startTime,d.endTime,d.text);var c=function(t,e,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=t&&t.hasAttribute("style")?t.getAttribute("style"):null;return s&&r.hasOwnProperty(s)&&(n=r[s]),a.reduce((function(r,a){var s=Sa(e,i,a)||Sa(t,i,a)||Sa(n,i,a);return s&&(r[a]=s),r}),{})}(l[t.getAttribute("region")],s[t.getAttribute("style")],s),f=c.textAlign;if(f){var g=ma[f];g&&(d.lineAlign=g),d.align=f}return o(d,c),d})).filter((function(t){return null!==t}))}(t,d))}))}catch(t){i(t)}}else i(new Error("Could not parse IMSC1 mdat"))}function ya(t,e,r){var i=t.getElementsByTagName(e)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function Ta(t){return t.reduce((function(t,e){var r=e.getAttribute("xml:id");return r&&(t[r]=e),t}),{})}function Ea(t,e){return[].slice.call(t.childNodes).reduce((function(t,r,i){var n;return"br"===r.nodeName&&i?t+"\n":null!=(n=r.childNodes)&&n.length?Ea(r,e):e?t+r.textContent.trim().replace(/\s+/g," "):t+r.textContent}),"")}function Sa(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function La(t){return new Error("Could not parse ttml timestamp "+t)}function Ra(t,e){if(!t)return null;var r=ta(t);return null===r&&(ga.test(t)?r=function(t,e){var r=ga.exec(t),i=(0|r[4])+(0|r[5])/e.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/e.frameRate}(t,e):va.test(t)&&(r=function(t,e){var r=va.exec(t),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return 1e3*i;case"f":return i/e.frameRate;case"t":return i/e.tickRate}return i}(t,e))),r}var Aa=function(){function t(t){if(this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},this.config.enableCEA708Captions){var e=new $n(this,"textTrack1"),r=new $n(this,"textTrack2"),i=new $n(this,"textTrack3"),n=new $n(this,"textTrack4");this.cea608Parser1=new Xn(1,e,r),this.cea608Parser2=new Xn(3,i,n)}t.on(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(R.MANIFEST_LOADING,this.onManifestLoading,this),t.on(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(R.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(R.FRAG_LOADING,this.onFragLoading,this),t.on(R.FRAG_LOADED,this.onFragLoaded,this),t.on(R.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(R.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(R.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(R.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(R.BUFFER_FLUSHING,this.onBufferFlushing,this)}var e=t.prototype;return e.destroy=function(){var t=this.hls;t.off(R.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(R.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(R.MANIFEST_LOADING,this.onManifestLoading,this),t.off(R.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(R.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(R.FRAG_LOADING,this.onFragLoading,this),t.off(R.FRAG_LOADED,this.onFragLoaded,this),t.off(R.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(R.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(R.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(R.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(R.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.cea608Parser1=this.cea608Parser2=null},e.addCues=function(t,e,r,i,n){for(var a,s,o,l,u=!1,h=n.length;h--;){var d=n[h],c=(a=d[0],s=d[1],o=e,l=r,Math.min(s,l)-Math.max(a,o));if(c>=0&&(d[0]=Math.min(d[0],e),d[1]=Math.max(d[1],r),u=!0,c/(r-e)>.5))return}if(u||n.push([e,r]),this.config.renderTextTracksNatively){var f=this.captionsTracks[t];this.Cues.newCue(f,e,r,i)}else{var g=this.Cues.newCue(null,e,r,i);this.hls.trigger(R.CUES_PARSED,{type:"captions",cues:g,track:t})}},e.onInitPtsFound=function(t,e){var r=this,i=e.frag,n=e.id,a=e.initPTS,s=e.timescale,o=this.unparsedVttFrags;"main"===n&&(this.initPTS[i.cc]={baseTime:a,timescale:s}),o.length&&(this.unparsedVttFrags=[],o.forEach((function(t){r.onFragLoaded(R.FRAG_LOADED,t)})))},e.getExistingTrack=function(t){var e=this.media;if(e)for(var r=0;ri.cc||l.trigger(R.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i,error:e})}))}else s.push(t)},e._fallbackToIMSC1=function(t,e){var r=this,i=this.tracks[t.level];i.textCodec||pa(e,this.initPTS[t.cc],(function(){i.textCodec=fa,r._parseIMSC1(t,e)}),(function(){i.textCodec="wvtt"}))},e._appendCues=function(t,e){var r=this.hls;if(this.config.renderTextTracksNatively){var i=this.textTracks[e];if(!i||"disabled"===i.mode)return;t.forEach((function(t){return Re(i,t)}))}else{var n=this.tracks[e];if(!n)return;var a=n.default?"default":"subtitles"+e;r.trigger(R.CUES_PARSED,{type:"subtitles",cues:t,track:a})}},e.onFragDecrypted=function(t,e){e.frag.type===ye&&this.onFragLoaded(R.FRAG_LOADED,e)},e.onSubtitleTracksCleared=function(){this.tracks=[],this.captionsTracks={}},e.onFragParsingUserdata=function(t,e){var r=this.cea608Parser1,i=this.cea608Parser2;if(this.enabled&&r&&i){var n=e.frag,a=e.samples;if(n.type!==me||"NONE"!==this.closedCaptionsForLevel(n))for(var s=0;s0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},e.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(t,i){return r.isLevelAllowed(t)&&i<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},e.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},e.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},e.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},e.isLevelAllowed=function(t){return!this.restrictedLevels.some((function(e){return t.bitrate===e.bitrate&&t.width===e.width&&t.height===e.height}))},t.getMaxLevelByMediaSize=function(t,e,r){if(null==t||!t.length)return-1;for(var i,n,a=t.length-1,s=0;s=e||o.height>=r)&&(i=o,!(n=t[s+1])||i.width!==n.width||i.height!==n.height)){a=s;break}}return a},a(t,[{key:"mediaWidth",get:function(){return this.getDimensions().width*this.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*this.contentScaleFactor}},{key:"contentScaleFactor",get:function(){var t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch(t){}return t}}]),t}(),Da=function(){function t(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(R.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(R.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=e-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(R.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;_.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(R.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}(),Ia="[eme]",wa=function(){function t(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=_.debug.bind(_,Ia),this.log=_.log.bind(_,Ia),this.warn=_.warn.bind(_,Ia),this.error=_.error.bind(_,Ia),this.hls=e,this.config=e.config,this.registerListeners()}var e=t.prototype;return e.destroy=function(){this.unregisterListeners(),this.onMediaDetached();var t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null},e.registerListeners=function(){this.hls.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(R.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(R.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(R.MANIFEST_LOADED,this.onManifestLoaded,this)},e.unregisterListeners=function(){this.hls.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(R.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(R.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(R.MANIFEST_LOADED,this.onManifestLoaded,this)},e.getLicenseServerUrl=function(t){var e=this.config,r=e.drmSystems,i=e.widevineLicenseUrl,n=r[t];if(n)return n.licenseUrl;if(t===X.WIDEVINE&&i)return i;throw new Error('no license server URL configured for key-system "'+t+'"')},e.getServerCertificateUrl=function(t){var e=this.config.drmSystems[t];if(e)return e.serverCertificateUrl;this.log('No Server Certificate in config.drmSystems["'+t+'"]')},e.attemptKeySystemAccess=function(t){var e=this,r=this.hls.levels,i=function(t,e,r){return!!t&&r.indexOf(t)===e},n=r.map((function(t){return t.audioCodec})).filter(i),a=r.map((function(t){return t.videoCodec})).filter(i);return n.length+a.length===0&&a.push("avc1.42e01e"),new Promise((function(r,i){!function t(s){var o=s.shift();e.getMediaKeysPromise(o,n,a).then((function(t){return r({keySystem:o,mediaKeys:t})})).catch((function(e){s.length?t(s):i(e instanceof Ca?e:new Ca({type:A.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_ACCESS,error:e,fatal:!0},e.message))}))}(t)}))},e.requestMediaKeySystemAccess=function(t,e){var r=this.config.requestMediaKeySystemAccessFunc;if("function"!=typeof r){var i="Configured requestMediaKeySystemAccess is not a function "+r;return null===it&&"http:"===self.location.protocol&&(i="navigator.requestMediaKeySystemAccess is not available over insecure protocol "+location.protocol),Promise.reject(new Error(i))}return r(t,e)},e.getMediaKeysPromise=function(t,e,r){var i=this,n=function(t,e,r,i){var n;switch(t){case X.FAIRPLAY:n=["cenc","sinf"];break;case X.WIDEVINE:case X.PLAYREADY:n=["cenc"];break;case X.CLEARKEY:n=["cenc","keyids"];break;default:throw new Error("Unknown key-system: "+t)}return function(t,e,r,i){return[{initDataTypes:t,persistentState:i.persistentState||"not-allowed",distinctiveIdentifier:i.distinctiveIdentifier||"not-allowed",sessionTypes:i.sessionTypes||[i.sessionType||"temporary"],audioCapabilities:e.map((function(t){return{contentType:'audio/mp4; codecs="'+t+'"',robustness:i.audioRobustness||"",encryptionScheme:i.audioEncryptionScheme||null}})),videoCapabilities:r.map((function(t){return{contentType:'video/mp4; codecs="'+t+'"',robustness:i.videoRobustness||"",encryptionScheme:i.videoEncryptionScheme||null}}))}]}(n,e,r,i)}(t,e,r,this.config.drmSystemOptions),a=this.keySystemAccessPromises[t],s=null==a?void 0:a.keySystemAccess;if(!s){this.log('Requesting encrypted media "'+t+'" key-system access with config: '+JSON.stringify(n)),s=this.requestMediaKeySystemAccess(t,n);var o=this.keySystemAccessPromises[t]={keySystemAccess:s};return s.catch((function(e){i.log('Failed to obtain access to key-system "'+t+'": '+e)})),s.then((function(e){i.log('Access for key-system "'+e.keySystem+'" obtained');var r=i.fetchServerCertificate(t);return i.log('Create media-keys for "'+t+'"'),o.mediaKeys=e.createMediaKeys().then((function(e){return i.log('Media-keys created for "'+t+'"'),r.then((function(r){return r?i.setMediaKeysServerCertificate(e,t,r):e}))})),o.mediaKeys.catch((function(e){i.error('Failed to create media-keys for "'+t+'"}: '+e)})),o.mediaKeys}))}return s.then((function(){return a.mediaKeys}))},e.createMediaKeySessionContext=function(t){var e=t.decryptdata,r=t.keySystem,i=t.mediaKeys;this.log('Creating key-system session "'+r+'" keyId: '+St(e.keyId||[]));var n=i.createSession(),a={decryptdata:e,keySystem:r,mediaKeys:i,mediaKeysSession:n,keyStatus:"status-pending"};return this.mediaKeySessions.push(a),a},e.renewKeySession=function(t){var e=t.decryptdata;if(e.pssh){var r=this.createMediaKeySessionContext(t),i=this.getKeyIdString(e);this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(r,"cenc",e.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)},e.getKeyIdString=function(t){if(!t)throw new Error("Could not read keyId of undefined decryptdata");if(null===t.keyId)throw new Error("keyId is null");return St(t.keyId)},e.updateKeySession=function(t,e){var r,i=t.mediaKeysSession;return this.log('Updating key-session "'+i.sessionId+'" for keyID '+St((null==(r=t.decryptdata)?void 0:r.keyId)||[])+"\n } (data length: "+(e?e.byteLength:e)+")"),i.update(e)},e.selectKeySystemFormat=function(t){var e=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log("Selecting key-system from fragment (sn: "+t.sn+" "+t.type+": "+t.level+") key formats "+e.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(e)),this.keyFormatPromise},e.getKeyFormatPromise=function(t){var e=this;return new Promise((function(r,i){var n=rt(e.config),a=t.map(Z).filter((function(t){return!!t&&-1!==n.indexOf(t)}));return e.getKeySystemSelectionPromise(a).then((function(t){var e=t.keySystem,n=et(e);n?r(n):i(new Error('Unable to find format for key-system "'+e+'"'))})).catch(i)}))},e.loadKey=function(t){var e=this,r=t.keyInfo.decryptdata,i=this.getKeyIdString(r),n="(keyId: "+i+' format: "'+r.keyFormat+'" method: '+r.method+" uri: "+r.uri+")";this.log("Starting session for key "+n);var a=this.keyIdToKeySessionPromise[i];return a||(a=this.keyIdToKeySessionPromise[i]=this.getKeySystemForKeyPromise(r).then((function(i){var a=i.keySystem,s=i.mediaKeys;return e.throwIfDestroyed(),e.log("Handle encrypted media sn: "+t.frag.sn+" "+t.frag.type+": "+t.frag.level+" using key "+n),e.attemptSetMediaKeys(a,s).then((function(){e.throwIfDestroyed();var t=e.createMediaKeySessionContext({keySystem:a,mediaKeys:s,decryptdata:r});return e.generateRequestWithPreferredKeySession(t,"cenc",r.pssh,"playlist-key")}))}))).catch((function(t){return e.handleError(t)})),a},e.throwIfDestroyed=function(t){if(!this.hls)throw new Error("invalid state")},e.handleError=function(t){this.hls&&(this.error(t.message),t instanceof Ca?this.hls.trigger(R.ERROR,t.data):this.hls.trigger(R.ERROR,{type:A.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0}))},e.getKeySystemForKeyPromise=function(t){var e=this.getKeyIdString(t),r=this.keyIdToKeySessionPromise[e];if(!r){var i=Z(t.keyFormat),n=i?[i]:rt(this.config);return this.attemptKeySystemAccess(n)}return r},e.getKeySystemSelectionPromise=function(t){if(t.length||(t=rt(this.config)),0===t.length)throw new Ca({type:A.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},"Missing key-system license configuration options "+JSON.stringify({drmSystems:this.config.drmSystems}));return this.attemptKeySystemAccess(t)},e._onMediaEncrypted=function(t){var e=this,r=t.initDataType,i=t.initData;if(this.debug('"'+t.type+'" event: init data type: "'+r+'"'),null!==i){var n,a;if("sinf"===r&&this.config.drmSystems[X.FAIRPLAY]){var s=kt(new Uint8Array(i));try{var o=W(JSON.parse(s).sinf),l=xt(new Uint8Array(o));if(!l)return;n=l.subarray(8,24),a=X.FAIRPLAY}catch(t){return void this.warn('Failed to parse sinf "encrypted" event message initData')}}else{var u=function(t){if(!(t instanceof ArrayBuffer)||t.byteLength<32)return null;var e={version:0,systemId:"",kids:null,data:null},r=new DataView(t),i=r.getUint32(0);if(t.byteLength!==i&&i>44)return null;if(1886614376!==r.getUint32(4))return null;if(e.version=r.getUint32(8)>>>24,e.version>1)return null;e.systemId=St(new Uint8Array(t,12,16));var n=r.getUint32(28);if(0===e.version){if(i-32d||o.status>=400&&o.status<500)a(new Ca({type:A.KEY_SYSTEM_ERROR,details:k.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:s,data:void 0,code:o.status,text:o.statusText}},"License Request XHR failed ("+s+"). Status: "+o.status+" ("+o.statusText+")"));else{var c=d-r._requestLicenseFailureCount+1;r.warn("Retrying license request, "+c+" attempts left"),r.requestLicense(t,e).then(n,a)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,r.setupLicenseXHR(o,s,t,e).then((function(t){var e=t.xhr,r=t.licenseChallenge;e.send(r)}))}))},e.onMediaAttached=function(t,e){if(this.config.emeEnabled){var r=e.media;this.media=r,r.addEventListener("encrypted",this.onMediaEncrypted),r.addEventListener("waitingforkey",this.onWaitingForKey)}},e.onMediaDetached=function(){var e=this,r=this.media,i=this.mediaKeySessions;r&&(r.removeEventListener("encrypted",this.onMediaEncrypted),r.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},Ht.clearKeyUriToKeyIdMap();var n=i.length;t.CDMCleanupPromise=Promise.all(i.map((function(t){return e.removeSession(t)})).concat(null==r?void 0:r.setMediaKeys(null).catch((function(t){e.log("Could not clear media keys: "+t+". media.src: "+(null==r?void 0:r.src))})))).then((function(){n&&(e.log("finished closing key sessions and clearing media keys"),i.length=0)})).catch((function(t){e.log("Could not close sessions and clear media keys: "+t+". media.src: "+(null==r?void 0:r.src))}))},e.onManifestLoading=function(){this.keyFormatPromise=null},e.onManifestLoaded=function(t,e){var r=e.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce((function(t,e){return-1===t.indexOf(e.keyFormat)&&t.push(e.keyFormat),t}),[]);this.log("Selecting key-system from session-keys "+i.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(i)}},e.removeSession=function(t){var e=this,r=t.mediaKeysSession,i=t.licenseXhr;if(r){this.log("Remove licenses and keys and close session "+r.sessionId),r.onmessage=null,r.onkeystatuseschange=null,i&&i.readyState!==XMLHttpRequest.DONE&&i.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;var n=this.mediaKeySessions.indexOf(t);return n>-1&&this.mediaKeySessions.splice(n,1),r.remove().catch((function(t){e.log("Could not remove session: "+t)})).then((function(){return r.close()})).catch((function(t){e.log("Could not close session: "+t)}))}},t}();wa.CDMCleanupPromise=void 0;var Ca=function(t){function e(e,r){var i;return(i=t.call(this,r)||this).data=void 0,e.error||(e.error=new Error(r)),i.data=e,e.err=e.error,i}return l(e,t),e}(f(Error)),_a="m",Pa="a",xa="v",Fa="av",Ma="i",Oa="tt",Na=function(){function t(e){var r=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=function(){r.initialized&&(r.starved=!0),r.buffering=!0},this.onPlaying=function(){r.initialized||(r.initialized=!0),r.buffering=!1},this.applyPlaylistData=function(t){try{r.apply(t,{ot:_a,su:!r.initialized})}catch(t){_.warn("Could not generate manifest CMCD data.",t)}},this.applyFragmentData=function(t){try{var e=t.frag,i=r.hls.levels[e.level],n=r.getObjectType(e),a={d:1e3*e.duration,ot:n};n!==xa&&n!==Pa&&n!=Fa||(a.br=i.bitrate/1e3,a.tb=r.getTopBandwidth(n)/1e3,a.bl=r.getBufferLength(n)),r.apply(t,a)}catch(t){_.warn("Could not generate segment CMCD data.",t)}},this.hls=e;var i=this.config=e.config,n=i.cmcd;null!=n&&(i.pLoader=this.createPlaylistLoader(),i.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||t.uuid(),this.cid=n.contentId,this.useHeaders=!0===n.useHeaders,this.registerListeners())}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(R.MEDIA_DETACHED,this.onMediaDetached,this),t.on(R.BUFFER_CREATED,this.onBufferCreated,this)},e.unregisterListeners=function(){var t=this.hls;t.off(R.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(R.MEDIA_DETACHED,this.onMediaDetached,this),t.off(R.BUFFER_CREATED,this.onBufferCreated,this)},e.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null},e.onMediaAttached=function(t,e){this.media=e.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)},e.onMediaDetached=function(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)},e.onBufferCreated=function(t,e){var r,i;this.audioBuffer=null==(r=e.tracks.audio)?void 0:r.buffer,this.videoBuffer=null==(i=e.tracks.video)?void 0:i.buffer},e.createData=function(){var t;return{v:1,sf:"h",sid:this.sid,cid:this.cid,pr:null==(t=this.media)?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}},e.apply=function(e,r){void 0===r&&(r={}),o(r,this.createData());var i=r.ot===Ma||r.ot===xa||r.ot===Fa;if(this.starved&&i&&(r.bs=!0,r.su=!0,this.starved=!1),null==r.su&&(r.su=this.buffering),this.useHeaders){var n=t.toHeaders(r);if(!Object.keys(n).length)return;e.headers||(e.headers={}),o(e.headers,n)}else{var a=t.toQuery(r);if(!a)return;e.url=t.appendQueryToUri(e.url,a)}},e.getObjectType=function(t){var e=t.type;return"subtitle"===e?Oa:"initSegment"===t.sn?Ma:"audio"===e?Pa:"main"===e?this.hls.audioTracks.length?xa:Fa:void 0},e.getTopBandwidth=function(t){var e,r=0,i=this.hls;if(t===Pa)e=i.audioTracks;else{var n=i.maxAutoLevel,a=n>-1?n+1:i.levels.length;e=i.levels.slice(0,a)}for(var s,o=v(e);!(s=o()).done;){var l=s.value;l.bitrate>r&&(r=l.bitrate)}return r>0?r:NaN},e.getBufferLength=function(t){var e=this.hls.media,r=t===Pa?this.audioBuffer:this.videoBuffer;return r&&e?1e3*_r.bufferInfo(r,e.currentTime,this.config.maxBufferHole).len:NaN},e.createPlaylistLoader=function(){var t=this.config.pLoader,e=this.applyPlaylistData,r=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new r(t)}var i=t.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(t,r,i){e(t),this.loader.load(t,r,i)},a(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},e.createFragmentLoader=function(){var t=this.config.fLoader,e=this.applyFragmentData,r=t||this.config.loader;return function(){function t(t){this.loader=void 0,this.loader=new r(t)}var i=t.prototype;return i.destroy=function(){this.loader.destroy()},i.abort=function(){this.loader.abort()},i.load=function(t,r,i){e(t),this.loader.load(t,r,i)},a(t,[{key:"stats",get:function(){return this.loader.stats}},{key:"context",get:function(){return this.loader.context}}]),t}()},t.uuid=function(){var t=URL.createObjectURL(new Blob),e=t.toString();return URL.revokeObjectURL(t),e.slice(e.lastIndexOf("/")+1)},t.serialize=function(t){for(var e,r=[],i=function(t){return!Number.isNaN(t)&&null!=t&&""!==t&&!1!==t},n=function(t){return Math.round(t)},a=function(t){return 100*n(t/100)},s={br:n,d:n,bl:a,dl:a,mtp:a,nor:function(t){return encodeURIComponent(t)},rtp:a,tb:n},o=v(Object.keys(t||{}).sort());!(e=o()).done;){var l=e.value,u=t[l];if(i(u)&&!("v"===l&&1===u||"pr"==l&&1===u)){var h=s[l];h&&(u=h(u));var d=typeof u,c=void 0;c="ot"===l||"sf"===l||"st"===l?l+"="+u:"boolean"===d?l:"number"===d?l+"="+u:l+"="+JSON.stringify(u),r.push(c)}}return r.join(",")},t.toHeaders=function(e){for(var r={},i=["Object","Request","Session","Status"],n=[{},{},{},{}],a={br:0,d:0,ot:0,tb:0,bl:1,dl:1,mtp:1,nor:1,nrr:1,su:1,cid:2,pr:2,sf:2,sid:2,st:2,v:2,bs:3,rtp:3},s=0,o=Object.keys(e);s1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==n)}},e.filterParsedLevels=function(t){this.levels=t;var e=this.getLevelsForPathway(this.pathwayId);if(0===e.length){var r=t[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),e=this.getLevelsForPathway(r),this.pathwayId=r}return e.length!==t.length?(this.log("Found "+e.length+"/"+t.length+' levels in Pathway "'+this.pathwayId+'"'),e):t},e.getLevelsForPathway=function(t){return null===this.levels?[]:this.levels.filter((function(e){return t===e.pathwayId}))},e.updatePathwayPriority=function(t){var e;this.pathwayPriority=t;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(t){i-r[t]>3e5&&delete r[t]}));for(var n=0;n0){this.log('Setting Pathway to "'+a+'"'),this.pathwayId=a,this.hls.trigger(R.LEVELS_UPDATED,{levels:e});var l=this.hls.levels[s];o&&l&&this.levels&&(l.attrs["STABLE-VARIANT-ID"]!==o.attrs["STABLE-VARIANT-ID"]&&l.bitrate!==o.bitrate&&this.log("Unstable Pathways change from bitrate "+o.bitrate+" to "+l.bitrate),this.hls.nextLoadLevel=s);break}}}},e.clonePathways=function(t){var e=this,r=this.levels;if(r){var i={},n={};t.forEach((function(t){var a=t.ID,s=t["BASE-ID"],l=t["URI-REPLACEMENT"];if(!r.some((function(t){return t.pathwayId===a}))){var u=e.getLevelsForPathway(s).map((function(t){var e=o({},t);e.details=void 0,e.url=Ga(t.uri,t.attrs["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l);var r=new F(t.attrs);r["PATHWAY-ID"]=a;var s=r.AUDIO&&r.AUDIO+"_clone_"+a,u=r.SUBTITLES&&r.SUBTITLES+"_clone_"+a;s&&(i[r.AUDIO]=s,r.AUDIO=s),u&&(n[r.SUBTITLES]=u,r.SUBTITLES=u),e.attrs=r;var h=new Ge(e);return gr(h,"audio",s),gr(h,"text",u),h}));r.push.apply(r,u),Ba(e.audioTracks,i,l,a),Ba(e.subtitleTracks,n,l,a)}}))}},e.loadSteeringManifest=function(t){var e,r=this,i=this.hls.config,n=i.loader;this.loader&&this.loader.destroy(),this.loader=new n(i);try{e=new self.URL(t)}catch(e){return this.enabled=!1,void this.log("Failed to parse Steering Manifest URI: "+t)}if("data:"!==e.protocol){var a=0|(this.hls.bandwidthEstimate||i.abrEwmaDefaultEstimate);e.searchParams.set("_HLS_pathway",this.pathwayId),e.searchParams.set("_HLS_throughput",""+a)}var s={responseType:"json",url:e.href},o=i.steeringManifestLoadPolicy.default,l=o.errorRetry||o.timeoutRetry||{},u={loadPolicy:o,timeout:o.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},h={onSuccess:function(t,i,n,a){r.log('Loaded steering manifest: "'+e+'"');var s=t.data;if(1===s.VERSION){r.updated=performance.now(),r.timeToLoad=s.TTL;var o=s["RELOAD-URI"],l=s["PATHWAY-CLONES"],u=s["PATHWAY-PRIORITY"];if(o)try{r.uri=new self.URL(o,e).href}catch(t){return r.enabled=!1,void r.log("Failed to parse Steering Manifest RELOAD-URI: "+o)}r.scheduleRefresh(r.uri||n.url),l&&r.clonePathways(l),u&&r.updatePathwayPriority(u)}else r.log("Steering VERSION "+s.VERSION+" not supported!")},onError:function(t,e,i,n){if(r.log("Error loading steering manifest: "+t.code+" "+t.text+" ("+e.url+")"),r.stopLoad(),410===t.code)return r.enabled=!1,void r.log("Steering manifest "+e.url+" no longer available");var a=1e3*r.timeToLoad;if(429!==t.code)r.scheduleRefresh(r.uri||e.url,a);else{var s=r.loader;if("function"==typeof(null==s?void 0:s.getResponseHeader)){var o=s.getResponseHeader("Retry-After");o&&(a=1e3*parseFloat(o))}r.log("Steering manifest "+e.url+" rate limited")}},onTimeout:function(t,e,i){r.log("Timeout loading steering manifest ("+e.url+")"),r.scheduleRefresh(r.uri||e.url)}};this.log("Requesting steering manifest: "+e),this.loader.load(s,u,h)},e.scheduleRefresh=function(t,e){var r=this;void 0===e&&(e=1e3*this.timeToLoad),self.clearTimeout(this.reloadTimer),this.reloadTimer=self.setTimeout((function(){r.loadSteeringManifest(t)}),e)},t}();function Ba(t,e,r,i){t&&Object.keys(e).forEach((function(n){var a=t.filter((function(t){return t.groupId===n})).map((function(t){var a=o({},t);return a.details=void 0,a.attrs=new F(a.attrs),a.url=a.attrs.URI=Ga(t.url,t.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),a.groupId=a.attrs["GROUP-ID"]=e[n],a.attrs["PATHWAY-ID"]=i,a}));t.push.apply(t,a)}))}function Ga(t,e,r,i){var n,a=i.HOST,s=i.PARAMS,o=i[r];e&&(n=null==o?void 0:o[e])&&(t=n);var l=new self.URL(t);return a&&!n&&(l.host=a),s&&Object.keys(s).sort().forEach((function(t){t&&l.searchParams.set(t,s[t])})),l.href}var Ka=/^age:\s*[\d.]+\s*$/im,Ha=function(){function t(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t&&t.xhrSetup||null,this.stats=new N,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},e.abortInternal=function(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))},e.abort=function(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.loadInternal()},e.loadInternal=function(){var t=this,e=this.config,r=this.context;if(e){var i=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;var a=this.xhrSetup;a?Promise.resolve().then((function(){if(!t.stats.aborted)return a(i,r.url)})).catch((function(t){return i.open("GET",r.url,!0),a(i,r.url)})).then((function(){t.stats.aborted||t.openAndSendXhr(i,r,e)})).catch((function(e){t.callbacks.onError({code:i.status,text:e.message},r,i,n)})):this.openAndSendXhr(i,r,e)}},e.openAndSendXhr=function(t,e,r){t.readyState||t.open("GET",e.url,!0);var i=this.context.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)t.setRequestHeader(o,i[o]);e.rangeEnd&&t.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=e.responseType,self.clearTimeout(this.requestTimeout),r.timeout=a&&E(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()},e.readystatechange=function(){var t=this.context,e=this.loader,r=this.stats;if(t&&e){var i=e.readyState,n=this.config;if(!r.aborted&&i>=2&&(0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),n.timeout!==n.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),n.timeout=n.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),4===i)){self.clearTimeout(this.requestTimeout),e.onreadystatechange=null,e.onprogress=null;var a=e.status,s="text"!==e.responseType;if(a>=200&&a<300&&(s&&e.response||null!==e.responseText)){r.loading.end=Math.max(self.performance.now(),r.loading.first);var o=s?e.response:e.responseText,l="arraybuffer"===e.responseType?o.byteLength:o.length;if(r.loaded=r.total=l,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first),!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,o,e),!this.callbacks)return;var h={url:e.responseURL,data:o,code:a};this.callbacks.onSuccess(h,r,t,e)}else{var d=n.loadPolicy.errorRetry;Je(d,r.retry,!1,a)?this.retry(d):(_.error(a+" while loading "+t.url),this.callbacks.onError({code:a,text:e.statusText},t,e,r))}}}},e.loadtimeout=function(){var t,e=null==(t=this.config)?void 0:t.loadPolicy.timeoutRetry;if(Je(e,this.stats.retry,!0))this.retry(e);else{_.warn("timeout while loading "+this.context.url);var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.loader))}},e.retry=function(t){var e=this.context,r=this.stats;this.retryDelay=Qe(t,r.retry),r.retry++,_.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+e.url+", retrying "+r.retry+"/"+t.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&Ka.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},e.getResponseHeader=function(t){return this.loader&&new RegExp("^"+t+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null},t}(),Va=/(\d+)-(\d+)\/(\d+)/,Ya=function(){function t(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Wa,this.controller=new self.AbortController,this.stats=new N}var e=t.prototype;return e.destroy=function(){this.loader=this.callbacks=null,this.abortInternal()},e.abortInternal=function(){var t=this.response;null!=t&&t.ok||(this.stats.aborted=!0,this.controller.abort())},e.abort=function(){var t;this.abortInternal(),null!=(t=this.callbacks)&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function(t,e,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var a=function(t,e){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(o({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}(t,this.controller.signal),s=r.onProgress,l="arraybuffer"===t.responseType,u=l?"byteLength":"length",h=e.loadPolicy,d=h.maxTimeToFirstByteMs,c=h.maxLoadTimeMs;this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,a),self.clearTimeout(this.requestTimeout),e.timeout=d&&E(d)?d:c,this.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,t,i.response)}),e.timeout),self.fetch(this.request).then((function(a){i.response=i.loader=a;var o=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(i.requestTimeout),e.timeout=c,i.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,t,i.response)}),c-(o-n.loading.start)),!a.ok){var u=a.status,h=a.statusText;throw new ja(h||"fetch, bad network response",u,a)}return n.loading.first=o,n.total=function(t){var e=t.get("Content-Range");if(e){var r=function(t){var e=Va.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}(e);if(E(r))return r}var i=t.get("Content-Length");if(i)return parseInt(i)}(a.headers)||n.total,s&&E(e.highWaterMark)?i.loadProgressively(a,n,t,e.highWaterMark,s):l?a.arrayBuffer():"json"===t.responseType?a.json():a.text()})).then((function(a){var o=i.response;self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);var l=a[u];l&&(n.loaded=n.total=l);var h={url:o.url,data:a,code:o.status};s&&!E(e.highWaterMark)&&s(n,t,a,o),r.onSuccess(h,n,t,o)})).catch((function(e){if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=e&&e.code||0,s=e?e.message:null;r.onError({code:a,text:s},t,e?e.details:null,n)}}))},e.getCacheAge=function(){var t=null;if(this.response){var e=this.response.headers.get("age");t=e?parseFloat(e):null}return t},e.getResponseHeader=function(t){return this.response?this.response.headers.get(t):null},e.loadProgressively=function(t,e,r,i,n){void 0===i&&(i=0);var a=new Tn,s=t.body.getReader();return function o(){return s.read().then((function(s){if(s.done)return a.dataLength&&n(e,r,a.flush(),t),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return e.loaded+=u,u=i&&n(e,r,a.flush(),t)):n(e,r,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function Wa(t,e){return new self.Request(t.url,e)}var ja=function(t){function e(e,r,i){var n;return(n=t.call(this,e)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return l(e,t),e}(f(Error)),qa=/\s/,Xa=i(i({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,maxBufferSize:6e7,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,loader:Ha,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:yn,bufferController:_n,capLevelController:ba,errorController:dr,fpsController:Da,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:it,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},{cueHandler:{newCue:function(t,e,r,i){for(var n,a,s,o,l,u=[],h=self.VTTCue||self.TextTrackCue,d=0;d=16?o--:o++;var g=sa(l.trim()),v=da(e,r,g);null!=t&&null!=(c=t.cues)&&c.getCueById(v)||((a=new h(e,r,g)).id=v,a.line=d+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return t&&u.length&&(u.sort((function(t,e){return"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line})),u.forEach((function(e){return Re(t,e)}))),u}},enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:An,subtitleTrackController:bn,timelineController:Aa,audioStreamController:En,audioTrackController:Sn,emeController:wa,cmcdController:Na,contentSteeringController:Ua});function za(t){return t&&"object"==typeof t?Array.isArray(t)?t.map(za):Object.keys(t).reduce((function(e,r){return e[r]=za(t[r]),e}),{}):t}function Qa(t){var e=t.loader;e!==Ya&&e!==Ha?(_.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=Ya,t.progressive=!0,t.enableSoftwareAES=!0,_.log("[config]: Progressive streaming enabled, using FetchLoader"))}var $a=function(){function t(e){void 0===e&&(e={}),this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new ln,this._autoLevelCapping=void 0,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,C(e.debug||!1,"Hls instance");var r=this.config=function(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==e.liveMaxLatencyDurationCount&&(void 0===e.liveSyncDurationCount||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==e.liveMaxLatencyDuration&&(void 0===e.liveSyncDuration||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');var r=za(t),n=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(t){var i=("level"===t?"playlist":t)+"LoadPolicy",a=void 0===e[i],s=[];n.forEach((function(n){var o=t+"Loading"+n,l=e[o];if(void 0!==l&&a){s.push(o);var u=r[i].default;switch(e[i]={default:u},n){case"TimeOut":u.maxLoadTimeMs=l,u.maxTimeToFirstByteMs=l;break;case"MaxRetry":u.errorRetry.maxNumRetry=l,u.timeoutRetry.maxNumRetry=l;break;case"RetryDelay":u.errorRetry.retryDelayMs=l,u.timeoutRetry.retryDelayMs=l;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=l,u.timeoutRetry.maxRetryDelayMs=l}}})),s.length&&_.warn('hls.js config: "'+s.join('", "')+'" setting(s) are deprecated, use "'+i+'": '+JSON.stringify(e[i]))})),i(i({},r),e)}(t.DefaultConfig,e);this.userConfig=e,this._autoLevelCapping=-1,r.progressive&&Qa(r);var n=r.abrController,a=r.bufferController,s=r.capLevelController,o=r.errorController,l=r.fpsController,u=new o(this),h=this.abrController=new n(this),d=this.bufferController=new a(this),c=this.capLevelController=new s(this),f=new l(this),g=new Se(this),v=new xe(this),m=r.contentSteeringController,p=m?new m(this):null,y=this.levelController=new fr(this,p),T=new Er(this),E=new Ir(this.config),S=this.streamController=new vn(this,T,E);c.setStreamController(S),f.setStreamController(S);var L=[g,y,S];p&&L.splice(1,0,p),this.networkControllers=L;var A=[h,d,c,f,v,T];this.audioTrackController=this.createController(r.audioTrackController,L);var k=r.audioStreamController;k&&L.push(new k(this,T,E)),this.subtitleTrackController=this.createController(r.subtitleTrackController,L);var b=r.subtitleStreamController;b&&L.push(new b(this,T,E)),this.createController(r.timelineController,A),E.emeController=this.emeController=this.createController(r.emeController,A),this.cmcdController=this.createController(r.cmcdController,A),this.latencyController=this.createController(Fe,A),this.coreComponents=A,L.push(u);var D=u.onErrorOut;"function"==typeof D&&this.on(R.ERROR,D,u)}t.isSupported=function(){return function(){var t=zt();if(!t)return!1;var e=ri(),r=t&&"function"==typeof t.isTypeSupported&&t.isTypeSupported('video/mp4; codecs="avc1.42E01E,mp4a.40.2"'),i=!e||e.prototype&&"function"==typeof e.prototype.appendBuffer&&"function"==typeof e.prototype.remove;return!!r&&!!i}()};var e=t.prototype;return e.createController=function(t,e){if(t){var r=new t(this);return e&&e.push(r),r}return null},e.on=function(t,e,r){void 0===r&&(r=this),this._emitter.on(t,e,r)},e.once=function(t,e,r){void 0===r&&(r=this),this._emitter.once(t,e,r)},e.removeAllListeners=function(t){this._emitter.removeAllListeners(t)},e.off=function(t,e,r,i){void 0===r&&(r=this),this._emitter.off(t,e,r,i)},e.listeners=function(t){return this._emitter.listeners(t)},e.emit=function(t,e,r){return this._emitter.emit(t,e,r)},e.trigger=function(t,e){if(this.config.debug)return this.emit(t,t,e);try{return this.emit(t,t,e)}catch(e){_.error("An internal error happened while handling event "+t+'. Error message: "'+e.message+'". Here is a stacktrace:',e),this.trigger(R.ERROR,{type:A.OTHER_ERROR,details:k.INTERNAL_EXCEPTION,fatal:!1,event:t,error:e})}return!1},e.listenerCount=function(t){return this._emitter.listenerCount(t)},e.destroy=function(){_.log("destroy"),this.trigger(R.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this.url=null,this.networkControllers.forEach((function(t){return t.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(t){return t.destroy()})),this.coreComponents.length=0;var t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null},e.attachMedia=function(t){_.log("attachMedia"),this._media=t,this.trigger(R.MEDIA_ATTACHING,{media:t})},e.detachMedia=function(){_.log("detachMedia"),this.trigger(R.MEDIA_DETACHING,void 0),this._media=null},e.loadSource=function(t){this.stopLoad();var e=this.media,r=this.url,i=this.url=T.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});_.log("loadSource:"+i),e&&r&&(r!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(e)),this.trigger(R.MANIFEST_LOADING,{url:t})},e.startLoad=function(t){void 0===t&&(t=-1),_.log("startLoad("+t+")"),this.networkControllers.forEach((function(e){e.startLoad(t)}))},e.stopLoad=function(){_.log("stopLoad"),this.networkControllers.forEach((function(t){t.stopLoad()}))},e.swapAudioCodec=function(){_.log("swapAudioCodec"),this.streamController.swapAudioCodec()},e.recoverMediaError=function(){_.log("recoverMediaError");var t=this._media;this.detachMedia(),t&&this.attachMedia(t)},e.removeLevel=function(t,e){void 0===e&&(e=0),this.levelController.removeLevel(t,e)},a(t,[{key:"levels",get:function(){var t=this.levelController.levels;return t||[]}},{key:"currentLevel",get:function(){return this.streamController.currentLevel},set:function(t){_.log("set currentLevel:"+t),this.loadLevel=t,this.abrController.clearTimer(),this.streamController.immediateLevelSwitch()}},{key:"nextLevel",get:function(){return this.streamController.nextLevel},set:function(t){_.log("set nextLevel:"+t),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}},{key:"loadLevel",get:function(){return this.levelController.level},set:function(t){_.log("set loadLevel:"+t),this.levelController.manualLevel=t}},{key:"nextLoadLevel",get:function(){return this.levelController.nextLoadLevel},set:function(t){this.levelController.nextLoadLevel=t}},{key:"firstLevel",get:function(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)},set:function(t){_.log("set firstLevel:"+t),this.levelController.firstLevel=t}},{key:"startLevel",get:function(){return this.levelController.startLevel},set:function(t){_.log("set startLevel:"+t),-1!==t&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(t){var e=!!t;e!==this.config.capLevelToPlayerSize&&(e?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=e)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(t){this._autoLevelCapping!==t&&(_.log("set autoLevelCapping:"+t),this._autoLevelCapping=t)}},{key:"bandwidthEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimate():NaN}},{key:"ttfbEstimate",get:function(){var t=this.abrController.bwEstimator;return t?t.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(t){Me.indexOf(t)>-1&&(this._maxHdcpLevel=t)}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var t=this.levels,e=this.config.minAutoBitrate;if(!t)return 0;for(var r=t.length,i=0;i=e)return i;return 0}},{key:"maxAutoLevel",get:function(){var t,e=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(t=-1===r&&e&&e.length?e.length-1:r,i)for(var n=t;n--;){var a=e[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return t}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}],[{key:"version",get:function(){return"1.4.14"}},{key:"Events",get:function(){return R}},{key:"ErrorTypes",get:function(){return A}},{key:"ErrorDetails",get:function(){return k}},{key:"DefaultConfig",get:function(){return t.defaultConfig?t.defaultConfig:Xa},set:function(e){t.defaultConfig=e}}]),t}();return $a.defaultConfig=void 0,$a},"object"==typeof exports&&"undefined"!=typeof module?module.exports=i():"function"==typeof define&&define.amd?define(i):(r="undefined"!=typeof globalThis?globalThis:r||self).Hls=i()}(!1); +//# sourceMappingURL=hls.min.js.map diff --git a/trunk/research/players/js/hls.min.js.map b/trunk/research/players/js/hls.min.js.map index 74b36022ec..29d731d076 100644 --- a/trunk/research/players/js/hls.min.js.map +++ b/trunk/research/players/js/hls.min.js.map @@ -1 +1 @@ -{"version":3,"sources":["webpack://Hls/webpack/universalModuleDefinition","webpack://Hls/webpack/bootstrap","webpack://Hls/./src/utils/logger.js","webpack://Hls/./src/events.js","webpack://Hls/./src/errors.ts","webpack://Hls/./src/polyfills/number.js","webpack://Hls/./src/demux/id3.js","webpack://Hls/./src/utils/get-self-scope.js","webpack://Hls/./node_modules/url-toolkit/src/url-toolkit.js","webpack://Hls/./src/crypt/aes-crypto.js","webpack://Hls/./src/crypt/fast-aes-key.js","webpack://Hls/./src/crypt/aes-decryptor.js","webpack://Hls/./src/crypt/decrypter.js","webpack://Hls/./node_modules/eventemitter3/index.js","webpack://Hls/./src/demux/adts.js","webpack://Hls/./src/demux/aacdemuxer.js","webpack://Hls/./src/demux/mpegaudio.js","webpack://Hls/./src/demux/exp-golomb.js","webpack://Hls/./src/demux/sample-aes.js","webpack://Hls/./src/demux/tsdemuxer.js","webpack://Hls/./src/demux/mp3demuxer.js","webpack://Hls/./src/remux/aac-helper.js","webpack://Hls/./src/remux/mp4-generator.js","webpack://Hls/./src/utils/timescale-conversion.ts","webpack://Hls/./src/remux/mp4-remuxer.js","webpack://Hls/./src/demux/demuxer-inline.js","webpack://Hls/./src/remux/passthrough-remuxer.js","webpack://Hls/./src/demux/mp4demuxer.js","webpack://Hls/./node_modules/webworkify-webpack/index.js","webpack://Hls/./src/demux/demuxer-worker.js","webpack://Hls/./src/types/loader.ts","webpack://Hls/./src/event-handler.ts","webpack://Hls/./src/loader/fragment.ts","webpack://Hls/./src/loader/level-key.ts","webpack://Hls/./src/loader/level.js","webpack://Hls/./src/utils/attr-list.js","webpack://Hls/./src/utils/codecs.ts","webpack://Hls/./src/loader/m3u8-parser.ts","webpack://Hls/./src/loader/playlist-loader.ts","webpack://Hls/./src/loader/fragment-loader.js","webpack://Hls/./src/loader/key-loader.ts","webpack://Hls/./src/controller/fragment-tracker.js","webpack://Hls/./src/utils/binary-search.ts","webpack://Hls/./src/utils/buffer-helper.ts","webpack://Hls/./src/utils/mediasource-helper.ts","webpack://Hls/./src/observer.ts","webpack://Hls/./src/demux/demuxer.js","webpack://Hls/./src/controller/level-helper.js","webpack://Hls/./src/utils/time-ranges.ts","webpack://Hls/./src/utils/discontinuities.js","webpack://Hls/./src/controller/fragment-finders.ts","webpack://Hls/./src/controller/gap-controller.js","webpack://Hls/./src/task-loop.ts","webpack://Hls/./src/controller/base-stream-controller.js","webpack://Hls/./src/controller/stream-controller.js","webpack://Hls/./src/controller/level-controller.js","webpack://Hls/./src/utils/texttrack-utils.ts","webpack://Hls/./src/controller/id3-track-controller.js","webpack://Hls/./src/utils/ewma.ts","webpack://Hls/./src/utils/ewma-bandwidth-estimator.ts","webpack://Hls/./src/controller/abr-controller.js","webpack://Hls/./src/controller/buffer-controller.ts","webpack://Hls/./src/controller/cap-level-controller.js","webpack://Hls/./src/controller/fps-controller.js","webpack://Hls/./src/utils/xhr-loader.js","webpack://Hls/./src/controller/audio-track-controller.js","webpack://Hls/./src/controller/audio-stream-controller.js","webpack://Hls/./src/utils/vttcue.js","webpack://Hls/./src/utils/vttparser.js","webpack://Hls/./src/utils/cues.ts","webpack://Hls/./src/utils/cea-608-parser.ts","webpack://Hls/./src/utils/output-filter.ts","webpack://Hls/./src/utils/webvtt-parser.js","webpack://Hls/./src/controller/timeline-controller.ts","webpack://Hls/./src/controller/subtitle-track-controller.js","webpack://Hls/./src/utils/mediakeys-helper.ts","webpack://Hls/./src/controller/subtitle-stream-controller.js","webpack://Hls/./src/controller/eme-controller.ts","webpack://Hls/./src/config.ts","webpack://Hls/./src/hls.ts","webpack://Hls/./src/is-supported.ts"],"names":["root","factory","exports","module","define","amd","this","installedModules","__webpack_require__","moduleId","i","l","modules","call","m","c","d","name","getter","o","Object","defineProperty","enumerable","get","r","Symbol","toStringTag","value","t","mode","__esModule","ns","create","key","bind","n","object","property","prototype","hasOwnProperty","p","s","noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","formatMsg","type","msg","global","getSelfScope","consolePrintFn","func","console","args","apply","enableLogs","debugConfig","functions","forEach","exportLoggerFunctions","e","logger","HlsEvents","MEDIA_ATTACHING","MEDIA_ATTACHED","MEDIA_DETACHING","MEDIA_DETACHED","BUFFER_RESET","BUFFER_CODECS","BUFFER_CREATED","BUFFER_APPENDING","BUFFER_APPENDED","BUFFER_EOS","BUFFER_FLUSHING","BUFFER_FLUSHED","MANIFEST_LOADING","MANIFEST_LOADED","MANIFEST_PARSED","LEVEL_SWITCHING","LEVEL_SWITCHED","LEVEL_LOADING","LEVEL_LOADED","LEVEL_UPDATED","LEVEL_PTS_UPDATED","LEVELS_UPDATED","AUDIO_TRACKS_UPDATED","AUDIO_TRACK_SWITCHING","AUDIO_TRACK_SWITCHED","AUDIO_TRACK_LOADING","AUDIO_TRACK_LOADED","SUBTITLE_TRACKS_UPDATED","SUBTITLE_TRACK_SWITCH","SUBTITLE_TRACK_LOADING","SUBTITLE_TRACK_LOADED","SUBTITLE_FRAG_PROCESSED","CUES_PARSED","NON_NATIVE_TEXT_TRACKS_FOUND","INIT_PTS_FOUND","FRAG_LOADING","FRAG_LOAD_PROGRESS","FRAG_LOAD_EMERGENCY_ABORTED","FRAG_LOADED","FRAG_DECRYPTED","FRAG_PARSING_INIT_SEGMENT","FRAG_PARSING_USERDATA","FRAG_PARSING_METADATA","FRAG_PARSING_DATA","FRAG_PARSED","FRAG_BUFFERED","FRAG_CHANGED","FPS_DROP","FPS_DROP_LEVEL_CAPPING","ERROR","DESTROYING","KEY_LOADING","KEY_LOADED","STREAM_STATE_TRANSITION","LIVE_BACK_BUFFER_REACHED","ErrorTypes","ErrorDetails","isFiniteNumber","Number","isFinite","MAX_SAFE_INTEGER","decoder","ID3","isHeader","data","offset","length","isFooter","getID3Data","front","_readSize","subarray","size","getTimeStamp","frames","getID3Frames","frame","isTimeStampFrame","_readTimeStamp","_getFrameData","String","fromCharCode","id3Data","end","frameData","_decodeFrame","push","_decodePrivFrame","_decodeURLFrame","_decodeTextFrame","timeStampFrame","byteLength","Uint8Array","pts33Bit","timestamp","Math","round","owner","_utf8ArrayToStr","privateData","buffer","index","description","text","url","array","exitOnNull","getTextDecoder","decoded","decode","idx","indexOf","substring","replace","char2","char3","len","out","TextDecoder","utf8ArrayToStr","window","self","URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","Error","path","normalizePath","buildURLFromParts","relativeParts","scheme","baseParts","netLoc","pathParts","exec","builtParts","params","query","fragment","baseURLPath","newPath","lastIndexOf","parts","split","reverse","join","AESCrypto","subtle","iv","aesIV","decrypt","FastAESKey","expandKey","importKey","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","DataView","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","x","xi","sx","x2","x4","x8","keyBuffer","sameKey","keySize","ksRow","invKsRow","prev","ksRows","keySchedule","invKeySchedule","sbox","networkToHostOrderSwap","word","inputArrayBuffer","removePKCS7Padding","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","outputBytes","paddingBytes","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","swapWord","getUint8","slice","destroy","undefined","Decrypter","observer","config","logEnabled","browserCrypto","crypto","webkitSubtle","disableWebCrypto","isSync","enableSoftwareAES","callback","decryptor","fastAesKey","then","aesKey","catch","err","onWebCryptoError","result","message","trigger","Event","MEDIA_ERROR","details","FRAG_DECRYPT_ERROR","fatal","reason","has","prefix","Events","EE","fn","context","once","addListener","emitter","event","TypeError","listener","evt","_events","_eventsCount","clearEvent","EventEmitter","__proto__","eventNames","events","names","getOwnPropertySymbols","concat","listeners","handlers","ee","Array","listenerCount","emit","a1","a2","a3","a4","a5","arguments","removeListener","j","on","removeAllListeners","off","prefixed","isHeaderPattern","getHeaderLength","getFullFrameLength","probe","headerLength","frameLength","newOffset","initTrackConfig","track","audioCodec","samplerate","adtsObjectType","adtsSampleingIndex","adtsExtensionSampleingIndex","adtsChanelConfig","userAgent","navigator","toLowerCase","manifestCodec","adtsSampleingRates","test","channelCount","codec","FRAG_PARSING_ERROR","getAudioConfig","getFrameDuration","appendFrame","pts","frameIndex","header","frameDuration","stamp","parseFrameHeader","aacSample","unit","dts","samples","sample","AACDemuxer","remuxer","resetInitSegment","initSegment","videoCodec","duration","_audioTrack","container","id","sequenceNumber","isAAC","inputTimeScale","resetTimeStamp","ADTS","append","timeOffset","contiguous","accurateTimeOffset","id3Samples","remux","MpegAudio","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","headerB","headerC","headerE","headerF","headerG","columnInBitrates","bitRate","columnInSampleRates","sampleCoefficient","bytesInSlot","parseInt","ExpGolomb","bytesAvailable","bitsAvailable","loadWord","position","workingBytes","availableBytes","min","set","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","readUByte","readUShort","readUInt","skipScalingList","lastScale","nextScale","readSPS","profileIdc","numRefFramesInPicOrderCntCycle","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","scalingListCount","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","chromaFormatIdc","picOrderCntType","pixelRatio","width","ceil","height","readSliceType","SampleAesDecrypter","decryptdata","discardEPB","decrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","sync","curUnit","encryptedBuffer","byteOffset","localthis","decryptedData","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","floor","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","units","RemuxerTrackIdConfig","video","audio","id3","TSDemuxer","typeSupported","sampleAes","pmtUnknownTypes","setDecryptData","method","syncOffset","_syncOffset","scanwindow","createTrack","pid","dropped","pmtParsed","_pmtId","_avcTrack","_id3Track","_txtTrack","aacOverFlow","aacLastPTS","avcSample","_duration","start","stt","pes","unknownPIDs","avcTrack","audioTrack","id3Track","avcId","audioId","id3Id","pmtId","avcData","pesData","audioData","parsePAT","_parsePAT","parsePMT","_parsePMT","parsePES","_parsePES","parseAVCPES","_parseAVCPES","parseAACPES","_parseAACPES","parseMPEGPES","_parseMPEGPES","parseID3PES","_parseID3PES","parsedPIDs","mpeg","mp3","avc","decryptAndRemux","videoTrack","textTrack","decryptAndRemuxAvc","_initPTS","_initDTS","_trackUnknownPmt","logLevel","mpegSupported","isSampleAes","tableEnd","stream","frag","pesFlags","pesLen","pesHdrLen","pesPts","pesDts","payloadStartOffset","newData","splice","dataLen","pushAccesUnit","nbSamples","isNaN","lastSample","forceKeyFrameOnDiscontinuity","sps","last","expGolombDecoder","_parseAVCNALu","spsfound","createAVCSample","audFound","sliceType","payloadType","payloadSize","endOfCaptions","b","firstByte","totalCCs","byteArray","_insertSampleInOrder","bytes","uuidStrArray","toString","userDataPayloadBytes","uuid","userDataBytes","userData","codecarray","codecstring","h","pps","arr","pos","_getLastNalUnit","lastUnit","overflow","lastUnitType","state","naluState","lastState","lastUnitStart","tmp","newLength","EPBPositions","sourceIndex","shift","newPTS","abs","MP3Demuxer","AAC","getSilentFrame","UINT32_MAX","pow","MP4","init","types","avc1","avcC","btrt","dinf","dref","esds","ftyp","hdlr","mdat","mdhd","mdia","mfhd","minf","moof","moov","mp4a","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsd","stsz","stts","tfdt","tfhd","traf","trak","trun","trex","tkhd","vmhd","smhd","charCodeAt","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","payload","timescale","upperWordDuration","lowerWordDuration","sn","baseMediaDecodeTime","tracks","boxes","flags","dependsOn","isDependedOn","hasRedundancy","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","cts","arraylen","isLeading","paddingValue","isNonSync","degradPrio","movie","toTimescaleFromBase","destScale","srcBase","toMsFromMpegTsClock","toMpegTsClockFromTimescale","srcScale","MAX_SILENT_FRAME_DURATION_90KHZ","PTS_DTS_SHIFT_TOLERANCE_90KHZ","chromeVersion","PTSNormalize","reference","MP4Remuxer","now","vendor","ISGenerated","match","defaultTimeStamp","getVideoStartPts","videoSamples","rolloverDetected","startPTS","reduce","minPTS","delta","generateIS","nbAudioSamples","nbVideoSamples","audioTimeOffset","videoTimeOffset","audiovideoTimestampDelta","max","audioTrackLength","remuxAudio","endPTS","remuxVideo","videoData","remuxEmptyAudio","remuxID3","remuxText","initPTS","initDTS","audioSamples","computePTSDTS","Infinity","metadata","startOffset","keys","mp4SampleDuration","firstDTS","lastDTS","timeScale","inputSamples","outputSamples","POSITIVE_INFINITY","maxPTS","NEGATIVE_INFINITY","ptsDtsShift","sortSamples","nextAvcDts","sort","a","deltadts","deltapts","averageSampleDuration","lastDts","foundHole","firstPTS","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","MUX_ERROR","REMUX_ALLOC_ERROR","setUint32","compositionTimeOffset","avcSampleUnits","mp4SampleLength","unitData","unitDataLen","lastFrameDuration","stretchShortVideoTrack","maxBufferHole","gapTolerance","deltaToFrameEnd","nextAudioPts","data1","data2","startDTS","endDTS","hasAudio","hasVideo","nb","mp4Sample","fillFrame","lastPTS","mp4timeScale","scaleFactor","inputSampleDuration","rawMPEG","filter","maxAudioFramesDrift","nextPts","missing","newStamp","audioSample","numMissingFrames","unitLen","lastSampleDuration","silentFrame","PassThroughRemuxer","rawData","streamType","performance","Date","DemuxerInline","demuxer","discontinuity","trackSwitch","defaultInitPTS","startTime","endTime","stats","tstart","tdecrypt","pushDecrypted","mux","muxConfig","demux","MP4Demuxer","initData","parseInitSegment","audiovideo","findBox","bin2str","readUint16","val","readUint32","writeUint32","subresults","endbox","results","parseSegmentIndex","references","moovEndOffset","sidx","version","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","earliestPresentationTime","trackId","codecBox","codecType","getStartDTS","trafs","baseTimes","map","scale","offsetStartDTS","upper","lower","webpackBootstrapFunc","configurable","oe","f","ENTRY_MODULE","default","quoteRegExp","str","getModuleDependencies","sources","queueName","retval","fnString","wrapperSignature","webpackRequireName","re","RegExp","hasValuesInQueues","queues","hasValues","options","main","requiredModules","all","modulesQueue","seenModules","moduleToCheck","pop","newModules","newModulesKeys","getRequiredModules","src","entryModule","JSON","stringify","blob","Blob","bare","workerUrl","URL","webkitURL","mozURL","msURL","createObjectURL","worker","Worker","objectURL","DemuxerWorker","forwardMessage","ev","postMessage","addEventListener","cmd","parse","transferable","PlaylistContextType","PlaylistLevelType","FORBIDDEN_EVENT_NAMES","EventHandler","hls","handledEvents","useGenericHandler","onEvent","registerListeners","onHandlerDestroying","unregisterListeners","onHandlerDestroyed","isEventHandler","onEventGeneric","funcName","constructor","OTHER_ERROR","INTERNAL_EXCEPTION","ElementaryStreamTypes","LevelKey","baseURI","relativeURI","_uri","baseuri","reluri","Fragment","_url","_byteRange","_decryptdata","_elementaryStreams","AUDIO","VIDEO","deltaPTS","rawProgramDateTime","programDateTime","title","tagList","cc","relurl","baseurl","urlId","level","levelkey","loader","setByteRange","previousFrag","byteRange","byteRangeEndOffset","addElementaryStream","hasElementaryStream","createInitializationVector","segmentNumber","uint8View","setDecryptDataFromLevelKey","uri","Level","baseUrl","endCC","endSN","fragments","live","needSidxRanges","startCC","startSN","startTimeOffset","targetduration","totalduration","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","attr","parseAttrList","decimalInteger","attrName","intValue","hexadecimalInteger","stringValue","hexadecimalIntegerAsNumber","decimalFloatingPoint","parseFloat","enumeratedString","decimalResolution","res","input","lastIndex","sampleEntryCodesISO","isCodecSupportedInMp4","MediaSource","isTypeSupported","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","LEVEL_PLAYLIST_REGEX_FAST","source","LEVEL_PLAYLIST_REGEX_SLOW","MP4_REGEX_SUFFIX","M3U8Parser","findGroup","groups","mediaGroupId","group","convertAVC1ToAVCOTI","avcdata","substr","resolve","parseMasterPlaylist","string","levels","sessionData","hasSessionData","setCodecs","codecs","filtered","typeCodes","isCodecType","preferred","unknownCodecs","resolution","bitrate","NAME","CODECS","sessionAttrs","parseMasterPlaylistMedia","audioGroups","medias","TYPE","media","groupId","instreamId","LANGUAGE","DEFAULT","autoselect","AUTOSELECT","forced","FORCED","lang","URI","groupCodec","parseLevelPlaylist","levelUrlId","currentSN","discontinuityCounter","prevFrag","firstPdtIndex","assignProgramDateTime","value1","value2","toUpperCase","keyAttrs","decryptmethod","decrypturi","decryptiv","KEYFORMAT","mapAttrs","BYTERANGE","averagetargetduration","every","startIndex","fragPrev","backfillProgramDateTimes","endProgramDateTime","PlaylistLoader","loaders","canHaveQualityLevels","AUDIO_TRACK","SUBTITLE_TRACK","mapContextToLevelType","SUBTITLE","MAIN","getResponseUrl","response","createInternalLoader","PLoader","pLoader","Loader","getInternalLoader","resetInternalLoader","contextType","destroyInternalLoaders","onManifestLoading","load","MANIFEST","responseType","onLevelLoading","LEVEL","onAudioTrackLoading","onSubtitleTrackLoading","maxRetry","timeout","retryDelay","maxRetryDelay","loaderContext","abort","manifestLoadingMaxRetry","manifestLoadingTimeOut","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","loaderConfig","loaderCallbacks","onSuccess","loadsuccess","onError","loaderror","onTimeout","loadtimeout","networkDetails","isSidxRequest","_handleSidxRequest","_handlePlaylistLoaded","tload","_handleTrackOrLevelPlaylist","_handleMasterPlaylist","_handleManifestParsingError","_handleNetworkError","audioTracks","subtitles","captions","embeddedAudioFound","unshift","levelId","levelType","levelDetails","singleLevel","tparsed","sidxUrl","rangeStart","rangeEnd","NETWORK_ERROR","LEVEL_EMPTY_ERROR","sidxInfo","sidxReferences","segmentRef","segRefInfo","MANIFEST_PARSING_ERROR","MANIFEST_LOAD_TIMEOUT","MANIFEST_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","LEVEL_LOAD_ERROR","AUDIO_TRACK_LOAD_TIMEOUT","AUDIO_TRACK_LOAD_ERROR","errorData","FragmentLoader","loaderName","onFragLoading","FragmentILoader","fLoader","DefaultILoader","loaded","progressData","byteRangeStartOffset","fragLoadingTimeOut","fragLoadingMaxRetryTimeout","onProgress","loadprogress","FRAG_LOAD_ERROR","FRAG_LOAD_TIMEOUT","KeyLoader","decryptkey","decrypturl","onKeyLoading","fragLoadingRetryDelay","KEY_LOAD_ERROR","KEY_LOAD_TIMEOUT","FragmentState","FragmentTracker","bufferPadding","timeRanges","getBufferedFrag","bufferedFrags","fragmentEntity","body","buffered","bufferedFragKey","detectEvictedFragments","elementaryStream","timeRange","esData","range","fragmentTimes","time","isTimeBuffered","removeFragment","detectPartialFragments","fragKey","getFragmentKey","getBufferedTimes","fragmentPartial","partial","getPartialFragment","timePadding","bestFragment","bestOverlap","isPartial","getState","onFragLoaded","bitrateTest","onBufferAppended","onFragBuffered","hasFragment","removeAllFragments","BinarySearch","search","list","comparisonFn","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","BufferHelper","isBuffered","bufferInfo","maxHoleDuration","vbuffered","bufferedInfo","nextStart","diff","buffered2","buf2len","buf2end","bufferStartNext","bufferLen","bufferStart","bufferEnd","getMediaSource","WebKitMediaSource","Observer","Demuxer","mp4","enableWorker","w","work","onwmsg","onWorkerMessage","onerror","filename","lineno","revokeObjectURL","removeEventListener","terminate","lastFrag","nextSN","ArrayBuffer","addGroupId","audioGroupIds","textGroupIds","updatePTS","fromIdx","toIdx","fragFrom","fragTo","fragToPTS","minEndPTS","updateFragPTSDTS","maxStartPTS","drift","fragIdx","PTSKnown","mergeDetails","oldDetails","newDetails","PTSFrag","ccOffset","mapFragmentIntersection","oldFrag","newFrag","backtracked","newFragments","oldPlaylist","newPlaylist","oldFragments","adjustSliding","intersectionFn","computeReloadInterval","currentPlaylist","lastRequestTime","reloadInterval","minReloadInterval","TimeRanges","toFixed","adjustPts","sliding","alignStream","lastLevel","shouldAlign","shouldAlignOnDiscontinuities","referenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","firstFrag","currentFrag","findFirstFragWithCC","findDiscontinuousReferenceFrag","alignDiscontinuities","lastDetails","hasProgramDateTime","lastPDT","alignPDT","findFragmentByPDT","PDTValue","maxFragLookUpTolerance","isArray","seg","pdtWithinToleranceTest","findFragmentByPTS","fragPrevious","fragNext","fragmentWithinToleranceTest","foundFragment","candidate","candidateLookupTolerance","pdtBufferEnd","GapController","fragmentTracker","nudgeRetry","stallReported","stalled","moved","seeking","poll","lastCurrentTime","currentTime","seeked","beginSeek","paused","ended","playbackRate","hasEnoughBuffer","noBufferGap","startJump","_trySkipBufferHole","tnow","stalledDuration","_reportStall","bufferedWithHoles","_tryFixBufferStall","stalledDurationMs","highBufferWatchdogPeriod","_tryNudgeBuffer","BUFFER_STALLED_ERROR","lastEndTime","targetTime","BUFFER_SEEK_OVER_HOLE","nudgeMaxRetry","nudgeOffset","BUFFER_NUDGE_ON_STALL","TaskLoop","_boundTick","_tickTimer","_tickInterval","_tickCallCount","tick","clearNextTick","clearInterval","hasInterval","hasNextTick","setInterval","millis","clearTimeout","doTick","setTimeout","State","BaseStreamController","startLoad","stopLoad","fragCurrent","_streamEnded","fragState","onMediaSeeking","mediaBuffer","tolerance","fragStartOffset","fragEndOffset","loadedmetadata","nextLoadPosition","startPosition","onMediaEnded","computeLivePosition","targetLatency","liveSyncDuration","liveSyncDurationCount","chromeOrFirefox","StreamController","audioCodecSwap","_state","gapController","altAudio","audioOnly","fragLoadError","startFragRequested","startLevel","testBandwidth","nextAutoLevel","nextLoadLevel","forceStartLoad","_doTickIdle","retryDate","_checkBuffer","_checkFragmentChanged","levelLastLoaded","startFragPrefetch","levelInfo","maxBufLen","levelBitrate","maxBufferSize","maxBufferLength","maxMaxBufferLength","_fetchPayloadOrEos","fragLen","initialLiveManifestSize","_ensureFragmentAtLivePoint","_findFragment","encrypted","_loadKey","_loadFragment","maxLatency","liveMaxLatencyDuration","liveMaxLatencyDurationCount","liveSyncPosition","readyState","targetSN","fragPreviousLoad","fragmentIndexRange","fragNextLoad","curSNIdx","sameLevel","prevSnFrag","nextSnFrag","autoLevel","autoLevelEnabled","_reduceMaxBufferLength","followingBufferedFrag","fragPlayingCurrent","fragPlaying","fragPlayingLevel","immediateLevelSwitch","immediateSwitch","previouslyPaused","pause","flushMainBuffer","immediateLevelSwitchEnd","play","nextLevelSwitch","fetchdelay","nextLevelId","nextLevel","fragLastKbps","bufferedFrag","nextBufferedFrag","startPts","endOffset","flushScope","onMediaAttached","onvseeking","onvseeked","onMediaSeeked","onvended","autoStartLoad","onMediaDetaching","onManifestParsed","aac","heaac","audioCodecSwitch","onLevelLoaded","newLevelId","curLevel","LevelHelper","onKeyLoaded","fragLoaded","currentLevel","tbuffered","pendingBuffering","appended","initSegmentData","_getAudioCodec","onFragParsingInitSegment","fragNew","trackName","ua","levelCodec","parent","content","onFragParsingData","onFragParsed","_checkAppendedParsed","onAudioTrackSwitching","fromAltAudio","onAudioTrackSwitched","videoBuffer","onBufferCreated","mediaTrack","alternate","pending","total","tfirst","mediaBuffered","fragLoadingMaxRetry","delay","levelRetry","BUFFER_FULL_ERROR","minLength","_seekToStartPos","onFragLoadEmergencyAborted","onBufferFlushed","elementaryStreamType","onLevelsUpdated","swapAudioCodec","defaultAudioCodec","nextState","previousState","_liveSyncPosition","LevelController","canload","currentLevelIndex","manualLevelIndex","timer","clearTimer","_levels","levelRetryCount","loadError","loadLevel","onManifestLoaded","bitrateStart","levelSet","levelFromSet","videoCodecFound","audioCodecFound","attributes","fragmentError","SUBTITLES","_firstLevel","firstLevel","some","MANIFEST_INCOMPATIBLE_CODECS_ERROR","setLevelInternal","newLevel","levelProperties","LEVEL_SWITCH_ERROR","levelIndex","levelError","recoverLevel","errorEvent","redundantLevels","errorDetails","trequest","audioGroupId","levelObject","removeLevel","_startLevel","configStartLevel","sendAddTrackEvent","videoEl","document","createEvent","initEvent","dispatchEvent","clearCurrentCues","cues","removeCue","ID3TrackController","getID3Track","textTracks","kind","label","addTextTrack","onFragParsingMetadata","Cue","WebKitDataCue","VTTCue","TextTrackCue","cue","addCue","onLiveBackBufferReached","foundCue","left","right","mid","getClosestCue","EWMA","halfLife","alpha_","estimate_","totalWeight_","exp","weight","adjAlpha","getTotalWeight","getEstimate","zeroFactor","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","durationMs","numBytes","durationS","bandwidthInBps","canEstimate","AbrController","lastLoadedFragLevel","_nextAutoLevel","_bwEstimator","onCheck","_abandonRulesCheck","ewmaFast","ewmaSlow","abrEwmaFastLive","abrEwmaSlowLive","abrEwmaFastVoD","abrEwmaSlowVoD","abrEwmaDefaultEstimate","aborted","requestDelay","loadRate","bw","realBitrate","expectedLen","fragLoadedDelay","bufferStarvationDelay","minAutoLevel","levelNextBitrate","fragLevelNextLoadedDelay","abrMaxWithRealBitrate","loadedBytes","loadedDuration","fragLoadingProcessingMs","bwEstimate","bitrateTestDelay","_findBestLevel","currentFragDuration","currentBw","maxAutoLevel","maxFetchDuration","bwFactor","bwUpFactor","avgDuration","adjustedbw","fetchDuration","forcedAutoLevel","bwEstimator","nextABRAutoLevel","_nextABRAutoLevel","avgbw","bestLevel","abrBandWidthFactor","abrBandWidthUpFactor","maxStarvationDelay","maxLoadingDelay","BufferController","_msDuration","_levelDuration","_levelTargetDuration","_live","_objectUrl","_needsFlush","_needsEos","audioTimestampOffset","bufferCodecEventsExpected","_bufferCodecEventsTotal","mediaSource","segments","appending","appendError","flushBufferCounter","pendingTracks","sourceBuffer","flushRange","_onMediaSourceOpen","checkPendingTracks","_onMediaSourceClose","_onMediaSourceEnded","_onSBUpdateEnd","audioBuffer","timestampOffset","doFlush","checkEos","counter","segment","sbSet","sb","doAppending","updateMediaElementDuration","flushLiveBackBuffer","_onSBUpdateError","BUFFER_APPENDING_ERROR","onLevelPtsUpdated","updating","codecEvents","onMediaAttaching","ms","endOfStream","removeAttribute","pendingTracksCount","createSourceBuffers","onBufferReset","removeSourceBuffer","onBufferCodecs","mimeType","addSourceBuffer","BUFFER_ADD_CODEC_ERROR","onBufferAppending","onBufferEos","onBufferFlushing","liveBackBufferLength","bufferTypes","targetBackBufferPosition","bufferType","removeBufferRange","onLevelUpdated","liveDurationInfinity","flushBuffer","appendBuffer","code","BUFFER_APPEND_ERROR","appendErrorMaxRetry","sbType","bufStart","bufEnd","removeStart","removeEnd","remove","CapLevelController","autoLevelCapping","restrictedLevels","clientRect","capLevelToPlayerSize","stopCapping","onFpsDropLevelCapping","isLevelAllowed","droppedLevel","HTMLVideoElement","startCapping","detectPlayerSize","levelsLength","getMaxLevel","streamController","capLevelIndex","validLevels","getMaxLevelByMediaSize","mediaWidth","mediaHeight","getDimensions","boundsRect","getBoundingClientRect","bottom","top","maxLevelIndex","devicePixelRatio","contentScaleFactor","FPSController","isVideoPlaybackQualityAvailable","capLevelOnFPSDrop","getVideoPlaybackQuality","checkFPSInterval","fpsDroppedMonitoringPeriod","checkFPS","decodedFrames","droppedFrames","lastTime","currentPeriod","currentDropped","lastDroppedFrames","currentDecoded","lastDecodedFrames","droppedFPS","totalDroppedFrames","fpsDroppedMonitoringThreshold","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","XhrLoader","xhrSetup","requestTimeout","retryTimeout","callbacks","retry","loadInternal","xhr","XMLHttpRequest","open","status","setRequestHeader","onreadystatechange","readystatechange","onprogress","send","currentTarget","responseText","responseURL","statusText","lengthComputable","AudioTrackController","_trackId","_selectDefaultTrack","trackIdBlacklist","_selectAudioGroup","onAudioTrackLoaded","updatePeriodMs","_handleLoadError","_setAudioTrack","newId","_loadTrackDetailsIfNeeded","_updateTrack","_selectInitialAudioTrack","currentAudioTrack","defaultTracks","trackFound","traverseTracks","_needsTrackLoading","previousId","language","AudioStreamController","waitingFragment","videoTrackCC","waitingVideoCC","onInitPtsFound","demuxerId","trackDetails","mainBufferInfo","maxConfigBuffer","audioSwitch","CC","findFragWithCC","loadIdx","fragLoadIdx","nextBuffered","foundFrag","isSeeking","waitingFrag","waitingFragCC","clearWaitingFragment","onAudioTracksUpdated","appendObj","pendingData","appendOnBufferFlush","directionSetting","lr","rl","alignSetting","middle","findAlignSetting","extend","obj","cobj","baseObj","hasBeenReset","_id","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","setting","findDirectionSetting","SyntaxError","displayState","getCueAsHTML","WebVTT","convertCueToDOMTree","StringDecoder","decodeURIComponent","encodeURIComponent","VTTParser","regionList","Settings","values","parseOptions","keyValueDelim","groupDelim","kv","k","v","dflt","defaultKey","alt","integer","percent","defaults","center","align","parseCue","oInput","consumeTimeStamp","ts","computeSeconds","parseTimeStamp","skipWhitespace","settings","region","vals","vals0","vertical","line","lineAlign","snapToLines","consumeCueSettings","fixLineBreaks","collectNextLine","alreadyCollectedLine","hasSubstring","oncue","flush","onflush","newCue","captionScreen","row","indenting","indent","rows","isEmpty","chars","uchar","cueStartTime","VerboseLevel","specialCea608CharsCodes","getCharForByte","byte","charCode","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","CaptionsLogger","verboseLevel","severity","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","reset","setStyles","styles","attribs","style","isDefault","equals","other","copy","newPenState","StyledUnicodeChar","penState","setChar","setPenState","newChar","Row","currPenState","equal","empty","setCursor","absPos","DEBUG","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","CaptionScreen","currRow","nrRollUpRows","lastOutputScreen","NR_ROWS","setPen","INFO","setPAC","pacData","newRow","topRowIndex","prevLineTime","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","TEXT","getDisplayText","topRow","asOneRow","displayText","rowNr","rowText","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","currRollUpRow","writeScreen","getHandler","setHandler","newHandler","setMode","newMode","insertChars","screen","outputDataUpdate","ccRCL","ccBS","ccAOF","ccAON","ccDER","ccRU","ccFON","ccRDC","ccTR","ccRTD","ccEDM","ccCR","ccENM","ccEOC","ccTO","nrCols","ccMIDROW","secondByte","colorIndex","dispatch","dispatchCue","cueSplitAtTime","setLastCmd","cmdHistory","hasCmdRepeated","Cea608Parser","field","out1","out2","channels","currentChannel","channel","addData","byteList","cmdFound","charsFound","DATA","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","currChNr","WARNING","interpretPAC","pacIndex","channelNr","charCodes","charCode1","oneCode","hexCodes","OutputFilter","timelineController","cueRanges","addCues","createCaptionsTrack","startsWith","inputString","searchString","hash","WebVTTParser","vttByteArray","syncPTS","vttCCs","callBack","errorCallBack","parsingError","vttLines","cueTime","mpegTs","localTime","presentationTime","inHeader","timestampMap","parser","currCC","cueOffset","new","prevCC","presentationOffset","calculateOffset","onparsingerror","timeString","secs","mins","hours","cueString2millis","canReuseVttTextTrack","inUseTrack","manifestTrack","textTrack1","textTrack2","TimelineController","enabled","Cues","unparsedVttFrags","captionsTracks","nonNativeCaptionsTracks","captionsProperties","cea608Parser1","cea608Parser2","lastSn","0","cueHandler","captionsTextTrack1Label","languageCode","captionsTextTrack1LanguageCode","captionsTextTrack2Label","captionsTextTrack2LanguageCode","textTrack3","captionsTextTrack3Label","captionsTextTrack3LanguageCode","textTrack4","captionsTextTrack4Label","captionsTextTrack4LanguageCode","enableCEA708Captions","channel1","channel2","channel3","channel4","x1","y1","y2","merged","cueRange","overlap","renderTextTracksNatively","getExistingTrack","createNativeTrack","createNonNativeTrack","existingTrack","createTextTrack","trackProperties","closedCaptions","_cleanTracks","enableWebVTT","sameTracks","inUseTracks","subtitleDisplay","tracksList","subtitleTrack","captionsTrack","instreamIdMatch","success","decryptData","_parseVTTs","currentTrack","getCueById","textTrackCue","onFragDecrypted","onFragParsingUserdata","ccBytes","ccdatas","extractCea608Data","actualCCBytes","tmpByte","ccbyte1","ccbyte2","ccType","filterSubtitleTracks","textTrackList","SubtitleTrackController","stopped","queuedDefaultTrack","trackChangeListener","_onTextTracksChanged","useTextTrackPolling","subtitlePollingInterval","subtitleTracks","onSubtitleTrackLoaded","_clearReloadTimer","_loadCurrentTrack","_toggleTrackModes","oldTrack","nextTrack","_setSubtitleTrackInternal","subtitleTrackId","KeySystems","SubtitleStreamController","tracksBuffered","currentTrackId","lastAVStart","_onMediaSeeking","onSubtitleFragProcessed","fragStart","fragEnd","onSubtitleTracksUpdated","onSubtitleTrackSwitch","referenceStart","frags","mergeSubtitlePlaylists","_getBuffered","requestMediaKeySystemAccess","EMEController","_widevineLicenseUrl","_licenseXhrSetup","_emeEnabled","_requestMediaKeySystemAccess","_drmSystemOptions","_config","_mediaKeysList","_media","_hasSetMediaKeys","_requestLicenseFailureCount","mediaKeysPromise","_onMediaEncrypted","initDataType","KEY_SYSTEM_ERROR","KEY_SYSTEM_NO_KEYS","finallySetKeyAndStartSession","mediaKeys","_attemptSetMediaKeys","_generateRequestWithPreferredKeySession","widevineLicenseUrl","licenseXhrSetup","emeEnabled","requestMediaKeySystemAccessFunc","drmSystemOptions","getLicenseServerUrl","keySystem","WIDEVINE","_attemptKeySystemAccess","audioCodecs","videoCodecs","mediaKeySystemConfigs","baseConfig","audioCapabilities","videoCapabilities","contentType","robustness","audioRobustness","videoRobustness","createWidevineMediaKeySystemConfigurations","getSupportedMediaKeySystemConfigurations","keySystemAccessPromise","mediaKeySystemAccess","_onMediaKeySystemAccessObtained","mediaKeysListItem","mediaKeysSessionInitialized","mediaKeySystemDomain","Promise","createMediaKeys","_onMediaKeysCreated","mediaKeysSession","createSession","_onNewMediaKeySession","keySession","sessionId","_onKeySessionMessage","_requestLicense","update","keysListItem","setMediaKeys","KEY_SYSTEM_NO_ACCESS","KEY_SYSTEM_NO_SESSION","KEY_SYSTEM_NO_INIT_DATA","generateRequest","_createLicenseXhr","keyMessage","_onLicenseRequestReadyStageChange","KEY_SYSTEM_LICENSE_REQUEST_FAILED","attemptsLeft","_generateLicenseRequestChallenge","challenge","onMediaDetached","mediaKeysList","close","hlsDefaultConfig","lowBufferWatchdogPeriod","abrController","bufferController","capLevelController","fpsController","minAutoBitrate","__USE_SUBTITLES__","subtitleStreamController","subtitleTrackController","audioStreamController","audioTrackController","emeController","Hls","userConfig","_autoLevelCapping","levelController","networkControllers","coreComponents","defaultConfig","DefaultConfig","playListLoader","fragmentLoader","keyLoader","id3TrackController","Controller","isSupported","SourceBuffer","WebKitSourceBuffer","sourceBufferValidAPI","__VERSION__","detachMedia","component","attachMedia","loadSource","location","href","controller","recoverMediaError","manualLevel","shouldStartCapping","newCapLevelToPlayerSize","NaN","audioTrackId"],"mappings":"4BAAA,SAA2CA,EAAMC,GAC1B,iBAAZC,SAA0C,iBAAXC,OACxCA,OAAOD,QAAUD,IACQ,mBAAXG,QAAyBA,OAAOC,IAC9CD,OAAO,GAAIH,GACe,iBAAZC,QACdA,QAAa,IAAID,IAEjBD,EAAU,IAAIC,IARhB,CASGK,MAAM,WACT,O,YCTE,IAAIC,EAAmB,GAGvB,SAASC,EAAoBC,GAG5B,GAAGF,EAAiBE,GACnB,OAAOF,EAAiBE,GAAUP,QAGnC,IAAIC,EAASI,EAAiBE,GAAY,CACzCC,EAAGD,EACHE,GAAG,EACHT,QAAS,IAUV,OANAU,EAAQH,GAAUI,KAAKV,EAAOD,QAASC,EAAQA,EAAOD,QAASM,GAG/DL,EAAOQ,GAAI,EAGJR,EAAOD,QA0Df,OArDAM,EAAoBM,EAAIF,EAGxBJ,EAAoBO,EAAIR,EAGxBC,EAAoBQ,EAAI,SAASd,EAASe,EAAMC,GAC3CV,EAAoBW,EAAEjB,EAASe,IAClCG,OAAOC,eAAenB,EAASe,EAAM,CAAEK,YAAY,EAAMC,IAAKL,KAKhEV,EAAoBgB,EAAI,SAAStB,GACX,oBAAXuB,QAA0BA,OAAOC,aAC1CN,OAAOC,eAAenB,EAASuB,OAAOC,YAAa,CAAEC,MAAO,WAE7DP,OAAOC,eAAenB,EAAS,aAAc,CAAEyB,OAAO,KAQvDnB,EAAoBoB,EAAI,SAASD,EAAOE,GAEvC,GADU,EAAPA,IAAUF,EAAQnB,EAAoBmB,IAC/B,EAAPE,EAAU,OAAOF,EACpB,GAAW,EAAPE,GAA8B,iBAAVF,GAAsBA,GAASA,EAAMG,WAAY,OAAOH,EAChF,IAAII,EAAKX,OAAOY,OAAO,MAGvB,GAFAxB,EAAoBgB,EAAEO,GACtBX,OAAOC,eAAeU,EAAI,UAAW,CAAET,YAAY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0B3zE,KAAK2zE,wBACrC,OAAOA,EAA0BA,EAAwBxI,eAAiB,G,aAOzDoC,GACjB,IAAMoG,EAA0B3zE,KAAK2zE,wBACjCA,IACFA,EAAwBxI,cAAgBoC,K,sCAQ1C,IAAMoG,EAA0B3zE,KAAK2zE,wBACrC,QAAOA,GAA0BA,EAAwB1I,iB,aAOtC5pE,GACnB,IAAMsyE,EAA0B3zE,KAAK2zE,wBACjCA,IACFA,EAAwB1I,gBAAkB5pE,O,GA7oBf6uC,GAAZ6jC,GACLM,mB","file":"hls.min.js","sourcesContent":["(function webpackUniversalModuleDefinition(root, factory) {\n\tif(typeof exports === 'object' && typeof module === 'object')\n\t\tmodule.exports = factory();\n\telse if(typeof define === 'function' && define.amd)\n\t\tdefine([], factory);\n\telse if(typeof exports === 'object')\n\t\texports[\"Hls\"] = factory();\n\telse\n\t\troot[\"Hls\"] = factory();\n})(this, function() {\nreturn "," \t// The module cache\n \tvar installedModules = {};\n\n \t// The require function\n \tfunction __webpack_require__(moduleId) {\n\n \t\t// Check if module is in cache\n \t\tif(installedModules[moduleId]) {\n \t\t\treturn installedModules[moduleId].exports;\n \t\t}\n \t\t// Create a new module (and put it into the cache)\n \t\tvar module = installedModules[moduleId] = {\n \t\t\ti: moduleId,\n \t\t\tl: false,\n \t\t\texports: {}\n \t\t};\n\n \t\t// Execute the module function\n \t\tmodules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n \t\t// Flag the module as loaded\n \t\tmodule.l = true;\n\n \t\t// Return the exports of the module\n \t\treturn module.exports;\n \t}\n\n\n \t// expose the modules object (__webpack_modules__)\n \t__webpack_require__.m = modules;\n\n \t// expose the module cache\n \t__webpack_require__.c = installedModules;\n\n \t// define getter function for harmony exports\n \t__webpack_require__.d = function(exports, name, getter) {\n \t\tif(!__webpack_require__.o(exports, name)) {\n \t\t\tObject.defineProperty(exports, name, { enumerable: true, get: getter });\n \t\t}\n \t};\n\n \t// define __esModule on exports\n \t__webpack_require__.r = function(exports) {\n \t\tif(typeof Symbol !== 'undefined' && Symbol.toStringTag) {\n \t\t\tObject.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });\n \t\t}\n \t\tObject.defineProperty(exports, '__esModule', { value: true });\n \t};\n\n \t// create a fake namespace object\n \t// mode & 1: value is a module id, require it\n \t// mode & 2: merge all properties of value into the ns\n \t// mode & 4: return value when already ns object\n \t// mode & 8|1: behave like require\n \t__webpack_require__.t = function(value, mode) {\n \t\tif(mode & 1) value = __webpack_require__(value);\n \t\tif(mode & 8) return value;\n \t\tif((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;\n \t\tvar ns = Object.create(null);\n \t\t__webpack_require__.r(ns);\n \t\tObject.defineProperty(ns, 'default', { enumerable: true, value: value });\n \t\tif(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));\n \t\treturn ns;\n \t};\n\n \t// getDefaultExport function for compatibility with non-harmony modules\n \t__webpack_require__.n = function(module) {\n \t\tvar getter = module && module.__esModule ?\n \t\t\tfunction getDefault() { return module['default']; } :\n \t\t\tfunction getModuleExports() { return module; };\n \t\t__webpack_require__.d(getter, 'a', getter);\n \t\treturn getter;\n \t};\n\n \t// Object.prototype.hasOwnProperty.call\n \t__webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n \t// __webpack_public_path__\n \t__webpack_require__.p = \"/dist/\";\n\n\n \t// Load entry module and return exports\n \treturn __webpack_require__(__webpack_require__.s = 13);\n","import { getSelfScope } from './get-self-scope';\n\nfunction noop (...args) {}\n\nconst fakeLogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop\n};\n\nlet exportedLogger = fakeLogger;\n\n// let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction formatMsg (type, msg) {\n msg = '[' + type + '] > ' + msg;\n return msg;\n}\n\nconst global = getSelfScope();\n\nfunction consolePrintFn (type) {\n const func = global.console[type];\n if (func) {\n return function (...args) {\n if (args[0]) {\n args[0] = formatMsg(type, args[0]);\n }\n\n func.apply(global.console, args);\n };\n }\n return noop;\n}\n\nfunction exportLoggerFunctions (debugConfig, ...functions) {\n functions.forEach(function (type) {\n exportedLogger[type] = debugConfig[type] ? debugConfig[type].bind(debugConfig) : consolePrintFn(type);\n });\n}\n\nexport const enableLogs = function (debugConfig) {\n // check that console is available\n if ((global.console && debugConfig === true) || typeof debugConfig === 'object') {\n exportLoggerFunctions(debugConfig,\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug',\n 'log',\n 'info',\n 'warn',\n 'error'\n );\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n exportedLogger.log();\n } catch (e) {\n exportedLogger = fakeLogger;\n }\n } else {\n exportedLogger = fakeLogger;\n }\n};\n\nexport const logger = exportedLogger;\n","/**\n * @readonly\n * @enum {string}\n */\nconst HlsEvents = {\n // fired before MediaSource is attaching to media element - data: { media }\n MEDIA_ATTACHING: 'hlsMediaAttaching',\n // fired when MediaSource has been succesfully attached to media element - data: { }\n MEDIA_ATTACHED: 'hlsMediaAttached',\n // fired before detaching MediaSource from media element - data: { }\n MEDIA_DETACHING: 'hlsMediaDetaching',\n // fired when MediaSource has been detached from media element - data: { }\n MEDIA_DETACHED: 'hlsMediaDetached',\n // fired when we buffer is going to be reset - data: { }\n BUFFER_RESET: 'hlsBufferReset',\n // fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n BUFFER_CODECS: 'hlsBufferCodecs',\n // fired when sourcebuffers have been created - data: { tracks : tracks }\n BUFFER_CREATED: 'hlsBufferCreated',\n // fired when we append a segment to the buffer - data: { segment: segment object }\n BUFFER_APPENDING: 'hlsBufferAppending',\n // 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}\n BUFFER_APPENDED: 'hlsBufferAppended',\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }\n BUFFER_EOS: 'hlsBufferEos',\n // fired when the media buffer should be flushed - data { startOffset, endOffset }\n BUFFER_FLUSHING: 'hlsBufferFlushing',\n // fired when the media buffer has been flushed - data: { }\n BUFFER_FLUSHED: 'hlsBufferFlushed',\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n MANIFEST_LOADING: 'hlsManifestLoading',\n // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks], url : manifestURL, stats : { trequest, tfirst, tload, mtime}}\n MANIFEST_LOADED: 'hlsManifestLoaded',\n // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}\n MANIFEST_PARSED: 'hlsManifestParsed',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCHING: 'hlsLevelSwitching',\n // fired when a level switch is effective - data: { level : id of new level }\n LEVEL_SWITCHED: 'hlsLevelSwitched',\n // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}\n LEVEL_LOADING: 'hlsLevelLoading',\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : { trequest, tfirst, tload, mtime} }\n LEVEL_LOADED: 'hlsLevelLoaded',\n // 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 }\n LEVEL_UPDATED: 'hlsLevelUpdated',\n // 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 }\n LEVEL_PTS_UPDATED: 'hlsLevelPtsUpdated',\n // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }\n LEVELS_UPDATED: 'hlsLevelsUpdated',\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED: 'hlsAudioTracksUpdated',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING: 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED: 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING: 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : { trequest, tfirst, tload, mtime } }\n AUDIO_TRACK_LOADED: 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED: 'hlsSubtitleTracksUpdated',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH: 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING: 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : { trequest, tfirst, tload, mtime } }\n SUBTITLE_TRACK_LOADED: 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED: 'hlsSubtitleFragProcessed',\n // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }\n CUES_PARSED: 'hlsCuesParsed',\n // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }\n NON_NATIVE_TEXT_TRACKS_FOUND: 'hlsNonNativeTextTracksFound',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, frag : fragment object }\n INIT_PTS_FOUND: 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING: 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n FRAG_LOAD_PROGRESS: 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED: 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : { trequest, tfirst, tload, length } }\n FRAG_LOADED: 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED: 'hlsFragDecrypted',\n // 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 }\n FRAG_PARSING_INIT_SEGMENT: 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA: 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA: 'hlsFragParsingMetadata',\n // 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}\n FRAG_PARSING_DATA: 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED: 'hlsFragParsed',\n // 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 } }\n FRAG_BUFFERED: 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED: 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { curentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP: 'hlsFpsDrop',\n // triggered when FPS drop triggers auto level capping - data: { level, droppedlevel }\n FPS_DROP_LEVEL_CAPPING: 'hlsFpsDropLevelCapping',\n // 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 }\n ERROR: 'hlsError',\n // 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: { }\n DESTROYING: 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING: 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, payload : key payload, stats : { trequest, tfirst, tload, length } }\n KEY_LOADED: 'hlsKeyLoaded',\n // fired upon stream controller state transitions - data: { previousState, nextState }\n STREAM_STATE_TRANSITION: 'hlsStreamStateTransition',\n // fired when the live back buffer is reached defined by the liveBackBufferLength config option - data : { bufferEnd: number }\n LIVE_BACK_BUFFER_REACHED: 'hlsLiveBackBufferReached'\n};\n\nexport default HlsEvents;\n","export enum ErrorTypes {\n // Identifier for a network error (loading error / timeout ...)\n NETWORK_ERROR = 'networkError',\n // Identifier for a media Error (video/parsing/mediasource error)\n MEDIA_ERROR = 'mediaError',\n // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR = 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR = 'muxError',\n // Identifier for all other errors\n OTHER_ERROR = 'otherError'\n}\n\n/**\n * @enum {ErrorDetails}\n * @typedef {string} ErrorDetail\n */\nexport enum ErrorDetails {\n KEY_SYSTEM_NO_KEYS = 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS = 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION = 'keySystemNoSession',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED = 'keySystemLicenseRequestFailed',\n KEY_SYSTEM_NO_INIT_DATA = 'keySystemNoInitData',\n // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_ERROR = 'manifestLoadError',\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_TIMEOUT = 'manifestLoadTimeOut',\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n MANIFEST_PARSING_ERROR = 'manifestParsingError',\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n MANIFEST_INCOMPATIBLE_CODECS_ERROR = 'manifestIncompatibleCodecsError',\n // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: \"no fragments found in level\", level: index of the bad level }\n LEVEL_EMPTY_ERROR = 'levelEmptyError',\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_ERROR = 'levelLoadError',\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_TIMEOUT = 'levelLoadTimeOut',\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n LEVEL_SWITCH_ERROR = 'levelSwitchError',\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_ERROR = 'audioTrackLoadError',\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_TIMEOUT = 'audioTrackLoadTimeOut',\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n FRAG_LOAD_ERROR = 'fragLoadError',\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n FRAG_LOAD_TIMEOUT = 'fragLoadTimeOut',\n // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }\n FRAG_DECRYPT_ERROR = 'fragDecryptError',\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n FRAG_PARSING_ERROR = 'fragParsingError',\n // 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 }\n REMUX_ALLOC_ERROR = 'remuxAllocError',\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n KEY_LOAD_ERROR = 'keyLoadError',\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n KEY_LOAD_TIMEOUT = 'keyLoadTimeOut',\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { err : exception , mimeType : mimeType }\n BUFFER_ADD_CODEC_ERROR = 'bufferAddCodecError',\n // Identifier for a buffer append error - data: append error description\n BUFFER_APPEND_ERROR = 'bufferAppendError',\n // Identifier for a buffer appending error event - data: appending error description\n BUFFER_APPENDING_ERROR = 'bufferAppendingError',\n // Identifier for a buffer stalled error event\n BUFFER_STALLED_ERROR = 'bufferStalledError',\n // Identifier for a buffer full event\n BUFFER_FULL_ERROR = 'bufferFullError',\n // Identifier for a buffer seek over hole event\n BUFFER_SEEK_OVER_HOLE = 'bufferSeekOverHole',\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n BUFFER_NUDGE_ON_STALL = 'bufferNudgeOnStall',\n // Identifier for an internal exception happening inside hls.js while handling an event\n INTERNAL_EXCEPTION = 'internalException'\n}\n","export const isFiniteNumber = Number.isFinite || function (value) {\n return typeof value === 'number' && isFinite(value);\n};\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n","import { getSelfScope } from '../utils/get-self-scope';\n\n/**\n * ID3 parser\n */\nclass ID3 {\n /**\n * Returns true if an ID3 header can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 header is found\n */\n static isHeader (data, offset) {\n /*\n * http://id3.org/id3v2.3.0\n * [0] = 'I'\n * [1] = 'D'\n * [2] = '3'\n * [3,4] = {Version}\n * [5] = {Flags}\n * [6-9] = {ID3 Size}\n *\n * An ID3v2 tag can be detected with the following pattern:\n * $49 44 33 yy yy xx zz zz zz zz\n * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n */\n if (offset + 10 <= data.length) {\n // look for 'ID3' identifier\n if (data[offset] === 0x49 && data[offset + 1] === 0x44 && data[offset + 2] === 0x33) {\n // check version is within range\n if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {\n // check size is within range\n if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns true if an ID3 footer can be found at offset in data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {boolean} - True if an ID3 footer is found\n */\n static isFooter (data, offset) {\n /*\n * The footer is a copy of the header, but with a different identifier\n */\n if (offset + 10 <= data.length) {\n // look for '3DI' identifier\n if (data[offset] === 0x33 && data[offset + 1] === 0x44 && data[offset + 2] === 0x49) {\n // check version is within range\n if (data[offset + 3] < 0xFF && data[offset + 4] < 0xFF) {\n // check size is within range\n if (data[offset + 6] < 0x80 && data[offset + 7] < 0x80 && data[offset + 8] < 0x80 && data[offset + 9] < 0x80) {\n return true;\n }\n }\n }\n }\n\n return false;\n }\n\n /**\n * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n * @param {Uint8Array} data - The data to search in\n * @param {number} offset - The offset at which to start searching\n * @return {Uint8Array} - The block of data containing any ID3 tags found\n */\n static getID3Data (data, offset) {\n const front = offset;\n let length = 0;\n\n while (ID3.isHeader(data, offset)) {\n // ID3 header is 10 bytes\n length += 10;\n\n const size = ID3._readSize(data, offset + 6);\n length += size;\n\n if (ID3.isFooter(data, offset + 10)) {\n // ID3 footer is 10 bytes\n length += 10;\n }\n\n offset += length;\n }\n\n if (length > 0) {\n return data.subarray(front, front + length);\n }\n\n return undefined;\n }\n\n static _readSize (data, offset) {\n let size = 0;\n size = ((data[offset] & 0x7f) << 21);\n size |= ((data[offset + 1] & 0x7f) << 14);\n size |= ((data[offset + 2] & 0x7f) << 7);\n size |= (data[offset + 3] & 0x7f);\n return size;\n }\n\n /**\n * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n * @param {Uint8Array} data - Block of data containing one or more ID3 tags\n * @return {number} - The timestamp\n */\n static getTimeStamp (data) {\n const frames = ID3.getID3Frames(data);\n for (let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n if (ID3.isTimeStampFrame(frame)) {\n return ID3._readTimeStamp(frame);\n }\n }\n\n return undefined;\n }\n\n /**\n * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n * @param {ID3 frame} frame\n */\n static isTimeStampFrame (frame) {\n return (frame && frame.key === 'PRIV' && frame.info === 'com.apple.streaming.transportStreamTimestamp');\n }\n\n static _getFrameData (data) {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n const type = String.fromCharCode(data[0], data[1], data[2], data[3]);\n const size = ID3._readSize(data, 4);\n\n // skip frame id, size, and flags\n let offset = 10;\n\n return { type, size, data: data.subarray(offset, offset + size) };\n }\n\n /**\n * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n * @param {Uint8Array} id3Data - The ID3 data containing one or more ID3 tags\n * @return {ID3 frame[]} - Array of ID3 frame objects\n */\n static getID3Frames (id3Data) {\n let offset = 0;\n const frames = [];\n\n while (ID3.isHeader(id3Data, offset)) {\n const size = ID3._readSize(id3Data, offset + 6);\n // skip past ID3 header\n offset += 10;\n const end = offset + size;\n // loop through frames in the ID3 tag\n while (offset + 8 < end) {\n const frameData = ID3._getFrameData(id3Data.subarray(offset));\n const frame = ID3._decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\n\n // skip frame header and frame data\n offset += frameData.size + 10;\n }\n\n if (ID3.isFooter(id3Data, offset)) {\n offset += 10;\n }\n }\n\n return frames;\n }\n\n static _decodeFrame (frame) {\n if (frame.type === 'PRIV') {\n return ID3._decodePrivFrame(frame);\n } else if (frame.type[0] === 'W') {\n return ID3._decodeURLFrame(frame);\n }\n\n return ID3._decodeTextFrame(frame);\n }\n\n static _readTimeStamp (timeStampFrame) {\n if (timeStampFrame.data.byteLength === 8) {\n const data = new Uint8Array(timeStampFrame.data);\n // timestamp is 33 bit expressed as a big-endian eight-octet number,\n // with the upper 31 bits set to zero.\n const pts33Bit = data[3] & 0x1;\n let timestamp = (data[4] << 23) +\n (data[5] << 15) +\n (data[6] << 7) +\n data[7];\n timestamp /= 45;\n\n if (pts33Bit) {\n timestamp += 47721858.84;\n } // 2^32 / 90\n\n return Math.round(timestamp);\n }\n\n return undefined;\n }\n\n static _decodePrivFrame (frame) {\n /*\n Format: \\0\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n const owner = ID3._utf8ArrayToStr(frame.data, true);\n const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n }\n\n static _decodeTextFrame (frame) {\n if (frame.size < 2) {\n return undefined;\n }\n\n if (frame.type === 'TXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{Value}\n */\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index), true);\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Value}\n */\n const text = ID3._utf8ArrayToStr(frame.data.subarray(1));\n return { key: frame.type, data: text };\n }\n }\n\n static _decodeURLFrame (frame) {\n if (frame.type === 'WXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{URL}\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n let index = 1;\n const description = ID3._utf8ArrayToStr(frame.data.subarray(index), true);\n\n index += description.length + 1;\n const value = ID3._utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n } else {\n /*\n Format:\n [0-?] = {URL}\n */\n const url = ID3._utf8ArrayToStr(frame.data);\n return { key: frame.type, data: url };\n }\n }\n\n // http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n // http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n /* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo \n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\n static _utf8ArrayToStr (array, exitOnNull = false) {\n const decoder = getTextDecoder();\n if (decoder) {\n const decoded = decoder.decode(array);\n\n if (exitOnNull) {\n // grab up to the first null\n const idx = decoded.indexOf('\\0');\n return idx !== -1 ? decoded.substring(0, idx) : decoded;\n }\n\n // remove any null characters\n return decoded.replace(/\\0/g, '');\n }\n\n const len = array.length;\n let c;\n let char2;\n let char3;\n let out = '';\n let i = 0;\n while (i < len) {\n c = array[i++];\n if (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\n continue;\n }\n switch (c >> 4) {\n case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:\n // 0xxxxxxx\n out += String.fromCharCode(c);\n break;\n case 12: case 13:\n // 110x xxxx 10xx xxxx\n char2 = array[i++];\n out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));\n break;\n case 14:\n // 1110 xxxx 10xx xxxx 10xx xxxx\n char2 = array[i++];\n char3 = array[i++];\n out += String.fromCharCode(((c & 0x0F) << 12) |\n ((char2 & 0x3F) << 6) |\n ((char3 & 0x3F) << 0));\n break;\n default:\n }\n }\n return out;\n }\n}\n\nlet decoder;\n\nfunction getTextDecoder () {\n const global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n if (!decoder && typeof global.TextDecoder !== 'undefined') {\n decoder = new global.TextDecoder('utf-8');\n }\n\n return decoder;\n}\n\nconst utf8ArrayToStr = ID3._utf8ArrayToStr;\n\nexport default ID3;\n\nexport { utf8ArrayToStr };\n","export function getSelfScope () {\n // see https://stackoverflow.com/a/11237259/589493\n if (typeof window === 'undefined') {\n /* eslint-disable-next-line no-undef */\n return self;\n } else {\n return window;\n }\n}\n","// see https://tools.ietf.org/html/rfc1808\n\n(function (root) {\n var URL_REGEX = /^((?:[a-zA-Z0-9+\\-.]+:)?)(\\/\\/[^\\/?#]*)?((?:[^\\/?#]*\\/)*[^;?#]*)?(;[^?#]*)?(\\?[^#]*)?(#.*)?$/;\n var FIRST_SEGMENT_REGEX = /^([^\\/?#]*)(.*)$/;\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/)[^\\/]*(?=\\/)/g;\n\n var URLToolkit = {\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n // E.g\n // With opts.alwaysNormalize = false (default, spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n // With opts.alwaysNormalize = true (not spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n buildAbsoluteURL: function (baseURL, relativeURL, opts) {\n opts = opts || {};\n // remove any remaining space and CRLF\n baseURL = baseURL.trim();\n relativeURL = relativeURL.trim();\n if (!relativeURL) {\n // 2a) If the embedded URL is entirely empty, it inherits the\n // entire base URL (i.e., is set equal to the base URL)\n // and we are done.\n if (!opts.alwaysNormalize) {\n return baseURL;\n }\n var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n if (!basePartsForNormalise) {\n throw new Error('Error trying to parse base URL.');\n }\n basePartsForNormalise.path = URLToolkit.normalizePath(\n basePartsForNormalise.path\n );\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\n }\n var relativeParts = URLToolkit.parseURL(relativeURL);\n if (!relativeParts) {\n throw new Error('Error trying to parse relative URL.');\n }\n if (relativeParts.scheme) {\n // 2b) If the embedded URL starts with a scheme name, it is\n // interpreted as an absolute URL and we are done.\n if (!opts.alwaysNormalize) {\n return relativeURL;\n }\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n return URLToolkit.buildURLFromParts(relativeParts);\n }\n var baseParts = URLToolkit.parseURL(baseURL);\n if (!baseParts) {\n throw new Error('Error trying to parse base URL.');\n }\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n baseParts.netLoc = pathParts[1];\n baseParts.path = pathParts[2];\n }\n if (baseParts.netLoc && !baseParts.path) {\n baseParts.path = '/';\n }\n var builtParts = {\n // 2c) Otherwise, the embedded URL inherits the scheme of\n // the base URL.\n scheme: baseParts.scheme,\n netLoc: relativeParts.netLoc,\n path: null,\n params: relativeParts.params,\n query: relativeParts.query,\n fragment: relativeParts.fragment,\n };\n if (!relativeParts.netLoc) {\n // 3) If the embedded URL's is non-empty, we skip to\n // Step 7. Otherwise, the embedded URL inherits the \n // (if any) of the base URL.\n builtParts.netLoc = baseParts.netLoc;\n // 4) If the embedded URL path is preceded by a slash \"/\", the\n // path is not relative and we skip to Step 7.\n if (relativeParts.path[0] !== '/') {\n if (!relativeParts.path) {\n // 5) If the embedded URL path is empty (and not preceded by a\n // slash), then the embedded URL inherits the base URL path\n builtParts.path = baseParts.path;\n // 5a) if the embedded URL's is non-empty, we skip to\n // step 7; otherwise, it inherits the of the base\n // URL (if any) and\n if (!relativeParts.params) {\n builtParts.params = baseParts.params;\n // 5b) if the embedded URL's is non-empty, we skip to\n // step 7; otherwise, it inherits the of the base\n // URL (if any) and we skip to step 7.\n if (!relativeParts.query) {\n builtParts.query = baseParts.query;\n }\n }\n } else {\n // 6) The last segment of the base URL's path (anything\n // following the rightmost slash \"/\", or the entire path if no\n // slash is present) is removed and the embedded URL's path is\n // appended in its place.\n var baseURLPath = baseParts.path;\n var newPath =\n baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +\n relativeParts.path;\n builtParts.path = URLToolkit.normalizePath(newPath);\n }\n }\n }\n if (builtParts.path === null) {\n builtParts.path = opts.alwaysNormalize\n ? URLToolkit.normalizePath(relativeParts.path)\n : relativeParts.path;\n }\n return URLToolkit.buildURLFromParts(builtParts);\n },\n parseURL: function (url) {\n var parts = URL_REGEX.exec(url);\n if (!parts) {\n return null;\n }\n return {\n scheme: parts[1] || '',\n netLoc: parts[2] || '',\n path: parts[3] || '',\n params: parts[4] || '',\n query: parts[5] || '',\n fragment: parts[6] || '',\n };\n },\n normalizePath: function (path) {\n // The following operations are\n // then applied, in order, to the new path:\n // 6a) All occurrences of \"./\", where \".\" is a complete path\n // segment, are removed.\n // 6b) If the path ends with \".\" as a complete path segment,\n // that \".\" is removed.\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n // 6c) All occurrences of \"/../\", where is a\n // complete path segment not equal to \"..\", are removed.\n // Removal of these path segments is performed iteratively,\n // removing the leftmost matching pattern on each iteration,\n // until no matching pattern remains.\n // 6d) If the path ends with \"/..\", where is a\n // complete path segment not equal to \"..\", that\n // \"/..\" is removed.\n while (\n path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length\n ) {}\n return path.split('').reverse().join('');\n },\n buildURLFromParts: function (parts) {\n return (\n parts.scheme +\n parts.netLoc +\n parts.path +\n parts.params +\n parts.query +\n parts.fragment\n );\n },\n };\n\n if (typeof exports === 'object' && typeof module === 'object')\n module.exports = URLToolkit;\n else if (typeof define === 'function' && define.amd)\n define([], function () {\n return URLToolkit;\n });\n else if (typeof exports === 'object') exports['URLToolkit'] = URLToolkit;\n else root['URLToolkit'] = URLToolkit;\n})(this);\n","export default class AESCrypto {\n constructor (subtle, iv) {\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n decrypt (data, key) {\n return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);\n }\n}\n","class FastAESKey {\n constructor (subtle, key) {\n this.subtle = subtle;\n this.key = key;\n }\n\n expandKey () {\n return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, ['encrypt', 'decrypt']);\n }\n}\n\nexport default FastAESKey;\n","// PKCS7\nexport function removePadding (buffer) {\n const outputBytes = buffer.byteLength;\n const paddingBytes = outputBytes && (new DataView(buffer)).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return buffer.slice(0, outputBytes - paddingBytes);\n } else {\n return buffer;\n }\n}\n\nclass AESDecryptor {\n constructor () {\n // Static after running initTable\n this.rcon = [0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];\n this.subMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n this.invSubMix = [new Uint32Array(256), new Uint32Array(256), new Uint32Array(256), new Uint32Array(256)];\n this.sBox = new Uint32Array(256);\n this.invSBox = new Uint32Array(256);\n\n // Changes during runtime\n this.key = new Uint32Array(0);\n\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_ (arrayBuffer) {\n let view = new DataView(arrayBuffer);\n let newArray = new Uint32Array(4);\n for (let i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n\n return newArray;\n }\n\n initTable () {\n let sBox = this.sBox;\n let invSBox = this.invSBox;\n let subMix = this.subMix;\n let subMix0 = subMix[0];\n let subMix1 = subMix[1];\n let subMix2 = subMix[2];\n let subMix3 = subMix[3];\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n }\n\n for (i = 0; i < 256; i++) {\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n let x2 = d[x];\n let x4 = d[x2];\n let x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n subMix0[x] = (t << 24) | (t >>> 8);\n subMix1[x] = (t << 16) | (t >>> 16);\n subMix2[x] = (t << 8) | (t >>> 24);\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n invSubMix0[sx] = (t << 24) | (t >>> 8);\n invSubMix1[sx] = (t << 16) | (t >>> 16);\n invSubMix2[sx] = (t << 8) | (t >>> 24);\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n\n expandKey (keyBuffer) {\n // convert keyBuffer to Uint32Array\n let key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n\n while (offset < key.length && sameKey) {\n sameKey = (key[offset] === this.key[offset]);\n offset++;\n }\n\n if (sameKey) {\n return;\n }\n\n this.key = key;\n let keySize = this.keySize = key.length;\n\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n\n let ksRows = this.ksRows = (keySize + 6 + 1) * 4;\n let ksRow;\n let invKsRow;\n\n let keySchedule = this.keySchedule = new Uint32Array(ksRows);\n let invKeySchedule = this.invKeySchedule = new Uint32Array(ksRows);\n let sbox = this.sBox;\n let rcon = this.rcon;\n\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let prev;\n let t;\n\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n\n if (ksRow % keySize === 0) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t = (sbox[t >>> 24] << 24) | (sbox[(t >>> 16) & 0xff] << 16) | (sbox[(t >>> 8) & 0xff] << 8) | sbox[t & 0xff];\n }\n\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] = invSubMix0[sbox[t >>> 24]] ^ invSubMix1[sbox[(t >>> 16) & 0xff]] ^ invSubMix2[sbox[(t >>> 8) & 0xff]] ^ invSubMix3[sbox[t & 0xff]];\n }\n\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap (word) {\n return (word << 24) | ((word & 0xff00) << 8) | ((word & 0xff0000) >> 8) | (word >>> 24);\n }\n\n decrypt (inputArrayBuffer, offset, aesIV, removePKCS7Padding) {\n let nRounds = this.keySize + 6;\n let invKeySchedule = this.invKeySchedule;\n let invSBOX = this.invSBox;\n\n let invSubMix = this.invSubMix;\n let invSubMix0 = invSubMix[0];\n let invSubMix1 = invSubMix[1];\n let invSubMix2 = invSubMix[2];\n let invSubMix3 = invSubMix[3];\n\n let initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n\n let inputInt32 = new Int32Array(inputArrayBuffer);\n let outputInt32 = new Int32Array(inputInt32.length);\n\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n\n let ksRow, i;\n let swapWord = this.networkToHostOrderSwap;\n\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(inputInt32[offset + 3]);\n\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 = invSubMix0[s0 >>> 24] ^ invSubMix1[(s1 >> 16) & 0xff] ^ invSubMix2[(s2 >> 8) & 0xff] ^ invSubMix3[s3 & 0xff] ^ invKeySchedule[ksRow];\n t1 = invSubMix0[s1 >>> 24] ^ invSubMix1[(s2 >> 16) & 0xff] ^ invSubMix2[(s3 >> 8) & 0xff] ^ invSubMix3[s0 & 0xff] ^ invKeySchedule[ksRow + 1];\n t2 = invSubMix0[s2 >>> 24] ^ invSubMix1[(s3 >> 16) & 0xff] ^ invSubMix2[(s0 >> 8) & 0xff] ^ invSubMix3[s1 & 0xff] ^ invKeySchedule[ksRow + 2];\n t3 = invSubMix0[s3 >>> 24] ^ invSubMix1[(s0 >> 16) & 0xff] ^ invSubMix2[(s1 >> 8) & 0xff] ^ invSubMix3[s2 & 0xff] ^ invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 = ((invSBOX[s0 >>> 24] << 24) ^ (invSBOX[(s1 >> 16) & 0xff] << 16) ^ (invSBOX[(s2 >> 8) & 0xff] << 8) ^ invSBOX[s3 & 0xff]) ^ invKeySchedule[ksRow];\n t1 = ((invSBOX[s1 >>> 24] << 24) ^ (invSBOX[(s2 >> 16) & 0xff] << 16) ^ (invSBOX[(s3 >> 8) & 0xff] << 8) ^ invSBOX[s0 & 0xff]) ^ invKeySchedule[ksRow + 1];\n t2 = ((invSBOX[s2 >>> 24] << 24) ^ (invSBOX[(s3 >> 16) & 0xff] << 16) ^ (invSBOX[(s0 >> 8) & 0xff] << 8) ^ invSBOX[s1 & 0xff]) ^ invKeySchedule[ksRow + 2];\n t3 = ((invSBOX[s3 >>> 24] << 24) ^ (invSBOX[(s0 >> 16) & 0xff] << 16) ^ (invSBOX[(s1 >> 8) & 0xff] << 8) ^ invSBOX[s2 & 0xff]) ^ invKeySchedule[ksRow + 3];\n ksRow = ksRow + 3;\n\n // Write\n outputInt32[offset] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n\n offset = offset + 4;\n }\n\n return removePKCS7Padding ? removePadding(outputInt32.buffer) : outputInt32.buffer;\n }\n\n destroy () {\n this.key = undefined;\n this.keySize = undefined;\n this.ksRows = undefined;\n\n this.sBox = undefined;\n this.invSBox = undefined;\n this.subMix = undefined;\n this.invSubMix = undefined;\n this.keySchedule = undefined;\n this.invKeySchedule = undefined;\n\n this.rcon = undefined;\n }\n}\n\nexport default AESDecryptor;\n","import AESCrypto from './aes-crypto';\nimport FastAESKey from './fast-aes-key';\nimport AESDecryptor from './aes-decryptor';\n\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\n\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nclass Decrypter {\n constructor (observer, config, { removePKCS7Padding = true } = {}) {\n this.logEnabled = true;\n this.observer = observer;\n this.config = config;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = global.crypto;\n if (browserCrypto) {\n this.subtle = browserCrypto.subtle || browserCrypto.webkitSubtle;\n }\n } catch (e) {}\n }\n this.disableWebCrypto = !this.subtle;\n }\n\n isSync () {\n return (this.disableWebCrypto && this.config.enableSoftwareAES);\n }\n\n decrypt (data, key, iv, callback) {\n if (this.disableWebCrypto && this.config.enableSoftwareAES) {\n if (this.logEnabled) {\n logger.log('JS AES decrypt');\n this.logEnabled = false;\n }\n let decryptor = this.decryptor;\n if (!decryptor) {\n this.decryptor = decryptor = new AESDecryptor();\n }\n\n decryptor.expandKey(key);\n callback(decryptor.decrypt(data, 0, iv, this.removePKCS7Padding));\n } else {\n if (this.logEnabled) {\n logger.log('WebCrypto AES decrypt');\n this.logEnabled = false;\n }\n const subtle = this.subtle;\n if (this.key !== key) {\n this.key = key;\n this.fastAesKey = new FastAESKey(subtle, key);\n }\n\n this.fastAesKey.expandKey()\n .then((aesKey) => {\n // decrypt using web crypto\n let crypto = new AESCrypto(subtle, iv);\n crypto.decrypt(data, aesKey)\n .catch((err) => {\n this.onWebCryptoError(err, data, key, iv, callback);\n })\n .then((result) => {\n callback(result);\n });\n })\n .catch((err) => {\n this.onWebCryptoError(err, data, key, iv, callback);\n });\n }\n }\n\n onWebCryptoError (err, data, key, iv, callback) {\n if (this.config.enableSoftwareAES) {\n logger.log('WebCrypto Error, disable WebCrypto API');\n this.disableWebCrypto = true;\n this.logEnabled = true;\n this.decrypt(data, key, iv, callback);\n } else {\n logger.error(`decrypting error : ${err.message}`);\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_DECRYPT_ERROR, fatal: true, reason: err.message });\n }\n }\n\n destroy () {\n let decryptor = this.decryptor;\n if (decryptor) {\n decryptor.destroy();\n this.decryptor = undefined;\n }\n }\n}\n\nexport default Decrypter;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","/**\n * ADTS parser helper\n * @link https://wiki.multimedia.cx/index.php?title=ADTS\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport Event from '../events';\n\nimport { getSelfScope } from '../utils/get-self-scope';\n\nexport function getAudioConfig (observer, data, offset, audioCodec) {\n let adtsObjectType, // :int\n adtsSampleingIndex, // :int\n adtsExtensionSampleingIndex, // :int\n adtsChanelConfig, // :int\n config,\n userAgent = navigator.userAgent.toLowerCase(),\n manifestCodec = audioCodec,\n adtsSampleingRates = [\n 96000, 88200,\n 64000, 48000,\n 44100, 32000,\n 24000, 22050,\n 16000, 12000,\n 11025, 8000,\n 7350];\n // byte 2\n adtsObjectType = ((data[offset + 2] & 0xC0) >>> 6) + 1;\n adtsSampleingIndex = ((data[offset + 2] & 0x3C) >>> 2);\n if (adtsSampleingIndex > adtsSampleingRates.length - 1) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: `invalid ADTS sampling index:${adtsSampleingIndex}` });\n return;\n }\n adtsChanelConfig = ((data[offset + 2] & 0x01) << 2);\n // byte 3\n adtsChanelConfig |= ((data[offset + 3] & 0xC0) >>> 6);\n logger.log(`manifest codec:${audioCodec},ADTS data:type:${adtsObjectType},sampleingIndex:${adtsSampleingIndex}[${adtsSampleingRates[adtsSampleingIndex]}Hz],channelConfig:${adtsChanelConfig}`);\n // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox/i.test(userAgent)) {\n if (adtsSampleingIndex >= 6) {\n adtsObjectType = 5;\n config = new Array(4);\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSampleingIndex = adtsSampleingIndex - 3;\n } else {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n }\n // Android : always use AAC\n } else if (userAgent.indexOf('android') !== -1) {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n } else {\n /* for other browsers (Chrome/Vivaldi/Opera ...)\n always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n */\n adtsObjectType = 5;\n config = new Array(4);\n // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n if ((audioCodec && ((audioCodec.indexOf('mp4a.40.29') !== -1) ||\n (audioCodec.indexOf('mp4a.40.5') !== -1))) ||\n (!audioCodec && adtsSampleingIndex >= 6)) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSampleingIndex = adtsSampleingIndex - 3;\n } else {\n // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.\n if (audioCodec && audioCodec.indexOf('mp4a.40.2') !== -1 && ((adtsSampleingIndex >= 6 && adtsChanelConfig === 1) ||\n /vivaldi/i.test(userAgent)) ||\n (!audioCodec && adtsChanelConfig === 1)) {\n adtsObjectType = 2;\n config = new Array(2);\n }\n adtsExtensionSampleingIndex = adtsSampleingIndex;\n }\n }\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n config[0] = adtsObjectType << 3;\n // samplingFrequencyIndex\n config[0] |= (adtsSampleingIndex & 0x0E) >> 1;\n config[1] |= (adtsSampleingIndex & 0x01) << 7;\n // channelConfiguration\n config[1] |= adtsChanelConfig << 3;\n if (adtsObjectType === 5) {\n // adtsExtensionSampleingIndex\n config[1] |= (adtsExtensionSampleingIndex & 0x0E) >> 1;\n config[2] = (adtsExtensionSampleingIndex & 0x01) << 7;\n // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n config[2] |= 2 << 2;\n config[3] = 0;\n }\n return { config: config, samplerate: adtsSampleingRates[adtsSampleingIndex], channelCount: adtsChanelConfig, codec: ('mp4a.40.' + adtsObjectType), manifestCodec: manifestCodec };\n}\n\nexport function isHeaderPattern (data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nexport function getHeaderLength (data, offset) {\n return (data[offset + 1] & 0x01 ? 7 : 9);\n}\n\nexport function getFullFrameLength (data, offset) {\n return ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xE0) >>> 5);\n}\n\nexport function isHeader (data, offset) {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n return true;\n }\n\n return false;\n}\n\nexport function probe (data, offset) {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (isHeader(data, offset)) {\n // ADTS header Length\n let headerLength = getHeaderLength(data, offset);\n if (offset + headerLength >= data.length) {\n return false;\n }\n // ADTS frame Length\n let frameLength = getFullFrameLength(data, offset);\n if (frameLength <= headerLength) {\n return false;\n }\n\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n}\n\nexport function initTrackConfig (track, observer, data, offset, audioCodec) {\n if (!track.samplerate) {\n let config = getAudioConfig(observer, data, offset, audioCodec);\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(`parsed codec:${track.codec},rate:${config.samplerate},nb channel:${config.channelCount}`);\n }\n}\n\nexport function getFrameDuration (samplerate) {\n return 1024 * 90000 / samplerate;\n}\n\nexport function parseFrameHeader (data, offset, pts, frameIndex, frameDuration) {\n let headerLength, frameLength, stamp;\n let length = data.length;\n\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n headerLength = getHeaderLength(data, offset);\n // retrieve frame size\n frameLength = getFullFrameLength(data, offset);\n frameLength -= headerLength;\n\n if ((frameLength > 0) && ((offset + headerLength + frameLength) <= length)) {\n stamp = pts + frameIndex * frameDuration;\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n return { headerLength, frameLength, stamp };\n }\n\n return undefined;\n}\n\nexport function appendFrame (track, data, offset, pts, frameIndex) {\n let frameDuration = getFrameDuration(track.samplerate);\n let header = parseFrameHeader(data, offset, pts, frameIndex, frameDuration);\n if (header) {\n let stamp = header.stamp;\n let headerLength = header.headerLength;\n let frameLength = header.frameLength;\n\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}/${(stamp/90).toFixed(0)}`);\n let aacSample = {\n unit: data.subarray(offset + headerLength, offset + headerLength + frameLength),\n pts: stamp,\n dts: stamp\n };\n\n track.samples.push(aacSample);\n return { sample: aacSample, length: frameLength + headerLength };\n }\n\n return undefined;\n}\n","/**\n * AAC demuxer\n */\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport ID3 from '../demux/id3';\n\nclass AACDemuxer {\n constructor (observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/adts', type: 'audio', id: 0, sequenceNumber: 0, isAAC: true, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp () {\n }\n\n static probe (data) {\n if (!data) {\n return false;\n }\n\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\n\n for (let length = data.length; offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let track = this._audioTrack;\n let id3Data = ID3.getID3Data(data, 0) || [];\n let timestamp = ID3.getTimeStamp(id3Data);\n let pts = Number.isFinite(timestamp) ? timestamp * 90 : timeOffset * 90000;\n let frameIndex = 0;\n let stamp = pts;\n let length = data.length;\n let offset = id3Data.length;\n\n let id3Samples = [{ pts: stamp, dts: stamp, data: id3Data }];\n\n while (offset < length - 1) {\n if (ADTS.isHeader(data, offset) && (offset + 5) < length) {\n ADTS.initTrackConfig(track, this.observer, data, offset, track.manifestCodec);\n let frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n logger.log('Unable to parse AAC frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy () {\n }\n}\n\nexport default AACDemuxer;\n","/**\n * MPEG parser helper\n */\n\nconst MpegAudio = {\n\n BitratesMap: [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448,\n 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384,\n 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,\n 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256,\n 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160],\n\n SamplingRateMap: [44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000],\n\n SamplesCoefficients: [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0 // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12 // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12 // Layer1\n ]\n ],\n\n BytesInSlot: [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4 // Layer1\n ],\n\n appendFrame: function (track, data, offset, pts, frameIndex) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return undefined;\n }\n\n let header = this.parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n let frameDuration = header.samplesPerFrame * 90000 / header.sampleRate;\n let stamp = pts + frameIndex * frameDuration;\n let sample = { unit: data.subarray(offset, offset + header.frameLength), pts: stamp, dts: stamp };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n\n return { sample, length: header.frameLength };\n }\n\n return undefined;\n },\n\n parseHeader: function (data, offset) {\n let headerB = (data[offset + 1] >> 3) & 3;\n let headerC = (data[offset + 1] >> 1) & 3;\n let headerE = (data[offset + 2] >> 4) & 15;\n let headerF = (data[offset + 2] >> 2) & 3;\n let headerG = (data[offset + 2] >> 1) & 1;\n if (headerB !== 1 && headerE !== 0 && headerE !== 15 && headerF !== 3) {\n let columnInBitrates = headerB === 3 ? (3 - headerC) : (headerC === 3 ? 3 : 4);\n let bitRate = MpegAudio.BitratesMap[columnInBitrates * 14 + headerE - 1] * 1000;\n let columnInSampleRates = headerB === 3 ? 0 : headerB === 2 ? 1 : 2;\n let sampleRate = MpegAudio.SamplingRateMap[columnInSampleRates * 3 + headerF];\n let channelCount = data[offset + 3] >> 6 === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n let sampleCoefficient = MpegAudio.SamplesCoefficients[headerB][headerC];\n let bytesInSlot = MpegAudio.BytesInSlot[headerC];\n let samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n let frameLength = parseInt(sampleCoefficient * bitRate / sampleRate + headerG, 10) * bytesInSlot;\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\n }\n\n return undefined;\n },\n\n isHeaderPattern: function (data, offset) {\n return data[offset] === 0xff && (data[offset + 1] & 0xe0) === 0xe0 && (data[offset + 1] & 0x06) !== 0x00;\n },\n\n isHeader: function (data, offset) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n return true;\n }\n\n return false;\n },\n\n probe: function (data, offset) {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && this.isHeaderPattern(data, offset)) {\n // MPEG header Length\n let headerLength = 4;\n // MPEG frame Length\n let header = this.parseHeader(data, offset);\n let frameLength = headerLength;\n if (header && header.frameLength) {\n frameLength = header.frameLength;\n }\n\n let newOffset = offset + frameLength;\n if (newOffset === data.length || (newOffset + 1 < data.length && this.isHeaderPattern(data, newOffset))) {\n return true;\n }\n }\n return false;\n }\n};\n\nexport default MpegAudio;\n","/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n*/\n\nimport { logger } from '../utils/logger';\n\nclass ExpGolomb {\n constructor (data) {\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord () {\n let\n data = this.data,\n bytesAvailable = this.bytesAvailable,\n position = data.byteLength - bytesAvailable,\n workingBytes = new Uint8Array(4),\n availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits (count) {\n let skipBytes; // :int\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= (skipBytes >> 3);\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits (size) {\n let\n bits = Math.min(this.bitsAvailable, size), // :uint\n valu = this.word >>> (32 - bits); // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n }\n\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return valu << bits | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ () {\n let leadingZeroCount; // :uint\n for (leadingZeroCount = 0; leadingZeroCount < this.bitsAvailable; ++leadingZeroCount) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG () {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG () {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG () {\n let clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG () {\n let valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean () {\n return this.readBits(1) === 1;\n }\n\n // ():int\n readUByte () {\n return this.readBits(8);\n }\n\n // ():int\n readUShort () {\n return this.readBits(16);\n }\n // ():int\n readUInt () {\n return this.readBits(32);\n }\n\n /**\n * Advance the ExpGolomb decoder past a scaling list. The scaling\n * list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count {number} the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList (count) {\n let\n lastScale = 8,\n nextScale = 8,\n j,\n deltaScale;\n for (j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = this.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = (nextScale === 0) ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @param data {Uint8Array} the bytes of a sequence parameter set\n * @return {object} an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS () {\n let\n frameCropLeftOffset = 0,\n frameCropRightOffset = 0,\n frameCropTopOffset = 0,\n frameCropBottomOffset = 0,\n profileIdc, profileCompat, levelIdc,\n numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,\n picHeightInMapUnitsMinus1,\n frameMbsOnlyFlag,\n scalingListCount,\n i,\n readUByte = this.readUByte.bind(this),\n readBits = this.readBits.bind(this),\n readUEG = this.readUEG.bind(this),\n readBoolean = this.readBoolean.bind(this),\n skipBits = this.skipBits.bind(this),\n skipEG = this.skipEG.bind(this),\n skipUEG = this.skipUEG.bind(this),\n skipScalingList = this.skipScalingList.bind(this);\n\n readUByte();\n profileIdc = readUByte(); // profile_idc\n profileCompat = readBits(5); // constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n levelIdc = readUByte(); // level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (profileIdc === 100 ||\n profileIdc === 110 ||\n profileIdc === 122 ||\n profileIdc === 244 ||\n profileIdc === 44 ||\n profileIdc === 83 ||\n profileIdc === 86 ||\n profileIdc === 118 ||\n profileIdc === 128) {\n let chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // separate_colour_plane_flag\n\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) { // seq_scaling_matrix_present_flag\n scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) { // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16);\n } else {\n skipScalingList(64);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n let picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG();\n } // offset_for_ref_frame[ i ]\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n picWidthInMbsMinus1 = readUEG();\n picHeightInMapUnitsMinus1 = readUEG();\n frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) { // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n let pixelRatio = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1: pixelRatio = [1, 1]; break;\n case 2: pixelRatio = [12, 11]; break;\n case 3: pixelRatio = [10, 11]; break;\n case 4: pixelRatio = [16, 11]; break;\n case 5: pixelRatio = [40, 33]; break;\n case 6: pixelRatio = [24, 11]; break;\n case 7: pixelRatio = [20, 11]; break;\n case 8: pixelRatio = [32, 11]; break;\n case 9: pixelRatio = [80, 33]; break;\n case 10: pixelRatio = [18, 11]; break;\n case 11: pixelRatio = [15, 11]; break;\n case 12: pixelRatio = [64, 33]; break;\n case 13: pixelRatio = [160, 99]; break;\n case 14: pixelRatio = [4, 3]; break;\n case 15: pixelRatio = [3, 2]; break;\n case 16: pixelRatio = [2, 1]; break;\n case 255: {\n pixelRatio = [readUByte() << 8 | readUByte(), readUByte() << 8 | readUByte()];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2)),\n height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - ((frameMbsOnlyFlag ? 2 : 4) * (frameCropTopOffset + frameCropBottomOffset)),\n pixelRatio: pixelRatio\n };\n }\n\n readSliceType () {\n // skip NALu type\n this.readUByte();\n // discard first_mb_in_slice\n this.readUEG();\n // return slice_type\n return this.readUEG();\n }\n}\n\nexport default ExpGolomb;\n","/**\n * SAMPLE-AES decrypter\n*/\n\nimport Decrypter from '../crypt/decrypter';\n\nclass SampleAesDecrypter {\n constructor (observer, config, decryptdata, discardEPB) {\n this.decryptdata = decryptdata;\n this.discardEPB = discardEPB;\n this.decrypter = new Decrypter(observer, config, { removePKCS7Padding: false });\n }\n\n decryptBuffer (encryptedData, callback) {\n this.decrypter.decrypt(encryptedData, this.decryptdata.key.buffer, this.decryptdata.iv.buffer, callback);\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n decryptAacSample (samples, sampleIndex, callback, sync) {\n let curUnit = samples[sampleIndex].unit;\n let encryptedData = curUnit.subarray(16, curUnit.length - curUnit.length % 16);\n let encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length);\n\n let localthis = this;\n this.decryptBuffer(encryptedBuffer, function (decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n curUnit.set(decryptedData, 16);\n\n if (!sync) {\n localthis.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples (samples, sampleIndex, callback) {\n for (;; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAacSample(samples, sampleIndex, callback, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData (decodedData) {\n let encryptedDataLen = Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n let encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (let inputPos = 32; inputPos <= decodedData.length - 16; inputPos += 160, outputPos += 16) {\n encryptedData.set(decodedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return encryptedData;\n }\n\n getAvcDecryptedUnit (decodedData, decryptedData) {\n decryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (let outputPos = 32; outputPos <= decodedData.length - 16; outputPos += 160, inputPos += 16) {\n decodedData.set(decryptedData.subarray(inputPos, inputPos + 16), outputPos);\n }\n\n return decodedData;\n }\n\n decryptAvcSample (samples, sampleIndex, unitIndex, callback, curUnit, sync) {\n let decodedData = this.discardEPB(curUnit.data);\n let encryptedData = this.getAvcEncryptedData(decodedData);\n let localthis = this;\n\n this.decryptBuffer(encryptedData.buffer, function (decryptedData) {\n curUnit.data = localthis.getAvcDecryptedUnit(decodedData, decryptedData);\n\n if (!sync) {\n localthis.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n });\n }\n\n decryptAvcSamples (samples, sampleIndex, unitIndex, callback) {\n for (;; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n let curUnits = samples[sampleIndex].units;\n for (;; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n let curUnit = curUnits[unitIndex];\n if (curUnit.data.length <= 48 || (curUnit.type !== 1 && curUnit.type !== 5)) {\n continue;\n }\n\n let sync = this.decrypter.isSync();\n\n this.decryptAvcSample(samples, sampleIndex, unitIndex, callback, curUnit, sync);\n\n if (!sync) {\n return;\n }\n }\n }\n }\n}\n\nexport default SampleAesDecrypter;\n","/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * 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.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n*/\n\nimport * as ADTS from './adts';\nimport MpegAudio from './mpegaudio';\nimport Event from '../events';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\n// import Hex from '../utils/hex';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { utf8ArrayToStr } from './id3';\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nconst RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4\n};\n\nclass TSDemuxer {\n constructor (observer, remuxer, config, typeSupported) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.remuxer = remuxer;\n this.sampleAes = null;\n this.pmtUnknownTypes = {};\n }\n\n setDecryptData (decryptdata) {\n if ((decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'SAMPLE-AES')) {\n this.sampleAes = new SampleAesDecrypter(this.observer, this.config, decryptdata, this.discardEPB);\n } else {\n this.sampleAes = null;\n }\n }\n\n static probe (data) {\n const syncOffset = TSDemuxer._syncOffset(data);\n if (syncOffset < 0) {\n return false;\n } else {\n if (syncOffset) {\n logger.warn(`MPEG2-TS detected but first sync word found @ offset ${syncOffset}, junk ahead ?`);\n }\n\n return true;\n }\n }\n\n static _syncOffset (data) {\n // scan 1000 first bytes\n const scanwindow = Math.min(1000, data.length - 3 * 188);\n let i = 0;\n while (i < scanwindow) {\n // a TS fragment should contain at least 3 TS packets, a PAT, a PMT, and one PID, each starting with 0x47\n if (data[i] === 0x47 && data[i + 188] === 0x47 && data[i + 2 * 188] === 0x47) {\n return i;\n } else {\n i++;\n }\n }\n return -1;\n }\n\n /**\n * Creates a track model internal to demuxer used to drive remuxing input\n *\n * @param {string} type 'audio' | 'video' | 'id3' | 'text'\n * @param {number} duration\n * @return {object} TSDemuxer's internal track model\n */\n static createTrack (type, duration) {\n return {\n container: type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type,\n id: RemuxerTrackIdConfig[type],\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: type === 'video' ? 0 : undefined,\n isAAC: type === 'audio' ? true : undefined,\n duration: type === 'audio' ? duration : undefined\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n * Resets all internal track instances of the demuxer.\n *\n * @override Implements generic demuxing/remuxing interface (see DemuxerInline)\n * @param {object} initSegment\n * @param {string} audioCodec\n * @param {string} videoCodec\n * @param {number} duration (in TS timescale = 90kHz)\n */\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this.pmtParsed = false;\n this._pmtId = -1;\n this.pmtUnknownTypes = {};\n\n this._avcTrack = TSDemuxer.createTrack('video', duration);\n this._audioTrack = TSDemuxer.createTrack('audio', duration);\n this._id3Track = TSDemuxer.createTrack('id3', duration);\n this._txtTrack = TSDemuxer.createTrack('text', duration);\n\n // flush any partial content\n this.aacOverFlow = null;\n this.aacLastPTS = null;\n this.avcSample = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = duration;\n }\n\n /**\n *\n * @override\n */\n resetTimeStamp () {}\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let start, len = data.length, stt, pid, atf, offset, pes,\n unknownPIDs = false;\n this.pmtUnknownTypes = {};\n this.contiguous = contiguous;\n let pmtParsed = this.pmtParsed,\n avcTrack = this._avcTrack,\n audioTrack = this._audioTrack,\n id3Track = this._id3Track,\n avcId = avcTrack.pid,\n audioId = audioTrack.pid,\n id3Id = id3Track.pid,\n pmtId = this._pmtId,\n avcData = avcTrack.pesData,\n audioData = audioTrack.pesData,\n id3Data = id3Track.pesData,\n parsePAT = this._parsePAT,\n parsePMT = this._parsePMT.bind(this),\n parsePES = this._parsePES,\n parseAVCPES = this._parseAVCPES.bind(this),\n parseAACPES = this._parseAACPES.bind(this),\n parseMPEGPES = this._parseMPEGPES.bind(this),\n parseID3PES = this._parseID3PES.bind(this);\n\n const syncOffset = TSDemuxer._syncOffset(data);\n\n // don't parse last TS packet if incomplete\n len -= (len + syncOffset) % 188;\n\n // loop through TS packets\n for (start = syncOffset; start < len; start += 188) {\n if (data[start] === 0x47) {\n stt = !!(data[start + 1] & 0x40);\n // pid is a 13-bit field starting at the last bit of TS[1]\n pid = ((data[start + 1] & 0x1f) << 8) + data[start + 2];\n atf = (data[start + 3] & 0x30) >> 4;\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === (start + 188)) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData))) {\n parseAVCPES(pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + 188));\n avcData.size += start + 188 - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData))) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n }\n audioData = { data: [], size: 0 };\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + 188));\n audioData.size += start + 188 - offset;\n }\n break;\n case id3Id:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data))) {\n parseID3PES(pes);\n }\n\n id3Data = { data: [], size: 0 };\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + 188));\n id3Data.size += start + 188 - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n pmtId = this._pmtId = parsePAT(data, offset);\n break;\n case pmtId:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n let parsedPIDs = parsePMT(data, offset, this.typeSupported.mpeg === true || this.typeSupported.mp3 === true, this.sampleAes != null);\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n avcId = parsedPIDs.avc;\n if (avcId > 0) {\n avcTrack.pid = avcId;\n }\n\n audioId = parsedPIDs.audio;\n if (audioId > 0) {\n audioTrack.pid = audioId;\n audioTrack.isAAC = parsedPIDs.isAAC;\n }\n id3Id = parsedPIDs.id3;\n if (id3Id > 0) {\n id3Track.pid = id3Id;\n }\n\n if (unknownPIDs && !pmtParsed) {\n logger.log('reparse from beginning');\n unknownPIDs = false;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = syncOffset - 188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n case 17:\n case 0x1fff:\n break;\n default:\n unknownPIDs = true;\n break;\n }\n } else {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'TS packet did not start with 0x47' });\n }\n }\n // try to parse last PES packets\n if (avcData && (pes = parsePES(avcData))) {\n parseAVCPES(pes, true);\n avcTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n avcTrack.pesData = avcData;\n }\n\n if (audioData && (pes = parsePES(audioData))) {\n if (audioTrack.isAAC) {\n parseAACPES(pes);\n } else {\n parseMPEGPES(pes);\n }\n\n audioTrack.pesData = null;\n } else {\n if (audioData && audioData.size) {\n logger.log('last AAC PES packet truncated,might overlap between fragments');\n }\n\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data))) {\n parseID3PES(pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n\n if (this.sampleAes == null) {\n this.remuxer.remux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n } else {\n this.decryptAndRemux(audioTrack, avcTrack, id3Track, this._txtTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (audioTrack.samples && audioTrack.isAAC) {\n let localthis = this;\n this.sampleAes.decryptAacSamples(audioTrack.samples, 0, function () {\n localthis.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.decryptAndRemuxAvc(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n decryptAndRemuxAvc (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n if (videoTrack.samples) {\n let localthis = this;\n this.sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, function () {\n localthis.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n });\n } else {\n this.remuxer.remux(audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset);\n }\n }\n\n destroy () {\n this._initPTS = this._initDTS = undefined;\n this._duration = 0;\n }\n\n _parsePAT (data, offset) {\n // skip the PSI header and parse the first PMT entry\n return (data[offset + 10] & 0x1F) << 8 | data[offset + 11];\n // logger.log('PMT PID:' + this._pmtId);\n }\n\n _trackUnknownPmt (type, logLevel, message) {\n // Only log unknown and unsupported stream types once per append or stream (by resetting this.pmtUnknownTypes)\n // For more information on elementary stream types see:\n // https://en.wikipedia.org/wiki/Program-specific_information#Elementary_stream_types\n const result = this.pmtUnknownTypes[type] || 0;\n if (result === 0) {\n this.pmtUnknownTypes[type] = 0;\n logLevel.call(logger, message);\n }\n this.pmtUnknownTypes[type]++;\n return result;\n }\n\n _parsePMT (data, offset, mpegSupported, isSampleAes) {\n let sectionLength, tableEnd, programInfoLength, pid, result = { audio: -1, avc: -1, id3: -1, isAAC: true };\n sectionLength = (data[offset + 1] & 0x0f) << 8 | data[offset + 2];\n tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n programInfoLength = (data[offset + 10] & 0x0f) << 8 | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n pid = (data[offset + 1] & 0x1F) << 8 | data[offset + 2];\n switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n this._trackUnknownPmt(data[offset], logger.warn, 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream');\n break;\n }\n /* falls through */\n\n // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n case 0x0f:\n // logger.log('AAC PID:' + pid);\n if (result.audio === -1) {\n result.audio = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n this._trackUnknownPmt(data[offset], logger.warn, 'H.264 with AES-128-CBC slice encryption found in unencrypted stream');\n break;\n }\n /* falls through */\n\n // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n case 0x1b:\n // logger.log('AVC PID:' + pid);\n if (result.avc === -1) {\n result.avc = pid;\n }\n\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (!mpegSupported) {\n this._trackUnknownPmt(data[offset], logger.warn, 'MPEG audio found, not supported in this browser');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.isAAC = false;\n }\n break;\n\n case 0x24:\n this._trackUnknownPmt(data[offset], logger.warn, 'Unsupported HEVC stream type found');\n break;\n\n default:\n this._trackUnknownPmt(data[offset], logger.log, 'Unknown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += ((data[offset + 3] & 0x0F) << 8 | data[offset + 4]) + 5;\n }\n return result;\n }\n\n _parsePES (stream) {\n let i = 0, frag, pesFlags, pesPrefix, pesLen, pesHdrLen, pesData, pesPts, pesDts, payloadStartOffset, data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while (data[0].length < 19 && data.length > 1) {\n let newData = new Uint8Array(data[0].length + data[1].length);\n newData.set(data[0]);\n newData.set(data[1], data[0].length);\n data[0] = newData;\n data.splice(1, 1);\n }\n // retrieve PTS/DTS from first fragment\n frag = data[0];\n pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n\n pesFlags = frag[7];\n if (pesFlags & 0xC0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts = (frag[9] & 0x0E) * 536870912 +// 1 << 29\n (frag[10] & 0xFF) * 4194304 +// 1 << 22\n (frag[11] & 0xFE) * 16384 +// 1 << 14\n (frag[12] & 0xFF) * 128 +// 1 << 7\n (frag[13] & 0xFE) / 2;\n\n if (pesFlags & 0x40) {\n pesDts = (frag[14] & 0x0E) * 536870912 +// 1 << 29\n (frag[15] & 0xFF) * 4194304 +// 1 << 22\n (frag[16] & 0xFE) * 16384 +// 1 << 14\n (frag[17] & 0xFF) * 128 +// 1 << 7\n (frag[18] & 0xFE) / 2;\n\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(`${Math.round((pesPts - pesDts) / 90000)}s delta between PTS and DTS, align them`);\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n payloadStartOffset = pesHdrLen + 9;\n\n if (stream.size <= payloadStartOffset) {\n return null;\n }\n stream.size -= payloadStartOffset;\n // reassemble PES packet\n pesData = new Uint8Array(stream.size);\n for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset -= len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len -= payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i += len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen + 3;\n }\n return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };\n } else {\n return null;\n }\n }\n\n pushAccesUnit (avcSample, avcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n const samples = avcTrack.samples;\n const nbSamples = samples.length;\n // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (isNaN(avcSample.pts)) {\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n avcSample.pts = lastSample.pts;\n avcSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n avcTrack.dropped++;\n return;\n }\n }\n // only push AVC sample if starting with a keyframe is not mandatory OR\n // if keyframe already found in this fragment OR\n // keyframe found in last fragment (track.sps) AND\n // samples already appended (we already found a keyframe in this fragment) OR fragment is contiguous\n if (!this.config.forceKeyFrameOnDiscontinuity ||\n avcSample.key === true ||\n (avcTrack.sps && (nbSamples || this.contiguous))) {\n avcSample.id = nbSamples;\n samples.push(avcSample);\n } else {\n // dropped samples, track it\n avcTrack.dropped++;\n }\n }\n if (avcSample.debug.length) {\n logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n }\n\n _parseAVCPES (pes, last) {\n // logger.log('parse new PES');\n let track = this._avcTrack,\n units = this._parseAVCNALu(pes.data),\n debug = false,\n expGolombDecoder,\n avcSample = this.avcSample,\n push,\n spsfound = false,\n i,\n pushAccesUnit = this.pushAccesUnit.bind(this),\n createAVCSample = function (key, pts, dts, debug) {\n return { key: key, pts: pts, dts: dts, units: [], debug: debug };\n };\n // free pes.data to save up some memory\n pes.data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (avcSample && units.length && !track.audFound) {\n pushAccesUnit(avcSample, track);\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');\n }\n\n units.forEach(unit => {\n switch (unit.type) {\n // NDR\n case 1:\n push = true;\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');\n }\n\n if (debug) {\n avcSample.debug += 'NDR ';\n }\n\n avcSample.frame = true;\n let data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n let sliceType = new ExpGolomb(data).readSliceType();\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n // if (sliceType === 2 || sliceType === 7) {\n if (sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9) {\n avcSample.key = true;\n }\n }\n break;\n // IDR\n case 5:\n push = true;\n // handle PES not starting with AUD\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(true, pes.pts, pes.dts, '');\n }\n\n if (debug) {\n avcSample.debug += 'IDR ';\n }\n\n avcSample.key = true;\n avcSample.frame = true;\n break;\n // SEI\n case 6:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'SEI ';\n }\n\n expGolombDecoder = new ExpGolomb(this.discardEPB(unit.data));\n\n // skip frameType\n expGolombDecoder.readUByte();\n\n var payloadType = 0;\n var payloadSize = 0;\n var endOfCaptions = false;\n var b = 0;\n\n while (!endOfCaptions && expGolombDecoder.bytesAvailable > 1) {\n payloadType = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadType += b;\n } while (b === 0xFF);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n b = expGolombDecoder.readUByte();\n payloadSize += b;\n } while (b === 0xFF);\n\n // TODO: there can be more than one payload in an SEI packet...\n // TODO: need to read type and size in a while loop to get them all\n if (payloadType === 4 && expGolombDecoder.bytesAvailable !== 0) {\n endOfCaptions = true;\n\n let countryCode = expGolombDecoder.readUByte();\n\n if (countryCode === 181) {\n let providerCode = expGolombDecoder.readUShort();\n\n if (providerCode === 49) {\n let userStructure = expGolombDecoder.readUInt();\n\n if (userStructure === 0x47413934) {\n let userDataType = expGolombDecoder.readUByte();\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n let firstByte = expGolombDecoder.readUByte();\n let secondByte = expGolombDecoder.readUByte();\n\n let totalCCs = 31 & firstByte;\n let byteArray = [firstByte, secondByte];\n\n for (i = 0; i < totalCCs; i++) {\n // 3 bytes per CC\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n byteArray.push(expGolombDecoder.readUByte());\n }\n\n this._insertSampleInOrder(this._txtTrack.samples, { type: 3, pts: pes.pts, bytes: byteArray });\n }\n }\n }\n }\n } else if (payloadType === 5 && expGolombDecoder.bytesAvailable !== 0) {\n endOfCaptions = true;\n\n if (payloadSize > 16) {\n const uuidStrArray = [];\n for (i = 0; i < 16; i++) {\n uuidStrArray.push(expGolombDecoder.readUByte().toString(16));\n\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n uuidStrArray.push('-');\n }\n }\n const length = payloadSize - 16;\n const userDataPayloadBytes = new Uint8Array(length);\n for (i = 0; i < length; i++) {\n userDataPayloadBytes[i] = expGolombDecoder.readUByte();\n }\n\n this._insertSampleInOrder(this._txtTrack.samples, {\n pts: pes.pts,\n payloadType: payloadType,\n uuid: uuidStrArray.join(''),\n userDataBytes: userDataPayloadBytes,\n userData: utf8ArrayToStr(userDataPayloadBytes.buffer)\n });\n }\n } else if (payloadSize < expGolombDecoder.bytesAvailable) {\n for (i = 0; i < payloadSize; i++) {\n expGolombDecoder.readUByte();\n }\n }\n }\n break;\n // SPS\n case 7:\n push = true;\n spsfound = true;\n if (debug && avcSample) {\n avcSample.debug += 'SPS ';\n }\n\n if (!track.sps) {\n expGolombDecoder = new ExpGolomb(unit.data);\n let config = expGolombDecoder.readSPS();\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [unit.data];\n track.duration = this._duration;\n let codecarray = unit.data.subarray(1, 4);\n let codecstring = 'avc1.';\n for (i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n codecstring += h;\n }\n track.codec = codecstring;\n }\n break;\n // PPS\n case 8:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'PPS ';\n }\n\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccesUnit(avcSample, track);\n }\n\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, debug ? 'AUD ' : '');\n break;\n // Filler Data\n case 12:\n push = false;\n break;\n default:\n push = false;\n if (avcSample) {\n avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n\n break;\n }\n if (avcSample && push) {\n let units = avcSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n pushAccesUnit(avcSample, track);\n this.avcSample = null;\n }\n }\n\n _insertSampleInOrder (arr, data) {\n let len = arr.length;\n if (len > 0) {\n if (data.pts >= arr[len - 1].pts) {\n arr.push(data);\n } else {\n for (let pos = len - 1; pos >= 0; pos--) {\n if (data.pts < arr[pos].pts) {\n arr.splice(pos, 0, data);\n break;\n }\n }\n }\n } else {\n arr.push(data);\n }\n }\n\n _getLastNalUnit () {\n let avcSample = this.avcSample, lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n let track = this._avcTrack, samples = track.samples;\n avcSample = samples[samples.length - 1];\n }\n if (avcSample) {\n let units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n _parseAVCNALu (array) {\n let i = 0, len = array.byteLength, value, overflow, track = this._avcTrack, state = track.naluState || 0, lastState = state;\n let units = [], unit, unitType, lastUnitStart = -1, lastUnitType;\n // logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if (!value) {\n state = 3;\n } else if (value === 1) {\n if (lastUnitStart >= 0) {\n unit = { data: array.subarray(lastUnitStart, i - state - 1), type: lastUnitType };\n // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n if (lastState && (i <= 4 - lastState)) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(0, lastUnit.data.byteLength - lastState);\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n overflow = i - state - 1;\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n let tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n tmp.set(lastUnit.data, 0);\n tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >= 0 && state >= 0) {\n unit = { data: array.subarray(lastUnitStart, len), type: lastUnitType, state: state };\n units.push(unit);\n // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n let lastUnit = this._getLastNalUnit();\n if (lastUnit) {\n let tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n tmp.set(lastUnit.data, 0);\n tmp.set(array, lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n track.naluState = state;\n return units;\n }\n\n /**\n * remove Emulation Prevention bytes from a RBSP\n */\n discardEPB (data) {\n let length = data.byteLength,\n EPBPositions = [],\n i = 1,\n newLength, newData;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 &&\n data[i + 1] === 0 &&\n data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n newLength = length - EPBPositions.length;\n newData = new Uint8Array(newLength);\n let sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n }\n\n _parseAACPES (pes) {\n let track = this._audioTrack,\n data = pes.data,\n pts = pes.pts,\n startOffset = 0,\n aacOverFlow = this.aacOverFlow,\n aacLastPTS = this.aacLastPTS,\n frameDuration, frameIndex, offset, stamp, len;\n if (aacOverFlow) {\n let tmp = new Uint8Array(aacOverFlow.byteLength + data.byteLength);\n tmp.set(aacOverFlow, 0);\n tmp.set(data, aacOverFlow.byteLength);\n // logger.log(`AAC: append overflowing ${aacOverFlow.byteLength} bytes to beginning of new PES`);\n data = tmp;\n }\n // look for ADTS header (0xFFFx)\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset) {\n let reason, fatal;\n if (offset < len - 1) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n fatal = false;\n } else {\n reason = 'no ADTS header found in AAC PES';\n fatal = true;\n }\n logger.warn(`parsing error:${reason}`);\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: fatal, reason: reason });\n if (fatal) {\n return;\n }\n }\n\n ADTS.initTrackConfig(track, this.observer, data, offset, this.audioCodec);\n frameIndex = 0;\n frameDuration = ADTS.getFrameDuration(track.samplerate);\n\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n if (aacOverFlow && aacLastPTS) {\n let newPTS = aacLastPTS + frameDuration;\n if (Math.abs(newPTS - pts) > 1) {\n logger.log(`AAC: align PTS for overlapping frames by ${Math.round((newPTS - pts) / 90)}`);\n pts = newPTS;\n }\n }\n\n // scan for aac samples\n while (offset < len) {\n if (ADTS.isHeader(data, offset)) {\n if ((offset + 5) < len) {\n const frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n continue;\n }\n }\n // We are at an ADTS header, but do not have enough data for a frame\n // Remaining data will be added to aacOverFlow\n break;\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n if (offset < len) {\n aacOverFlow = data.subarray(offset, len);\n // logger.log(`AAC: overflow detected:${len-offset}`);\n } else {\n aacOverFlow = null;\n }\n\n this.aacOverFlow = aacOverFlow;\n this.aacLastPTS = stamp;\n }\n\n _parseMPEGPES (pes) {\n let data = pes.data;\n let length = data.length;\n let frameIndex = 0;\n let offset = 0;\n let pts = pes.pts;\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let frame = MpegAudio.appendFrame(this._audioTrack, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n }\n\n _parseID3PES (pes) {\n this._id3Track.samples.push(pes);\n }\n}\n\nexport default TSDemuxer;\n","/**\n * MP3 demuxer\n */\nimport ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport MpegAudio from './mpegaudio';\n\nclass MP3Demuxer {\n constructor (observer, remuxer, config) {\n this.observer = observer;\n this.config = config;\n this.remuxer = remuxer;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n this._audioTrack = { container: 'audio/mpeg', type: 'audio', id: -1, sequenceNumber: 0, isAAC: false, samples: [], len: 0, manifestCodec: audioCodec, duration: duration, inputTimeScale: 90000 };\n }\n\n resetTimeStamp () {\n }\n\n static probe (data) {\n // check if data contains ID3 timestamp and MPEG sync word\n let offset, length;\n let id3Data = ID3.getID3Data(data, 0);\n if (id3Data && ID3.getTimeStamp(id3Data) !== undefined) {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n for (offset = id3Data.length, length = Math.min(data.length - 1, offset + 100); offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n }\n return false;\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let id3Data = ID3.getID3Data(data, 0) || [];\n let timestamp = ID3.getTimeStamp(id3Data);\n let pts = timestamp !== undefined ? 90 * timestamp : timeOffset * 90000;\n let offset = id3Data.length;\n let length = data.length;\n let frameIndex = 0, stamp = 0;\n let track = this._audioTrack;\n\n let id3Samples = [{ pts: pts, dts: pts, data: id3Data }];\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n let frame = MpegAudio.appendFrame(track, data, offset, pts, frameIndex);\n if (frame) {\n offset += frame.length;\n stamp = frame.sample.pts;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else if (ID3.isHeader(data, offset)) {\n id3Data = ID3.getID3Data(data, offset);\n id3Samples.push({ pts: stamp, dts: stamp, data: id3Data });\n offset += id3Data.length;\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n\n this.remuxer.remux(track,\n { samples: [] },\n { samples: id3Samples, inputTimeScale: 90000 },\n { samples: [] },\n timeOffset,\n contiguous,\n accurateTimeOffset);\n }\n\n destroy () {\n }\n}\n\nexport default MP3Demuxer;\n","/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame (codec, channelCount) {\n switch (codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80]);\n } else if (channelCount === 3) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x8e]);\n } else if (channelCount === 4) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38]);\n } else if (channelCount === 5) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64, 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38]);\n } else if (channelCount === 6) {\n 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]);\n }\n\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // 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\n 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]);\n } else if (channelCount === 2) {\n // 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\n 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]);\n } else if (channelCount === 3) {\n // 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\n 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]);\n }\n break;\n }\n return null;\n }\n}\n\nexport default AAC;\n","/**\n * Generate MP4 Box\n*/\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4 {\n static init () {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: []\n };\n\n let i;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3)\n ];\n }\n }\n\n let videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x56, 0x69, 0x64, 0x65,\n 0x6f, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'\n ]);\n\n let audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x53, 0x6f, 0x75, 0x6e,\n 0x64, 0x48, 0x61, 0x6e,\n 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n 'video': videoHdlr,\n 'audio': audioHdlr\n };\n\n let dref = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01, // entry_count\n 0x00, 0x00, 0x00, 0x0c, // entry_size\n 0x75, 0x72, 0x6c, 0x20, // 'url' type\n 0x00, // version 0\n 0x00, 0x00, 0x01 // entry_flags\n ]);\n\n let stco = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00 // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, // sample_size\n 0x00, 0x00, 0x00, 0x00 // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x01, // flags\n 0x00, 0x00, // graphicsmode\n 0x00, 0x00,\n 0x00, 0x00,\n 0x00, 0x00 // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, // balance\n 0x00, 0x00 // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x01]);// entry_count\n\n let majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n let avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n let minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(MP4.types.ftyp, majorBrand, minorVersion, majorBrand, avc1Brand);\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box (type) {\n let\n payload = Array.prototype.slice.call(arguments, 1),\n size = 8,\n i = payload.length,\n len = i,\n result;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n\n result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr (type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat (data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd (timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.mdhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x55, 0xc4, // 'und' language (undetermined)\n 0x00, 0x00\n ]));\n }\n\n static mdia (track) {\n return MP4.box(MP4.types.mdia, MP4.mdhd(track.timescale, track.duration), MP4.hdlr(track.type), MP4.minf(track));\n }\n\n static mfhd (sequenceNumber) {\n return MP4.box(MP4.types.mfhd, new Uint8Array([\n 0x00,\n 0x00, 0x00, 0x00, // flags\n (sequenceNumber >> 24),\n (sequenceNumber >> 16) & 0xFF,\n (sequenceNumber >> 8) & 0xFF,\n sequenceNumber & 0xFF // sequence_number\n ]));\n }\n\n static minf (track) {\n if (track.type === 'audio') {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.smhd, MP4.SMHD), MP4.DINF, MP4.stbl(track));\n } else {\n return MP4.box(MP4.types.minf, MP4.box(MP4.types.vmhd, MP4.VMHD), MP4.DINF, MP4.stbl(track));\n }\n }\n\n static moof (sn, baseMediaDecodeTime, track) {\n return MP4.box(MP4.types.moof, MP4.mfhd(sn), MP4.traf(track, baseMediaDecodeTime));\n }\n /**\n * @param tracks... (optional) {array} the tracks associated with this movie\n */\n static moov (tracks) {\n let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)].concat(boxes).concat(MP4.mvex(tracks)));\n }\n\n static mvex (tracks) {\n let\n i = tracks.length,\n boxes = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex].concat(boxes));\n }\n\n static mvhd (timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n let\n bytes = new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (timescale >> 24) & 0xFF,\n (timescale >> 16) & 0xFF,\n (timescale >> 8) & 0xFF,\n timescale & 0xFF, // timescale\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x00, 0x01, 0x00, 0x00, // 1.0 rate\n 0x01, 0x00, // 1.0 volume\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n 0xff, 0xff, 0xff, 0xff // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp (track) {\n let\n samples = track.samples || [],\n bytes = new Uint8Array(4 + samples.length),\n flags,\n i;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] = (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n (flags.hasRedundancy);\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl (track) {\n 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));\n }\n\n static avc1 (track) {\n let sps = [], pps = [], i, data, len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xFF);\n sps.push((len & 0xFF));\n\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xFF);\n pps.push((len & 0xFF));\n\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n let avcc = MP4.box(MP4.types.avcC, new Uint8Array([\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xE0 | track.sps.length // 3bit reserved (111) + numOfSequenceParameterSets\n ].concat(sps).concat([\n track.pps.length // numOfPictureParameterSets\n ]).concat(pps))), // \"PPS\"\n width = track.width,\n height = track.height,\n hSpacing = track.pixelRatio[0],\n vSpacing = track.pixelRatio[1];\n\n return MP4.box(MP4.types.avc1, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, // pre_defined\n 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // pre_defined\n (width >> 8) & 0xFF,\n width & 0xff, // width\n (height >> 8) & 0xFF,\n height & 0xff, // height\n 0x00, 0x48, 0x00, 0x00, // horizresolution\n 0x00, 0x48, 0x00, 0x00, // vertresolution\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // frame_count\n 0x12,\n 0x64, 0x61, 0x69, 0x6C, // dailymotion/hls.js\n 0x79, 0x6D, 0x6F, 0x74,\n 0x69, 0x6F, 0x6E, 0x2F,\n 0x68, 0x6C, 0x73, 0x2E,\n 0x6A, 0x73, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, // compressorname\n 0x00, 0x18, // depth = 24\n 0x11, 0x11]), // pre_defined = -1\n avcc,\n MP4.box(MP4.types.btrt, new Uint8Array([\n 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB\n 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate\n 0x00, 0x2d, 0xc6, 0xc0])), // avgBitrate\n MP4.box(MP4.types.pasp, new Uint8Array([\n (hSpacing >> 24), // hSpacing\n (hSpacing >> 16) & 0xFF,\n (hSpacing >> 8) & 0xFF,\n hSpacing & 0xFF,\n (vSpacing >> 24), // vSpacing\n (vSpacing >> 16) & 0xFF,\n (vSpacing >> 8) & 0xFF,\n vSpacing & 0xFF]))\n );\n }\n\n static esds (track) {\n let configlen = track.config.length;\n return new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17 + configlen, // length\n 0x00, 0x01, // es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f + configlen, // length\n 0x40, // codec : mpeg4_audio\n 0x15, // stream_type\n 0x00, 0x00, 0x00, // buffer_size\n 0x00, 0x00, 0x00, 0x00, // maxBitrate\n 0x00, 0x00, 0x00, 0x00, // avgBitrate\n\n 0x05 // descriptor_type\n ].concat([configlen]).concat(track.config).concat([0x06, 0x01, 0x02])); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static mp4a (track) {\n let samplerate = track.samplerate;\n return MP4.box(MP4.types.mp4a, new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]),\n MP4.box(MP4.types.esds, MP4.esds(track)));\n }\n\n static mp3 (track) {\n let samplerate = track.samplerate;\n return MP4.box(MP4.types['.mp3'], new Uint8Array([\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, 0x00, // reserved\n 0x00, 0x01, // data_reference_index\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, track.channelCount, // channelcount\n 0x00, 0x10, // sampleSize:16bits\n 0x00, 0x00, 0x00, 0x00, // reserved2\n (samplerate >> 8) & 0xFF,\n samplerate & 0xff, //\n 0x00, 0x00]));\n }\n\n static stsd (track) {\n if (track.type === 'audio') {\n if (!track.isAAC && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd (track) {\n let id = track.id,\n duration = track.duration * track.timescale,\n width = track.width,\n height = track.height,\n upperWordDuration = Math.floor(duration / (UINT32_MAX + 1)),\n lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(MP4.types.tkhd, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x07, // flags\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, // creation_time\n 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, // modification_time\n (id >> 24) & 0xFF,\n (id >> 16) & 0xFF,\n (id >> 8) & 0xFF,\n id & 0xFF, // track_ID\n 0x00, 0x00, 0x00, 0x00, // reserved\n (upperWordDuration >> 24),\n (upperWordDuration >> 16) & 0xFF,\n (upperWordDuration >> 8) & 0xFF,\n upperWordDuration & 0xFF,\n (lowerWordDuration >> 24),\n (lowerWordDuration >> 16) & 0xFF,\n (lowerWordDuration >> 8) & 0xFF,\n lowerWordDuration & 0xFF,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00, // reserved\n 0x00, 0x00, // layer\n 0x00, 0x00, // alternate_group\n 0x00, 0x00, // non-audio track volume\n 0x00, 0x00, // reserved\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x01, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x00, 0x00, 0x00, 0x00,\n 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix\n (width >> 8) & 0xFF,\n width & 0xFF,\n 0x00, 0x00, // width\n (height >> 8) & 0xFF,\n height & 0xFF,\n 0x00, 0x00 // height\n ]));\n }\n\n static traf (track, baseMediaDecodeTime) {\n let sampleDependencyTable = MP4.sdtp(track),\n id = track.id,\n upperWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1)),\n lowerWordBaseMediaDecodeTime = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n return MP4.box(MP4.types.traf,\n MP4.box(MP4.types.tfhd, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF) // track_ID\n ])),\n MP4.box(MP4.types.tfdt, new Uint8Array([\n 0x01, // version 1\n 0x00, 0x00, 0x00, // flags\n (upperWordBaseMediaDecodeTime >> 24),\n (upperWordBaseMediaDecodeTime >> 16) & 0XFF,\n (upperWordBaseMediaDecodeTime >> 8) & 0XFF,\n (upperWordBaseMediaDecodeTime & 0xFF),\n (lowerWordBaseMediaDecodeTime >> 24),\n (lowerWordBaseMediaDecodeTime >> 16) & 0XFF,\n (lowerWordBaseMediaDecodeTime >> 8) & 0XFF,\n (lowerWordBaseMediaDecodeTime & 0xFF)\n ])),\n MP4.trun(track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8), // mdat header\n sampleDependencyTable);\n }\n\n /**\n * Generate a track box.\n * @param track {object} a track definition\n * @return {Uint8Array} the track box\n */\n static trak (track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex (track) {\n let id = track.id;\n return MP4.box(MP4.types.trex, new Uint8Array([\n 0x00, // version 0\n 0x00, 0x00, 0x00, // flags\n (id >> 24),\n (id >> 16) & 0XFF,\n (id >> 8) & 0XFF,\n (id & 0xFF), // track_ID\n 0x00, 0x00, 0x00, 0x01, // default_sample_description_index\n 0x00, 0x00, 0x00, 0x00, // default_sample_duration\n 0x00, 0x00, 0x00, 0x00, // default_sample_size\n 0x00, 0x01, 0x00, 0x01 // default_sample_flags\n ]));\n }\n\n static trun (track, offset) {\n let samples = track.samples || [],\n len = samples.length,\n arraylen = 12 + (16 * len),\n array = new Uint8Array(arraylen),\n i, sample, duration, size, flags, cts;\n offset += 8 + arraylen;\n array.set([\n 0x00, // version 0\n 0x00, 0x0f, 0x01, // flags\n (len >>> 24) & 0xFF,\n (len >>> 16) & 0xFF,\n (len >>> 8) & 0xFF,\n len & 0xFF, // sample_count\n (offset >>> 24) & 0xFF,\n (offset >>> 16) & 0xFF,\n (offset >>> 8) & 0xFF,\n offset & 0xFF // data_offset\n ], 0);\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set([\n (duration >>> 24) & 0xFF,\n (duration >>> 16) & 0xFF,\n (duration >>> 8) & 0xFF,\n duration & 0xFF, // sample_duration\n (size >>> 24) & 0xFF,\n (size >>> 16) & 0xFF,\n (size >>> 8) & 0xFF,\n size & 0xFF, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & 0xF0 << 8,\n flags.degradPrio & 0x0F, // sample_flags\n (cts >>> 24) & 0xFF,\n (cts >>> 16) & 0xFF,\n (cts >>> 8) & 0xFF,\n cts & 0xFF // sample_composition_time_offset\n ], 12 + 16 * i);\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment (tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n let movie = MP4.moov(tracks), result;\n result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n result.set(MP4.FTYP);\n result.set(movie, MP4.FTYP.byteLength);\n return result;\n }\n}\n\nexport default MP4;\n","const MPEG_TS_CLOCK_FREQ_HZ = 90000;\n\nexport function toTimescaleFromScale (value, destScale: number, srcScale: number = 1, round: boolean = false): number {\n return toTimescaleFromBase(value, destScale, 1 / srcScale);\n}\n\nexport function toTimescaleFromBase (value, destScale: number, srcBase: number = 1, round: boolean = false): number {\n const result = value * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n return round ? Math.round(result) : result;\n}\n\nexport function toMsFromMpegTsClock (value: number, round: boolean = false): number {\n return toTimescaleFromBase(value, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n}\n\nexport function toMpegTsClockFromTimescale (value: number, srcScale: number = 1): number {\n return toTimescaleFromBase(value, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\n}\n","/**\n * fMP4 remuxer\n*/\n\nimport AAC from './aac-helper';\nimport MP4 from './mp4-generator';\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { toMsFromMpegTsClock, toMpegTsClockFromTimescale } from '../utils/timescale-conversion';\n\nimport { logger } from '../utils/logger';\n\nconst MAX_SILENT_FRAME_DURATION_90KHZ = toMpegTsClockFromTimescale(10);\nconst PTS_DTS_SHIFT_TOLERANCE_90KHZ = toMpegTsClockFromTimescale(0.2);\n\nlet chromeVersion = null;\n\nclass MP4Remuxer {\n constructor (observer, config, typeSupported, vendor) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.ISGenerated = false;\n if (chromeVersion === null) {\n const result = navigator.userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n }\n\n destroy () {\n }\n\n resetTimeStamp (defaultTimeStamp) {\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetInitSegment () {\n this.ISGenerated = false;\n }\n\n getVideoStartPts (videoSamples) {\n let rolloverDetected = false;\n const startPTS = videoSamples.reduce((minPTS, sample) => {\n const delta = sample.pts - minPTS;\n if (delta < -4294967296) { // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n rolloverDetected = true;\n return PTSNormalize(minPTS, sample.pts);\n } else if (delta > 0) {\n return minPTS;\n } else {\n return sample.pts;\n }\n }, videoSamples[0].pts);\n if (rolloverDetected) {\n logger.debug('PTS rollover detected');\n }\n return startPTS;\n }\n\n remux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset) {\n // generate Init Segment if needed\n if (!this.ISGenerated) {\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n\n if (this.ISGenerated) {\n const nbAudioSamples = audioTrack.samples.length;\n const nbVideoSamples = videoTrack.samples.length;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n if (nbAudioSamples && nbVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n const tsDelta = PTSNormalize(audioTrack.samples[0].pts, startPTS) - startPTS;\n const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoTimestampDelta);\n videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);\n }\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is\n // calculated in remuxAudio.\n // logger.log('nb AAC samples:' + audioTrack.samples.length);\n if (nbAudioSamples) {\n // if initSegment was generated without video samples, regenerate it again\n if (!audioTrack.timescale) {\n logger.warn('regenerate InitSegment as audio detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n let audioData = this.remuxAudio(audioTrack, audioTimeOffset, contiguous, accurateTimeOffset);\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let audioTrackLength;\n if (audioData) {\n audioTrackLength = audioData.endPTS - audioData.startPTS;\n }\n\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.timescale) {\n logger.warn('regenerate InitSegment as video detected');\n this.generateIS(audioTrack, videoTrack, timeOffset);\n }\n this.remuxVideo(videoTrack, videoTimeOffset, contiguous, audioTrackLength);\n }\n } else {\n // logger.log('nb AVC samples:' + videoTrack.samples.length);\n if (nbVideoSamples) {\n let videoData = this.remuxVideo(videoTrack, videoTimeOffset, contiguous, 0, accurateTimeOffset);\n if (videoData && audioTrack.codec) {\n this.remuxEmptyAudio(audioTrack, audioTimeOffset, contiguous, videoData);\n }\n }\n }\n }\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (id3Track.samples.length) {\n this.remuxID3(id3Track, timeOffset);\n }\n\n // logger.log('nb ID3 samples:' + audioTrack.samples.length);\n if (textTrack.samples.length) {\n this.remuxText(textTrack, timeOffset);\n }\n\n // notify end of parsing\n this.observer.trigger(Event.FRAG_PARSED);\n }\n\n generateIS (audioTrack, videoTrack, timeOffset) {\n let observer = this.observer,\n audioSamples = audioTrack.samples,\n videoSamples = videoTrack.samples,\n typeSupported = this.typeSupported,\n container = 'audio/mp4',\n tracks = {},\n data = { tracks },\n computePTSDTS = (this._initPTS === undefined),\n initPTS, initDTS;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n logger.log(`audio sampling rate : ${audioTrack.samplerate}`);\n if (!audioTrack.isAAC) {\n if (typeSupported.mpeg) { // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) { // Firefox\n audioTrack.codec = 'mp3';\n }\n }\n tracks.audio = {\n container: container,\n codec: audioTrack.codec,\n initSegment: !audioTrack.isAAC && typeSupported.mpeg ? new Uint8Array() : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount\n }\n };\n if (computePTSDTS) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS = audioSamples[0].pts - Math.round(audioTrack.inputTimeScale * timeOffset);\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n const inputTimeScale = videoTrack.inputTimeScale;\n videoTrack.timescale = inputTimeScale;\n tracks.video = {\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: MP4.initSegment([videoTrack]),\n metadata: {\n width: videoTrack.width,\n height: videoTrack.height\n }\n };\n if (computePTSDTS) {\n const startPTS = this.getVideoStartPts(videoSamples);\n const startOffset = Math.round(inputTimeScale * timeOffset);\n initDTS = Math.min(initDTS, PTSNormalize(videoSamples[0].dts, startPTS) - startOffset);\n initPTS = Math.min(initPTS, startPTS - startOffset);\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS });\n }\n } else if (computePTSDTS && tracks.audio) {\n // initPTS found for audio-only stream with main and alt audio\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS });\n }\n\n if (Object.keys(tracks).length) {\n observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT, data);\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = initPTS;\n this._initDTS = initDTS;\n }\n } else {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: false, reason: 'no audio/video samples found' });\n }\n }\n\n remuxVideo (track, timeOffset, contiguous, audioTrackLength) {\n const timeScale = track.timescale;\n const inputSamples = track.samples;\n const outputSamples = [];\n const nbSamples = inputSamples.length;\n const initPTS = this._initPTS;\n\n let offset = 8;\n let mp4SampleDuration;\n let mdat;\n let moof;\n let firstDTS;\n let lastDTS;\n let minPTS = Number.POSITIVE_INFINITY;\n let maxPTS = Number.NEGATIVE_INFINITY;\n let ptsDtsShift = 0;\n let sortSamples = false;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n let nextAvcDts = this.nextAvcDts;\n\n if (nbSamples === 0) {\n return;\n }\n\n if (!contiguous) {\n const pts = timeOffset * timeScale;\n const cts = inputSamples[0].pts - PTSNormalize(inputSamples[0].dts, inputSamples[0].pts);\n // if not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n for (let i = 0; i < nbSamples; i++) {\n const sample = inputSamples[i];\n sample.pts = PTSNormalize(sample.pts - initPTS, nextAvcDts);\n sample.dts = PTSNormalize(sample.dts - initPTS, nextAvcDts);\n if (sample.dts > sample.pts) {\n ptsDtsShift = Math.max(Math.min(ptsDtsShift, sample.pts - sample.dts), -1 * PTS_DTS_SHIFT_TOLERANCE_90KHZ);\n }\n if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n sortSamples = true;\n }\n }\n\n // sort video samples by DTS then PTS then demux id order\n if (sortSamples) {\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || (deltapts || (a.id - b.id));\n });\n }\n\n // Get first/last DTS\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n // on Safari let's signal the same sample duration for all samples\n // sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n const averageSampleDuration = Math.round((lastDTS - firstDTS) / (nbSamples - 1));\n\n // handle broken streams with PTS < DTS, tolerance up 0.2 seconds\n if (ptsDtsShift < 0) {\n if (ptsDtsShift < averageSampleDuration * -2) {\n // Fix for \"CNN special report, with CC\" in test-streams (including Safari browser)\n // With large PTS < DTS errors such as this, we want to correct CTS while maintaining increasing DTS values\n logger.warn(`PTS < DTS detected in video samples, offsetting DTS from PTS by ${toMsFromMpegTsClock(-averageSampleDuration, true)} ms`);\n let lastDts = ptsDtsShift;\n for (let i = 0; i < nbSamples; i++) {\n inputSamples[i].dts = lastDts = Math.max(lastDts, inputSamples[i].pts - averageSampleDuration);\n inputSamples[i].pts = Math.max(lastDts, inputSamples[i].pts);\n }\n } else {\n // Fix for \"Custom IV with bad PTS DTS\" in test-streams\n // With smaller PTS < DTS errors we can simply move all DTS back. This increases CTS without causing buffer gaps or decode errors in Safari\n logger.warn(`PTS < DTS detected in video samples, shifting DTS by ${toMsFromMpegTsClock(ptsDtsShift, true)} ms to overcome this issue`);\n for (let i = 0; i < nbSamples; i++) {\n inputSamples[i].dts = inputSamples[i].dts + ptsDtsShift;\n }\n }\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[nbSamples - 1].dts;\n }\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n const delta = firstDTS - nextAvcDts;\n const foundHole = delta > averageSampleDuration;\n const foundOverlap = delta < -1;\n if (foundHole || foundOverlap) {\n if (foundHole) {\n logger.warn(`AVC: ${toMsFromMpegTsClock(delta, true)} ms (${delta}dts) hole between fragments detected, filling it`);\n } else {\n logger.warn(`AVC: ${toMsFromMpegTsClock(-delta, true)} ms (${delta}dts) overlapping between fragments detected`);\n }\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n logger.log(`Video: First PTS/DTS adjusted: ${toMsFromMpegTsClock(firstPTS, true)}/${toMsFromMpegTsClock(firstDTS, true)}, delta: ${toMsFromMpegTsClock(delta, true)} ms`);\n }\n }\n\n if (chromeVersion && chromeVersion < 75) {\n firstDTS = Math.max(0, firstDTS);\n }\n let nbNalu = 0;\n let naluLen = 0;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n const sample = inputSamples[i];\n const units = sample.units;\n const nbUnits = units.length;\n let sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // normalize PTS/DTS\n // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts, firstDTS);\n // ensure that computed value is greater or equal than sample DTS\n sample.pts = Math.max(sample.pts, sample.dts, 0);\n minPTS = Math.min(sample.pts, minPTS);\n maxPTS = Math.max(sample.pts, maxPTS);\n }\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n let mdatSize = naluLen + (4 * nbNalu) + 8;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating video mdat ${mdatSize}` });\n return;\n }\n let view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n for (let i = 0; i < nbSamples; i++) {\n const avcSample = inputSamples[i];\n const avcSampleUnits = avcSample.units;\n let mp4SampleLength = 0;\n let compositionTimeOffset;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {\n const unit = avcSampleUnits[j];\n const unitData = unit.data;\n const unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts;\n } else {\n const config = this.config;\n const lastFrameDuration = avcSample.dts - inputSamples[i > 0 ? i - 1 : i].dts;\n if (config.stretchShortVideoTrack) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n const maxBufferHole = config.maxBufferHole;\n const gapTolerance = Math.floor(maxBufferHole * timeScale);\n const deltaToFrameEnd = (audioTrackLength ? minPTS + audioTrackLength * timeScale : this.nextAudioPts) - avcSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n }\n\n logger.log(`It is approximately ${toMsFromMpegTsClock(deltaToFrameEnd, false)} ms to the next segment; using duration ${toMsFromMpegTsClock(mp4SampleDuration, false)} ms for the last video frame.`);\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n\n // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${avcSample.pts}/${avcSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(avcSample.pts/4294967296).toFixed(3)}');\n outputSamples.push({\n size: mp4SampleLength,\n // constant duration\n duration: mp4SampleDuration,\n cts: compositionTimeOffset,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: avcSample.key ? 2 : 1,\n isNonSync: avcSample.key ? 0 : 1\n }\n });\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n this.nextAvcDts = lastDTS + mp4SampleDuration;\n const dropped = track.dropped;\n track.nbNalu = 0;\n track.dropped = 0;\n if (outputSamples.length && navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {\n const flags = outputSamples[0].flags;\n // chrome workaround, mark first sample as being a Random Access Point to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n track.samples = outputSamples;\n moof = MP4.moof(track.sequenceNumber++, firstDTS, track);\n track.samples = [];\n\n const data = {\n data1: moof,\n data2: mdat,\n startPTS: minPTS / timeScale,\n endPTS: (maxPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: this.nextAvcDts / timeScale,\n type: 'video',\n hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: dropped\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, data);\n return data;\n }\n\n remuxAudio (track, timeOffset, contiguous, accurateTimeOffset) {\n const inputTimeScale = track.inputTimeScale;\n const mp4timeScale = track.timescale;\n const scaleFactor = inputTimeScale / mp4timeScale;\n const mp4SampleDuration = track.isAAC ? 1024 : 1152;\n const inputSampleDuration = mp4SampleDuration * scaleFactor;\n const initPTS = this._initPTS;\n const rawMPEG = !track.isAAC && this.typeSupported.mpeg;\n\n let mp4Sample;\n let fillFrame;\n let mdat;\n let moof;\n let firstPTS;\n let lastPTS;\n let offset = (rawMPEG ? 0 : 8);\n let inputSamples = track.samples;\n let outputSamples = [];\n let nextAudioPts = this.nextAudioPts;\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n contiguous |= (inputSamples.length && nextAudioPts &&\n ((accurateTimeOffset && Math.abs(timeOffset - nextAudioPts / inputTimeScale) < 0.1) ||\n Math.abs((inputSamples[0].pts - nextAudioPts - initPTS)) < 20 * inputSampleDuration)\n );\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = sample.dts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale);\n });\n\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter((sample) => sample.pts >= 0);\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (inputSamples.length === 0) {\n return;\n }\n\n if (!contiguous) {\n if (!accurateTimeOffset) {\n // if frag are mot contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n } else {\n // if timeOffset is accurate, let's use it as predicted next audio PTS\n nextAudioPts = Math.max(0, timeOffset * inputTimeScale);\n }\n }\n\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n if (track.isAAC) {\n const maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length;) {\n // First, let's see how far off this frame is from where we expect it to be\n const sample = inputSamples[i];\n let pts = sample.pts;\n let delta = pts - nextPts;\n\n // If we're overlapping by more than a duration, drop this sample\n if (delta <= -maxAudioFramesDrift * inputSampleDuration) {\n if (contiguous || i > 0) {\n logger.warn(`Dropping 1 audio frame @ ${toMsFromMpegTsClock(nextPts, true) / 1000}s due to ${toMsFromMpegTsClock(delta, true)} ms overlap.`);\n inputSamples.splice(i, 1);\n // Don't touch nextPtsNorm or i\n } else {\n // When changing qualities we can't trust that audio has been appended up to nextAudioPts\n // Warn about the overlap but do not drop samples as that can introduce buffer gaps\n logger.warn(`Audio frame @ ${toMsFromMpegTsClock(pts, true) / 1000}s overlaps nextAudioPts by ${toMsFromMpegTsClock(delta, true)} ms.`);\n nextPts = pts + inputSampleDuration;\n i++;\n }\n } // eslint-disable-line brace-style\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n else if (delta >= maxAudioFramesDrift * inputSampleDuration && delta < MAX_SILENT_FRAME_DURATION_90KHZ && nextPts) {\n let missing = Math.round(delta / inputSampleDuration);\n logger.warn(`Injecting ${missing} audio frames @ ${toMsFromMpegTsClock(nextPts, true) / 1000}s due to ${toMsFromMpegTsClock(delta, true)} ms gap.`);\n for (let j = 0; j < missing; j++) {\n let newStamp = Math.max(nextPts, 0);\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating last frame instead.');\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, { unit: fillFrame, pts: newStamp, dts: newStamp });\n nextPts += inputSampleDuration;\n i++;\n }\n\n // Adjust sample to next expected pts\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n } else {\n // Otherwise, just adjust pts\n if (Math.abs(delta) > (0.1 * inputSampleDuration)) {\n // logger.log(`Invalid frame delta ${Math.round(delta + inputSampleDuration)} at PTS ${Math.round(pts / 90)} (should be ${Math.round(inputSampleDuration)}).`);\n }\n sample.pts = sample.dts = nextPts;\n nextPts += inputSampleDuration;\n i++;\n }\n }\n }\n\n // compute mdat size, as we eventually filtered/added some samples\n let nbSamples = inputSamples.length;\n let mdatSize = 0;\n while (nbSamples--) {\n mdatSize += inputSamples[nbSamples].unit.byteLength;\n }\n\n for (let j = 0, nbSamples = inputSamples.length; j < nbSamples; j++) {\n let audioSample = inputSamples[j];\n let unit = audioSample.unit;\n let pts = audioSample.pts;\n\n // logger.log(`Audio/PTS:${toMsFromMpegTsClock(pts, true)}`);\n // if not first sample\n\n if (lastPTS !== undefined && mp4Sample) {\n mp4Sample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n let delta = pts - nextAudioPts;\n let numMissingFrames = 0;\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n if (contiguous && track.isAAC) {\n // log delta\n if (delta) {\n if (delta > 0 && delta < MAX_SILENT_FRAME_DURATION_90KHZ) {\n // Q: why do we have to round here, shouldn't this always result in an integer if timestamps are correct,\n // and if not, shouldn't we actually Math.ceil() instead?\n numMissingFrames = Math.round((pts - nextAudioPts) / inputSampleDuration);\n\n logger.log(`${toMsFromMpegTsClock(delta, true)} ms hole between AAC samples detected,filling it`);\n if (numMissingFrames > 0) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n fillFrame = unit.subarray();\n }\n\n mdatSize += numMissingFrames * fillFrame.length;\n }\n // if we have frame overlap, overlapping for more than half a frame duraion\n } else if (delta < -12) {\n // drop overlapping audio frames... browser will deal with it\n logger.log(`drop overlapping AAC sample, expected/parsed/delta: ${toMsFromMpegTsClock(nextAudioPts, true)} ms / ${toMsFromMpegTsClock(pts, true)} ms / ${toMsFromMpegTsClock(-delta, true)} ms`);\n mdatSize -= unit.byteLength;\n continue;\n }\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n }\n // remember first PTS of our audioSamples\n firstPTS = pts;\n if (mdatSize > 0) {\n mdatSize += offset;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.trigger(Event.ERROR, { type: ErrorTypes.MUX_ERROR, details: ErrorDetails.REMUX_ALLOC_ERROR, fatal: false, bytes: mdatSize, reason: `fail allocating audio mdat ${mdatSize}` });\n return;\n }\n if (!rawMPEG) {\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n for (let i = 0; i < numMissingFrames; i++) {\n fillFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n if (!fillFrame) {\n logger.log('Unable to get silent frame for given audio codec; duplicating this frame instead.');\n fillFrame = unit.subarray();\n }\n mdat.set(fillFrame, offset);\n offset += fillFrame.byteLength;\n mp4Sample = {\n size: fillFrame.byteLength,\n cts: 0,\n duration: 1024,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1\n }\n };\n outputSamples.push(mp4Sample);\n }\n }\n mdat.set(unit, offset);\n let unitLen = unit.byteLength;\n offset += unitLen;\n // console.log('PTS/DTS/initDTS/normPTS/normDTS/relative PTS : ${audioSample.pts}/${audioSample.dts}/${initDTS}/${ptsnorm}/${dtsnorm}/${(audioSample.pts/4294967296).toFixed(3)}');\n mp4Sample = {\n size: unitLen,\n cts: 0,\n duration: 0,\n flags: {\n isLeading: 0,\n isDependedOn: 0,\n hasRedundancy: 0,\n degradPrio: 0,\n dependsOn: 1\n }\n };\n outputSamples.push(mp4Sample);\n lastPTS = pts;\n }\n let lastSampleDuration = 0;\n nbSamples = outputSamples.length;\n // set last sample duration as being identical to previous sample\n if (nbSamples >= 2) {\n lastSampleDuration = outputSamples[nbSamples - 2].duration;\n mp4Sample.duration = lastSampleDuration;\n }\n if (nbSamples) {\n // next audio sample PTS should be equal to last sample PTS + duration\n this.nextAudioPts = nextAudioPts = lastPTS + scaleFactor * lastSampleDuration;\n // logger.log('Audio/PTS/PTSend:' + audioSample.pts.toFixed(0) + '/' + this.nextAacDts.toFixed(0));\n track.samples = outputSamples;\n if (rawMPEG) {\n moof = new Uint8Array();\n } else {\n moof = MP4.moof(track.sequenceNumber++, firstPTS / scaleFactor, track);\n }\n\n track.samples = [];\n const start = firstPTS / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type: 'audio',\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples\n };\n this.observer.trigger(Event.FRAG_PARSING_DATA, audioData);\n return audioData;\n }\n return null;\n }\n\n remuxEmptyAudio (track, timeOffset, contiguous, videoData) {\n let inputTimeScale = track.inputTimeScale;\n let mp4timeScale = track.samplerate ? track.samplerate : inputTimeScale;\n let scaleFactor = inputTimeScale / mp4timeScale;\n let nextAudioPts = this.nextAudioPts;\n\n // sync with video's timestamp\n let startDTS = (nextAudioPts !== undefined ? nextAudioPts : videoData.startDTS * inputTimeScale) + this._initDTS;\n let endDTS = videoData.endDTS * inputTimeScale + this._initDTS;\n // one sample's duration value\n let sampleDuration = 1024;\n let frameDuration = scaleFactor * sampleDuration;\n\n // samples count of this segment's duration\n let nbSamples = Math.ceil((endDTS - startDTS) / frameDuration);\n\n // silent frame\n let silentFrame = AAC.getSilentFrame(track.manifestCodec || track.codec, track.channelCount);\n\n logger.warn('remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace('Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec!');\n return;\n }\n\n let samples = [];\n for (let i = 0; i < nbSamples; i++) {\n let stamp = startDTS + i * frameDuration;\n samples.push({ unit: silentFrame, pts: stamp, dts: stamp });\n }\n track.samples = samples;\n\n this.remuxAudio(track, timeOffset, contiguous);\n }\n\n remuxID3 (track, timeOffset) {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n const initDTS = this._initDTS;\n // consume samples\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;\n sample.dts = PTSNormalize(sample.dts - initDTS, timeOffset * inputTimeScale) / inputTimeScale;\n }\n this.observer.trigger(Event.FRAG_PARSING_METADATA, {\n samples: track.samples\n });\n\n track.samples = [];\n }\n\n remuxText (track, timeOffset) {\n const length = track.samples.length;\n const inputTimeScale = track.inputTimeScale;\n const initPTS = this._initPTS;\n // consume samples\n if (length) {\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts = PTSNormalize(sample.pts - initPTS, timeOffset * inputTimeScale) / inputTimeScale;\n }\n track.samples.sort(function (a, b) {\n return (a.pts - b.pts);\n });\n this.observer.trigger(Event.FRAG_PARSING_USERDATA, {\n samples: track.samples\n });\n }\n\n track.samples = [];\n }\n}\n\nfunction PTSNormalize (value, reference) {\n let offset;\n if (reference === undefined) {\n return value;\n }\n\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n\n return value;\n}\n\nexport default MP4Remuxer;\n","/**\n *\n * inline demuxer: probe fragments and instantiate\n * appropriate demuxer depending on content type (TSDemuxer, AACDemuxer, ...)\n *\n */\n\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\n\nimport { getSelfScope } from '../utils/get-self-scope';\nimport { logger } from '../utils/logger';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\n\nlet now;\n// performance.now() not available on WebWorker, at least on Safari Desktop\ntry {\n now = global.performance.now.bind(global.performance);\n} catch (err) {\n logger.debug('Unable to use Performance API on this environment');\n now = global.Date.now;\n}\n\nclass DemuxerInline {\n constructor (observer, typeSupported, config, vendor) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n }\n\n destroy () {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n }\n }\n\n push (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n if ((data.byteLength > 0) && (decryptdata != null) && (decryptdata.key != null) && (decryptdata.method === 'AES-128')) {\n let decrypter = this.decrypter;\n if (decrypter == null) {\n decrypter = this.decrypter = new Decrypter(this.observer, this.config);\n }\n\n const startTime = now();\n decrypter.decrypt(data, decryptdata.key.buffer, decryptdata.iv.buffer, (decryptedData) => {\n const endTime = now();\n this.observer.trigger(Event.FRAG_DECRYPTED, { stats: { tstart: startTime, tdecrypt: endTime } });\n this.pushDecrypted(new Uint8Array(decryptedData), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n });\n } else {\n this.pushDecrypted(new Uint8Array(data), decryptdata, new Uint8Array(initSegment), audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n\n pushDecrypted (data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS) {\n let demuxer = this.demuxer;\n let remuxer = this.remuxer;\n if (!demuxer ||\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n (discontinuity || trackSwitch)) {\n const observer = this.observer;\n const typeSupported = this.typeSupported;\n const config = this.config;\n // probing order is TS/MP4/AAC/MP3\n const muxConfig = [\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer }\n ];\n\n // probe for content type\n let mux;\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n mux = muxConfig[i];\n if (mux.demux.probe(data)) {\n break;\n }\n }\n if (!mux) {\n observer.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.FRAG_PARSING_ERROR, fatal: true, reason: 'no demux matching with content found' });\n return;\n }\n // so let's check that current remuxer and demuxer are still valid\n if (!remuxer || !(remuxer instanceof mux.remux)) {\n remuxer = new mux.remux(observer, config, typeSupported, this.vendor);\n }\n if (!demuxer || !(demuxer instanceof mux.demux)) {\n demuxer = new mux.demux(observer, remuxer, config, typeSupported);\n this.probe = mux.demux.probe;\n }\n this.demuxer = demuxer;\n this.remuxer = remuxer;\n }\n\n if (discontinuity || trackSwitch) {\n demuxer.resetInitSegment(initSegment, audioCodec, videoCodec, duration);\n remuxer.resetInitSegment();\n }\n if (discontinuity) {\n demuxer.resetTimeStamp(defaultInitPTS);\n remuxer.resetTimeStamp(defaultInitPTS);\n }\n if (typeof demuxer.setDecryptData === 'function') {\n demuxer.setDecryptData(decryptdata);\n }\n\n demuxer.append(data, timeOffset, contiguous, accurateTimeOffset);\n }\n}\n\nexport default DemuxerInline;\n","/**\n * passthrough remuxer\n*/\nimport Event from '../events';\n\nclass PassThroughRemuxer {\n constructor (observer) {\n this.observer = observer;\n }\n\n destroy () {\n }\n\n resetTimeStamp () {\n }\n\n resetInitSegment () {\n }\n\n remux (audioTrack, videoTrack, id3Track, textTrack, timeOffset, contiguous, accurateTimeOffset, rawData) {\n let observer = this.observer;\n let streamType = '';\n if (audioTrack) {\n streamType += 'audio';\n }\n\n if (videoTrack) {\n streamType += 'video';\n }\n\n observer.trigger(Event.FRAG_PARSING_DATA, {\n data1: rawData,\n startPTS: timeOffset,\n startDTS: timeOffset,\n type: streamType,\n hasAudio: !!audioTrack,\n hasVideo: !!videoTrack,\n nb: 1,\n dropped: 0\n });\n // notify end of parsing\n observer.trigger(Event.FRAG_PARSED);\n }\n}\n\nexport default PassThroughRemuxer;\n","/**\n * MP4 demuxer\n */\nimport { logger } from '../utils/logger';\nimport Event from '../events';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4Demuxer {\n constructor (observer, remuxer) {\n this.observer = observer;\n this.remuxer = remuxer;\n }\n\n resetTimeStamp (initPTS) {\n this.initPTS = initPTS;\n }\n\n resetInitSegment (initSegment, audioCodec, videoCodec, duration) {\n // jshint unused:false\n if (initSegment && initSegment.byteLength) {\n const initData = this.initData = MP4Demuxer.parseInitSegment(initSegment);\n\n // default audio codec if nothing specified\n // TODO : extract that from initsegment\n if (audioCodec == null) {\n audioCodec = 'mp4a.40.5';\n }\n\n if (videoCodec == null) {\n videoCodec = 'avc1.42e01e';\n }\n\n const tracks = {};\n if (initData.audio && initData.video) {\n tracks.audiovideo = { container: 'video/mp4', codec: audioCodec + ',' + videoCodec, initSegment: duration ? initSegment : null };\n } else {\n if (initData.audio) {\n tracks.audio = { container: 'audio/mp4', codec: audioCodec, initSegment: duration ? initSegment : null };\n }\n\n if (initData.video) {\n tracks.video = { container: 'video/mp4', codec: videoCodec, initSegment: duration ? initSegment : null };\n }\n }\n this.observer.trigger(Event.FRAG_PARSING_INIT_SEGMENT, { tracks });\n } else {\n if (audioCodec) {\n this.audioCodec = audioCodec;\n }\n\n if (videoCodec) {\n this.videoCodec = videoCodec;\n }\n }\n }\n\n static probe (data) {\n // ensure we find a moof box in the first 16 kB\n return MP4Demuxer.findBox({ data: data, start: 0, end: Math.min(data.length, 16384) }, ['moof']).length > 0;\n }\n\n static bin2str (buffer) {\n return String.fromCharCode.apply(null, buffer);\n }\n\n static readUint16 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 8 |\n buffer[offset + 1];\n\n return val < 0 ? 65536 + val : val;\n }\n\n static readUint32 (buffer, offset) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n\n const val = buffer[offset] << 24 |\n buffer[offset + 1] << 16 |\n buffer[offset + 2] << 8 |\n buffer[offset + 3];\n return val < 0 ? 4294967296 + val : val;\n }\n\n static writeUint32 (buffer, offset, value) {\n if (buffer.data) {\n offset += buffer.start;\n buffer = buffer.data;\n }\n buffer[offset] = value >> 24;\n buffer[offset + 1] = (value >> 16) & 0xff;\n buffer[offset + 2] = (value >> 8) & 0xff;\n buffer[offset + 3] = value & 0xff;\n }\n\n // Find the data for a box specified by its path\n static findBox (data, path) {\n let results = [],\n i, size, type, end, subresults, start, endbox;\n\n if (data.data) {\n start = data.start;\n end = data.end;\n data = data.data;\n } else {\n start = 0;\n end = data.byteLength;\n }\n\n if (!path.length) {\n // short-circuit the search for empty paths\n return null;\n }\n\n for (i = start; i < end;) {\n size = MP4Demuxer.readUint32(data, i);\n type = MP4Demuxer.bin2str(data.subarray(i + 4, i + 8));\n endbox = size > 1 ? i + size : end;\n\n if (type === path[0]) {\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push({ data: data, start: i + 8, end: endbox });\n } else {\n // recursively search for the next box along the path\n subresults = MP4Demuxer.findBox({ data: data, start: i + 8, end: endbox }, path.slice(1));\n if (subresults.length) {\n results = results.concat(subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n }\n\n static parseSegmentIndex (initSegment) {\n const moov = MP4Demuxer.findBox(initSegment, ['moov'])[0];\n const moovEndOffset = moov ? moov.end : null; // we need this in case we need to chop of garbage of the end of current data\n\n let index = 0;\n let sidx = MP4Demuxer.findBox(initSegment, ['sidx']);\n let references;\n\n if (!sidx || !sidx[0]) {\n return null;\n }\n\n references = [];\n sidx = sidx[0];\n\n const version = sidx.data[0];\n\n // set initial offset, we skip the reference ID (not needed)\n index = version === 0 ? 8 : 16;\n\n const timescale = MP4Demuxer.readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n let earliestPresentationTime = 0;\n let firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.end + firstOffset;\n\n const referencesCount = MP4Demuxer.readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7FFFFFFF;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n console.warn('SIDX has hierarchical references (not supported)');\n return;\n }\n\n const subsegmentDuration = MP4Demuxer.readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1\n }\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n moovEndOffset\n };\n }\n\n /**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param init {Uint8Array} the bytes of the init segment\n * @return {object} a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n static parseInitSegment (initSegment) {\n let result = [];\n let traks = MP4Demuxer.findBox(initSegment, ['moov', 'trak']);\n\n traks.forEach(trak => {\n const tkhd = MP4Demuxer.findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd.data[tkhd.start];\n let index = version === 0 ? 12 : 20;\n let trackId = MP4Demuxer.readUint32(tkhd, index);\n\n const mdhd = MP4Demuxer.findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd.data[mdhd.start];\n index = version === 0 ? 12 : 20;\n const timescale = MP4Demuxer.readUint32(mdhd, index);\n\n const hdlr = MP4Demuxer.findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = MP4Demuxer.bin2str(hdlr.data.subarray(hdlr.start + 8, hdlr.start + 12));\n let type = { 'soun': 'audio', 'vide': 'video' }[hdlrType];\n if (type) {\n // extract codec info. TODO : parse codec details to be able to build MIME type\n let codecBox = MP4Demuxer.findBox(trak, ['mdia', 'minf', 'stbl', 'stsd']);\n if (codecBox.length) {\n codecBox = codecBox[0];\n let codecType = MP4Demuxer.bin2str(codecBox.data.subarray(codecBox.start + 12, codecBox.start + 16));\n logger.log(`MP4Demuxer:${type}:${codecType} found`);\n }\n result[trackId] = { timescale: timescale, type: type };\n result[type] = { timescale: timescale, id: trackId };\n }\n }\n }\n }\n });\n return result;\n }\n\n /**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param timescale {object} a hash of track ids to timescale values.\n * @return {number} the earliest base media decode start time for the\n * fragment, in seconds\n */\n static getStartDTS (initData, fragment) {\n let trafs, baseTimes, result;\n\n // we need info from two childrend of each track fragment box\n trafs = MP4Demuxer.findBox(fragment, ['moof', 'traf']);\n\n // determine the start times for each track\n baseTimes = [].concat.apply([], trafs.map(function (traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {\n let id, scale, baseTime;\n\n // get the track id from the tfhd\n id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n scale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n baseTime = MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {\n let version, result;\n\n version = tfdt.data[tfdt.start];\n result = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n\n result += MP4Demuxer.readUint32(tfdt, 8);\n }\n return result;\n })[0];\n // convert base time to seconds\n return baseTime / scale;\n });\n }));\n\n // return the minimum\n result = Math.min.apply(null, baseTimes);\n return isFinite(result) ? result : 0;\n }\n\n static offsetStartDTS (initData, fragment, timeOffset) {\n MP4Demuxer.findBox(fragment, ['moof', 'traf']).map(function (traf) {\n return MP4Demuxer.findBox(traf, ['tfhd']).map(function (tfhd) {\n // get the track id from the tfhd\n let id = MP4Demuxer.readUint32(tfhd, 4);\n // assume a 90kHz clock if no timescale was specified\n let timescale = initData[id].timescale || 90e3;\n\n // get the base media decode time from the tfdt\n MP4Demuxer.findBox(traf, ['tfdt']).map(function (tfdt) {\n let version = tfdt.data[tfdt.start];\n let baseMediaDecodeTime = MP4Demuxer.readUint32(tfdt, 4);\n if (version === 0) {\n MP4Demuxer.writeUint32(tfdt, 4, baseMediaDecodeTime - timeOffset * timescale);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += MP4Demuxer.readUint32(tfdt, 8);\n baseMediaDecodeTime -= timeOffset * timescale;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n MP4Demuxer.writeUint32(tfdt, 4, upper);\n MP4Demuxer.writeUint32(tfdt, 8, lower);\n }\n });\n });\n });\n }\n\n // feed incoming data to the front of the parsing pipeline\n append (data, timeOffset, contiguous, accurateTimeOffset) {\n let initData = this.initData;\n if (!initData) {\n this.resetInitSegment(data, this.audioCodec, this.videoCodec, false);\n initData = this.initData;\n }\n let startDTS, initPTS = this.initPTS;\n if (initPTS === undefined) {\n let startDTS = MP4Demuxer.getStartDTS(initData, data);\n this.initPTS = initPTS = startDTS - timeOffset;\n this.observer.trigger(Event.INIT_PTS_FOUND, { initPTS: initPTS });\n }\n MP4Demuxer.offsetStartDTS(initData, data, initPTS);\n startDTS = MP4Demuxer.getStartDTS(initData, data);\n this.remuxer.remux(initData.audio, initData.video, null, null, startDTS, contiguous, accurateTimeOffset, data);\n }\n\n destroy () {}\n}\n\nexport default MP4Demuxer;\n","function webpackBootstrapFunc (modules) {\n/******/ // The module cache\n/******/ var installedModules = {};\n\n/******/ // The require function\n/******/ function __webpack_require__(moduleId) {\n\n/******/ // Check if module is in cache\n/******/ if(installedModules[moduleId])\n/******/ return installedModules[moduleId].exports;\n\n/******/ // Create a new module (and put it into the cache)\n/******/ var module = installedModules[moduleId] = {\n/******/ i: moduleId,\n/******/ l: false,\n/******/ exports: {}\n/******/ };\n\n/******/ // Execute the module function\n/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);\n\n/******/ // Flag the module as loaded\n/******/ module.l = true;\n\n/******/ // Return the exports of the module\n/******/ return module.exports;\n/******/ }\n\n/******/ // expose the modules object (__webpack_modules__)\n/******/ __webpack_require__.m = modules;\n\n/******/ // expose the module cache\n/******/ __webpack_require__.c = installedModules;\n\n/******/ // identity function for calling harmony imports with the correct context\n/******/ __webpack_require__.i = function(value) { return value; };\n\n/******/ // define getter function for harmony exports\n/******/ __webpack_require__.d = function(exports, name, getter) {\n/******/ if(!__webpack_require__.o(exports, name)) {\n/******/ Object.defineProperty(exports, name, {\n/******/ configurable: false,\n/******/ enumerable: true,\n/******/ get: getter\n/******/ });\n/******/ }\n/******/ };\n\n/******/ // define __esModule on exports\n/******/ __webpack_require__.r = function(exports) {\n/******/ Object.defineProperty(exports, '__esModule', { value: true });\n/******/ };\n\n/******/ // getDefaultExport function for compatibility with non-harmony modules\n/******/ __webpack_require__.n = function(module) {\n/******/ var getter = module && module.__esModule ?\n/******/ function getDefault() { return module['default']; } :\n/******/ function getModuleExports() { return module; };\n/******/ __webpack_require__.d(getter, 'a', getter);\n/******/ return getter;\n/******/ };\n\n/******/ // Object.prototype.hasOwnProperty.call\n/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };\n\n/******/ // __webpack_public_path__\n/******/ __webpack_require__.p = \"/\";\n\n/******/ // on error function for async loading\n/******/ __webpack_require__.oe = function(err) { console.error(err); throw err; };\n\n var f = __webpack_require__(__webpack_require__.s = ENTRY_MODULE)\n return f.default || f // try to call default if defined to also support babel esmodule exports\n}\n\nvar moduleNameReqExp = '[\\\\.|\\\\-|\\\\+|\\\\w|\\/|@]+'\nvar dependencyRegExp = '\\\\(\\\\s*(\\/\\\\*.*?\\\\*\\/)?\\\\s*.*?(' + moduleNameReqExp + ').*?\\\\)' // additional chars when output.pathinfo is true\n\n// http://stackoverflow.com/a/2593661/130442\nfunction quoteRegExp (str) {\n return (str + '').replace(/[.?*+^$[\\]\\\\(){}|-]/g, '\\\\$&')\n}\n\nfunction isNumeric(n) {\n return !isNaN(1 * n); // 1 * n converts integers, integers as string (\"123\"), 1e3 and \"1e3\" to integers and strings to NaN\n}\n\nfunction getModuleDependencies (sources, module, queueName) {\n var retval = {}\n retval[queueName] = []\n\n var fnString = module.toString()\n var wrapperSignature = fnString.match(/^function\\s?\\w*\\(\\w+,\\s*\\w+,\\s*(\\w+)\\)/)\n if (!wrapperSignature) return retval\n var webpackRequireName = wrapperSignature[1]\n\n // main bundle deps\n var re = new RegExp('(\\\\\\\\n|\\\\W)' + quoteRegExp(webpackRequireName) + dependencyRegExp, 'g')\n var match\n while ((match = re.exec(fnString))) {\n if (match[3] === 'dll-reference') continue\n retval[queueName].push(match[3])\n }\n\n // dll deps\n re = new RegExp('\\\\(' + quoteRegExp(webpackRequireName) + '\\\\(\"(dll-reference\\\\s(' + moduleNameReqExp + '))\"\\\\)\\\\)' + dependencyRegExp, 'g')\n while ((match = re.exec(fnString))) {\n if (!sources[match[2]]) {\n retval[queueName].push(match[1])\n sources[match[2]] = __webpack_require__(match[1]).m\n }\n retval[match[2]] = retval[match[2]] || []\n retval[match[2]].push(match[4])\n }\n\n // convert 1e3 back to 1000 - this can be important after uglify-js converted 1000 to 1e3\n var keys = Object.keys(retval);\n for (var i = 0; i < keys.length; i++) {\n for (var j = 0; j < retval[keys[i]].length; j++) {\n if (isNumeric(retval[keys[i]][j])) {\n retval[keys[i]][j] = 1 * retval[keys[i]][j];\n }\n }\n }\n\n return retval\n}\n\nfunction hasValuesInQueues (queues) {\n var keys = Object.keys(queues)\n return keys.reduce(function (hasValues, key) {\n return hasValues || queues[key].length > 0\n }, false)\n}\n\nfunction getRequiredModules (sources, moduleId) {\n var modulesQueue = {\n main: [moduleId]\n }\n var requiredModules = {\n main: []\n }\n var seenModules = {\n main: {}\n }\n\n while (hasValuesInQueues(modulesQueue)) {\n var queues = Object.keys(modulesQueue)\n for (var i = 0; i < queues.length; i++) {\n var queueName = queues[i]\n var queue = modulesQueue[queueName]\n var moduleToCheck = queue.pop()\n seenModules[queueName] = seenModules[queueName] || {}\n if (seenModules[queueName][moduleToCheck] || !sources[queueName][moduleToCheck]) continue\n seenModules[queueName][moduleToCheck] = true\n requiredModules[queueName] = requiredModules[queueName] || []\n requiredModules[queueName].push(moduleToCheck)\n var newModules = getModuleDependencies(sources, sources[queueName][moduleToCheck], queueName)\n var newModulesKeys = Object.keys(newModules)\n for (var j = 0; j < newModulesKeys.length; j++) {\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]] || []\n modulesQueue[newModulesKeys[j]] = modulesQueue[newModulesKeys[j]].concat(newModules[newModulesKeys[j]])\n }\n }\n }\n\n return requiredModules\n}\n\nmodule.exports = function (moduleId, options) {\n options = options || {}\n var sources = {\n main: __webpack_modules__\n }\n\n var requiredModules = options.all ? { main: Object.keys(sources.main) } : getRequiredModules(sources, moduleId)\n\n var src = ''\n\n Object.keys(requiredModules).filter(function (m) { return m !== 'main' }).forEach(function (module) {\n var entryModule = 0\n while (requiredModules[module][entryModule]) {\n entryModule++\n }\n requiredModules[module].push(entryModule)\n sources[module][entryModule] = '(function(module, exports, __webpack_require__) { module.exports = __webpack_require__; })'\n 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'\n })\n\n 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);'\n\n var blob = new window.Blob([src], { type: 'text/javascript' })\n if (options.bare) { return blob }\n\n var URL = window.URL || window.webkitURL || window.mozURL || window.msURL\n\n var workerUrl = URL.createObjectURL(blob)\n var worker = new window.Worker(workerUrl)\n worker.objectURL = workerUrl\n\n return worker\n}\n","/* demuxer web worker.\n * - listen to worker message, and trigger DemuxerInline upon reception of Fragments.\n * - 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.\n */\n\nimport DemuxerInline from '../demux/demuxer-inline';\nimport Event from '../events';\nimport { enableLogs } from '../utils/logger';\n\nimport { EventEmitter } from 'eventemitter3';\n\nlet DemuxerWorker = function (self) {\n // observer setup\n let observer = new EventEmitter();\n observer.trigger = function trigger (event, ...data) {\n observer.emit(event, event, ...data);\n };\n\n observer.off = function off (event, ...data) {\n observer.removeListener(event, ...data);\n };\n\n let forwardMessage = function (ev, data) {\n self.postMessage({ event: ev, data: data });\n };\n\n self.addEventListener('message', function (ev) {\n let data = ev.data;\n // console.log('demuxer cmd:' + data.cmd);\n switch (data.cmd) {\n case 'init':\n const config = JSON.parse(data.config);\n self.demuxer = new DemuxerInline(observer, data.typeSupported, config, data.vendor);\n\n enableLogs(config.debug);\n\n // signal end of worker init\n forwardMessage('init', null);\n break;\n case 'demux':\n 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);\n break;\n default:\n break;\n }\n });\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n // special case for FRAG_PARSING_DATA: pass data1/data2 as transferable object (no copy)\n observer.on(Event.FRAG_PARSING_DATA, function (ev, data) {\n let transferable = [];\n let message = { event: ev, data: data };\n if (data.data1) {\n message.data1 = data.data1.buffer;\n transferable.push(data.data1.buffer);\n delete data.data1;\n }\n if (data.data2) {\n message.data2 = data.data2.buffer;\n transferable.push(data.data2.buffer);\n delete data.data2;\n }\n self.postMessage(message, transferable);\n });\n};\n\nexport default DemuxerWorker;\n","import Level from '../loader/level';\n\nexport interface LoaderContext {\n // target URL\n url: string\n // loader response type (arraybuffer or default response type for playlist)\n responseType: string\n // start byte range offset\n rangeStart?: number\n // end byte range offset\n rangeEnd?: number\n // true if onProgress should report partial chunk of loaded content\n progressData?: boolean\n}\n\nexport interface LoaderConfiguration {\n // Max number of load retries\n maxRetry: number\n // Timeout after which `onTimeOut` callback will be triggered\n // (if loading is still not finished after that delay)\n timeout: number\n // Delay between an I/O error and following connection retry (ms).\n // This to avoid spamming the server\n retryDelay: number\n // max connection retry delay (ms)\n maxRetryDelay: number\n}\n\nexport interface LoaderResponse {\n url: string,\n // TODO(jstackhouse): SharedArrayBuffer, es2017 extension to TS\n data: string | ArrayBuffer\n}\n\nexport interface LoaderStats {\n // performance.now() just after load() has been called\n trequest: number\n // performance.now() of first received byte\n tfirst: number\n // performance.now() on load complete\n tload: number\n // performance.now() on parse completion\n tparsed: number\n // number of loaded bytes\n loaded: number\n // total number of bytes\n total: number\n}\n\ntype LoaderOnSuccess < T extends LoaderContext > = (\n response: LoaderResponse,\n stats: LoaderStats,\n context: T,\n networkDetails: any\n) => void;\n\ntype LoaderOnProgress < T extends LoaderContext > = (\n stats: LoaderStats,\n context: T,\n data: string | ArrayBuffer,\n networkDetails: any,\n) => void;\n\ntype LoaderOnError < T extends LoaderContext > = (\n error: {\n // error status code\n code: number,\n // error description\n text: string,\n },\n context: T,\n networkDetails: any,\n) => void;\n\ntype LoaderOnTimeout < T extends LoaderContext > = (\n stats: LoaderStats,\n context: T,\n) => void;\n\nexport interface LoaderCallbacks{\n onSuccess: LoaderOnSuccess,\n onError: LoaderOnError,\n onTimeout: LoaderOnTimeout,\n onProgress?: LoaderOnProgress,\n}\n\nexport interface Loader {\n destroy(): void\n abort(): void\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks,\n ): void\n\n context: T\n}\n\n/**\n * `type` property values for this loaders' context object\n * @enum\n *\n */\nexport enum PlaylistContextType {\n MANIFEST = 'manifest',\n LEVEL = 'level',\n AUDIO_TRACK = 'audioTrack',\n SUBTITLE_TRACK= 'subtitleTrack'\n}\n\n/**\n * @enum {string}\n */\nexport enum PlaylistLevelType {\n MAIN = 'main',\n AUDIO = 'audio',\n SUBTITLE = 'subtitle'\n}\n\nexport interface PlaylistLoaderContext extends LoaderContext {\n loader?: Loader\n\n type: PlaylistContextType\n // the level index to load\n level: number | null\n // TODO: what is id?\n id: number | null\n // defines if the loader is handling a sidx request for the playlist\n isSidxRequest?: boolean\n // internal reprsentation of a parsed m3u8 level playlist\n levelDetails?: Level\n}\n","/*\n*\n* All objects in the event handling chain should inherit from this class\n*\n*/\n\nimport { logger } from './utils/logger';\nimport { ErrorTypes, ErrorDetails } from './errors';\nimport Event from './events';\nimport Hls from './hls';\n\nconst FORBIDDEN_EVENT_NAMES = {\n 'hlsEventGeneric': true,\n 'hlsHandlerDestroying': true,\n 'hlsHandlerDestroyed': true\n};\n\nclass EventHandler {\n hls: Hls;\n handledEvents: any[];\n useGenericHandler: boolean;\n\n constructor (hls: Hls, ...events: any[]) {\n this.hls = hls;\n this.onEvent = this.onEvent.bind(this);\n this.handledEvents = events;\n this.useGenericHandler = true;\n\n this.registerListeners();\n }\n\n destroy () {\n this.onHandlerDestroying();\n this.unregisterListeners();\n this.onHandlerDestroyed();\n }\n\n protected onHandlerDestroying () {}\n protected onHandlerDestroyed () {}\n\n isEventHandler () {\n return typeof this.handledEvents === 'object' && this.handledEvents.length && typeof this.onEvent === 'function';\n }\n\n registerListeners () {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function (event) {\n if (FORBIDDEN_EVENT_NAMES[event]) {\n throw new Error('Forbidden event-name: ' + event);\n }\n\n this.hls.on(event, this.onEvent);\n }, this);\n }\n }\n\n unregisterListeners () {\n if (this.isEventHandler()) {\n this.handledEvents.forEach(function (event) {\n this.hls.off(event, this.onEvent);\n }, this);\n }\n }\n\n /**\n * arguments: event (string), data (any)\n */\n onEvent (event: string, data: any) {\n this.onEventGeneric(event, data);\n }\n\n onEventGeneric (event: string, data: any) {\n let eventToFunction = function (event: string, data: any) {\n let funcName = 'on' + event.replace('hls', '');\n if (typeof this[funcName] !== 'function') {\n throw new Error(`Event ${event} has no generic handler in this ${this.constructor.name} class (tried ${funcName})`);\n }\n\n return this[funcName].bind(this, data);\n };\n try {\n eventToFunction.call(this, event, data).call();\n } catch (err) {\n logger.error(`An internal error happened while handling event ${event}. Error message: \"${err.message}\". Here is a stacktrace:`, err);\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: false, event: event, err: err });\n }\n }\n}\n\nexport default EventHandler;\n","\nimport { buildAbsoluteURL } from 'url-toolkit';\nimport { logger } from '../utils/logger';\nimport LevelKey from './level-key';\nimport { PlaylistLevelType } from '../types/loader';\n\nexport enum ElementaryStreamTypes {\n AUDIO = 'audio',\n VIDEO = 'video',\n}\n\nexport default class Fragment {\n private _url: string | null = null;\n private _byteRange: number[] | null = null;\n private _decryptdata: LevelKey | null = null;\n\n // Holds the types of data this fragment supports\n private _elementaryStreams: Record = {\n [ElementaryStreamTypes.AUDIO]: false,\n [ElementaryStreamTypes.VIDEO]: false\n };\n\n // deltaPTS tracks the change in presentation timestamp between fragments\n public deltaPTS: number = 0;\n\n public rawProgramDateTime: string | null = null;\n public programDateTime: number | null = null;\n public title: string | null = null;\n public tagList: Array = [];\n\n // TODO: Move at least baseurl to constructor.\n // Currently we do a two-pass construction as use the Fragment class almost like a object for holding parsing state.\n // It may make more sense to just use a POJO to keep state during the parsing phase.\n // Have Fragment be the representation once we have a known state?\n // Something to think on.\n\n // Discontinuity Counter\n public cc!: number;\n\n public type!: PlaylistLevelType;\n // relurl is the portion of the URL that comes from inside the playlist.\n public relurl!: string;\n // baseurl is the URL to the playlist\n public baseurl!: string;\n // EXTINF has to be present for a m3u8 to be considered valid\n public duration!: number;\n // When this segment starts in the timeline\n public start!: number;\n // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'\n public sn: number | 'initSegment' = 0;\n\n public urlId: number = 0;\n // level matches this fragment to a index playlist\n public level: number = 0;\n // levelkey is the EXT-X-KEY that applies to this segment for decryption\n // core difference from the private field _decryptdata is the lack of the initialized IV\n // _decryptdata will set the IV for this segment based on the segment number in the fragment\n public levelkey?: LevelKey;\n\n // TODO(typescript-xhrloader)\n public loader: any;\n\n // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array\n setByteRange (value: string, previousFrag?: Fragment) {\n const params = value.split('@', 2);\n const byteRange: number[] = [];\n if (params.length === 1) {\n byteRange[0] = previousFrag ? previousFrag.byteRangeEndOffset : 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n\n get url () {\n if (!this._url && this.relurl) {\n this._url = buildAbsoluteURL(this.baseurl, this.relurl, { alwaysNormalize: true });\n }\n\n return this._url;\n }\n\n set url (value) {\n this._url = value;\n }\n\n get byteRange (): number[] {\n if (!this._byteRange) {\n return [];\n }\n\n return this._byteRange;\n }\n\n /**\n * @type {number}\n */\n get byteRangeStartOffset () {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset () {\n return this.byteRange[1];\n }\n\n get decryptdata (): LevelKey | null {\n if (!this.levelkey && !this._decryptdata) {\n return null;\n }\n\n if (!this._decryptdata && this.levelkey) {\n let sn = this.sn;\n if (typeof sn !== 'number') {\n // We are fetching decryption data for a initialization segment\n // If the segment was encrypted with AES-128\n // It must have an IV defined. We cannot substitute the Segment Number in.\n if (this.levelkey && this.levelkey.method === 'AES-128' && !this.levelkey.iv) {\n logger.warn(`missing IV for initialization segment with method=\"${this.levelkey.method}\" - compliance issue`);\n }\n\n /*\n Be converted to a Number.\n 'initSegment' will become NaN.\n NaN, which when converted through ToInt32() -> +0.\n ---\n Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.\n */\n sn = 0;\n }\n this._decryptdata = this.setDecryptDataFromLevelKey(this.levelkey, sn);\n }\n\n return this._decryptdata;\n }\n\n get endProgramDateTime () {\n if (this.programDateTime === null) {\n return null;\n }\n\n if (!Number.isFinite(this.programDateTime)) {\n return null;\n }\n\n let duration = !Number.isFinite(this.duration) ? 0 : this.duration;\n\n return this.programDateTime + (duration * 1000);\n }\n\n get encrypted () {\n return !!((this.decryptdata && this.decryptdata.uri !== null) && (this.decryptdata.key === null));\n }\n\n /**\n * @param {ElementaryStreamTypes} type\n */\n addElementaryStream (type: ElementaryStreamTypes) {\n this._elementaryStreams[type] = true;\n }\n\n /**\n * @param {ElementaryStreamTypes} type\n */\n hasElementaryStream (type: ElementaryStreamTypes) {\n return this._elementaryStreams[type] === true;\n }\n\n /**\n * Utility method for parseLevelPlaylist to create an initialization vector for a given segment\n * @param {number} segmentNumber - segment number to generate IV with\n * @returns {Uint8Array}\n */\n createInitializationVector (segmentNumber: number): Uint8Array {\n let uint8View = new Uint8Array(16);\n\n for (let i = 12; i < 16; i++) {\n uint8View[i] = (segmentNumber >> 8 * (15 - i)) & 0xff;\n }\n\n return uint8View;\n }\n\n /**\n * Utility method for parseLevelPlaylist to get a fragment's decryption data from the currently parsed encryption key data\n * @param levelkey - a playlist's encryption info\n * @param segmentNumber - the fragment's segment number\n * @returns {LevelKey} - an object to be applied as a fragment's decryptdata\n */\n setDecryptDataFromLevelKey (levelkey: LevelKey, segmentNumber: number): LevelKey {\n let decryptdata = levelkey;\n\n if (levelkey?.method && levelkey.uri && !levelkey.iv) {\n decryptdata = new LevelKey(levelkey.baseuri, levelkey.reluri);\n decryptdata.method = levelkey.method;\n decryptdata.iv = this.createInitializationVector(segmentNumber);\n }\n\n return decryptdata;\n }\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\n\nexport default class LevelKey {\n private _uri: string | null = null;\n\n public baseuri: string;\n public reluri: string;\n public method: string | null = null;\n public key: Uint8Array | null = null;\n public iv: Uint8Array | null = null;\n\n constructor (baseURI: string, relativeURI: string) {\n this.baseuri = baseURI;\n this.reluri = relativeURI;\n }\n\n get uri () {\n if (!this._uri && this.reluri) {\n this._uri = buildAbsoluteURL(this.baseuri, this.reluri, { alwaysNormalize: true });\n }\n\n return this._uri;\n }\n}\n","export default class Level {\n constructor (baseUrl) {\n // Please keep properties in alphabetical order\n this.endCC = 0;\n this.endSN = 0;\n this.fragments = [];\n this.initSegment = null;\n this.live = true;\n this.needSidxRanges = false;\n this.startCC = 0;\n this.startSN = 0;\n this.startTimeOffset = null;\n this.targetduration = 0;\n this.totalduration = 0;\n this.type = null;\n this.url = baseUrl;\n this.version = null;\n }\n\n get hasProgramDateTime () {\n return !!(this.fragments[0] && Number.isFinite(this.fragments[0].programDateTime));\n }\n}\n","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/; // eslint-disable-line no-useless-escape\nconst ATTR_LIST_REGEX = /\\s*(.+?)\\s*=((?:\\\".*?\\\")|.*?)(?:,|$)/g; // eslint-disable-line no-useless-escape\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nclass AttrList {\n constructor (attrs) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (let attr in attrs) {\n if (attrs.hasOwnProperty(attr)) {\n this[attr] = attrs[attr];\n }\n }\n }\n\n decimalInteger (attrName) {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n hexadecimalInteger (attrName) {\n if (this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = ((stringValue.length & 1) ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber (attrName) {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n decimalFloatingPoint (attrName) {\n return parseFloat(this[attrName]);\n }\n\n enumeratedString (attrName) {\n return this[attrName];\n }\n\n decimalResolution (attrName) {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10)\n };\n }\n\n static parseAttrList (input) {\n let match, attrs = {};\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let value = match[2], quote = '\"';\n\n if (value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === (value.length - 1)) {\n value = value.slice(1, -1);\n }\n\n attrs[match[1]] = value;\n }\n return attrs;\n }\n}\n\nexport default AttrList;\n","// from http://mp4ra.org/codecs.html\nconst sampleEntryCodesISO = {\n audio: {\n 'a3ds': true,\n 'ac-3': true,\n 'ac-4': true,\n 'alac': true,\n 'alaw': true,\n 'dra1': true,\n 'dts+': true,\n 'dts-': true,\n 'dtsc': true,\n 'dtse': true,\n 'dtsh': true,\n 'ec-3': true,\n 'enca': true,\n 'g719': true,\n 'g726': true,\n 'm4ae': true,\n 'mha1': true,\n 'mha2': true,\n 'mhm1': true,\n 'mhm2': true,\n 'mlpa': true,\n 'mp4a': true,\n 'raw ': true,\n 'Opus': true,\n 'samr': true,\n 'sawb': true,\n 'sawp': true,\n 'sevc': true,\n 'sqcp': true,\n 'ssmv': true,\n 'twos': true,\n 'ulaw': true\n },\n video: {\n 'avc1': true,\n 'avc2': true,\n 'avc3': true,\n 'avc4': true,\n 'avcp': true,\n 'drac': true,\n 'dvav': true,\n 'dvhe': true,\n 'encv': true,\n 'hev1': true,\n 'hvc1': true,\n 'mjp2': true,\n 'mp4v': true,\n 'mvc1': true,\n 'mvc2': true,\n 'mvc3': true,\n 'mvc4': true,\n 'resv': true,\n 'rv60': true,\n 's263': true,\n 'svc1': true,\n 'svc2': true,\n 'vc-1': true,\n 'vp08': true,\n 'vp09': true\n }\n};\n\nexport type CodecType = 'audio' | 'video';\n\nfunction isCodecType (codec: string, type: CodecType): boolean {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nfunction isCodecSupportedInMp4 (codec: string, type: CodecType): boolean {\n return MediaSource.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`);\n}\n\nexport { isCodecType, isCodecSupportedInMp4 };\n","import * as URLToolkit from 'url-toolkit';\n\nimport Fragment from './fragment';\nimport Level from './level';\nimport LevelKey from './level-key';\n\nimport AttrList from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport { isCodecType, CodecType } from '../utils/codecs';\nimport { MediaPlaylist, AudioGroup, MediaPlaylistType } from '../types/media-playlist';\nimport { PlaylistLevelType } from '../types/loader';\n\n/**\n * M3U8 parser\n * @module\n */\n\n// https://regex101.com is your friend\nconst MASTER_PLAYLIST_REGEX = /(?:#EXT-X-STREAM-INF:([^\\n\\r]*)[\\r\\n]+([^\\r\\n]+)|#EXT-X-SESSION-DATA:([^\\n\\r]*)[\\r\\n]+)/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp([\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:,), group 1 => duration, group 2 => title\n /|(?!#)([\\S+ ?]+)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /|#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /|#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /|#.*/.source // All other non-segment oriented tags will match with all groups empty\n].join(''), 'g');\n\nconst 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?/;\n\nconst MP4_REGEX_SUFFIX = /\\.(mp4|m4s|m4v|m4a)$/i;\n\nexport default class M3U8Parser {\n static findGroup (groups: Array<AudioGroup>, mediaGroupId: string): AudioGroup | undefined {\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n return group;\n }\n }\n }\n\n static convertAVC1ToAVCOTI (codec) {\n let avcdata = codec.split('.');\n let result;\n if (avcdata.length > 2) {\n result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift()).toString(16);\n result += ('000' + parseInt(avcdata.shift()).toString(16)).substr(-4);\n } else {\n result = codec;\n }\n return result;\n }\n\n static resolve (url, baseUrl) {\n return URLToolkit.buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static parseMasterPlaylist (string: string, baseurl: string) {\n // TODO(typescript-level)\n let levels: Array<any> = [];\n let sessionData: Record<string, AttrList> = {};\n let hasSessionData = false;\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n // TODO(typescript-level)\n function setCodecs (codecs: Array<string>, level: any) {\n ['video', 'audio'].forEach((type: CodecType) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n const preferred = filtered.filter((codec) => {\n return codec.lastIndexOf('avc1', 0) === 0 || codec.lastIndexOf('mp4a', 0) === 0;\n });\n level[`${type}Codec`] = preferred.length > 0 ? preferred[0] : filtered[0];\n\n // remove from list\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n\n level.unknownCodecs = codecs;\n }\n\n let result: RegExpExecArray | null;\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n if (result[1]) {\n // '#EXT-X-STREAM-INF' is found, parse level tag in group 1\n\n // TODO(typescript-level)\n const level: any = {};\n\n const attrs = level.attrs = new AttrList(result[1]);\n level.url = M3U8Parser.resolve(result[2], baseurl);\n\n const resolution = attrs.decimalResolution('RESOLUTION');\n if (resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n level.bitrate = attrs.decimalInteger('AVERAGE-BANDWIDTH') || attrs.decimalInteger('BANDWIDTH');\n level.name = attrs.NAME;\n\n setCodecs([].concat((attrs.CODECS || '').split(/[ ,]+/)), level);\n\n if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {\n level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n levels.push(level);\n } else if (result[3]) {\n // '#EXT-X-SESSION-DATA' is found, parse session data in group 3\n let sessionAttrs = new AttrList(result[3]);\n if (sessionAttrs['DATA-ID']) {\n hasSessionData = true;\n sessionData[sessionAttrs['DATA-ID']] = sessionAttrs;\n }\n }\n }\n return {\n levels,\n sessionData: hasSessionData ? sessionData : null\n };\n }\n\n static parseMasterPlaylistMedia (string: string, baseurl: string, type: MediaPlaylistType, audioGroups: Array<AudioGroup> = []): Array<MediaPlaylist> {\n let result: RegExpExecArray | null;\n let medias: Array<MediaPlaylist> = [];\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const attrs = new AttrList(result[1]);\n if (attrs.TYPE === type) {\n const media: MediaPlaylist = {\n attrs,\n id: id++,\n groupId: attrs['GROUP-ID'],\n instreamId: attrs['INSTREAM-ID'],\n name: attrs.NAME || attrs.LANGUAGE,\n type,\n default: (attrs.DEFAULT === 'YES'),\n autoselect: (attrs.AUTOSELECT === 'YES'),\n forced: (attrs.FORCED === 'YES'),\n lang: attrs.LANGUAGE\n };\n\n if (attrs.URI) {\n media.url = M3U8Parser.resolve(attrs.URI, baseurl);\n }\n\n if (audioGroups.length) {\n // If there are audio groups signalled in the manifest, let's look for a matching codec string for this track\n const groupCodec = M3U8Parser.findGroup(audioGroups, media.groupId as string);\n\n // If we don't find the track signalled, lets use the first audio groups codec we have\n // Acting as a best guess\n media.audioCodec = groupCodec ? groupCodec.codec : audioGroups[0].codec;\n }\n\n medias.push(media);\n }\n }\n return medias;\n }\n\n static parseLevelPlaylist (string: string, baseurl: string, id: number, type: PlaylistLevelType, levelUrlId: number) {\n let currentSN = 0;\n let totalduration = 0;\n let level = new Level(baseurl);\n let discontinuityCounter = 0;\n let prevFrag: Fragment | null = null;\n let frag: Fragment | null = new Fragment();\n let result: RegExpExecArray | RegExpMatchArray | null;\n let i: number;\n let levelkey: LevelKey | undefined;\n\n let firstPdtIndex = null;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n const duration = result[1];\n if (duration) { // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? [ 'INF', duration, title ] : [ 'INF', duration ]);\n } else if (result[3]) { // url\n if (Number.isFinite(frag.duration)) {\n const sn = currentSN++;\n frag.type = type;\n frag.start = totalduration;\n if (levelkey) {\n frag.levelkey = levelkey;\n }\n frag.sn = sn;\n frag.level = id;\n frag.cc = discontinuityCounter;\n frag.urlId = levelUrlId;\n frag.baseurl = baseurl;\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.relurl = (' ' + result[3]).slice(1);\n assignProgramDateTime(frag, prevFrag);\n\n level.fragments.push(frag);\n prevFrag = frag;\n totalduration += frag.duration;\n\n frag = new Fragment();\n }\n } else if (result[4]) { // X-BYTERANGE\n const data = (' ' + result[4]).slice(1);\n if (prevFrag) {\n frag.setByteRange(data, prevFrag);\n } else {\n frag.setByteRange(data);\n }\n } else if (result[5]) { // PROGRAM-DATE-TIME\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = (' ' + result[5]).slice(1);\n frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\n if (firstPdtIndex === null) {\n firstPdtIndex = level.fragments.length;\n }\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n if (!result) {\n logger.warn('No matches on slow regex match for level playlist!');\n continue;\n }\n for (i = 1; i < result.length; i++) {\n if (typeof result[i] !== 'undefined') {\n break;\n }\n }\n\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const value1 = (' ' + result[i + 1]).slice(1);\n const value2 = (' ' + result[i + 2]).slice(1);\n\n switch (result[i]) {\n case '#':\n frag.tagList.push(value2 ? [ value1, value2 ] : [ value1 ]);\n break;\n case 'PLAYLIST-TYPE':\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'TARGETDURATION':\n level.targetduration = parseFloat(value1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case 'DIS':\n discontinuityCounter++;\n frag.tagList.push(['DIS']);\n break;\n case 'DISCONTINUITY-SEQ':\n discontinuityCounter = parseInt(value1);\n break;\n case 'KEY': {\n // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n const decryptparams = value1;\n const keyAttrs = new AttrList(decryptparams);\n const decryptmethod = keyAttrs.enumeratedString('METHOD');\n const decrypturi = keyAttrs.URI;\n const decryptiv = keyAttrs.hexadecimalInteger('IV');\n // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n const decryptkeyformat = keyAttrs.KEYFORMAT || 'identity';\n\n if (decryptkeyformat === 'com.apple.streamingkeydelivery') {\n logger.warn('Keyformat com.apple.streamingkeydelivery is not supported');\n continue;\n }\n\n if (decryptmethod) {\n levelkey = new LevelKey(baseurl, decrypturi);\n if ((decrypturi) && (['AES-128', 'SAMPLE-AES', 'SAMPLE-AES-CENC'].indexOf(decryptmethod) >= 0)) {\n levelkey.method = decryptmethod;\n levelkey.key = null;\n // Initialization Vector (IV)\n levelkey.iv = decryptiv;\n }\n }\n break;\n }\n case 'START': {\n const startAttrs = new AttrList(value1);\n const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n // TIME-OFFSET can be 0\n if (Number.isFinite(startTimeOffset)) {\n level.startTimeOffset = startTimeOffset;\n }\n break;\n }\n case 'MAP': {\n const mapAttrs = new AttrList(value1);\n frag.relurl = mapAttrs.URI;\n if (mapAttrs.BYTERANGE) {\n frag.setByteRange(mapAttrs.BYTERANGE);\n }\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n level.initSegment = frag;\n frag = new Fragment();\n frag.rawProgramDateTime = level.initSegment.rawProgramDateTime;\n break;\n }\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n frag = prevFrag;\n // logger.log('found ' + level.fragments.length + ' fragments');\n if (frag && !frag.relurl) {\n level.fragments.pop();\n totalduration -= frag.duration;\n }\n level.totalduration = totalduration;\n level.averagetargetduration = totalduration / level.fragments.length;\n level.endSN = currentSN - 1;\n level.startCC = level.fragments[0] ? level.fragments[0].cc : 0;\n level.endCC = discontinuityCounter;\n\n if (!level.initSegment && level.fragments.length) {\n // this is a bit lurky but HLS really has no other way to tell us\n // if the fragments are TS or MP4, except if we download them :/\n // but this is to be able to handle SIDX.\n if (level.fragments.every((frag) => MP4_REGEX_SUFFIX.test(frag.relurl))) {\n logger.warn('MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX');\n\n frag = new Fragment();\n frag.relurl = level.fragments[0].relurl;\n frag.baseurl = baseurl;\n frag.level = id;\n frag.type = type;\n frag.sn = 'initSegment';\n\n level.initSegment = frag;\n level.needSidxRanges = true;\n }\n }\n\n /**\n * Backfill any missing PDT values\n \"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after\n one or more Media Segment URIs, the client SHOULD extrapolate\n backward from that tag (using EXTINF durations and/or media\n timestamps) to associate dates with those segments.\"\n * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs\n * computed.\n */\n if (firstPdtIndex) {\n backfillProgramDateTimes(level.fragments, firstPdtIndex);\n }\n\n return level;\n }\n}\n\nfunction backfillProgramDateTimes (fragments, startIndex) {\n let fragPrev = fragments[startIndex];\n for (let i = startIndex - 1; i >= 0; i--) {\n const frag = fragments[i];\n frag.programDateTime = fragPrev.programDateTime - (frag.duration * 1000);\n fragPrev = frag;\n }\n}\n\nfunction assignProgramDateTime (frag, prevFrag) {\n if (frag.rawProgramDateTime) {\n frag.programDateTime = Date.parse(frag.rawProgramDateTime);\n } else if (prevFrag?.programDateTime) {\n frag.programDateTime = prevFrag.endProgramDateTime;\n }\n\n if (!Number.isFinite(frag.programDateTime)) {\n frag.programDateTime = null;\n frag.rawProgramDateTime = null;\n }\n}\n","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n *\n * @module\n *\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { Loader, PlaylistContextType, PlaylistLoaderContext, PlaylistLevelType, LoaderCallbacks, LoaderResponse, LoaderStats, LoaderConfiguration } from '../types/loader';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport M3U8Parser from './m3u8-parser';\nimport { AudioGroup } from '../types/media-playlist';\n\nconst { performance } = window;\n\n/**\n * @constructor\n */\nclass PlaylistLoader extends EventHandler {\n private loaders: Partial<Record<PlaylistContextType, Loader<PlaylistLoaderContext>>> = {};\n\n /**\n * @constructs\n * @param {Hls} hls\n */\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.LEVEL_LOADING,\n Event.AUDIO_TRACK_LOADING,\n Event.SUBTITLE_TRACK_LOADING);\n }\n\n /**\n * @param {PlaylistContextType} type\n * @returns {boolean}\n */\n static canHaveQualityLevels (type: PlaylistContextType): boolean {\n return (type !== PlaylistContextType.AUDIO_TRACK &&\n type !== PlaylistContextType.SUBTITLE_TRACK);\n }\n\n /**\n * Map context.type to LevelType\n * @param {PlaylistLoaderContext} context\n * @returns {LevelType}\n */\n static mapContextToLevelType (context: PlaylistLoaderContext): PlaylistLevelType {\n const { type } = context;\n\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n return PlaylistLevelType.AUDIO;\n case PlaylistContextType.SUBTITLE_TRACK:\n return PlaylistLevelType.SUBTITLE;\n default:\n return PlaylistLevelType.MAIN;\n }\n }\n\n static getResponseUrl (response: LoaderResponse, context: PlaylistLoaderContext): string {\n let url = response.url;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n return url;\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n * Default loader is XHRLoader (see utils)\n * @param {PlaylistLoaderContext} context\n * @returns {Loader} or other compatible configured overload\n */\n createInternalLoader (context: PlaylistLoaderContext): Loader<PlaylistLoaderContext> {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n // TODO(typescript-config): Verify once config is typed that InternalLoader always returns a Loader\n const InternalLoader = PLoader || Loader;\n\n const loader = new InternalLoader(config);\n\n // TODO - Do we really need to assign the instance or if the dep has been lost\n context.loader = loader;\n this.loaders[context.type] = loader;\n\n return loader;\n }\n\n getInternalLoader (context: PlaylistLoaderContext): Loader<PlaylistLoaderContext> | undefined {\n return this.loaders[context.type];\n }\n\n resetInternalLoader (contextType: PlaylistContextType) {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n destroyInternalLoaders () {\n for (let contextType in this.loaders) {\n let loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType as PlaylistContextType);\n }\n }\n\n destroy () {\n this.destroyInternalLoaders();\n\n super.destroy();\n }\n\n onManifestLoading (data: { url: string; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.MANIFEST,\n level: 0,\n id: null,\n responseType: 'text'\n });\n }\n\n onLevelLoading (data: { url: string; level: number | null; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.LEVEL,\n level: data.level,\n id: data.id,\n responseType: 'text'\n });\n }\n\n onAudioTrackLoading (data: { url: string; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.AUDIO_TRACK,\n level: null,\n id: data.id,\n responseType: 'text'\n });\n }\n\n onSubtitleTrackLoading (data: { url: string; id: number | null; }) {\n this.load({\n url: data.url,\n type: PlaylistContextType.SUBTITLE_TRACK,\n level: null,\n id: data.id,\n responseType: 'text'\n });\n }\n\n load (context: PlaylistLoaderContext): boolean {\n const config = this.hls.config;\n\n logger.debug(`Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === context.url) { // same URL can't overlap\n logger.trace('playlist request ongoing');\n return false;\n } else {\n logger.warn(`aborting previous loader for type: ${context.type}`);\n loader.abort();\n }\n }\n\n let maxRetry: number;\n let timeout: number;\n let retryDelay: number;\n let maxRetryDelay: number;\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n maxRetry = config.manifestLoadingMaxRetry;\n timeout = config.manifestLoadingTimeOut;\n retryDelay = config.manifestLoadingRetryDelay;\n maxRetryDelay = config.manifestLoadingMaxRetryTimeout;\n break;\n case PlaylistContextType.LEVEL:\n // Disable internal loader retry logic, since we are managing retries in Level Controller\n maxRetry = 0;\n maxRetryDelay = 0;\n retryDelay = 0;\n timeout = config.levelLoadingTimeOut;\n // TODO Introduce retry settings for audio-track and subtitle-track, it should not use level retry config\n break;\n default:\n maxRetry = config.levelLoadingMaxRetry;\n timeout = config.levelLoadingTimeOut;\n retryDelay = config.levelLoadingRetryDelay;\n maxRetryDelay = config.levelLoadingMaxRetryTimeout;\n break;\n }\n\n loader = this.createInternalLoader(context);\n\n const loaderConfig: LoaderConfiguration = {\n timeout,\n maxRetry,\n retryDelay,\n maxRetryDelay\n };\n\n const loaderCallbacks: LoaderCallbacks<PlaylistLoaderContext> = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n logger.debug(`Calling internal loader delegate for URL: ${context.url}`);\n loader.load(context, loaderConfig, loaderCallbacks);\n\n return true;\n }\n\n loadsuccess (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown = null) {\n if (context.isSidxRequest) {\n this._handleSidxRequest(response, context);\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n return;\n }\n\n this.resetInternalLoader(context.type);\n if (typeof response.data !== 'string') {\n throw new Error('expected responseType of \"text\" for PlaylistLoader');\n }\n\n const string = response.data;\n\n stats.tload = performance.now();\n // stats.mtime = new Date(target.getResponseHeader('Last-Modified'));\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this._handleManifestParsingError(response, context, 'no EXTM3U delimiter', networkDetails);\n return;\n }\n\n // Check if chunk-list or master. handle empty chunk list case (first EXTINF not signaled, but TARGETDURATION present)\n if (string.indexOf('#EXTINF:') > 0 || string.indexOf('#EXT-X-TARGETDURATION:') > 0) {\n this._handleTrackOrLevelPlaylist(response, stats, context, networkDetails);\n } else {\n this._handleMasterPlaylist(response, stats, context, networkDetails);\n }\n }\n\n loaderror (response: LoaderResponse, context: PlaylistLoaderContext, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, false, response);\n }\n\n loadtimeout (stats: LoaderStats, context: PlaylistLoaderContext, networkDetails = null) {\n this._handleNetworkError(context, networkDetails, true);\n }\n\n // TODO(typescript-config): networkDetails can currently be a XHR or Fetch impl,\n // but with custom loaders it could be generic investigate this further when config is typed\n _handleMasterPlaylist (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const hls = this.hls;\n const string = response.data as string;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n const { levels, sessionData } = M3U8Parser.parseMasterPlaylist(string, url);\n if (!levels.length) {\n this._handleManifestParsingError(response, context, 'no level found in manifest', networkDetails);\n return;\n }\n\n // multi level playlist, parse level info\n const audioGroups: Array<AudioGroup> = levels.map(level => ({\n id: level.attrs.AUDIO,\n codec: level.audioCodec\n }));\n\n const audioTracks = M3U8Parser.parseMasterPlaylistMedia(string, url, 'AUDIO', audioGroups);\n const subtitles = M3U8Parser.parseMasterPlaylistMedia(string, url, 'SUBTITLES');\n const captions = M3U8Parser.parseMasterPlaylistMedia(string, url, 'CLOSED-CAPTIONS');\n\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n let embeddedAudioFound = false;\n audioTracks.forEach(audioTrack => {\n if (!audioTrack.url) {\n embeddedAudioFound = true;\n }\n });\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (embeddedAudioFound === false && levels[0].audioCodec && !levels[0].attrs.AUDIO) {\n logger.log('audio codec signaled in quality level, but no embedded audio track signaled, create one');\n audioTracks.unshift({\n type: 'main',\n name: 'main',\n default: false,\n autoselect: false,\n forced: false,\n id: -1,\n attrs: {},\n url: ''\n });\n }\n }\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n captions,\n url,\n stats,\n networkDetails,\n sessionData\n });\n }\n\n _handleTrackOrLevelPlaylist (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const hls = this.hls;\n\n const { id, level, type } = context;\n\n const url = PlaylistLoader.getResponseUrl(response, context);\n\n // if the values are null, they will result in the else conditional\n const levelUrlId = Number.isFinite(id as number) ? id as number : 0;\n const levelId = Number.isFinite(level as number) ? level as number : levelUrlId;\n\n const levelType = PlaylistLoader.mapContextToLevelType(context);\n const levelDetails = M3U8Parser.parseLevelPlaylist(response.data as string, url, levelId, levelType, levelUrlId);\n\n // set stats on level structure\n // TODO(jstackhouse): why? mixing concerns, is it just treated as value bag?\n (levelDetails as any).tload = stats.tload;\n\n if (!levelDetails.fragments.length) {\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_EMPTY_ERROR,\n fatal: false,\n url: url,\n reason: 'no fragments found in level',\n level: typeof context.level === 'number' ? context.level : undefined\n });\n return;\n }\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === PlaylistContextType.MANIFEST) {\n const singleLevel = {\n url,\n details: levelDetails\n };\n\n hls.trigger(Event.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails,\n sessionData: null\n });\n }\n\n // save parsing time\n stats.tparsed = performance.now();\n\n // in case we need SIDX ranges\n // return early after calling load for\n // the SIDX box.\n if (levelDetails.needSidxRanges) {\n const sidxUrl = levelDetails.initSegment.url;\n this.load({\n url: sidxUrl,\n isSidxRequest: true,\n type,\n level,\n levelDetails,\n id,\n rangeStart: 0,\n rangeEnd: 2048,\n responseType: 'arraybuffer'\n });\n return;\n }\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this._handlePlaylistLoaded(response, stats, context, networkDetails);\n }\n\n _handleSidxRequest (response: LoaderResponse, context: PlaylistLoaderContext) {\n if (typeof response.data === 'string') {\n throw new Error('sidx request must be made with responseType of array buffer');\n }\n\n const sidxInfo = MP4Demuxer.parseSegmentIndex(new Uint8Array(response.data));\n // if provided fragment does not contain sidx, early return\n if (!sidxInfo) {\n return;\n }\n const sidxReferences = sidxInfo.references;\n const levelDetails = context.levelDetails;\n sidxReferences.forEach((segmentRef, index) => {\n const segRefInfo = segmentRef.info;\n if (!levelDetails) {\n return;\n }\n const frag = levelDetails.fragments[index];\n if (frag.byteRange.length === 0) {\n frag.setByteRange(String(1 + segRefInfo.end - segRefInfo.start) + '@' + String(segRefInfo.start));\n }\n });\n\n if (levelDetails) {\n levelDetails.initSegment.setByteRange(String(sidxInfo.moovEndOffset) + '@0');\n }\n }\n\n _handleManifestParsingError (response: LoaderResponse, context: PlaylistLoaderContext, reason: string, networkDetails: unknown) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: true,\n url: response.url,\n reason,\n networkDetails\n });\n }\n\n _handleNetworkError (context: PlaylistLoaderContext, networkDetails: unknown, timeout: boolean = false, response: LoaderResponse | null = null) {\n logger.info(`A network error occured while loading a ${context.type}-type playlist`);\n\n let details;\n let fatal;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n details = (timeout ? ErrorDetails.MANIFEST_LOAD_TIMEOUT : ErrorDetails.MANIFEST_LOAD_ERROR);\n fatal = true;\n break;\n case PlaylistContextType.LEVEL:\n details = (timeout ? ErrorDetails.LEVEL_LOAD_TIMEOUT : ErrorDetails.LEVEL_LOAD_ERROR);\n fatal = false;\n break;\n case PlaylistContextType.AUDIO_TRACK:\n details = (timeout ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT : ErrorDetails.AUDIO_TRACK_LOAD_ERROR);\n fatal = false;\n break;\n default:\n // details = ...?\n fatal = false;\n }\n\n if (loader) {\n loader.abort();\n this.resetInternalLoader(context.type);\n }\n\n // TODO(typescript-events): when error events are handled, type this\n let errorData: any = {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: context.url,\n loader,\n context,\n networkDetails\n };\n\n if (response) {\n errorData.response = response;\n }\n\n this.hls.trigger(Event.ERROR, errorData);\n }\n\n _handlePlaylistLoaded (response: LoaderResponse, stats: LoaderStats, context: PlaylistLoaderContext, networkDetails: unknown) {\n const { type, level, id, levelDetails } = context;\n\n if (!levelDetails || !levelDetails.targetduration) {\n this._handleManifestParsingError(response, context, 'invalid target duration', networkDetails);\n return;\n }\n\n const canHaveLevels = PlaylistLoader.canHaveQualityLevels(context.type);\n if (canHaveLevels) {\n this.hls.trigger(Event.LEVEL_LOADED, {\n details: levelDetails,\n level: level || 0,\n id: id || 0,\n stats,\n networkDetails\n });\n } else {\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n this.hls.trigger(Event.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n this.hls.trigger(Event.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id,\n stats,\n networkDetails\n });\n break;\n }\n }\n }\n}\n\nexport default PlaylistLoader;\n","/*\n * Fragment Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\n\nclass FragmentLoader extends EventHandler {\n constructor (hls) {\n super(hls, Event.FRAG_LOADING);\n this.loaders = {};\n }\n\n destroy () {\n let loaders = this.loaders;\n for (let loaderName in loaders) {\n let loader = loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n\n super.destroy();\n }\n\n onFragLoading (data) {\n const frag = data.frag,\n type = frag.type,\n loaders = this.loaders,\n config = this.hls.config,\n FragmentILoader = config.fLoader,\n DefaultILoader = config.loader;\n\n // reset fragment state\n frag.loaded = 0;\n\n let loader = loaders[type];\n if (loader) {\n logger.warn(`abort previous fragment loader for type: ${type}`);\n loader.abort();\n }\n\n loader = loaders[type] = frag.loader =\n config.fLoader ? new FragmentILoader(config) : new DefaultILoader(config);\n\n let loaderContext, loaderConfig, loaderCallbacks;\n\n loaderContext = { url: frag.url, frag: frag, responseType: 'arraybuffer', progressData: false };\n\n let start = frag.byteRangeStartOffset,\n end = frag.byteRangeEndOffset;\n\n if (Number.isFinite(start) && Number.isFinite(end)) {\n loaderContext.rangeStart = start;\n loaderContext.rangeEnd = end;\n }\n\n loaderConfig = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n loaderCallbacks = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this),\n onProgress: this.loadprogress.bind(this)\n };\n\n loader.load(loaderContext, loaderConfig, loaderCallbacks);\n }\n\n loadsuccess (response, stats, context, networkDetails = null) {\n let payload = response.data, frag = context.frag;\n // detach fragment loader on load success\n frag.loader = undefined;\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.FRAG_LOADED, { payload: payload, frag: frag, stats: stats, networkDetails: networkDetails });\n }\n\n loaderror (response, context, networkDetails = null) {\n const frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_ERROR, fatal: false, frag: context.frag, response: response, networkDetails: networkDetails });\n }\n\n loadtimeout (stats, context, networkDetails = null) {\n const frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n this.loaders[frag.type] = undefined;\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.FRAG_LOAD_TIMEOUT, fatal: false, frag: context.frag, networkDetails: networkDetails });\n }\n\n // data will be used for progressive parsing\n loadprogress (stats, context, data, networkDetails = null) { // jshint ignore:line\n let frag = context.frag;\n frag.loaded = stats.loaded;\n this.hls.trigger(Event.FRAG_LOAD_PROGRESS, { frag: frag, stats: stats, networkDetails: networkDetails });\n }\n}\n\nexport default FragmentLoader;\n","/*\n * Decrypt key Loader\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport Hls from '../hls';\nimport Fragment from './fragment';\nimport { LoaderStats, LoaderResponse, LoaderContext, LoaderConfiguration, LoaderCallbacks } from '../types/loader';\n\ninterface OnKeyLoadingPayload {\n frag: Fragment\n}\n\ninterface KeyLoaderContext extends LoaderContext {\n frag: Fragment\n}\n\nclass KeyLoader extends EventHandler {\n public loaders = {};\n public decryptkey: Uint8Array | null = null;\n public decrypturl: string | null = null;\n\n constructor (hls: Hls) {\n super(hls, Event.KEY_LOADING);\n }\n\n destroy (): void {\n for (const loaderName in this.loaders) {\n let loader = this.loaders[loaderName];\n if (loader) {\n loader.destroy();\n }\n }\n this.loaders = {};\n\n super.destroy();\n }\n\n onKeyLoading (data: OnKeyLoadingPayload) {\n const { frag } = data;\n const type = frag.type;\n const loader = this.loaders[type];\n if (!frag.decryptdata) {\n logger.warn('Missing decryption data on fragment in onKeyLoading');\n return;\n }\n\n // Load the key if the uri is different from previous one, or if the decrypt key has not yet been retrieved\n const uri = frag.decryptdata.uri;\n if (uri !== this.decrypturl || this.decryptkey === null) {\n let config = this.hls.config;\n if (loader) {\n logger.warn(`abort previous key loader for type:${type}`);\n loader.abort();\n }\n if (!uri) {\n logger.warn('key uri is falsy');\n return;\n }\n\n frag.loader = this.loaders[type] = new config.loader(config);\n this.decrypturl = uri;\n this.decryptkey = null;\n\n const loaderContext: KeyLoaderContext = {\n url: uri,\n frag: frag,\n responseType: 'arraybuffer'\n };\n\n // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,\n // key-loader will trigger an error and rely on stream-controller to handle retry logic.\n // this will also align retry logic with fragment-loader\n const loaderConfig: LoaderConfiguration = {\n timeout: config.fragLoadingTimeOut,\n maxRetry: 0,\n retryDelay: config.fragLoadingRetryDelay,\n maxRetryDelay: config.fragLoadingMaxRetryTimeout\n };\n\n const loaderCallbacks: LoaderCallbacks<KeyLoaderContext> = {\n onSuccess: this.loadsuccess.bind(this),\n onError: this.loaderror.bind(this),\n onTimeout: this.loadtimeout.bind(this)\n };\n\n frag.loader.load(loaderContext, loaderConfig, loaderCallbacks);\n } else if (this.decryptkey) {\n // Return the key if it's already been loaded\n frag.decryptdata.key = this.decryptkey;\n this.hls.trigger(Event.KEY_LOADED, { frag: frag });\n }\n }\n\n loadsuccess (response: LoaderResponse, stats: LoaderStats, context: KeyLoaderContext) {\n let frag = context.frag;\n if (!frag.decryptdata) {\n logger.error('after key load, decryptdata unset');\n return;\n }\n this.decryptkey = frag.decryptdata.key = new Uint8Array(response.data as ArrayBuffer);\n\n // detach fragment loader on load success\n frag.loader = undefined;\n delete this.loaders[frag.type];\n this.hls.trigger(Event.KEY_LOADED, { frag: frag });\n }\n\n loaderror (response: LoaderResponse, context: KeyLoaderContext) {\n let frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n delete this.loaders[frag.type];\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_ERROR, fatal: false, frag, response });\n }\n\n loadtimeout (stats: LoaderStats, context: KeyLoaderContext) {\n let frag = context.frag;\n let loader = frag.loader;\n if (loader) {\n loader.abort();\n }\n\n delete this.loaders[frag.type];\n this.hls.trigger(Event.ERROR, { type: ErrorTypes.NETWORK_ERROR, details: ErrorDetails.KEY_LOAD_TIMEOUT, fatal: false, frag });\n }\n}\n\nexport default KeyLoader;\n","import EventHandler from '../event-handler';\nimport Event from '../events';\n\nexport const FragmentState = {\n NOT_LOADED: 'NOT_LOADED',\n APPENDING: 'APPENDING',\n PARTIAL: 'PARTIAL',\n OK: 'OK'\n};\n\nexport class FragmentTracker extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.BUFFER_APPENDED,\n Event.FRAG_BUFFERED,\n Event.FRAG_LOADED\n );\n\n this.bufferPadding = 0.2;\n\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n\n this.config = hls.config;\n }\n\n destroy () {\n this.fragments = Object.create(null);\n this.timeRanges = Object.create(null);\n this.config = null;\n EventHandler.prototype.destroy.call(this);\n super.destroy();\n }\n\n /**\n * Return a Fragment that match the position and levelType.\n * If not found any Fragment, return null\n * @param {number} position\n * @param {LevelType} levelType\n * @returns {Fragment|null}\n */\n getBufferedFrag (position, levelType) {\n const fragments = this.fragments;\n const bufferedFrags = Object.keys(fragments).filter(key => {\n const fragmentEntity = fragments[key];\n if (fragmentEntity.body.type !== levelType) {\n return false;\n }\n\n if (!fragmentEntity.buffered) {\n return false;\n }\n\n const frag = fragmentEntity.body;\n return frag.startPTS <= position && position <= frag.endPTS;\n });\n if (bufferedFrags.length === 0) {\n return null;\n } else {\n // https://github.com/video-dev/hls.js/pull/1545#discussion_r166229566\n const bufferedFragKey = bufferedFrags.pop();\n return fragments[bufferedFragKey].body;\n }\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * 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)\n * @param {String} elementaryStream The elementaryStream of media this is (eg. video/audio)\n * @param {TimeRanges} timeRange TimeRange object from a sourceBuffer\n */\n detectEvictedFragments (elementaryStream, timeRange) {\n // Check if any flagged fragments have been unloaded\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity || !fragmentEntity.buffered) {\n return;\n }\n const esData = fragmentEntity.range[elementaryStream];\n if (!esData) {\n return;\n }\n const fragmentTimes = esData.time;\n for (let i = 0; i < fragmentTimes.length; i++) {\n const time = fragmentTimes[i];\n if (!this.isTimeBuffered(time.startPTS, time.endPTS, timeRange)) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n break;\n }\n }\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n * @param {Object} fragment Check the fragment against all sourceBuffers loaded\n */\n detectPartialFragments (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n if (fragmentEntity) {\n fragmentEntity.buffered = true;\n\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n if (fragment.hasElementaryStream(elementaryStream)) {\n let timeRange = this.timeRanges[elementaryStream];\n // Check for malformed fragments\n // Gaps need to be calculated for each elementaryStream\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(fragment.startPTS, fragment.endPTS, timeRange);\n }\n });\n }\n }\n\n getBufferedTimes (startPTS, endPTS, timeRange) {\n let fragmentTimes = [];\n let startTime, endTime;\n let fragmentPartial = false;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n // Check for intersection with buffer\n // Get playable sections of the fragment\n fragmentTimes.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i))\n });\n fragmentPartial = true;\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n\n return {\n time: fragmentTimes,\n partial: fragmentPartial\n };\n }\n\n getFragmentKey (fragment) {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n }\n\n /**\n * Gets the partial fragment for a certain time\n * @param {Number} time\n * @returns {Object} fragment Returns a partial fragment at a time or null if there is no partial fragment\n */\n getPartialFragment (time) {\n let timePadding, startTime, endTime;\n let bestFragment = null;\n let bestOverlap = 0;\n Object.keys(this.fragments).forEach(key => {\n const fragmentEntity = this.fragments[key];\n if (this.isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.startPTS - this.bufferPadding;\n endTime = fragmentEntity.body.endPTS + this.bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n /**\n * @param {Object} fragment The fragment to check\n * @returns {String} Returns the fragment state when a fragment never loaded or if it partially loaded\n */\n getState (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n let fragmentEntity = this.fragments[fragKey];\n let state = FragmentState.NOT_LOADED;\n\n if (fragmentEntity !== undefined) {\n if (!fragmentEntity.buffered) {\n state = FragmentState.APPENDING;\n } else if (this.isPartial(fragmentEntity) === true) {\n state = FragmentState.PARTIAL;\n } else {\n state = FragmentState.OK;\n }\n }\n\n return state;\n }\n\n isPartial (fragmentEntity) {\n return fragmentEntity.buffered === true &&\n ((fragmentEntity.range.video !== undefined && fragmentEntity.range.video.partial === true) ||\n (fragmentEntity.range.audio !== undefined && fragmentEntity.range.audio.partial === true));\n }\n\n isTimeBuffered (startPTS, endPTS, timeRange) {\n let startTime, endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n /**\n * Fires when a fragment loading is completed\n */\n onFragLoaded (e) {\n const fragment = e.frag;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (!Number.isFinite(fragment.sn) || fragment.bitrateTest) {\n return;\n }\n\n this.fragments[this.getFragmentKey(fragment)] = {\n body: fragment,\n range: Object.create(null),\n buffered: false\n };\n }\n\n /**\n * Fires when the buffer is updated\n */\n onBufferAppended (e) {\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = e.timeRanges;\n Object.keys(this.timeRanges).forEach(elementaryStream => {\n let timeRange = this.timeRanges[elementaryStream];\n this.detectEvictedFragments(elementaryStream, timeRange);\n });\n }\n\n /**\n * Fires after a fragment has been loaded into the source buffer\n */\n onFragBuffered (e) {\n this.detectPartialFragments(e.frag);\n }\n\n /**\n * Return true if fragment tracker has the fragment.\n * @param {Object} fragment\n * @returns {boolean}\n */\n hasFragment (fragment) {\n const fragKey = this.getFragmentKey(fragment);\n return this.fragments[fragKey] !== undefined;\n }\n\n /**\n * Remove a fragment from fragment tracker until it is loaded again\n * @param {Object} fragment The fragment to remove\n */\n removeFragment (fragment) {\n let fragKey = this.getFragmentKey(fragment);\n delete this.fragments[fragKey];\n }\n\n /**\n * Remove all fragments from fragment tracker.\n */\n removeAllFragments () {\n this.fragments = Object.create(null);\n }\n}\n","type BinarySearchComparison < T > = (candidate: T) => -1 | 0 | 1;\n\nconst BinarySearch = {\n\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param {Array<T>} list The array to search.\n * @param {BinarySearchComparison<T>} comparisonFn\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @return {T | null} The object if it is found or null otherwise.\n */\n search: function<T> (list: T[], comparisonFn: BinarySearchComparison<T>): T | null {\n let minIndex: number = 0;\n let maxIndex: number = list.length - 1;\n let currentIndex: number | null = null;\n let currentElement: T | null = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = (minIndex + maxIndex) / 2 | 0;\n currentElement = list[currentIndex];\n\n let comparisonResult = comparisonFn(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n\n return null;\n }\n};\n\nexport default BinarySearch;\n","/**\n * @module BufferHelper\n *\n * Providing methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n*/\n\ntype BufferTimeRange = {\n start: number\n end: number\n};\n\ntype Bufferable = {\n buffered: TimeRanges\n};\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n * @param {Bufferable} media\n * @param {number} position\n * @returns {boolean}\n */\n static isBuffered (media: Bufferable, position: number): boolean {\n try {\n if (media) {\n let buffered = media.buffered;\n for (let i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo (\n media: Bufferable,\n pos: number,\n maxHoleDuration: number\n ): {\n len: number,\n start: number,\n end: number,\n nextStart?: number,\n } {\n try {\n if (media) {\n let vbuffered = media.buffered;\n let buffered: BufferTimeRange[] = [];\n let i: number;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });\n }\n\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo (\n buffered: BufferTimeRange[],\n pos: number,\n maxHoleDuration: number\n ): {\n len: number,\n start: number,\n end: number,\n nextStart?: number,\n } {\n // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n buffered.sort(function (a, b) {\n let diff = a.start - b.start;\n if (diff) {\n return diff;\n } else {\n return b.end - a.end;\n }\n });\n\n let buffered2: BufferTimeRange[] = [];\n if (maxHoleDuration) {\n // there might be some small holes between buffer time range\n // consider that holes smaller than maxHoleDuration are irrelevant and build another\n // buffer time range representations that discards those holes\n for (let i = 0; i < buffered.length; i++) {\n let buf2len = buffered2.length;\n if (buf2len) {\n let buf2end = buffered2[buf2len - 1].end;\n // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n if ((buffered[i].start - buf2end) < maxHoleDuration) {\n // merge overlapping time ranges\n // update lastRange.end only if smaller than item.end\n // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n if (buffered[i].end > buf2end) {\n buffered2[buf2len - 1].end = buffered[i].end;\n }\n } else {\n // big hole\n buffered2.push(buffered[i]);\n }\n } else {\n // first value\n buffered2.push(buffered[i]);\n }\n }\n } else {\n buffered2 = buffered;\n }\n\n let bufferLen = 0;\n\n // bufferStartNext can possibly be undefined based on the conditional logic below\n let bufferStartNext: number | undefined;\n\n // bufferStart and bufferEnd are buffer boundaries around current video position\n let bufferStart: number = pos;\n let bufferEnd: number = pos;\n for (let i = 0; i < buffered2.length; i++) {\n let start = buffered2[i].start,\n end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if ((pos + maxHoleDuration) >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if ((pos + maxHoleDuration) < start) {\n bufferStartNext = start;\n break;\n }\n }\n return { len: bufferLen, start: bufferStart, end: bufferEnd, nextStart: bufferStartNext };\n }\n}\n","/**\n * MediaSource helper\n */\n\nexport function getMediaSource (): typeof MediaSource | undefined {\n return (window as any).MediaSource || (window as any).WebKitMediaSource;\n}\n","import { EventEmitter } from 'eventemitter3';\n\n/**\n * Simple adapter sub-class of Nodejs-like EventEmitter.\n */\nexport class Observer extends EventEmitter {\n /**\n * We simply want to pass along the event-name itself\n * in every call to a handler, which is the purpose of our `trigger` method\n * extending the standard API.\n */\n trigger (event: string, ...data: Array<any>): void {\n this.emit(event, event, ...data);\n }\n}\n","import { EventEmitter } from 'eventemitter3';\nimport * as work from 'webworkify-webpack';\n\nimport Event from '../events';\nimport DemuxerInline from '../demux/demuxer-inline';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { getSelfScope } from '../utils/get-self-scope';\n\nimport { Observer } from '../observer';\n\n// see https://stackoverflow.com/a/11237259/589493\nconst global = getSelfScope(); // safeguard for code that might run both on worker and main thread\nconst MediaSource = getMediaSource() || { isTypeSupported: () => false };\n\nclass Demuxer {\n constructor (hls, id) {\n this.hls = hls;\n this.id = id;\n\n const observer = this.observer = new Observer();\n const config = hls.config;\n\n const forwardMessage = (ev, data) => {\n data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n hls.trigger(ev, data);\n };\n\n // forward events to main thread\n observer.on(Event.FRAG_DECRYPTED, forwardMessage);\n observer.on(Event.FRAG_PARSING_INIT_SEGMENT, forwardMessage);\n observer.on(Event.FRAG_PARSING_DATA, forwardMessage);\n observer.on(Event.FRAG_PARSED, forwardMessage);\n observer.on(Event.ERROR, forwardMessage);\n observer.on(Event.FRAG_PARSING_METADATA, forwardMessage);\n observer.on(Event.FRAG_PARSING_USERDATA, forwardMessage);\n observer.on(Event.INIT_PTS_FOUND, forwardMessage);\n\n const typeSupported = {\n mp4: MediaSource.isTypeSupported('video/mp4'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"')\n };\n // navigator.vendor is not always available in Web Worker\n // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n const vendor = navigator.vendor;\n if (config.enableWorker && (typeof (Worker) !== 'undefined')) {\n logger.log('demuxing in webworker');\n let w;\n try {\n w = this.w = work(require.resolve('../demux/demuxer-worker.js'));\n this.onwmsg = this.onWorkerMessage.bind(this);\n w.addEventListener('message', this.onwmsg);\n w.onerror = function (event) {\n hls.trigger(Event.ERROR, { type: ErrorTypes.OTHER_ERROR, details: ErrorDetails.INTERNAL_EXCEPTION, fatal: true, event: 'demuxerWorker', err: { message: event.message + ' (' + event.filename + ':' + event.lineno + ')' } });\n };\n w.postMessage({ cmd: 'init', typeSupported: typeSupported, vendor: vendor, id: id, config: JSON.stringify(config) });\n } catch (err) {\n logger.warn('Error in worker:', err);\n logger.error('Error while initializing DemuxerWorker, fallback on DemuxerInline');\n if (w) {\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n global.URL.revokeObjectURL(w.objectURL);\n }\n this.demuxer = new DemuxerInline(observer, typeSupported, config, vendor);\n this.w = undefined;\n }\n } else {\n this.demuxer = new DemuxerInline(observer, typeSupported, config, vendor);\n }\n }\n\n destroy () {\n let w = this.w;\n if (w) {\n w.removeEventListener('message', this.onwmsg);\n w.terminate();\n this.w = null;\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.destroy();\n this.demuxer = null;\n }\n }\n const observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n this.observer = null;\n }\n }\n\n push (data, initSegment, audioCodec, videoCodec, frag, duration, accurateTimeOffset, defaultInitPTS) {\n const w = this.w;\n const timeOffset = Number.isFinite(frag.startPTS) ? frag.startPTS : frag.start;\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n const discontinuity = !(lastFrag && (frag.cc === lastFrag.cc));\n const trackSwitch = !(lastFrag && (frag.level === lastFrag.level));\n const nextSN = lastFrag && (frag.sn === (lastFrag.sn + 1));\n const contiguous = !trackSwitch && nextSN;\n if (discontinuity) {\n logger.log(`${this.id}:discontinuity detected`);\n }\n\n if (trackSwitch) {\n logger.log(`${this.id}:switch detected`);\n }\n\n this.frag = frag;\n if (w) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n w.postMessage({ cmd: 'demux', data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS }, data instanceof ArrayBuffer ? [data] : []);\n } else {\n let demuxer = this.demuxer;\n if (demuxer) {\n demuxer.push(data, decryptdata, initSegment, audioCodec, videoCodec, timeOffset, discontinuity, trackSwitch, contiguous, duration, accurateTimeOffset, defaultInitPTS);\n }\n }\n }\n\n onWorkerMessage (ev) {\n let data = ev.data,\n hls = this.hls;\n switch (data.event) {\n case 'init':\n // revoke the Object URL that was used to create demuxer worker, so as not to leak it\n global.URL.revokeObjectURL(this.w.objectURL);\n break;\n // special case for FRAG_PARSING_DATA: data1 and data2 are transferable objects\n case Event.FRAG_PARSING_DATA:\n data.data.data1 = new Uint8Array(data.data1);\n if (data.data2) {\n data.data.data2 = new Uint8Array(data.data2);\n }\n\n /* falls through */\n default:\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\n hls.trigger(data.event, data.data);\n break;\n }\n }\n}\n\nexport default Demuxer;\n","/**\n * @module LevelHelper\n *\n * Providing methods dealing with playlist sliding and drift\n *\n * TODO: Create an actual `Level` class/model that deals with all this logic in an object-oriented-manner.\n *\n * */\n\nimport { logger } from '../utils/logger';\n\nexport function addGroupId (level, type, id) {\n switch (type) {\n case 'audio':\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds.push(id);\n break;\n case 'text':\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds.push(id);\n break;\n }\n}\n\nexport function updatePTS (fragments, fromIdx, toIdx) {\n let fragFrom = fragments[fromIdx], fragTo = fragments[toIdx], fragToPTS = fragTo.startPTS;\n // if we know startPTS[toIdx]\n if (Number.isFinite(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n if (toIdx > fromIdx) {\n fragFrom.duration = fragToPTS - fragFrom.start;\n if (fragFrom.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragFrom.sn},level ${fragFrom.level}, there should be some duration drift between playlist and fragment!`);\n }\n } else {\n fragTo.duration = fragFrom.start - fragToPTS;\n if (fragTo.duration < 0) {\n logger.warn(`negative duration computed for frag ${fragTo.sn},level ${fragTo.level}, there should be some duration drift between playlist and fragment!`);\n }\n }\n } else {\n // we dont know startPTS[toIdx]\n if (toIdx > fromIdx) {\n const contiguous = fragFrom.cc === fragTo.cc;\n fragTo.start = fragFrom.start + ((contiguous && fragFrom.minEndPTS) ? fragFrom.minEndPTS - fragFrom.start : fragFrom.duration);\n } else {\n fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n }\n}\n\nexport function updateFragPTSDTS (details, frag, startPTS, endPTS, startDTS, endDTS) {\n // update frag PTS/DTS\n let maxStartPTS = startPTS;\n let minEndPTS = endPTS;\n if (Number.isFinite(frag.startPTS)) {\n // delta PTS between audio and video\n let deltaPTS = Math.abs(frag.startPTS - startPTS);\n if (!Number.isFinite(frag.deltaPTS)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS);\n }\n\n maxStartPTS = Math.max(startPTS, frag.startPTS);\n startPTS = Math.min(startPTS, frag.startPTS);\n minEndPTS = Math.min(endPTS, frag.endPTS);\n endPTS = Math.max(endPTS, frag.endPTS);\n startDTS = Math.min(startDTS, frag.startDTS);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n const drift = startPTS - frag.start;\n frag.start = frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.endPTS = endPTS;\n frag.minEndPTS = minEndPTS;\n frag.startDTS = startDTS;\n frag.endDTS = endDTS;\n frag.duration = endPTS - startPTS;\n\n const sn = frag.sn;\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n\n let fragIdx, fragments, i;\n fragIdx = sn - details.startSN;\n fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updatePTS(fragments, i, i - 1);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updatePTS(fragments, i, i + 1);\n }\n\n details.PTSKnown = true;\n return drift;\n}\n\nexport function mergeDetails (oldDetails, newDetails) {\n // potentially retrieve cached initsegment\n if (newDetails.initSegment && oldDetails.initSegment) {\n newDetails.initSegment = oldDetails.initSegment;\n }\n\n // check if old/new playlists have fragments in common\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n let ccOffset = 0;\n let PTSFrag;\n mapFragmentIntersection(oldDetails, newDetails, (oldFrag, newFrag) => {\n ccOffset = oldFrag.cc - newFrag.cc;\n if (Number.isFinite(oldFrag.startPTS)) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS;\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.duration = oldFrag.duration;\n newFrag.backtracked = oldFrag.backtracked;\n newFrag.dropped = oldFrag.dropped;\n PTSFrag = newFrag;\n }\n // PTS is known when there are overlapping segments\n newDetails.PTSKnown = true;\n });\n\n if (!newDetails.PTSKnown) {\n return;\n }\n\n if (ccOffset) {\n logger.log('discontinuity sliding from playlist, take drift into account');\n const newFragments = newDetails.fragments;\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n }\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(newDetails, PTSFrag, PTSFrag.startPTS, PTSFrag.endPTS, PTSFrag.startDTS, PTSFrag.endDTS);\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n // if we are here, it means we have fragments overlapping between\n // old and new level. reliable PTS info is thus relying on old level\n newDetails.PTSKnown = oldDetails.PTSKnown;\n}\n\nexport function mergeSubtitlePlaylists (oldPlaylist, newPlaylist, referenceStart = 0) {\n let lastIndex = -1;\n mapFragmentIntersection(oldPlaylist, newPlaylist, (oldFrag, newFrag, index) => {\n newFrag.start = oldFrag.start;\n lastIndex = index;\n });\n\n const frags = newPlaylist.fragments;\n if (lastIndex < 0) {\n frags.forEach(frag => {\n frag.start += referenceStart;\n });\n return;\n }\n\n for (let i = lastIndex + 1; i < frags.length; i++) {\n frags[i].start = (frags[i - 1].start + frags[i - 1].duration);\n }\n}\n\nexport function mapFragmentIntersection (oldPlaylist, newPlaylist, intersectionFn) {\n if (!oldPlaylist || !newPlaylist) {\n return;\n }\n\n const start = Math.max(oldPlaylist.startSN, newPlaylist.startSN) - newPlaylist.startSN;\n const end = Math.min(oldPlaylist.endSN, newPlaylist.endSN) - newPlaylist.startSN;\n const delta = newPlaylist.startSN - oldPlaylist.startSN;\n\n for (let i = start; i <= end; i++) {\n const oldFrag = oldPlaylist.fragments[delta + i];\n const newFrag = newPlaylist.fragments[i];\n if (!oldFrag || !newFrag) {\n break;\n }\n intersectionFn(oldFrag, newFrag, i);\n }\n}\n\nexport function adjustSliding (oldPlaylist, newPlaylist) {\n const delta = newPlaylist.startSN - oldPlaylist.startSN;\n const oldFragments = oldPlaylist.fragments;\n const newFragments = newPlaylist.fragments;\n\n if (delta < 0 || delta > oldFragments.length) {\n return;\n }\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].start += oldFragments[delta].start;\n }\n}\n\nexport function computeReloadInterval (currentPlaylist, newPlaylist, lastRequestTime) {\n let reloadInterval = 1000 * (newPlaylist.averagetargetduration ? newPlaylist.averagetargetduration : newPlaylist.targetduration);\n const minReloadInterval = reloadInterval / 2;\n if (currentPlaylist && newPlaylist.endSN === currentPlaylist.endSN) {\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval = minReloadInterval;\n }\n\n if (lastRequestTime) {\n reloadInterval = Math.max(minReloadInterval, reloadInterval - (window.performance.now() - lastRequestTime));\n }\n // in any case, don't reload more than half of target duration\n return Math.round(reloadInterval);\n}\n","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r: TimeRanges) {\n let log = '';\n let len = r.length;\n for (let i = 0; i < len; i++) {\n log += '[' + r.start(i).toFixed(3) + ',' + r.end(i).toFixed(3) + ']';\n }\n\n return log;\n }\n};\n\nexport default TimeRanges;\n","import BinarySearch from './binary-search';\nimport { logger } from '../utils/logger';\n\nexport function findFirstFragWithCC (fragments, cc) {\n let firstFrag = null;\n\n for (let i = 0; i < fragments.length; i += 1) {\n const currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nexport function findFragWithCC (fragments, CC) {\n return BinarySearch.search(fragments, (candidate) => {\n if (candidate.cc < CC) {\n return 1;\n } else if (candidate.cc > CC) {\n return -1;\n } else {\n return 0;\n }\n });\n}\n\nexport function shouldAlignOnDiscontinuities (lastFrag, lastLevel, details) {\n let shouldAlign = false;\n if (lastLevel && lastLevel.details && details) {\n if (details.endCC > details.startCC || (lastFrag && lastFrag.cc < details.startCC)) {\n shouldAlign = true;\n }\n }\n return shouldAlign;\n}\n\n// Find the first frag in the previous level which matches the CC of the first frag of the new level\nexport function findDiscontinuousReferenceFrag (prevDetails, curDetails) {\n const prevFrags = prevDetails.fragments;\n const curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n logger.log('No fragments to align');\n return;\n }\n\n const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n logger.log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nexport function adjustPts (sliding, details) {\n details.fragments.forEach((frag) => {\n if (frag) {\n let start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n });\n details.PTSKnown = true;\n}\n\n/**\n * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n * contiguous stream with the last fragments.\n * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n * and an extra download.\n * @param lastFrag\n * @param lastLevel\n * @param details\n */\nexport function alignStream (lastFrag, lastLevel, details) {\n alignDiscontinuities(lastFrag, details, lastLevel);\n if (!details.PTSKnown && lastLevel) {\n // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n // discontinuity sequence.\n alignPDT(details, lastLevel.details);\n }\n}\n\n/**\n * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same\n * discontinuity sequence.\n * @param lastLevel - The details of the last loaded level\n * @param details - The details of the new level\n */\nexport function alignDiscontinuities (lastFrag, details, lastLevel) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(lastLevel.details, details);\n if (referenceFrag) {\n logger.log('Adjusting PTS using last level due to CC increase within current level');\n adjustPts(referenceFrag.start, details);\n }\n }\n}\n\n/**\n * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.\n * @param details - The details of the new level\n * @param lastDetails - The details of the last loaded level\n */\nexport function alignPDT (details, lastDetails) {\n if (lastDetails && lastDetails.fragments.length) {\n if (!details.hasProgramDateTime || !lastDetails.hasProgramDateTime) {\n return;\n }\n // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM\n // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM\n // then we can deduce that playlist B sliding is 1000+8 = 1008s\n let lastPDT = lastDetails.fragments[0].programDateTime;\n let newPDT = details.fragments[0].programDateTime;\n // date diff is in ms. frag.start is in seconds\n let sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;\n if (Number.isFinite(sliding)) {\n logger.log(`adjusting PTS using programDateTime delta, sliding:${sliding.toFixed(3)}`);\n adjustPts(sliding, details);\n }\n }\n}\n","import BinarySearch from '../utils/binary-search';\nimport Fragment from '../loader/fragment';\n\n/**\n * Returns first fragment whose endPdt value exceeds the given PDT.\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number|null} [PDTValue = null] - The PDT value which must be exceeded\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns {*|null} fragment - The best matching fragment\n */\nexport function findFragmentByPDT (fragments: Array<Fragment>, PDTValue: number | null, maxFragLookUpTolerance: number): Fragment | null {\n if (PDTValue === null || !Array.isArray(fragments) || !fragments.length || !Number.isFinite(PDTValue)) {\n return null;\n }\n\n // if less than start\n const startPDT = fragments[0].programDateTime;\n if (PDTValue < (startPDT || 0)) {\n return null;\n }\n\n const endPDT = fragments[fragments.length - 1].endProgramDateTime;\n if (PDTValue >= (endPDT || 0)) {\n return null;\n }\n\n maxFragLookUpTolerance = maxFragLookUpTolerance || 0;\n for (let seg = 0; seg < fragments.length; ++seg) {\n let frag = fragments[seg];\n if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {\n return frag;\n }\n }\n\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param {*} fragPrevious - The last frag successfully appended\n * @param {Array<Fragment>} fragments - The array of candidate fragments\n * @param {number} [bufferEnd = 0] - The end of the contiguous buffered range the playhead is currently within\n * @param {number} maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns {*} foundFrag - The best matching fragment\n */\nexport function findFragmentByPTS (fragPrevious: Fragment, fragments: Array<Fragment>, bufferEnd: number = 0, maxFragLookUpTolerance: number = 0): Fragment | null {\n let fragNext: Fragment | null = null;\n if (fragPrevious) {\n fragNext = fragments[fragPrevious.sn as number - (fragments[0].sn as number) + 1];\n } else if (bufferEnd === 0 && fragments[0].start === 0) {\n fragNext = fragments[0];\n }\n // Prefer the next fragment if it's within tolerance\n if (fragNext && fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) === 0) {\n return fragNext;\n }\n // We might be seeking past the tolerance so find the best match\n const foundFragment = BinarySearch.search(fragments, fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance));\n if (foundFragment) {\n return foundFragment;\n }\n // If no match was found return the next fragment after fragPrevious, or null\n return fragNext;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param {*} candidate - The fragment to test\n * @param {number} [bufferEnd = 0] - The end of the current buffered range the playhead is currently within\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {number} - 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest (bufferEnd = 0, maxFragLookUpTolerance = 0, candidate: Fragment) {\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0));\n if (candidate.start + candidate.duration - candidateLookupTolerance <= bufferEnd) {\n return 1;\n } else if (candidate.start - candidateLookupTolerance > bufferEnd && candidate.start) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n/**\n * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.\n * This function tests the candidate's program date time values, as represented in Unix time\n * @param {*} candidate - The fragment to test\n * @param {number} [pdtBufferEnd = 0] - The Unix time representing the end of the current buffered range\n * @param {number} [maxFragLookUpTolerance = 0] - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns {boolean} True if contiguous, false otherwise\n */\nexport function pdtWithinToleranceTest (pdtBufferEnd: number, maxFragLookUpTolerance: number, candidate: Fragment): boolean {\n let candidateLookupTolerance = Math.min(maxFragLookUpTolerance, candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)) * 1000;\n\n // endProgramDateTime can be null, default to zero\n const endProgramDateTime = candidate.endProgramDateTime || 0;\n return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n}\n","import { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Event from '../events';\nimport { logger } from '../utils/logger';\n\nexport const STALL_MINIMUM_DURATION_MS = 250;\nexport const MAX_START_GAP_JUMP = 2.0;\nexport const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;\nexport const SKIP_BUFFER_RANGE_START = 0.05;\n\nexport default class GapController {\n constructor (config, media, fragmentTracker, hls) {\n this.config = config;\n this.media = media;\n this.fragmentTracker = fragmentTracker;\n this.hls = hls;\n this.nudgeRetry = 0;\n this.stallReported = false;\n this.stalled = null;\n this.moved = false;\n this.seeking = false;\n }\n\n /**\n * Checks if the playhead is stuck within a gap, and if so, attempts to free it.\n * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).\n *\n * @param {number} lastCurrentTime Previously read playhead position\n */\n poll (lastCurrentTime) {\n const { config, media, stalled } = this;\n const { currentTime, seeking } = media;\n const seeked = this.seeking && !seeking;\n const beginSeek = !this.seeking && seeking;\n\n this.seeking = seeking;\n\n // The playhead is moving, no-op\n if (currentTime !== lastCurrentTime) {\n this.moved = true;\n if (stalled !== null) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n const stalledDuration = self.performance.now() - stalled;\n logger.warn(`playback not stuck anymore @${currentTime}, after ${Math.round(stalledDuration)}ms`);\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n }\n return;\n }\n\n // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n if (beginSeek || seeked) {\n this.stalled = null;\n }\n\n // The playhead should not be moving\n if (media.paused || media.ended || media.playbackRate === 0 || !media.buffered.length) {\n return;\n }\n\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const isBuffered = bufferInfo.len > 0;\n const nextStart = bufferInfo.nextStart || 0;\n\n // There is no playable buffer (waiting for buffer append)\n if (!isBuffered && !nextStart) {\n return;\n }\n\n if (seeking) {\n // Waiting for seeking in a buffered range to complete\n const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;\n // Next buffered range is too far ahead to jump to while still seeking\n const noBufferGap = !nextStart ||\n (nextStart - currentTime > MAX_START_GAP_JUMP && !this.fragmentTracker.getPartialFragment(currentTime));\n if (hasEnoughBuffer || noBufferGap) {\n return;\n }\n // Reset moved state when seeking to a point in or before a gap\n this.moved = false;\n }\n\n // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n // The addition poll gives the browser a chance to jump the gap for us\n if (!this.moved && this.stalled) {\n // Jump start gaps within jump threshold\n const startJump = Math.max(nextStart, bufferInfo.start || 0) - currentTime;\n if (startJump > 0 && startJump <= MAX_START_GAP_JUMP) {\n this._trySkipBufferHole(null);\n return;\n }\n }\n\n // Start tracking stall time\n const tnow = self.performance.now();\n if (stalled === null) {\n this.stalled = tnow;\n return;\n }\n\n const stalledDuration = tnow - stalled;\n if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo.len);\n }\n\n const bufferedWithHoles = BufferHelper.bufferInfo(media, currentTime, config.maxBufferHole);\n this._tryFixBufferStall(bufferedWithHoles, stalledDuration);\n }\n\n /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDurationMs - The amount of time Hls.js has been stalling for.\n * @private\n */\n _tryFixBufferStall (bufferInfo, stalledDurationMs) {\n const { config, fragmentTracker, media } = this;\n const currentTime = media.currentTime;\n\n const partial = fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n const targetTime = this._trySkipBufferHole(partial);\n // we return here in this case, meaning\n // the branch below only executes when we don't handle a partial fragment\n if (targetTime) {\n return;\n }\n }\n\n // if we haven't had to skip over a buffer hole of a partial fragment\n // we may just have to \"nudge\" the playlist as the browser decoding/rendering engine\n // needs to cross some sort of threshold covering all source-buffers content\n // to start playing properly.\n if (bufferInfo.len > config.maxBufferHole &&\n stalledDurationMs > config.highBufferWatchdogPeriod * 1000) {\n logger.warn('Trying to nudge playhead over buffer-hole');\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n _reportStall (bufferLen) {\n const { hls, media, stallReported } = this;\n if (!stallReported) {\n // Report stalled error once\n this.stallReported = true;\n logger.warn(`Playback stalling at @${media.currentTime} due to low buffer (buffer=${bufferLen})`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n buffer: bufferLen\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n _trySkipBufferHole (partial) {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n let lastEndTime = 0;\n // Check if currentTime is between unbuffered regions of partial fragments\n for (let i = 0; i < media.buffered.length; i++) {\n const startTime = media.buffered.start(i);\n if (currentTime + config.maxBufferHole >= lastEndTime && currentTime < startTime) {\n const targetTime = Math.max(startTime + SKIP_BUFFER_RANGE_START, media.currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS);\n logger.warn(`skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`);\n this.moved = true;\n this.stalled = null;\n media.currentTime = targetTime;\n if (partial) {\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n reason: `fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`,\n frag: partial\n });\n }\n return targetTime;\n }\n lastEndTime = media.buffered.end(i);\n }\n return 0;\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n _tryNudgeBuffer () {\n const { config, hls, media } = this;\n const currentTime = media.currentTime;\n const nudgeRetry = (this.nudgeRetry || 0) + 1;\n this.nudgeRetry = nudgeRetry;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n const targetTime = currentTime + nudgeRetry * config.nudgeOffset;\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n logger.warn(`Nudging 'currentTime' from ${currentTime} to ${targetTime}`);\n media.currentTime = targetTime;\n\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n fatal: false\n });\n } else {\n logger.error(`Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`);\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: true\n });\n }\n }\n}\n","import EventHandler from './event-handler';\nimport Hls from './hls';\n\n/**\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\n\nexport default class TaskLoop extends EventHandler {\n private readonly _boundTick: () => void;\n private _tickTimer: number | null = null;\n private _tickInterval: number | null = null;\n private _tickCallCount = 0;\n\n constructor (hls: Hls, ...events: string[]) {\n super(hls, ...events);\n this._boundTick = this.tick.bind(this);\n }\n\n /**\n * @override\n */\n protected onHandlerDestroying () {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n /**\n * @returns {boolean}\n */\n public hasInterval (): boolean {\n return !!this._tickInterval;\n }\n\n /**\n * @returns {boolean}\n */\n public hasNextTick (): boolean {\n return !!this._tickTimer;\n }\n\n /**\n * @param {number} millis Interval time (ms)\n * @returns {boolean} True when interval has been scheduled, false when already scheduled (no effect)\n */\n public setInterval (millis: number): boolean {\n if (!this._tickInterval) {\n this._tickInterval = self.setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when interval was cleared, false when none was set (no effect)\n */\n public clearInterval (): boolean {\n if (this._tickInterval) {\n self.clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns {boolean} True when timeout was cleared, false when none was set (no effect)\n */\n public clearNextTick (): boolean {\n if (this._tickTimer) {\n self.clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n public tick (): void {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.clearNextTick();\n this._tickTimer = self.setTimeout(this._boundTick, 0);\n }\n this._tickCallCount = 0;\n }\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n protected doTick (): void {}\n}\n","import TaskLoop from '../task-loop';\nimport { FragmentState } from './fragment-tracker';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\n\nexport const State = {\n STOPPED: 'STOPPED',\n STARTING: 'STARTING',\n IDLE: 'IDLE',\n PAUSED: 'PAUSED',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK: 'WAITING_TRACK',\n PARSING: 'PARSING',\n PARSED: 'PARSED',\n BUFFER_FLUSHING: 'BUFFER_FLUSHING',\n ENDED: 'ENDED',\n ERROR: 'ERROR',\n WAITING_INIT_PTS: 'WAITING_INIT_PTS',\n WAITING_LEVEL: 'WAITING_LEVEL'\n};\n\nexport default class BaseStreamController extends TaskLoop {\n doTick () {}\n\n startLoad () {}\n\n stopLoad () {\n let frag = this.fragCurrent;\n if (frag) {\n if (frag.loader) {\n frag.loader.abort();\n }\n this.fragmentTracker.removeFragment(frag);\n }\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.clearInterval();\n this.clearNextTick();\n this.state = State.STOPPED;\n }\n\n _streamEnded (bufferInfo, levelDetails) {\n const { fragCurrent, fragmentTracker } = this;\n // we just got done loading the final fragment and there is no other buffered range after ...\n // rationale is that in case there are any buffered ranges after, it means that there are unbuffered portion in between\n // so we should not switch to ENDED in that case, to be able to buffer them\n // dont switch to ENDED if we need to backtrack last fragment\n if (!levelDetails.live && fragCurrent && !fragCurrent.backtracked && fragCurrent.sn === levelDetails.endSN && !bufferInfo.nextStart) {\n const fragState = fragmentTracker.getState(fragCurrent);\n return fragState === FragmentState.PARTIAL || fragState === FragmentState.OK;\n }\n return false;\n }\n\n onMediaSeeking () {\n const { config, media, mediaBuffer, state } = this;\n const currentTime = media ? media.currentTime : null;\n const bufferInfo = BufferHelper.bufferInfo(mediaBuffer || media, currentTime, this.config.maxBufferHole);\n\n logger.log(`media seeking to ${Number.isFinite(currentTime) ? currentTime.toFixed(3) : currentTime}`);\n\n if (state === State.FRAG_LOADING) {\n let fragCurrent = this.fragCurrent;\n // check if we are seeking to a unbuffered area AND if frag loading is in progress\n if (bufferInfo.len === 0 && fragCurrent) {\n const tolerance = config.maxFragLookUpTolerance;\n const fragStartOffset = fragCurrent.start - tolerance;\n const fragEndOffset = fragCurrent.start + fragCurrent.duration + tolerance;\n // check if we seek position will be out of currently loaded frag range : if out cancel frag load, if in, don't do anything\n if (currentTime < fragStartOffset || currentTime > fragEndOffset) {\n if (fragCurrent.loader) {\n logger.log('seeking outside of buffer while fragment load in progress, cancel fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n } else {\n logger.log('seeking outside of buffer but within currently loaded fragment range');\n }\n }\n } else if (state === State.ENDED) {\n // if seeking to unbuffered area, clean up fragPrevious\n if (bufferInfo.len === 0) {\n this.fragPrevious = null;\n this.fragCurrent = null;\n }\n\n // switch to IDLE state to check for potential new fragment\n this.state = State.IDLE;\n }\n if (media) {\n this.lastCurrentTime = currentTime;\n }\n\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if (!this.loadedmetadata) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n\n // tick to speed up processing\n this.tick();\n }\n\n onMediaEnded () {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onHandlerDestroying () {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n onHandlerDestroyed () {\n this.state = State.STOPPED;\n this.fragmentTracker = null;\n }\n\n computeLivePosition (sliding, levelDetails) {\n let targetLatency = this.config.liveSyncDuration !== undefined ? this.config.liveSyncDuration : this.config.liveSyncDurationCount * levelDetails.targetduration;\n return sliding + Math.max(0, levelDetails.totalduration - targetLatency);\n }\n}\n","/*\n * Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport { FragmentState } from './fragment-tracker';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport { PlaylistLevelType } from '../types/loader';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { alignStream } from '../utils/discontinuities';\nimport { findFragmentByPDT, findFragmentByPTS } from './fragment-finders';\nimport GapController, { MAX_START_GAP_JUMP } from './gap-controller';\nimport BaseStreamController, { State } from './base-stream-controller';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nclass StreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.LEVEL_LOADED,\n Event.LEVELS_UPDATED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_LOAD_EMERGENCY_ABORTED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_SWITCHED,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED);\n\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.stallReported = false;\n this.gapController = null;\n this.altAudio = false;\n this.audioOnly = false;\n this.bitrateTest = false;\n }\n\n startLoad (startPosition) {\n if (this.levels) {\n let lastCurrentTime = this.lastCurrentTime, hls = this.hls;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.level = -1;\n this.fragLoadError = 0;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n if (hls.config.testBandwidth) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n } else {\n startLevel = hls.nextAutoLevel;\n }\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n this.level = hls.nextLoadLevel = startLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime = startPosition;\n this.tick();\n } else {\n this.forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n stopLoad () {\n this.forceStartLoad = false;\n super.stopLoad();\n }\n\n doTick () {\n switch (this.state) {\n case State.BUFFER_FLUSHING:\n // in buffer flushing state, reset fragLoadError counter\n this.fragLoadError = 0;\n break;\n case State.IDLE:\n this._doTickIdle();\n break;\n case State.WAITING_LEVEL:\n var level = this.levels[this.level];\n // check if playlist is already loaded\n if (level && level.details) {\n this.state = State.IDLE;\n }\n\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = window.performance.now();\n var retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || (this.media && this.media.seeking)) {\n logger.log('mediaController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.ERROR:\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n // check buffer\n this._checkBuffer();\n // check/update current fragment\n this._checkFragmentChanged();\n }\n\n // Ironically the \"idle\" state is the on we do the most logic in it seems ....\n // NOTE: Maybe we could rather schedule a check for buffer length after half of the currently\n // played segment, or on pause/play/seek instead of naively checking every 100ms?\n _doTickIdle () {\n const hls = this.hls,\n config = hls.config,\n media = this.media;\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch disable\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (this.levelLastLoaded === undefined || (\n !media && (this.startFragRequested || !config.startFragPrefetch))) {\n return;\n }\n\n // If the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n if (this.altAudio && this.audioOnly) {\n // Clear audio demuxer state so when switching back to main audio we're not still appending where we left off\n this.demuxer.frag = null;\n return;\n }\n\n // if we have not yet loaded any fragment, start loading from start position\n let pos;\n if (this.loadedmetadata) {\n pos = media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n }\n\n // determine next load level\n let level = hls.nextLoadLevel,\n levelInfo = this.levels[level];\n\n if (!levelInfo) {\n return;\n }\n\n let levelBitrate = levelInfo.bitrate,\n maxBufLen;\n\n // compute max Buffer Length that we could get from this load level, based on level bitrate.\n if (levelBitrate) {\n maxBufLen = Math.max(8 * config.maxBufferSize / levelBitrate, config.maxBufferLength);\n } else {\n maxBufLen = config.maxBufferLength;\n }\n\n maxBufLen = Math.min(maxBufLen, config.maxMaxBufferLength);\n\n // determine next candidate fragment to be loaded, based on current position and end of buffer position\n // ensure up to `config.maxMaxBufferLength` of buffer upfront\n\n const maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer ? this.mediaBuffer : media, pos, maxBufferHole);\n const bufferLen = bufferInfo.len;\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n\n // if buffer length is less than maxBufLen try to load a new fragment ...\n logger.trace(`buffer length of ${bufferLen.toFixed(3)} is below max of ${maxBufLen.toFixed(3)}. checking for more payload ...`);\n\n // set next load level : this will trigger a playlist load if needed\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (!levelDetails || (levelDetails.live && this.levelLastLoaded !== level)) {\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n if (this._streamEnded(bufferInfo, levelDetails)) {\n const data = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(Event.BUFFER_EOS, data);\n this.state = State.ENDED;\n return;\n }\n // if we have the levelDetails for the selected variant, lets continue enrichen our stream (load keys/fragments or trigger EOS, etc..)\n this._fetchPayloadOrEos(pos, bufferInfo, levelDetails);\n }\n\n _fetchPayloadOrEos (pos, bufferInfo, levelDetails) {\n const fragPrevious = this.fragPrevious,\n level = this.level,\n fragments = levelDetails.fragments,\n fragLen = fragments.length;\n\n // empty playlist\n if (fragLen === 0) {\n return;\n }\n\n // find fragment index, contiguous with end of buffer position\n let start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n bufferEnd = bufferInfo.end,\n frag;\n\n if (levelDetails.initSegment && !levelDetails.initSegment.data) {\n frag = levelDetails.initSegment;\n } else {\n // in case of live playlist we need to ensure that requested position is not located before playlist start\n if (levelDetails.live) {\n let initialLiveManifestSize = this.config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n logger.warn(`Can not start playback of a level, reason: not enough fragments ${fragLen} < ${initialLiveManifestSize}`);\n return;\n }\n\n frag = this._ensureFragmentAtLivePoint(levelDetails, bufferEnd, start, end, fragPrevious, fragments);\n // if it explicitely returns null don't load any fragment and exit function now\n if (frag === null) {\n return;\n }\n } else {\n // VoD playlist: if bufferEnd before start of playlist, load first fragment\n if (bufferEnd < start) {\n frag = fragments[0];\n }\n }\n }\n if (!frag) {\n frag = this._findFragment(start, fragPrevious, fragLen, fragments, bufferEnd, end, levelDetails);\n }\n\n if (frag) {\n if (frag.encrypted) {\n this._loadKey(frag, levelDetails);\n } else {\n this._loadFragment(frag, levelDetails, pos, bufferEnd);\n }\n }\n }\n\n _ensureFragmentAtLivePoint (levelDetails, bufferEnd, start, end, fragPrevious, fragments) {\n const config = this.hls.config, media = this.media;\n\n let frag;\n\n // check if requested position is within seekable boundaries :\n // logger.log(`start/pos/bufEnd/seeking:${start.toFixed(3)}/${pos.toFixed(3)}/${bufferEnd.toFixed(3)}/${this.media.seeking}`);\n let maxLatency = Infinity;\n\n if (config.liveMaxLatencyDuration !== undefined) {\n maxLatency = config.liveMaxLatencyDuration;\n } else if (Number.isFinite(config.liveMaxLatencyDurationCount)) {\n maxLatency = config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n }\n\n if (bufferEnd < Math.max(start - config.maxFragLookUpTolerance, end - maxLatency)) {\n let liveSyncPosition = this.liveSyncPosition = this.computeLivePosition(start, levelDetails);\n bufferEnd = liveSyncPosition;\n if (media && !media.paused && media.readyState && media.duration > liveSyncPosition && liveSyncPosition > media.currentTime) {\n logger.log(`buffer end: ${bufferEnd.toFixed(3)} is located too far from the end of live sliding playlist, reset currentTime to : ${liveSyncPosition.toFixed(3)}`);\n media.currentTime = liveSyncPosition;\n }\n\n this.nextLoadPosition = liveSyncPosition;\n }\n\n // if end of buffer greater than live edge, don't load any fragment\n // this could happen if live playlist intermittently slides in the past.\n // level 1 loaded [182580161,182580167]\n // level 1 loaded [182580162,182580169]\n // Loading 182580168 of [182580162 ,182580169],level 1 ..\n // Loading 182580169 of [182580162 ,182580169],level 1 ..\n // level 1 loaded [182580162,182580168] <============= here we should have bufferEnd > end. in that case break to avoid reloading 182580168\n // level 1 loaded [182580164,182580171]\n //\n // don't return null in case media not loaded yet (readystate === 0)\n if (levelDetails.PTSKnown && bufferEnd > end && media && media.readyState) {\n return null;\n }\n\n if (this.startFragRequested && !levelDetails.PTSKnown) {\n /* we are switching level on live playlist, but we don't have any PTS info for that quality level ...\n try to load frag matching with next SN.\n even if SN are not synchronized between playlists, loading this frag will help us\n compute playlist sliding and find the right one after in case it was not the right consecutive one */\n if (fragPrevious) {\n if (levelDetails.hasProgramDateTime) {\n // Relies on PDT in order to switch bitrates (Support EXT-X-DISCONTINUITY without EXT-X-DISCONTINUITY-SEQUENCE)\n logger.log(`live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`);\n frag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, config.maxFragLookUpTolerance);\n } else {\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n const targetSN = fragPrevious.sn + 1;\n if (targetSN >= levelDetails.startSN && targetSN <= levelDetails.endSN) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n logger.log(`live playlist, switching playlist, load frag with next SN: ${frag.sn}`);\n }\n }\n // next frag SN not available (or not with same continuity counter)\n // look for a frag sharing the same CC\n if (!frag) {\n frag = BinarySearch.search(fragments, function (frag) {\n return fragPrevious.cc - frag.cc;\n });\n if (frag) {\n logger.log(`live playlist, switching playlist, load frag with same CC: ${frag.sn}`);\n }\n }\n }\n }\n }\n\n return frag;\n }\n\n _findFragment (start, fragPreviousLoad, fragmentIndexRange, fragments, bufferEnd, end, levelDetails) {\n const config = this.hls.config;\n let fragNextLoad;\n\n if (bufferEnd < end) {\n const lookupTolerance = (bufferEnd > end - config.maxFragLookUpTolerance) ? 0 : config.maxFragLookUpTolerance;\n // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n fragNextLoad = findFragmentByPTS(fragPreviousLoad, fragments, bufferEnd, lookupTolerance);\n } else {\n // reach end of playlist\n fragNextLoad = fragments[fragmentIndexRange - 1];\n }\n\n if (fragNextLoad) {\n const curSNIdx = fragNextLoad.sn - levelDetails.startSN;\n const sameLevel = fragPreviousLoad && fragNextLoad.level === fragPreviousLoad.level;\n const prevSnFrag = fragments[curSNIdx - 1];\n const nextSnFrag = fragments[curSNIdx + 1];\n\n // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPreviousLoad && fragNextLoad.sn === fragPreviousLoad.sn) {\n if (sameLevel && !fragNextLoad.backtracked) {\n if (fragNextLoad.sn < levelDetails.endSN) {\n let deltaPTS = fragPreviousLoad.deltaPTS;\n // if there is a significant delta between audio and video, larger than max allowed hole,\n // and if previous remuxed fragment did not start with a keyframe. (fragPrevious.dropped)\n // let's try to load previous fragment again to get last keyframe\n // then we will reload again current fragment (that way we should be able to fill the buffer hole ...)\n if (deltaPTS && deltaPTS > config.maxBufferHole && fragPreviousLoad.dropped && curSNIdx) {\n fragNextLoad = prevSnFrag;\n logger.warn('Previous fragment was dropped with large PTS gap between audio and video. Maybe fragment is not starting with a keyframe? Loading previous one to try to overcome this');\n } else {\n fragNextLoad = nextSnFrag;\n if (this.fragmentTracker.getState(fragNextLoad) !== FragmentState.OK) {\n logger.log(`Re-loading fragment with SN: ${fragNextLoad.sn}`);\n }\n }\n } else {\n fragNextLoad = null;\n }\n } else if (fragNextLoad.backtracked) {\n // Only backtrack a max of 1 consecutive fragment to prevent sliding back too far when little or no frags start with keyframes\n if (nextSnFrag && nextSnFrag.backtracked) {\n logger.warn(`Already backtracked from fragment ${nextSnFrag.sn}, will not backtrack to fragment ${fragNextLoad.sn}. Loading fragment ${nextSnFrag.sn}`);\n fragNextLoad = nextSnFrag;\n } else {\n // If a fragment has dropped frames and it's in a same level/sequence, load the previous fragment to try and find the keyframe\n // 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\n logger.warn('Loaded fragment with dropped frames, backtracking 1 segment to find a keyframe');\n fragNextLoad.dropped = 0;\n if (prevSnFrag) {\n fragNextLoad = prevSnFrag;\n fragNextLoad.backtracked = true;\n } else if (curSNIdx) {\n // can't backtrack on very first fragment\n fragNextLoad = null;\n }\n }\n }\n }\n }\n\n return fragNextLoad;\n }\n\n _loadKey (frag, levelDetails) {\n logger.log(`Loading key for ${frag.sn} of [${levelDetails.startSN}-${levelDetails.endSN}], level ${this.level}`);\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag });\n }\n\n _loadFragment (frag, levelDetails, pos, bufferEnd) {\n // Check if fragment is not loaded\n let fragState = this.fragmentTracker.getState(frag);\n\n this.fragCurrent = frag;\n if (frag.sn !== 'initSegment') {\n this.startFragRequested = true;\n }\n // Don't update nextLoadPosition for fragments which are not buffered\n if (Number.isFinite(frag.sn) && !frag.bitrateTest) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n // Allow backtracked fragments to load\n if (frag.backtracked || fragState === FragmentState.NOT_LOADED || fragState === FragmentState.PARTIAL) {\n frag.autoLevel = this.hls.autoLevelEnabled;\n frag.bitrateTest = this.bitrateTest;\n\n logger.log(`Loading ${frag.sn} of [${levelDetails.startSN}-${levelDetails.endSN}], level ${this.level}, ${\n this.loadedmetadata ? 'currentTime' : 'nextLoadPosition'\n }: ${parseFloat(pos.toFixed(3))}, bufferEnd: ${parseFloat(bufferEnd.toFixed(3))}`);\n\n this.hls.trigger(Event.FRAG_LOADING, { frag });\n // lazy demuxer init, as this could take some time ... do it during frag loading\n if (!this.demuxer) {\n this.demuxer = new Demuxer(this.hls, 'main');\n }\n\n this.state = State.FRAG_LOADING;\n } else if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n if (this._reduceMaxBufferLength(frag.duration)) {\n this.fragmentTracker.removeFragment(frag);\n }\n }\n }\n\n set state (nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`main stream-controller: ${previousState}->${nextState}`);\n this.hls.trigger(Event.STREAM_STATE_TRANSITION, { previousState, nextState });\n }\n }\n\n get state () {\n return this._state;\n }\n\n getBufferedFrag (position) {\n return this.fragmentTracker.getBufferedFrag(position, PlaylistLevelType.MAIN);\n }\n\n get currentLevel () {\n let media = this.media;\n if (media) {\n const frag = this.getBufferedFrag(media.currentTime);\n if (frag) {\n return frag.level;\n }\n }\n return -1;\n }\n\n get nextBufferedFrag () {\n let media = this.media;\n if (media) {\n // first get end range of current fragment\n return this.followingBufferedFrag(this.getBufferedFrag(media.currentTime));\n } else {\n return null;\n }\n }\n\n followingBufferedFrag (frag) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.endPTS + 0.5);\n }\n return null;\n }\n\n get nextLevel () {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n } else {\n return -1;\n }\n }\n\n _checkFragmentChanged () {\n let fragPlayingCurrent, currentTime, video = this.media;\n if (video && video.readyState && video.seeking === false) {\n currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n if (currentTime > this.lastCurrentTime) {\n this.lastCurrentTime = currentTime;\n }\n\n if (BufferHelper.isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getBufferedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getBufferedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n let fragPlaying = fragPlayingCurrent;\n if (fragPlaying !== this.fragPlaying) {\n this.hls.trigger(Event.FRAG_CHANGED, { frag: fragPlaying });\n const fragPlayingLevel = fragPlaying.level;\n if (!this.fragPlaying || this.fragPlaying.level !== fragPlayingLevel) {\n this.hls.trigger(Event.LEVEL_SWITCHED, { level: fragPlayingLevel });\n }\n\n this.fragPlaying = fragPlaying;\n }\n }\n }\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n immediateLevelSwitch () {\n logger.log('immediateLevelSwitch');\n if (!this.immediateSwitch) {\n this.immediateSwitch = true;\n let media = this.media, previouslyPaused;\n if (media) {\n previouslyPaused = media.paused;\n if (!previouslyPaused) {\n media.pause();\n }\n } else {\n // don't restart playback after instant level switch in case media not attached\n previouslyPaused = true;\n }\n this.previouslyPaused = previouslyPaused;\n }\n let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n\n /**\n * on immediate level switch end, after new fragment has been buffered:\n * - nudge video decoder by slightly adjusting video currentTime (if currentTime buffered)\n * - resume the playback if needed\n */\n immediateLevelSwitchEnd () {\n const media = this.media;\n if (media && media.buffered.length) {\n this.immediateSwitch = false;\n if (media.currentTime > 0 && BufferHelper.isBuffered(media, media.currentTime)) {\n // only nudge if currentTime is buffered\n media.currentTime -= 0.0001;\n }\n if (!this.previouslyPaused) {\n media.play();\n }\n }\n }\n\n /**\n * try to switch ASAP without breaking video playback:\n * in order to ensure smooth but quick level switching,\n * we need to find the next flushable buffer range\n * we should take into account new segment fetch time\n */\n nextLevelSwitch () {\n const media = this.media;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media && media.readyState) {\n let fetchdelay;\n const fragPlayingCurrent = this.getBufferedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.startPTS > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0, fragPlayingCurrent.startPTS - 1);\n }\n if (!media.paused) {\n // add a safety delay of 1s\n let nextLevelId = this.hls.nextLoadLevel, nextLevel = this.levels[nextLevelId], fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay = this.fragCurrent.duration * nextLevel.bitrate / (1000 * fragLastKbps) + 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // logger.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (bufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n let fragCurrent = this.fragCurrent;\n if (fragCurrent && fragCurrent.loader) {\n fragCurrent.loader.abort();\n }\n\n this.fragCurrent = null;\n // start flush position is the start PTS of next buffered frag.\n // we use frag.naxStartPTS which is max(audio startPTS, video startPTS).\n // in case there is a small PTS Delta between audio and video, using maxStartPTS avoids flushing last samples from current fragment\n const startPts = Math.max(bufferedFrag.endPTS, nextBufferedFrag.maxStartPTS + Math.min(this.config.maxFragLookUpTolerance, nextBufferedFrag.duration));\n this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n flushMainBuffer (startOffset, endOffset) {\n this.state = State.BUFFER_FLUSHING;\n let flushScope = { startOffset: startOffset, endOffset: endOffset };\n // if alternate audio tracks are used, only flush video, otherwise flush everything\n if (this.altAudio) {\n flushScope.type = 'video';\n }\n\n this.hls.trigger(Event.BUFFER_FLUSHING, flushScope);\n }\n\n onMediaAttached (data) {\n let media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('seeked', this.onvseeked);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if (this.levels && config.autoStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n\n this.gapController = new GapController(config, media, this.fragmentTracker, this.hls);\n }\n\n onMediaDetaching () {\n let media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // reset fragment backtracked flag\n let levels = this.levels;\n if (levels) {\n levels.forEach(level => {\n if (level.details) {\n level.details.fragments.forEach(fragment => {\n fragment.backtracked = undefined;\n });\n }\n });\n }\n\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('seeked', this.onvseeked);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n\n this.fragmentTracker.removeAllFragments();\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.stopLoad();\n }\n\n onMediaSeeked () {\n const media = this.media;\n const currentTime = media ? media.currentTime : undefined;\n if (Number.isFinite(currentTime)) {\n logger.log(`media seeked to ${currentTime.toFixed(3)}`);\n }\n\n // tick to speed up FRAGMENT_PLAYING triggering\n this.tick();\n }\n\n onManifestLoading () {\n // reset buffer on manifest loading\n logger.log('trigger BUFFER_RESET');\n this.hls.trigger(Event.BUFFER_RESET);\n this.fragmentTracker.removeAllFragments();\n this.stalled = false;\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n onManifestParsed (data) {\n let aac = false, heaac = false, codec;\n data.levels.forEach(level => {\n // detect if we have different kind of audio codecs used amongst playlists\n codec = level.audioCodec;\n if (codec) {\n if (codec.indexOf('mp4a.40.2') !== -1) {\n aac = true;\n }\n\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = (aac && heaac);\n if (this.audioCodecSwitch) {\n logger.log('both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC');\n }\n\n this.altAudio = data.altAudio;\n this.levels = data.levels;\n this.startFragRequested = false;\n let config = this.config;\n if (config.autoStartLoad || this.forceStartLoad) {\n this.hls.startLoad(config.startPosition);\n }\n }\n\n onLevelLoaded (data) {\n const newDetails = data.details;\n const newLevelId = data.level;\n const lastLevel = this.levels[this.levelLastLoaded];\n const curLevel = this.levels[newLevelId];\n const duration = newDetails.totalduration;\n let sliding = 0;\n\n logger.log(`level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live || (curLevel.details && curLevel.details.live)) {\n let curDetails = curLevel.details;\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails, newDetails);\n sliding = newDetails.fragments[0].start;\n this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown && Number.isFinite(sliding)) {\n logger.log(`live playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live playlist - outdated PTS, unknown sliding');\n alignStream(this.fragPrevious, lastLevel, newDetails);\n }\n } else {\n logger.log('live playlist - first load, unknown sliding');\n newDetails.PTSKnown = false;\n alignStream(this.fragPrevious, lastLevel, newDetails);\n }\n } else {\n newDetails.PTSKnown = false;\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = newLevelId;\n this.hls.trigger(Event.LEVEL_UPDATED, { details: newDetails, level: newLevelId });\n\n if (this.startFragRequested === false) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1 || this.lastCurrentTime === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if (Number.isFinite(startTimeOffset)) {\n if (startTimeOffset < 0) {\n logger.log(`negative start time offset ${startTimeOffset}, count from end of last fragment`);\n startTimeOffset = sliding + duration + startTimeOffset;\n }\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n // if live playlist, set start position to be fragment N-this.config.liveSyncDurationCount (usually 3)\n if (newDetails.live) {\n this.startPosition = this.computeLivePosition(sliding, newDetails);\n logger.log(`configure startPosition to ${this.startPosition}`);\n } else {\n this.startPosition = 0;\n }\n }\n this.lastCurrentTime = this.startPosition;\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded (data) {\n const { fragCurrent, hls, levels, media } = this;\n const fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'main' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n const stats = data.stats;\n const currentLevel = levels[fragCurrent.level];\n const details = currentLevel.details;\n // reset frag bitrate test in any case after frag loaded event\n // if this frag was loaded to perform a bitrate test AND if hls.nextLoadLevel is greater than 0\n // then this means that we should be able to load a fragment at a higher quality level\n this.bitrateTest = false;\n this.stats = stats;\n\n logger.log(`Loaded ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}`);\n if (fragLoaded.bitrateTest && hls.nextLoadLevel) {\n // switch back to IDLE state ... we just loaded a fragment to determine adequate start bitrate and initialize autoswitch algo\n this.state = State.IDLE;\n this.startFragRequested = false;\n stats.tparsed = stats.tbuffered = window.performance.now();\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });\n this.tick();\n } else if (fragLoaded.sn === 'initSegment') {\n this.state = State.IDLE;\n stats.tparsed = stats.tbuffered = window.performance.now();\n details.initSegment.data = data.payload;\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'main' });\n this.tick();\n } else {\n logger.log(`Parsing ${fragCurrent.sn} of [${details.startSN} ,${details.endSN}],level ${fragCurrent.level}, cc ${fragCurrent.cc}`);\n this.state = State.PARSING;\n this.pendingBuffering = true;\n this.appended = false;\n\n // Bitrate test frags are not usually buffered so the fragment tracker ignores them. If Hls.js decides to buffer\n // it (and therefore ends up at this line), then the fragment tracker needs to be manually informed.\n if (fragLoaded.bitrateTest) {\n fragLoaded.bitrateTest = false;\n this.fragmentTracker.onFragLoaded({\n frag: fragLoaded\n });\n }\n\n // 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)\n const accurateTimeOffset = !(media && media.seeking) && (details.PTSKnown || !details.live);\n const initSegmentData = details.initSegment ? details.initSegment.data : [];\n const audioCodec = this._getAudioCodec(currentLevel);\n\n // transmux the MPEG-TS data to ISO-BMFF segments\n const demuxer = this.demuxer = this.demuxer || new Demuxer(this.hls, 'main');\n demuxer.push(\n data.payload,\n initSegmentData,\n audioCodec,\n currentLevel.videoCodec,\n fragCurrent,\n details.totalduration,\n accurateTimeOffset\n );\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let tracks = data.tracks, trackName, track;\n\n this.audioOnly = tracks.audio && !tracks.video;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (this.altAudio && !this.audioOnly) {\n delete tracks.audio;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n let audioCodec = this.levels[this.level].audioCodec,\n ua = navigator.userAgent.toLowerCase();\n if (audioCodec && this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // in case AAC and HE-AAC audio codecs are signalled in manifest\n // force HE-AAC , as it seems that most browsers prefers that way,\n // except for mono streams OR on FF\n // these conditions might need to be reviewed ...\n if (this.audioCodecSwitch) {\n // don't force HE-AAC if mono stream\n if (track.metadata.channelCount !== 1 &&\n // don't force HE-AAC if firefox\n ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (ua.indexOf('android') !== -1 && track.container !== 'audio/mpeg') { // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n logger.log(`Android: force audio codec to ${audioCodec}`);\n }\n track.levelCodec = audioCodec;\n track.id = data.id;\n }\n track = tracks.video;\n if (track) {\n track.levelCodec = this.levels[this.level].videoCodec;\n track.id = data.id;\n }\n this.hls.trigger(Event.BUFFER_CODECS, tracks);\n // loop through tracks that are going to be provided to bufferController\n for (trackName in tracks) {\n track = tracks[trackName];\n logger.log(`main track:${trackName},container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, { type: trackName, data: initSegment, parent: 'main', content: 'initSegment' });\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsingData (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n !(data.type === 'audio' && this.altAudio) && // filter out main audio if audio track is loaded through audio stream controller\n this.state === State.PARSING) {\n let level = this.levels[this.level],\n frag = fragCurrent;\n if (!Number.isFinite(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n if (data.hasAudio === true) {\n frag.addElementaryStream(ElementaryStreamTypes.AUDIO);\n }\n\n if (data.hasVideo === true) {\n frag.addElementaryStream(ElementaryStreamTypes.VIDEO);\n }\n\n 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}`);\n\n // Detect gaps in a fragment and try to fix it by finding a keyframe in the previous fragment (see _findFragments)\n if (data.type === 'video') {\n frag.dropped = data.dropped;\n if (frag.dropped) {\n if (!frag.backtracked) {\n const levelDetails = level.details;\n if (levelDetails && frag.sn === levelDetails.startSN) {\n logger.warn('missing video frame(s) on first frag, appending with gap', frag.sn);\n } else {\n logger.warn('missing video frame(s), backtracking fragment', frag.sn);\n // Return back to the IDLE state without appending to buffer\n // Causes findFragments to backtrack a segment and find the keyframe\n // Audio fragments arriving before video sets the nextLoadPosition, causing _findFragments to skip the backtracked fragment\n this.fragmentTracker.removeFragment(frag);\n frag.backtracked = true;\n this.nextLoadPosition = data.startPTS;\n this.state = State.IDLE;\n this.fragPrevious = frag;\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n this.tick();\n return;\n }\n } else {\n logger.warn('Already backtracked on this fragment, appending with the gap', frag.sn);\n }\n } else {\n // Only reset the backtracked flag if we've loaded the frag without any dropped frames\n frag.backtracked = false;\n }\n }\n\n let drift = LevelHelper.updateFragPTSDTS(level.details, frag, data.startPTS, data.endPTS, data.startDTS, data.endDTS),\n hls = this.hls;\n hls.trigger(Event.LEVEL_PTS_UPDATED, { details: level.details, level: this.level, drift: drift, type: data.type, start: data.startPTS, end: data.endPTS });\n // has remuxer dropped video frames located before first keyframe ?\n [data.data1, data.data2].forEach(buffer => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (buffer && buffer.length && this.state === State.PARSING) {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n hls.trigger(Event.BUFFER_APPENDING, { type: data.type, data: buffer, parent: 'main', content: 'data' });\n }\n });\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'main' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = window.performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onAudioTrackSwitching (data) {\n // if any URL found on new audio track, it is an alternate audio track\n const fromAltAudio = this.altAudio;\n const altAudio = !!data.url;\n const trackId = data.id;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n logger.log('switching on main audio, use media.buffered to schedule main fragment loading');\n this.mediaBuffer = this.media;\n let fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent.loader) {\n logger.log('switching to main audio track, cancel main fragment load');\n fragCurrent.loader.abort();\n }\n this.fragCurrent = null;\n this.fragPrevious = null;\n // destroy demuxer to force init segment generation (following audio switch)\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n }\n let hls = this.hls;\n // If switching from alt to main audio, flush all audio and trigger track switched\n if (fromAltAudio) {\n hls.trigger(Event.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: Number.POSITIVE_INFINITY,\n type: 'audio'\n });\n }\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, {\n id: trackId\n });\n }\n }\n\n onAudioTrackSwitched (data) {\n let trackId = data.id,\n altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n let videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n logger.log('switching on alternate audio, use video.buffered to schedule main fragment loading');\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n onBufferCreated (data) {\n let tracks = data.tracks, mediaTrack, name, alternate = false;\n for (let type in tracks) {\n let track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n this.videoBuffer = tracks[type].buffer;\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n logger.log(`alternate track found, use ${name}.buffered to schedule main fragment loading`);\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n onBufferAppended (data) {\n if (data.parent === 'main') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed () {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n const frag = this.fragCurrent;\n if (frag) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n logger.log(`main buffered : ${TimeRanges.toString(media.buffered)}`);\n this.fragPrevious = frag;\n const stats = this.stats;\n stats.tbuffered = window.performance.now();\n // we should get rid of this.fragLastKbps\n this.fragLastKbps = Math.round(8 * stats.total / (stats.tbuffered - stats.tfirst));\n this.hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'main' });\n this.state = State.IDLE;\n }\n // Do not tick when _seekToStartPos needs to be called as seeking to the start can fail on live streams at this point\n if (this.loadedmetadata || this.startPosition <= 0) {\n this.tick();\n }\n }\n }\n\n onError (data) {\n let frag = data.frag || this.fragCurrent;\n // don't handle frag error not related to main fragment\n if (frag && frag.type !== 'main') {\n return;\n }\n\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n let mediaBuffered = !!this.media && BufferHelper.isBuffered(this.media, this.media.currentTime) && BufferHelper.isBuffered(this.media, this.media.currentTime + 0.5);\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n if (!data.fatal) {\n // keep retrying until the limit will be reached\n if ((this.fragLoadError + 1) <= this.config.fragLoadingMaxRetry) {\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n let delay = Math.min(Math.pow(2, this.fragLoadError) * this.config.fragLoadingRetryDelay, this.config.fragLoadingMaxRetryTimeout);\n logger.warn(`mediaController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = window.performance.now() + delay;\n // retry loading state\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.fragLoadError++;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`mediaController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (this.state !== State.ERROR) {\n if (data.fatal) {\n // if fatal error, stop processing\n this.state = State.ERROR;\n logger.warn(`streamController: ${data.details},switch to ${this.state} state ...`);\n } else {\n // in case of non fatal error while loading level, if level controller is not retrying to load level , switch back to IDLE\n if (!data.levelRetry && this.state === State.WAITING_LEVEL) {\n this.state = State.IDLE;\n }\n }\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'main' && (this.state === State.PARSING || this.state === State.PARSED)) {\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n this._reduceMaxBufferLength(this.config.maxBufferLength);\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole buffer to recover\n logger.warn('buffer full error also media.currentTime is not buffered, flush everything');\n this.fragCurrent = null;\n // flush everything\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n }\n break;\n default:\n break;\n }\n }\n\n _reduceMaxBufferLength (minLength) {\n let config = this.config;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n logger.warn(`main:reduce max buffer length to ${config.maxMaxBufferLength}s`);\n return true;\n }\n return false;\n }\n\n /**\n * Checks the health of the buffer and attempts to resolve playback stalls.\n * @private\n */\n _checkBuffer () {\n const { media } = this;\n if (!media || media.readyState === 0) {\n // Exit early if we don't have media or if the media hasn't bufferd anything yet (readyState 0)\n return;\n }\n\n const mediaBuffer = this.mediaBuffer ? this.mediaBuffer : media;\n const buffered = mediaBuffer.buffered;\n\n if (!this.loadedmetadata && buffered.length) {\n this.loadedmetadata = true;\n this._seekToStartPos();\n } else if (this.immediateSwitch) {\n this.immediateLevelSwitchEnd();\n } else {\n this.gapController.poll(this.lastCurrentTime, buffered);\n }\n }\n\n onFragLoadEmergencyAborted () {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.tick();\n }\n\n onBufferFlushed () {\n /* after successful buffer flushing, filter flushed fragments from bufferedFrags\n use mediaBuffered instead of media (so that we will check against video.buffered ranges in case of alt audio track)\n */\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (media) {\n // filter fragments potentially evicted from buffer. this is to avoid memleak on live streams\n const elementaryStreamType = this.audioOnly ? ElementaryStreamTypes.AUDIO : ElementaryStreamTypes.VIDEO;\n this.fragmentTracker.detectEvictedFragments(elementaryStreamType, media.buffered);\n }\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\n }\n\n swapAudioCodec () {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n * @private\n */\n _seekToStartPos () {\n const { media } = this;\n const currentTime = media.currentTime;\n let startPosition = this.startPosition;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n if (currentTime !== startPosition && startPosition >= 0) {\n if (media.seeking) {\n logger.log(`could not seek to ${startPosition}, already seeking at ${currentTime}`);\n return;\n }\n const bufferStart = media.buffered.length ? media.buffered.start(0) : 0;\n const delta = bufferStart - startPosition;\n if (delta > 0 && delta < this.config.maxBufferHole) {\n logger.log(`adjusting start position by ${delta} to match buffer start`);\n startPosition += delta;\n this.startPosition = startPosition;\n }\n logger.log(`seek to target start position ${startPosition} from current time ${currentTime}. ready state ${media.readyState}`);\n media.currentTime = startPosition;\n }\n }\n\n _getAudioCodec (currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap) {\n logger.log('swapping playlist audio codec');\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n }\n\n return audioCodec;\n }\n\n get liveSyncPosition () {\n return this._liveSyncPosition;\n }\n\n set liveSyncPosition (value) {\n this._liveSyncPosition = value;\n }\n}\nexport default StreamController;\n","/*\n * Level Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { isCodecSupportedInMp4 } from '../utils/codecs';\nimport { addGroupId, computeReloadInterval } from './level-helper';\n\nlet chromeOrFirefox;\n\nexport default class LevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADED,\n Event.LEVEL_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.FRAG_LOADED,\n Event.ERROR);\n\n this.canload = false;\n this.currentLevelIndex = null;\n this.manualLevelIndex = -1;\n this.timer = null;\n\n chromeOrFirefox = /chrome|firefox/.test(navigator.userAgent.toLowerCase());\n }\n\n onHandlerDestroying () {\n this.clearTimer();\n this.manualLevelIndex = -1;\n }\n\n clearTimer () {\n if (this.timer !== null) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n startLoad () {\n let levels = this._levels;\n\n this.canload = true;\n this.levelRetryCount = 0;\n\n // clean up live level details to force reload them, and reset load errors\n if (levels) {\n levels.forEach(level => {\n level.loadError = 0;\n const levelDetails = level.details;\n if (levelDetails && levelDetails.live) {\n level.details = undefined;\n }\n });\n }\n // speed up live playlist refresh if timer exists\n if (this.timer !== null) {\n this.loadLevel();\n }\n }\n\n stopLoad () {\n this.canload = false;\n }\n\n onManifestLoaded (data) {\n let levels = [];\n let audioTracks = [];\n let bitrateStart;\n let levelSet = {};\n let levelFromSet = null;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n // regroup redundant levels together\n data.levels.forEach(level => {\n const attributes = level.attrs;\n level.loadError = 0;\n level.fragmentError = false;\n\n videoCodecFound = videoCodecFound || !!level.videoCodec;\n audioCodecFound = audioCodecFound || !!level.audioCodec;\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n if (chromeOrFirefox && level.audioCodec && level.audioCodec.indexOf('mp4a.40.34') !== -1) {\n level.audioCodec = undefined;\n }\n\n levelFromSet = levelSet[level.bitrate]; // FIXME: we would also have to match the resolution here\n\n if (!levelFromSet) {\n level.url = [level.url];\n level.urlId = 0;\n levelSet[level.bitrate] = level;\n levels.push(level);\n } else {\n levelFromSet.url.push(level.url);\n }\n\n if (attributes) {\n if (attributes.AUDIO) {\n addGroupId(levelFromSet || level, 'audio', attributes.AUDIO);\n }\n if (attributes.SUBTITLES) {\n addGroupId(levelFromSet || level, 'text', attributes.SUBTITLES);\n }\n }\n });\n\n // remove audio-only level if we also have levels with audio+video codecs signalled\n if (videoCodecFound && audioCodecFound) {\n levels = levels.filter(({ videoCodec }) => !!videoCodec);\n }\n\n // only keep levels with supported audio/video codecs\n levels = levels.filter(({ audioCodec, videoCodec }) => {\n return (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) && (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'));\n });\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(track => !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio'));\n // Reassign id's after filtering since they're used as array indices\n audioTracks.forEach((track, index) => {\n track.id = index;\n });\n }\n\n if (levels.length > 0) {\n // start bitrate is the first bitrate of the manifest\n bitrateStart = levels[0].bitrate;\n // sort level on bitrate\n levels.sort((a, b) => a.bitrate - b.bitrate);\n this._levels = levels;\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i].bitrate === bitrateStart) {\n this._firstLevel = i;\n logger.log(`manifest loaded,${levels.length} level(s) found, first bitrate:${bitrateStart}`);\n break;\n }\n }\n\n // Audio is only alternate if manifest include a URI along with the audio group tag,\n // and this is not an audio-only stream where levels contain audio-only\n const audioOnly = audioCodecFound && !videoCodecFound;\n this.hls.trigger(Event.MANIFEST_PARSED, {\n levels,\n audioTracks,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: !audioOnly && audioTracks.some(t => !!t.url)\n });\n } else {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n url: this.hls.url,\n reason: 'no level with compatible codecs found in manifest'\n });\n }\n }\n\n get levels () {\n return this._levels;\n }\n\n get level () {\n return this.currentLevelIndex;\n }\n\n set level (newLevel) {\n let levels = this._levels;\n if (levels) {\n newLevel = Math.min(newLevel, levels.length - 1);\n if (this.currentLevelIndex !== newLevel || !levels[newLevel].details) {\n this.setLevelInternal(newLevel);\n }\n }\n }\n\n setLevelInternal (newLevel) {\n const levels = this._levels;\n const hls = this.hls;\n // check if level idx is valid\n if (newLevel >= 0 && newLevel < levels.length) {\n // stopping live reloading timer if any\n this.clearTimer();\n if (this.currentLevelIndex !== newLevel) {\n logger.log(`switching to level ${newLevel}`);\n this.currentLevelIndex = newLevel;\n const levelProperties = levels[newLevel];\n levelProperties.level = newLevel;\n hls.trigger(Event.LEVEL_SWITCHING, levelProperties);\n }\n const level = levels[newLevel];\n const levelDetails = level.details;\n\n // check if we need to load playlist for this level\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n let urlId = level.urlId;\n hls.trigger(Event.LEVEL_LOADING, { url: level.url[urlId], level: newLevel, id: urlId });\n }\n } else {\n // invalid level id given, trigger error\n hls.trigger(Event.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal: false,\n reason: 'invalid level idx'\n });\n }\n }\n\n get manualLevel () {\n return this.manualLevelIndex;\n }\n\n set manualLevel (newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel () {\n return this._firstLevel;\n }\n\n set firstLevel (newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel () {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n let configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel (newLevel) {\n this._startLevel = newLevel;\n }\n\n onError (data) {\n if (data.fatal) {\n if (data.type === ErrorTypes.NETWORK_ERROR) {\n this.clearTimer();\n }\n\n return;\n }\n\n let levelError = false, fragmentError = false;\n let levelIndex;\n\n // try to recover not fatal errors\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n levelIndex = data.frag.level;\n fragmentError = true;\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n levelIndex = data.context.level;\n levelError = true;\n break;\n case ErrorDetails.REMUX_ALLOC_ERROR:\n levelIndex = data.level;\n levelError = true;\n break;\n }\n\n if (levelIndex !== undefined) {\n this.recoverLevel(data, levelIndex, levelError, fragmentError);\n }\n }\n\n /**\n * Switch to a redundant stream if any available.\n * If redundant stream is not available, emergency switch down if ABR mode is enabled.\n *\n * @param {Object} errorEvent\n * @param {Number} levelIndex current level index\n * @param {Boolean} levelError\n * @param {Boolean} fragmentError\n */\n // FIXME Find a better abstraction where fragment/level retry management is well decoupled\n recoverLevel (errorEvent, levelIndex, levelError, fragmentError) {\n let { config } = this.hls;\n let { details: errorDetails } = errorEvent;\n let level = this._levels[levelIndex];\n let redundantLevels, delay, nextLevel;\n\n level.loadError++;\n level.fragmentError = fragmentError;\n\n if (levelError) {\n if ((this.levelRetryCount + 1) <= config.levelLoadingMaxRetry) {\n // exponential backoff capped to max retry timeout\n delay = Math.min(Math.pow(2, this.levelRetryCount) * config.levelLoadingRetryDelay, config.levelLoadingMaxRetryTimeout);\n // Schedule level reload\n this.timer = setTimeout(() => this.loadLevel(), delay);\n // boolean used to inform stream controller not to switch back to IDLE on non fatal error\n errorEvent.levelRetry = true;\n this.levelRetryCount++;\n logger.warn(`level controller, ${errorDetails}, retry in ${delay} ms, current retry count is ${this.levelRetryCount}`);\n } else {\n logger.error(`level controller, cannot recover from ${errorDetails} error`);\n this.currentLevelIndex = null;\n // stopping live reloading timer if any\n this.clearTimer();\n // switch error to fatal\n errorEvent.fatal = true;\n return;\n }\n }\n\n // Try any redundant streams if available for both errors: level and fragment\n // If level.loadError reaches redundantLevels it means that we tried them all, no hope => let's switch down\n if (levelError || fragmentError) {\n redundantLevels = level.url.length;\n\n if (redundantLevels > 1 && level.loadError < redundantLevels) {\n level.urlId = (level.urlId + 1) % redundantLevels;\n level.details = undefined;\n\n logger.warn(`level controller, ${errorDetails} for level ${levelIndex}: switching to redundant URL-id ${level.urlId}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', level.attrs.AUDIO);\n } else {\n // Search for available level\n if (this.manualLevelIndex === -1) {\n // When lowest level has been reached, let's start hunt from the top\n nextLevel = (levelIndex === 0) ? this._levels.length - 1 : levelIndex - 1;\n logger.warn(`level controller, ${errorDetails}: switch to ${nextLevel}`);\n this.hls.nextAutoLevel = this.currentLevelIndex = nextLevel;\n } else if (fragmentError) {\n // Allow fragment retry as long as configuration allows.\n // reset this._level so that another call to set level() will trigger again a frag load\n logger.warn(`level controller, ${errorDetails}: reload a fragment`);\n this.currentLevelIndex = null;\n }\n }\n }\n }\n\n // reset errors on the successful load of a fragment\n onFragLoaded ({ frag }) {\n if (frag !== undefined && frag.type === 'main') {\n const level = this._levels[frag.level];\n if (level !== undefined) {\n level.fragmentError = false;\n level.loadError = 0;\n this.levelRetryCount = 0;\n }\n }\n }\n\n onLevelLoaded (data) {\n const { level, details } = data;\n // only process level loaded events matching with expected level\n if (level !== this.currentLevelIndex) {\n return;\n }\n\n const curLevel = this._levels[level];\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if (!curLevel.fragmentError) {\n curLevel.loadError = 0;\n this.levelRetryCount = 0;\n }\n // if current playlist is a live playlist, arm a timer to reload it\n if (details.live) {\n const reloadInterval = computeReloadInterval(curLevel.details, details, data.stats.trequest);\n logger.log(`live playlist, reload in ${Math.round(reloadInterval)} ms`);\n this.timer = setTimeout(() => this.loadLevel(), reloadInterval);\n } else {\n this.clearTimer();\n }\n }\n\n onAudioTrackSwitched (data) {\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n\n const currentLevel = this.hls.levels[this.currentLevelIndex];\n if (!currentLevel) {\n return;\n }\n\n if (currentLevel.audioGroupIds) {\n let urlId = -1;\n\n for (let i = 0; i < currentLevel.audioGroupIds.length; i++) {\n if (currentLevel.audioGroupIds[i] === audioGroupId) {\n urlId = i;\n break;\n }\n }\n\n if (urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n this.startLoad();\n }\n }\n }\n\n loadLevel () {\n logger.debug('call to loadLevel');\n\n if (this.currentLevelIndex !== null && this.canload) {\n const levelObject = this._levels[this.currentLevelIndex];\n\n if (typeof levelObject === 'object' &&\n levelObject.url.length > 0) {\n const level = this.currentLevelIndex;\n const id = levelObject.urlId;\n const url = levelObject.url[id];\n\n logger.log(`Attempt loading level index ${level} with URL-id ${id}`);\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n\n this.hls.trigger(Event.LEVEL_LOADING, { url, level, id });\n }\n }\n }\n\n get nextLoadLevel () {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel (nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n\n removeLevel (levelIndex, urlId) {\n const levels = this.levels.filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n\n if (level.url.length > 1 && urlId !== undefined) {\n level.url = level.url.filter((url, id) => id !== urlId);\n level.urlId = 0;\n return true;\n }\n return false;\n }).map((level, index) => {\n const { details } = level;\n if (details && details.fragments) {\n details.fragments.forEach((fragment) => {\n fragment.level = index;\n });\n }\n return level;\n });\n\n this._levels = levels;\n\n this.hls.trigger(Event.LEVELS_UPDATED, { levels });\n }\n}\n","\nexport function sendAddTrackEvent (track: TextTrack, videoEl: HTMLMediaElement) {\n let event: Event;\n try {\n event = new Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n (event as any).track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function clearCurrentCues (track: TextTrack) {\n if (track?.cues) {\n while (track.cues.length > 0) {\n track.removeCue(track.cues[0]);\n }\n }\n}\n\n/**\n * Given a list of Cues, finds the closest cue matching the given time.\n * Modified verison of binary search O(log(n)).\n *\n * @export\n * @param {(TextTrackCueList | TextTrackCue[])} cues - List of cues.\n * @param {number} time - Target time, to find closest cue to.\n * @returns {TextTrackCue}\n */\nexport function getClosestCue (cues: TextTrackCueList | TextTrackCue[], time: number): TextTrackCue {\n // If the offset is less than the first element, the first element is the closest.\n if (time < cues[0].endTime) {\n return cues[0];\n }\n // If the offset is greater than the last cue, the last is the closest.\n if (time > cues[cues.length - 1].endTime) {\n return cues[cues.length - 1];\n }\n\n let left = 0;\n let right = cues.length - 1;\n\n while (left <= right) {\n const mid = Math.floor((right + left) / 2);\n\n if (time < cues[mid].endTime) {\n right = mid - 1;\n } else if (time > cues[mid].endTime) {\n left = mid + 1;\n } else {\n // If it's not lower or higher, it must be equal.\n return cues[mid];\n }\n }\n // At this point, left and right have swapped.\n // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.\n return (cues[left].endTime - time) < (time - cues[right].endTime) ? cues[left] : cues[right];\n}\n","/*\n * id3 metadata track controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport ID3 from '../demux/id3';\nimport { sendAddTrackEvent, clearCurrentCues, getClosestCue } from '../utils/texttrack-utils';\n\nconst MIN_CUE_DURATION = 0.25;\n\nclass ID3TrackController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_METADATA,\n Event.LIVE_BACK_BUFFER_REACHED\n );\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Add ID3 metatadata text track.\n onMediaAttached (data) {\n this.media = data.media;\n if (!this.media) {\n\n }\n }\n\n onMediaDetaching () {\n clearCurrentCues(this.id3Track);\n this.id3Track = undefined;\n this.media = undefined;\n }\n\n getID3Track (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n let textTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n }\n\n onFragParsingMetadata (data) {\n const fragment = data.frag;\n const samples = data.samples;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.getID3Track(this.media.textTracks);\n this.id3Track.mode = 'hidden';\n }\n\n // Attempt to recreate Safari functionality by creating\n // WebKitDataCue objects when available and store the decoded\n // ID3 data in the value property of the cue\n let Cue = window.WebKitDataCue || window.VTTCue || window.TextTrackCue;\n\n for (let i = 0; i < samples.length; i++) {\n const frames = ID3.getID3Frames(samples[i].data);\n if (frames) {\n // Ensure the pts is positive - sometimes it's reported as a small negative number\n let startTime = Math.max(samples[i].pts, 0);\n let endTime = i < samples.length - 1 ? samples[i + 1].pts : fragment.endPTS;\n if (!endTime) {\n endTime = fragment.start + fragment.duration;\n }\n\n const timeDiff = endTime - startTime;\n if (timeDiff <= 0) {\n endTime = startTime + MIN_CUE_DURATION;\n }\n\n for (let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!ID3.isTimeStampFrame(frame)) {\n const cue = new Cue(startTime, endTime, '');\n cue.value = frame;\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n\n onLiveBackBufferReached ({ bufferEnd }) {\n const { id3Track } = this;\n if (!id3Track || !id3Track.cues || !id3Track.cues.length) {\n return;\n }\n const foundCue = getClosestCue(id3Track.cues, bufferEnd);\n if (!foundCue) {\n return;\n }\n while (id3Track.cues[0] !== foundCue) {\n id3Track.removeCue(id3Track.cues[0]);\n }\n }\n}\n\nexport default ID3TrackController;\n","/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n private alpha_: number;\n private estimate_: number;\n private totalWeight_: number;\n\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor (halfLife: number) {\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = 0;\n this.totalWeight_ = 0;\n }\n\n sample (weight: number, value: number) {\n let adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n\n getTotalWeight (): number {\n return this.totalWeight_;\n }\n\n getEstimate (): number {\n if (this.alpha_) {\n let zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n return this.estimate_ / zeroFactor;\n } else {\n return this.estimate_;\n }\n }\n}\n\nexport default EWMA;\n","/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nimport EWMA from '../utils/ewma';\n\nclass EwmaBandWidthEstimator {\n hls: any;\n\n private defaultEstimate_: number;\n private minWeight_: number;\n private minDelayMs_: number;\n private slow_: EWMA;\n private fast_: EWMA;\n\n // TODO(typescript-hls)\n constructor (hls: any, slow: number, fast: number, defaultEstimate: number) {\n this.hls = hls;\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n }\n\n sample (durationMs: number, numBytes: number) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n let numBits = 8 * numBytes,\n // weight is duration in seconds\n durationS = durationMs / 1000,\n // value is bandwidth in bits/s\n bandwidthInBps = numBits / durationS;\n this.fast_.sample(durationS, bandwidthInBps);\n this.slow_.sample(durationS, bandwidthInBps);\n }\n\n canEstimate (): boolean {\n let fast = this.fast_;\n return (fast && fast.getTotalWeight() >= this.minWeight_);\n }\n\n getEstimate (): number {\n if (this.canEstimate()) {\n // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n\n destroy () {\n }\n}\nexport default EwmaBandWidthEstimator;\n","/*\n * simple ABR Controller\n * - compute next level based on last fragment bw heuristics\n * - implement an abandon rules triggered if we have less than 2 frag buffered and if computed bw shows that we risk buffer stalling\n */\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\n\nconst { performance } = window;\n\nclass AbrController extends EventHandler {\n constructor (hls) {\n super(hls, Event.FRAG_LOADING,\n Event.FRAG_LOADED,\n Event.FRAG_BUFFERED,\n Event.ERROR);\n this.lastLoadedFragLevel = 0;\n this._nextAutoLevel = -1;\n this.hls = hls;\n this.timer = null;\n this._bwEstimator = null;\n this.onCheck = this._abandonRulesCheck.bind(this);\n }\n\n destroy () {\n this.clearTimer();\n EventHandler.prototype.destroy.call(this);\n }\n\n onFragLoading (data) {\n const frag = data.frag;\n if (frag.type === 'main') {\n if (!this.timer) {\n this.fragCurrent = frag;\n this.timer = setInterval(this.onCheck, 100);\n }\n\n // lazy init of BwEstimator, rationale is that we use different params for Live/VoD\n // so we need to wait for stream manifest / playlist type to instantiate it.\n if (!this._bwEstimator) {\n const hls = this.hls;\n const config = hls.config;\n const level = frag.level;\n const isLive = hls.levels[level].details.live;\n\n let ewmaFast;\n let ewmaSlow;\n if (isLive) {\n ewmaFast = config.abrEwmaFastLive;\n ewmaSlow = config.abrEwmaSlowLive;\n } else {\n ewmaFast = config.abrEwmaFastVoD;\n ewmaSlow = config.abrEwmaSlowVoD;\n }\n this._bwEstimator = new EwmaBandWidthEstimator(hls, ewmaSlow, ewmaFast, config.abrEwmaDefaultEstimate);\n }\n }\n }\n\n _abandonRulesCheck () {\n /*\n monitor fragment retrieval time...\n we compute expected time of arrival of the complete fragment.\n we compare it to expected time of buffer starvation\n */\n const hls = this.hls;\n const video = hls.media;\n const frag = this.fragCurrent;\n\n if (!frag) {\n return;\n }\n\n const loader = frag.loader;\n\n // if loader has been destroyed or loading has been aborted, stop timer and return\n if (!loader || (loader.stats && loader.stats.aborted)) {\n logger.warn('frag loader destroy or aborted, disarm abandonRules');\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n let stats = loader.stats;\n /* only monitor frag retrieval time if\n (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) */\n if (video && stats && ((!video.paused && (video.playbackRate !== 0)) || !video.readyState) && frag.autoLevel && frag.level) {\n const requestDelay = performance.now() - stats.trequest;\n const playbackRate = Math.abs(video.playbackRate);\n\n // monitor fragment load progress after half of expected fragment duration,to stabilize bitrate\n if (requestDelay > (500 * frag.duration / playbackRate)) {\n const levels = hls.levels;\n const 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\n\n // compute expected fragment length using frag duration and level bitrate. also ensure that expected len is gte than already loaded size\n const level = levels[frag.level];\n if (!level) {\n return;\n }\n const levelBitrate = level.realBitrate ? Math.max(level.realBitrate, level.bitrate) : level.bitrate;\n const expectedLen = stats.total ? stats.total : Math.max(stats.loaded, Math.round(frag.duration * levelBitrate / 8));\n const pos = video.currentTime;\n const fragLoadedDelay = (expectedLen - stats.loaded) / loadRate;\n const bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, hls.config.maxBufferHole).end - pos) / playbackRate;\n\n // consider emergency switch down only if we have less than 2 frag buffered AND\n // time to finish loading current fragment is bigger than buffer starvation delay\n // ie if we risk buffer starvation if bw does not increase quickly\n if ((bufferStarvationDelay < (2 * frag.duration / playbackRate)) && (fragLoadedDelay > bufferStarvationDelay)) {\n const minAutoLevel = hls.minAutoLevel;\n let fragLevelNextLoadedDelay;\n let nextLoadLevel;\n // lets iterate through lower level and try to find the biggest one that could avoid rebuffering\n // we start from current level - 1 and we step down , until we find a matching level\n for (nextLoadLevel = frag.level - 1; nextLoadLevel > minAutoLevel; nextLoadLevel--) {\n // compute time to load next fragment at lower level\n // 0.8 : consider only 80% of current bw to be conservative\n // 8 = bits per byte (bps/Bps)\n const levelNextBitrate = levels[nextLoadLevel].realBitrate\n ? Math.max(levels[nextLoadLevel].realBitrate, levels[nextLoadLevel].bitrate)\n : levels[nextLoadLevel].bitrate;\n\n const fragLevelNextLoadedDelay = frag.duration * levelNextBitrate / (8 * 0.8 * loadRate);\n\n if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n // we found a lower level that be rebuffering free with current estimated bw !\n break;\n }\n }\n // only emergency switch down if it takes less time to load new fragment at lowest level instead\n // of finishing loading current one ...\n if (fragLevelNextLoadedDelay < fragLoadedDelay) {\n 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)}`);\n // force next load level in auto mode\n hls.nextLoadLevel = nextLoadLevel;\n // update bw estimate for this fragment before cancelling load (this will help reducing the bw)\n this._bwEstimator.sample(requestDelay, stats.loaded);\n // abort fragment loading\n loader.abort();\n // stop abandon rules timer\n this.clearTimer();\n hls.trigger(Event.FRAG_LOAD_EMERGENCY_ABORTED, { frag: frag, stats: stats });\n }\n }\n }\n }\n }\n\n onFragLoaded (data) {\n const frag = data.frag;\n if (frag.type === 'main' && Number.isFinite(frag.sn)) {\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // store level id after successful fragment load\n this.lastLoadedFragLevel = frag.level;\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const level = this.hls.levels[frag.level];\n let loadedBytes = (level.loaded ? level.loaded.bytes : 0) + data.stats.loaded;\n let loadedDuration = (level.loaded ? level.loaded.duration : 0) + data.frag.duration;\n level.loaded = { bytes: loadedBytes, duration: loadedDuration };\n level.realBitrate = Math.round(8 * loadedBytes / loadedDuration);\n }\n // if fragment has been loaded to perform a bitrate test,\n if (data.frag.bitrateTest) {\n let stats = data.stats;\n stats.tparsed = stats.tbuffered = stats.tload;\n this.onFragBuffered(data);\n }\n }\n }\n\n onFragBuffered (data) {\n const stats = data.stats;\n const frag = data.frag;\n // only update stats on first frag buffering\n // if same frag is loaded multiple times, it might be in browser cache, and loaded quickly\n // and leading to wrong bw estimation\n // on bitrate test, also only update stats once (if tload = tbuffered == on FRAG_LOADED)\n if (stats.aborted !== true && frag.type === 'main' && Number.isFinite(frag.sn) && ((!frag.bitrateTest || stats.tload === stats.tbuffered))) {\n // use tparsed-trequest instead of tbuffered-trequest to compute fragLoadingProcessing; rationale is that buffer appending only happens once media is attached\n // 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\n // as a consequence it could happen really late in the process. meaning that appending duration might appears huge ... leading to underestimated throughput estimation\n let fragLoadingProcessingMs = stats.tparsed - stats.trequest;\n 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))}`);\n this._bwEstimator.sample(fragLoadingProcessingMs, stats.loaded);\n stats.bwEstimate = this._bwEstimator.getEstimate();\n // if fragment has been loaded to perform a bitrate test, (hls.startLevel = -1), store bitrate test delay duration\n if (frag.bitrateTest) {\n this.bitrateTestDelay = fragLoadingProcessingMs / 1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n }\n\n onError (data) {\n // stop timer in case of frag loading error\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n this.clearTimer();\n break;\n default:\n break;\n }\n }\n\n clearTimer () {\n clearInterval(this.timer);\n this.timer = null;\n }\n\n // return next auto level\n get nextAutoLevel () {\n const forcedAutoLevel = this._nextAutoLevel;\n const bwEstimator = this._bwEstimator;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && (!bwEstimator || !bwEstimator.canEstimate())) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n let nextABRAutoLevel = this._nextABRAutoLevel;\n // if forced auto level has been defined, use it to cap ABR computed quality level\n if (forcedAutoLevel !== -1) {\n nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);\n }\n\n return nextABRAutoLevel;\n }\n get _nextABRAutoLevel () {\n let hls = this.hls;\n const { maxAutoLevel, levels, config, minAutoLevel } = hls;\n const video = hls.media;\n const currentLevel = this.lastLoadedFragLevel;\n const currentFragDuration = this.fragCurrent ? this.fragCurrent.duration : 0;\n const pos = (video ? video.currentTime : 0);\n\n // playbackRate is the absolute value of the playback rate; if video.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n const playbackRate = ((video && (video.playbackRate !== 0)) ? Math.abs(video.playbackRate) : 1.0);\n const avgbw = this._bwEstimator ? this._bwEstimator.getEstimate() : config.abrEwmaDefaultEstimate;\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const bufferStarvationDelay = (BufferHelper.bufferInfo(video, pos, config.maxBufferHole).end - pos) / playbackRate;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n let bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay, config.abrBandWidthFactor, config.abrBandWidthUpFactor, levels);\n if (bestLevel >= 0) {\n return bestLevel;\n } else {\n logger.trace('rebuffering expected to happen, lets try to find a quality level minimizing the rebuffering');\n // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n // if no matching level found, logic will return 0\n let maxStarvationDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxStarvationDelay) : config.maxStarvationDelay;\n let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\n\n if (bufferStarvationDelay === 0) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n let bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration ? Math.min(currentFragDuration, config.maxLoadingDelay) : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n logger.trace(`bitrate test took ${Math.round(1000 * bitrateTestDelay)}ms, set first fragment max fetchDuration to ${Math.round(1000 * maxStarvationDelay)} ms`);\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n bestLevel = this._findBestLevel(currentLevel, currentFragDuration, avgbw, minAutoLevel, maxAutoLevel, bufferStarvationDelay + maxStarvationDelay, bwFactor, bwUpFactor, levels);\n return Math.max(bestLevel, 0);\n }\n }\n\n _findBestLevel (currentLevel, currentFragDuration, currentBw, minAutoLevel, maxAutoLevel, maxFetchDuration, bwFactor, bwUpFactor, levels) {\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n let levelInfo = levels[i];\n\n if (!levelInfo) {\n continue;\n }\n\n const levelDetails = levelInfo.details;\n const avgDuration = levelDetails ? levelDetails.totalduration / levelDetails.fragments.length : currentFragDuration;\n const live = levelDetails ? levelDetails.live : false;\n\n let adjustedbw;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (i <= currentLevel) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n const bitrate = levels[i].realBitrate ? Math.max(levels[i].realBitrate, levels[i].bitrate) : levels[i].bitrate;\n const fetchDuration = bitrate * avgDuration / adjustedbw;\n\n logger.trace(`level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: ${i}/${Math.round(adjustedbw)}/${bitrate}/${avgDuration}/${maxFetchDuration}/${fetchDuration}`);\n // if adjusted bw is greater than level bitrate AND\n if (adjustedbw > bitrate &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // 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 ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that _findBestLevel will return -1\n (!fetchDuration || (live && !this.bitrateTestDelay) || fetchDuration < maxFetchDuration)) {\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n set nextAutoLevel (nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n}\n\nexport default AbrController;\n","/*\n * Buffer Controller\n */\n\nimport Events from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\n\nimport { TrackSet } from '../types/track';\nimport { Segment } from '../types/segment';\nimport { BufferControllerConfig } from '../config';\n\n// Add extension properties to SourceBuffers from the DOM API.\ntype ExtendedSourceBuffer = SourceBuffer & {\n ended?: boolean\n};\n\ntype SourceBufferName = 'video' | 'audio';\ntype SourceBuffers = Partial<Record<SourceBufferName, ExtendedSourceBuffer>>;\n\ninterface SourceBufferFlushRange {\n start: number;\n end: number;\n type: SourceBufferName\n}\n\nconst MediaSource = getMediaSource();\n\nclass BufferController extends EventHandler {\n // the value that we have set mediasource.duration to\n // (the actual duration may be tweaked slighly by the browser)\n private _msDuration: number | null = null;\n // the value that we want to set mediaSource.duration to\n private _levelDuration: number | null = null;\n // the target duration of the current media playlist\n private _levelTargetDuration: number = 10;\n // current stream state: true - for live broadcast, false - for VoD content\n private _live: boolean | null = null;\n // cache the self generated object url to detect hijack of video tag\n private _objectUrl: string | null = null;\n\n // signals that the sourceBuffers need to be flushed\n private _needsFlush: boolean = false;\n\n // signals that mediaSource should have endOfStream called\n private _needsEos: boolean = false;\n\n private config: BufferControllerConfig;\n\n // this is optional because this property is removed from the class sometimes\n public audioTimestampOffset?: number;\n\n // The number of BUFFER_CODEC events received before any sourceBuffers are created\n public bufferCodecEventsExpected: number = 0;\n\n // The total number of BUFFER_CODEC events received\n private _bufferCodecEventsTotal: number = 0;\n\n // A reference to the attached media element\n public media: HTMLMediaElement | null = null;\n\n // A reference to the active media source\n public mediaSource: MediaSource | null = null;\n\n // List of pending segments to be appended to source buffer\n public segments: Segment[] = [];\n\n public parent?: string;\n\n // A guard to see if we are currently appending to the source buffer\n public appending: boolean = false;\n\n // counters\n public appended: number = 0;\n public appendError: number = 0;\n public flushBufferCounter: number = 0;\n\n public tracks: TrackSet = {};\n public pendingTracks: TrackSet = {};\n public sourceBuffer: SourceBuffers = {};\n public flushRange: SourceBufferFlushRange[] = [];\n\n constructor (hls: any) {\n super(hls,\n Events.MEDIA_ATTACHING,\n Events.MEDIA_DETACHING,\n Events.MANIFEST_PARSED,\n Events.BUFFER_RESET,\n Events.BUFFER_APPENDING,\n Events.BUFFER_CODECS,\n Events.BUFFER_EOS,\n Events.BUFFER_FLUSHING,\n Events.LEVEL_PTS_UPDATED,\n Events.LEVEL_UPDATED);\n\n this.config = hls.config;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n onLevelPtsUpdated (data: { type: SourceBufferName, start: number }) {\n let type = data.type;\n let audioTrack = this.tracks.audio;\n\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // 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\n // `SourceBuffer.abort()` and adjusting `SourceBuffer.timestampOffset` if `SourceBuffer.updating` is false or awaiting `updateend`\n // event if SB is in updating state.\n // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n\n if (type === 'audio' && audioTrack && audioTrack.container === 'audio/mpeg') { // Chrome audio mp3 track\n let audioBuffer = this.sourceBuffer.audio;\n if (!audioBuffer) {\n throw Error('Level PTS Updated and source buffer for audio uninitalized');\n }\n\n let delta = Math.abs(audioBuffer.timestampOffset - data.start);\n\n // adjust timestamp offset if time delta is greater than 100ms\n if (delta > 0.1) {\n let updating = audioBuffer.updating;\n\n try {\n audioBuffer.abort();\n } catch (err) {\n logger.warn('can not abort audio buffer: ' + err);\n }\n\n if (!updating) {\n logger.warn('change mpeg audio timestamp offset from ' + audioBuffer.timestampOffset + ' to ' + data.start);\n audioBuffer.timestampOffset = data.start;\n } else {\n this.audioTimestampOffset = data.start;\n }\n }\n }\n }\n\n onManifestParsed (data: { altAudio: boolean, audio: boolean, video: boolean }) {\n // in case of alt audio (where all tracks have urls) 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n let codecEvents: number = 2;\n if (data.audio && !data.video || !data.altAudio) {\n codecEvents = 1;\n }\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;\n\n logger.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`);\n }\n\n onMediaAttaching (data: { media: HTMLMediaElement }) {\n let media = this.media = data.media;\n if (media && MediaSource) {\n // setup the media source\n let ms = this.mediaSource = new MediaSource();\n // Media Source listeners\n ms.addEventListener('sourceopen', this._onMediaSourceOpen);\n ms.addEventListener('sourceended', this._onMediaSourceEnded);\n ms.addEventListener('sourceclose', this._onMediaSourceClose);\n // link video and media Source\n media.src = window.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n }\n }\n\n onMediaDetaching () {\n logger.log('media source detaching');\n let ms = this.mediaSource;\n if (ms) {\n if (ms.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n ms.endOfStream();\n } catch (err) {\n logger.warn(`onMediaDetaching:${err.message} while calling endOfStream`);\n }\n }\n ms.removeEventListener('sourceopen', this._onMediaSourceOpen);\n ms.removeEventListener('sourceended', this._onMediaSourceEnded);\n ms.removeEventListener('sourceclose', this._onMediaSourceClose);\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (this.media) {\n if (this._objectUrl) {\n window.URL.revokeObjectURL(this._objectUrl);\n }\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (this.media.src === this._objectUrl) {\n this.media.removeAttribute('src');\n this.media.load();\n } else {\n logger.warn('media.src was changed by a third party - skip cleanup');\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = null;\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;\n this.pendingTracks = {};\n this.tracks = {};\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n this.hls.trigger(Events.MEDIA_DETACHED);\n }\n\n checkPendingTracks () {\n let { bufferCodecEventsExpected, pendingTracks } = this;\n\n // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n // data has been appended to existing ones.\n // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n const pendingTracksCount = Object.keys(pendingTracks).length;\n if ((pendingTracksCount && !bufferCodecEventsExpected) || pendingTracksCount === 2) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n this.doAppending();\n }\n }\n\n private _onMediaSourceOpen = () => {\n logger.log('media source opened');\n this.hls.trigger(Events.MEDIA_ATTACHED, { media: this.media });\n let mediaSource = this.mediaSource;\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n }\n this.checkPendingTracks();\n }\n\n private _onMediaSourceClose = () => {\n logger.log('media source closed');\n }\n\n private _onMediaSourceEnded = () => {\n logger.log('media source ended');\n }\n\n private _onSBUpdateEnd = () => {\n // update timestampOffset\n if (this.audioTimestampOffset && this.sourceBuffer.audio) {\n let audioBuffer = this.sourceBuffer.audio;\n\n logger.warn(`change mpeg audio timestamp offset from ${audioBuffer.timestampOffset} to ${this.audioTimestampOffset}`);\n audioBuffer.timestampOffset = this.audioTimestampOffset;\n delete this.audioTimestampOffset;\n }\n\n if (this._needsFlush) {\n this.doFlush();\n }\n\n if (this._needsEos) {\n this.checkEos();\n }\n\n this.appending = false;\n let parent = this.parent;\n // count nb of pending segments waiting for appending on this sourcebuffer\n let pending = this.segments.reduce((counter, segment) => (segment.parent === parent) ? counter + 1 : counter, 0);\n\n // this.sourceBuffer is better to use than media.buffered as it is closer to the PTS data from the fragments\n const timeRanges: Partial<Record<SourceBufferName, TimeRanges>> = {};\n const sbSet = this.sourceBuffer;\n for (let streamType in sbSet) {\n const sb = sbSet[streamType as SourceBufferName];\n if (!sb) {\n throw Error(`handling source buffer update end error: source buffer for ${streamType} uninitilized and unable to update buffered TimeRanges.`);\n }\n timeRanges[streamType as SourceBufferName] = sb.buffered;\n }\n\n this.hls.trigger(Events.BUFFER_APPENDED, { parent, pending, timeRanges });\n // don't append in flushing mode\n if (!this._needsFlush) {\n this.doAppending();\n }\n\n this.updateMediaElementDuration();\n\n // appending goes first\n if (pending === 0) {\n this.flushLiveBackBuffer();\n }\n }\n\n private _onSBUpdateError = (event: Event) => {\n logger.error('sourceBuffer error:', event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // this error might not always be fatal (it is fatal if decode error is set, in that case\n // it will be followed by a mediaElement error ...)\n this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_APPENDING_ERROR, fatal: false });\n // we don't need to do more than that, as accordin to the spec, updateend will be fired just after\n }\n\n onBufferReset () {\n const sourceBuffer = this.sourceBuffer;\n for (let type in sourceBuffer) {\n const sb = sourceBuffer[type];\n try {\n if (sb) {\n if (this.mediaSource) {\n this.mediaSource.removeSourceBuffer(sb);\n }\n sb.removeEventListener('updateend', this._onSBUpdateEnd);\n sb.removeEventListener('error', this._onSBUpdateError);\n }\n } catch (err) {\n }\n }\n this.sourceBuffer = {};\n this.flushRange = [];\n this.segments = [];\n this.appended = 0;\n }\n\n onBufferCodecs (tracks: TrackSet) {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n // if sourcebuffers already created, do nothing ...\n if (Object.keys(this.sourceBuffer).length) {\n return;\n }\n\n Object.keys(tracks).forEach(trackName => {\n this.pendingTracks[trackName] = tracks[trackName];\n });\n\n this.bufferCodecEventsExpected = Math.max(this.bufferCodecEventsExpected - 1, 0);\n if (this.mediaSource && this.mediaSource.readyState === 'open') {\n this.checkPendingTracks();\n }\n }\n\n createSourceBuffers (tracks: TrackSet) {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource) {\n throw Error('createSourceBuffers called when mediaSource was null');\n }\n\n for (let trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n let track = tracks[trackName as keyof TrackSet];\n if (!track) {\n throw Error(`source buffer exists for track ${trackName}, however track does not`);\n }\n // use levelCodec as first priority\n let codec = track.levelCodec || track.codec;\n let mimeType = `${track.container};codecs=${codec}`;\n logger.log(`creating sourceBuffer(${mimeType})`);\n try {\n let sb = sourceBuffer[trackName] = mediaSource.addSourceBuffer(mimeType);\n sb.addEventListener('updateend', this._onSBUpdateEnd);\n sb.addEventListener('error', this._onSBUpdateError);\n this.tracks[trackName] = {\n buffer: sb,\n codec: codec,\n id: track.id,\n container: track.container,\n levelCodec: track.levelCodec\n };\n } catch (err) {\n logger.error(`error while trying to add sourceBuffer:${err.message}`);\n this.hls.trigger(Events.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: ErrorDetails.BUFFER_ADD_CODEC_ERROR, fatal: false, err: err, mimeType: mimeType });\n }\n }\n }\n this.hls.trigger(Events.BUFFER_CREATED, { tracks: this.tracks });\n }\n\n onBufferAppending (data: Segment) {\n if (!this._needsFlush) {\n if (!this.segments) {\n this.segments = [ data ];\n } else {\n this.segments.push(data);\n }\n\n this.doAppending();\n }\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n // an undefined data.type will mark all buffers as EOS.\n onBufferEos (data: { type?: SourceBufferName }) {\n for (const type in this.sourceBuffer) {\n if (!data.type || data.type === type) {\n const sb = this.sourceBuffer[type as SourceBufferName];\n if (sb && !sb.ended) {\n sb.ended = true;\n logger.log(`${type} sourceBuffer now EOS`);\n }\n }\n }\n\n this.checkEos();\n }\n\n // if all source buffers are marked as ended, signal endOfStream() to MediaSource.\n checkEos () {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n this._needsEos = false;\n return;\n }\n\n for (let type in sourceBuffer) {\n const sb = sourceBuffer[type as SourceBufferName];\n if (!sb) continue;\n\n if (!sb.ended) {\n return;\n }\n\n if (sb.updating) {\n this._needsEos = true;\n return;\n }\n }\n\n logger.log('all media data are available, signal endOfStream() to MediaSource and stop loading fragment');\n // Notify the media element that it now has all of the media data\n try {\n mediaSource.endOfStream();\n } catch (e) {\n logger.warn('exception while calling mediaSource.endOfStream()');\n }\n this._needsEos = false;\n }\n\n onBufferFlushing (data: { startOffset: number, endOffset: number, type?: SourceBufferName }) {\n if (data.type) {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: data.type });\n } else {\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: 'video' });\n this.flushRange.push({ start: data.startOffset, end: data.endOffset, type: 'audio' });\n }\n\n // attempt flush immediately\n this.flushBufferCounter = 0;\n this.doFlush();\n }\n\n flushLiveBackBuffer () {\n // clear back buffer for live only\n if (!this._live) {\n return;\n }\n\n const liveBackBufferLength = this.config.liveBackBufferLength;\n if (!isFinite(liveBackBufferLength) || liveBackBufferLength < 0) {\n return;\n }\n\n if (!this.media) {\n logger.error('flushLiveBackBuffer called without attaching media');\n return;\n }\n\n const currentTime = this.media.currentTime;\n const sourceBuffer = this.sourceBuffer;\n const bufferTypes = Object.keys(sourceBuffer);\n const targetBackBufferPosition = currentTime - Math.max(liveBackBufferLength, this._levelTargetDuration);\n\n for (let index = bufferTypes.length - 1; index >= 0; index--) {\n const bufferType = bufferTypes[index];\n const sb = sourceBuffer[bufferType as SourceBufferName];\n if (sb) {\n const buffered = sb.buffered;\n // when target buffer start exceeds actual buffer start\n if (buffered.length > 0 && targetBackBufferPosition > buffered.start(0)) {\n // remove buffer up until current time minus minimum back buffer length (removing buffer too close to current\n // time will lead to playback freezing)\n // credits for level target duration - https://github.com/videojs/http-streaming/blob/3132933b6aa99ddefab29c10447624efd6fd6e52/src/segment-loader.js#L91\n if (this.removeBufferRange(bufferType, sb, 0, targetBackBufferPosition)) {\n this.hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, { bufferEnd: targetBackBufferPosition });\n }\n }\n }\n }\n }\n\n onLevelUpdated ({ details }: { details: { totalduration: number, targetduration?: number, averagetargetduration?: number, live: boolean, fragments: any[] } }) {\n if (details.fragments.length > 0) {\n this._levelDuration = details.totalduration + details.fragments[0].start;\n this._levelTargetDuration = details.averagetargetduration || details.targetduration || 10;\n this._live = details.live;\n this.updateMediaElementDuration();\n }\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n updateMediaElementDuration () {\n let { config } = this;\n let duration: number;\n\n if (this._levelDuration === null ||\n !this.media ||\n !this.mediaSource ||\n !this.sourceBuffer ||\n this.media.readyState === 0 ||\n this.mediaSource.readyState !== 'open') {\n return;\n }\n\n for (let type in this.sourceBuffer) {\n const sb = this.sourceBuffer[type];\n if (sb && sb.updating === true) {\n // can't set duration whilst a buffer is updating\n return;\n }\n }\n\n duration = this.media.duration;\n // initialise to the value that the media source is reporting\n if (this._msDuration === null) {\n this._msDuration = this.mediaSource.duration;\n }\n\n if (this._live === true && config.liveDurationInfinity === true) {\n // Override duration to Infinity\n logger.log('Media Source duration is set to Infinity');\n this._msDuration = this.mediaSource.duration = Infinity;\n } else if ((this._levelDuration > this._msDuration && this._levelDuration > duration) || !Number.isFinite(duration)) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(`Updating Media Source duration to ${this._levelDuration.toFixed(3)}`);\n this._msDuration = this.mediaSource.duration = this._levelDuration;\n }\n }\n\n doFlush () {\n // loop through all buffer ranges to flush\n while (this.flushRange.length) {\n let range = this.flushRange[0];\n // flushBuffer will abort any buffer append in progress and flush Audio/Video Buffer\n if (this.flushBuffer(range.start, range.end, range.type)) {\n // range flushed, remove from flush array\n this.flushRange.shift();\n this.flushBufferCounter = 0;\n } else {\n this._needsFlush = true;\n // avoid looping, wait for SB update end to retrigger a flush\n return;\n }\n }\n if (this.flushRange.length === 0) {\n // everything flushed\n this._needsFlush = false;\n\n // let's recompute this.appended, which is used to avoid flush looping\n let appended = 0;\n let sourceBuffer = this.sourceBuffer;\n try {\n for (let type in sourceBuffer) {\n const sb = sourceBuffer[type];\n if (sb) {\n appended += sb.buffered.length;\n }\n }\n } catch (error) {\n // error could be thrown while accessing buffered, in case sourcebuffer has already been removed from MediaSource\n // this is harmess at this stage, catch this to avoid reporting an internal exception\n logger.error('error while accessing sourceBuffer.buffered');\n }\n this.appended = appended;\n this.hls.trigger(Events.BUFFER_FLUSHED);\n }\n }\n\n doAppending () {\n let { config, hls, segments, sourceBuffer } = this;\n if (!Object.keys(sourceBuffer).length) {\n // early exit if no source buffers have been initialized yet\n return;\n }\n\n if (!this.media || this.media.error) {\n this.segments = [];\n logger.error('trying to append although a media error occured, flush segment and abort');\n return;\n }\n\n if (this.appending) {\n // logger.log(`sb appending in progress`);\n return;\n }\n\n const segment = segments.shift();\n if (!segment) { // handle undefined shift\n return;\n }\n\n try {\n const sb = sourceBuffer[segment.type];\n if (!sb) {\n // in case we don't have any source buffer matching with this segment type,\n // it means that Mediasource fails to create sourcebuffer\n // discard this segment, and trigger update end\n this._onSBUpdateEnd();\n return;\n }\n\n if (sb.updating) {\n // if we are still updating the source buffer from the last segment, place this back at the front of the queue\n segments.unshift(segment);\n return;\n }\n\n // reset sourceBuffer ended flag before appending segment\n sb.ended = false;\n // logger.log(`appending ${segment.content} ${type} SB, size:${segment.data.length}, ${segment.parent}`);\n this.parent = segment.parent;\n sb.appendBuffer(segment.data);\n this.appendError = 0;\n this.appended++;\n this.appending = true;\n } catch (err) {\n // in case any error occured while appending, put back segment in segments table\n logger.error(`error while trying to append buffer:${err.message}`);\n segments.unshift(segment);\n let event = { type: ErrorTypes.MEDIA_ERROR, parent: segment.parent, details: '', fatal: false };\n if (err.code === 22) {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n this.segments = [];\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n } else {\n this.appendError++;\n event.details = ErrorDetails.BUFFER_APPEND_ERROR;\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. retrying help recovering this\n */\n if (this.appendError > config.appendErrorMaxRetry) {\n logger.log(`fail ${config.appendErrorMaxRetry} times to append segment in sourceBuffer`);\n this.segments = [];\n event.fatal = true;\n }\n }\n hls.trigger(Events.ERROR, event);\n }\n }\n\n /*\n flush specified buffered range,\n return true once range has been flushed.\n as sourceBuffer.remove() is asynchronous, flushBuffer will be retriggered on sourceBuffer update end\n */\n flushBuffer (startOffset: number, endOffset: number, sbType: SourceBufferName): boolean {\n const sourceBuffer = this.sourceBuffer;\n // exit if no sourceBuffers are initialized\n if (!Object.keys(sourceBuffer).length) {\n return true;\n }\n\n let currentTime: string = 'null';\n if (this.media) {\n currentTime = this.media.currentTime.toFixed(3);\n }\n logger.log(`flushBuffer,pos/start/end: ${currentTime}/${startOffset}/${endOffset}`);\n\n // safeguard to avoid infinite looping : don't try to flush more than the nb of appended segments\n if (this.flushBufferCounter >= this.appended) {\n logger.warn('abort flushing too many retries');\n return true;\n }\n\n const sb = sourceBuffer[sbType];\n // we are going to flush buffer, mark source buffer as 'not ended'\n if (sb) {\n sb.ended = false;\n if (!sb.updating) {\n if (this.removeBufferRange(sbType, sb, startOffset, endOffset)) {\n this.flushBufferCounter++;\n return false;\n }\n } else {\n logger.warn('cannot flush, sb updating in progress');\n return false;\n }\n }\n\n logger.log('buffer flushed');\n // everything flushed !\n return true;\n }\n\n /**\n * Removes first buffered range from provided source buffer that lies within given start and end offsets.\n *\n * @param {string} type Type of the source buffer, logging purposes only.\n * @param {SourceBuffer} sb Target SourceBuffer instance.\n * @param {number} startOffset\n * @param {number} endOffset\n *\n * @returns {boolean} True when source buffer remove requested.\n */\n removeBufferRange (type: string, sb: ExtendedSourceBuffer, startOffset: number, endOffset: number): boolean {\n try {\n for (let i = 0; i < sb.buffered.length; i++) {\n let bufStart = sb.buffered.start(i);\n let bufEnd = sb.buffered.end(i);\n let removeStart = Math.max(bufStart, startOffset);\n let removeEnd = Math.min(bufEnd, endOffset);\n\n /* sometimes sourcebuffer.remove() does not flush\n the exact expected time range.\n to avoid rounding issues/infinite loop,\n only flush buffer range of length greater than 500ms.\n */\n if (Math.min(removeEnd, bufEnd) - removeStart > 0.5) {\n let currentTime: string = 'null';\n if (this.media) {\n currentTime = this.media.currentTime.toString();\n }\n\n logger.log(`sb remove ${type} [${removeStart},${removeEnd}], of [${bufStart},${bufEnd}], pos:${currentTime}`);\n sb.remove(removeStart, removeEnd);\n return true;\n }\n }\n } catch (error) {\n logger.warn('removeBufferRange failed', error);\n }\n\n return false;\n }\n}\n\nexport default BufferController;\n","/*\n * cap stream level to media size dimension controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\n\nclass CapLevelController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.FPS_DROP_LEVEL_CAPPING,\n Event.MEDIA_ATTACHING,\n Event.MANIFEST_PARSED,\n Event.LEVELS_UPDATED,\n Event.BUFFER_CODECS,\n Event.MEDIA_DETACHING);\n\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = null;\n this.levels = [];\n this.media = null;\n this.restrictedLevels = [];\n this.timer = null;\n this.clientRect = null;\n }\n\n destroy () {\n if (this.hls.config.capLevelToPlayerSize) {\n this.media = null;\n this.clientRect = null;\n this.stopCapping();\n }\n }\n\n onFpsDropLevelCapping (data) {\n // Don't add a restricted level more than once\n if (CapLevelController.isLevelAllowed(data.droppedLevel, this.restrictedLevels)) {\n this.restrictedLevels.push(data.droppedLevel);\n }\n }\n\n onMediaAttaching (data) {\n this.media = data.media instanceof window.HTMLVideoElement ? data.media : null;\n }\n\n onManifestParsed (data) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.levels = data.levels;\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this.startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n onBufferCodecs (data) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this.startCapping();\n }\n }\n\n onLevelsUpdated (data) {\n this.levels = data.levels;\n }\n\n onMediaDetaching () {\n this.stopCapping();\n }\n\n detectPlayerSize () {\n if (this.media) {\n let levelsLength = this.levels ? this.levels.length : 0;\n if (levelsLength) {\n const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levelsLength - 1);\n if (hls.autoLevelCapping > this.autoLevelCapping) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n hls.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel (capLevelIndex) {\n if (!this.levels) {\n return -1;\n }\n\n const validLevels = this.levels.filter((level, index) =>\n CapLevelController.isLevelAllowed(index, this.restrictedLevels) && index <= capLevelIndex\n );\n\n this.clientRect = null;\n return CapLevelController.getMaxLevelByMediaSize(validLevels, this.mediaWidth, this.mediaHeight);\n }\n\n startCapping () {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n clearInterval(this.timer);\n this.timer = setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n stopCapping () {\n this.restrictedLevels = [];\n this.firstLevel = null;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n this.timer = clearInterval(this.timer);\n this.timer = null;\n }\n }\n\n getDimensions () {\n if (this.clientRect) {\n return this.clientRect;\n }\n const media = this.media;\n const boundsRect = {\n width: 0,\n height: 0\n };\n\n if (media) {\n const clientRect = media.getBoundingClientRect();\n boundsRect.width = clientRect.width;\n boundsRect.height = clientRect.height;\n if (!boundsRect.width && !boundsRect.height) {\n // When the media element has no width or height (equivalent to not being in the DOM),\n // then use its width and height attributes (media.width, media.height)\n boundsRect.width = clientRect.right - clientRect.left || media.width || 0;\n boundsRect.height = clientRect.bottom - clientRect.top || media.height || 0;\n }\n }\n this.clientRect = boundsRect;\n return boundsRect;\n }\n\n get mediaWidth () {\n return this.getDimensions().width * CapLevelController.contentScaleFactor;\n }\n\n get mediaHeight () {\n return this.getDimensions().height * CapLevelController.contentScaleFactor;\n }\n\n static get contentScaleFactor () {\n let pixelRatio = 1;\n try {\n pixelRatio = window.devicePixelRatio;\n } catch (e) {}\n return pixelRatio;\n }\n\n static isLevelAllowed (level, restrictedLevels = []) {\n return restrictedLevels.indexOf(level) === -1;\n }\n\n static getMaxLevelByMediaSize (levels, width, height) {\n if (!levels || (levels && !levels.length)) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandiwdth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n\n return curLevel.width !== nextLevel.width || curLevel.height !== nextLevel.height;\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if ((level.width >= width || level.height >= height) && atGreatestBandiwdth(level, levels[i + 1])) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n","/*\n * FPS Controller\n*/\n\nimport Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\n\nconst { performance } = window;\n\nclass FPSController extends EventHandler {\n constructor (hls) {\n super(hls, Event.MEDIA_ATTACHING);\n }\n\n destroy () {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.isVideoPlaybackQualityAvailable = false;\n }\n\n onMediaAttaching (data) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const video = this.video = data.media instanceof window.HTMLVideoElement ? data.media : null;\n if (typeof video.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n clearInterval(this.timer);\n this.timer = setInterval(this.checkFPSInterval.bind(this), config.fpsDroppedMonitoringPeriod);\n }\n }\n\n checkFPS (video, decodedFrames, droppedFrames) {\n let currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n let currentPeriod = currentTime - this.lastTime,\n currentDropped = droppedFrames - this.lastDroppedFrames,\n currentDecoded = decodedFrames - this.lastDecodedFrames,\n droppedFPS = 1000 * currentDropped / currentPeriod,\n hls = this.hls;\n hls.trigger(Event.FPS_DROP, { currentDropped: currentDropped, currentDecoded: currentDecoded, totalDroppedFrames: droppedFrames });\n if (droppedFPS > 0) {\n // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (currentDropped > hls.config.fpsDroppedMonitoringThreshold * currentDecoded) {\n let currentLevel = hls.currentLevel;\n logger.warn('drop FPS ratio greater than max allowed value for currentLevel: ' + currentLevel);\n if (currentLevel > 0 && (hls.autoLevelCapping === -1 || hls.autoLevelCapping >= currentLevel)) {\n currentLevel = currentLevel - 1;\n hls.trigger(Event.FPS_DROP_LEVEL_CAPPING, { level: currentLevel, droppedLevel: hls.currentLevel });\n hls.autoLevelCapping = currentLevel;\n hls.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval () {\n const video = this.video;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n let videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(video, videoPlaybackQuality.totalVideoFrames, videoPlaybackQuality.droppedVideoFrames);\n } else {\n this.checkFPS(video, video.webkitDecodedFrameCount, video.webkitDroppedFrameCount);\n }\n }\n }\n}\n\nexport default FPSController;\n","/**\n * XHR based logger\n*/\n\nimport { logger } from '../utils/logger';\n\nclass XhrLoader {\n constructor (config) {\n if (config && config.xhrSetup) {\n this.xhrSetup = config.xhrSetup;\n }\n }\n\n destroy () {\n this.abort();\n this.loader = null;\n }\n\n abort () {\n let loader = this.loader;\n if (loader && loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n\n window.clearTimeout(this.requestTimeout);\n this.requestTimeout = null;\n window.clearTimeout(this.retryTimeout);\n this.retryTimeout = null;\n }\n\n load (context, config, callbacks) {\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.stats = { trequest: window.performance.now(), retry: 0 };\n this.retryDelay = config.retryDelay;\n this.loadInternal();\n }\n\n loadInternal () {\n let xhr, context = this.context;\n xhr = this.loader = new window.XMLHttpRequest();\n\n let stats = this.stats;\n stats.tfirst = 0;\n stats.loaded = 0;\n const xhrSetup = this.xhrSetup;\n\n try {\n if (xhrSetup) {\n try {\n xhrSetup(xhr, context.url);\n } catch (e) {\n // fix xhrSetup: (xhr, url) => {xhr.setRequestHeader(\"Content-Language\", \"test\");}\n // not working, as xhr.setRequestHeader expects xhr.readyState === OPEN\n xhr.open('GET', context.url, true);\n xhrSetup(xhr, context.url);\n }\n }\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks.onError({ code: xhr.status, text: e.message }, context, xhr);\n return;\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader('Range', 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1));\n }\n\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType;\n\n // setup timeout before we perform request\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), this.config.timeout);\n xhr.send();\n }\n\n readystatechange (event) {\n let xhr = event.currentTarget,\n readyState = xhr.readyState,\n stats = this.stats,\n context = this.context,\n config = this.config;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >= 2) {\n // clear xhr timeout and rearm it if readyState less than 4\n window.clearTimeout(this.requestTimeout);\n if (stats.tfirst === 0) {\n stats.tfirst = Math.max(window.performance.now(), stats.trequest);\n }\n\n if (readyState === 4) {\n let status = xhr.status;\n // http status between 200 to 299 are all successful\n if (status >= 200 && status < 300) {\n stats.tload = Math.max(stats.tfirst, window.performance.now());\n let data, len;\n if (context.responseType === 'arraybuffer') {\n data = xhr.response;\n len = data.byteLength;\n } else {\n data = xhr.responseText;\n len = data.length;\n }\n stats.loaded = stats.total = len;\n let response = { url: xhr.responseURL, data: data };\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n if (stats.retry >= config.maxRetry || (status >= 400 && status < 499)) {\n logger.error(`${status} while loading ${context.url}`);\n this.callbacks.onError({ code: status, text: xhr.statusText }, context, xhr);\n } else {\n // retry\n logger.warn(`${status} while loading ${context.url}, retrying in ${this.retryDelay}...`);\n // aborts and resets internal state\n this.destroy();\n // schedule retry\n this.retryTimeout = window.setTimeout(this.loadInternal.bind(this), this.retryDelay);\n // set exponential backoff\n this.retryDelay = Math.min(2 * this.retryDelay, config.maxRetryDelay);\n stats.retry++;\n }\n }\n } else {\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n this.requestTimeout = window.setTimeout(this.loadtimeout.bind(this), config.timeout);\n }\n }\n }\n\n loadtimeout () {\n logger.warn(`timeout while loading ${this.context.url}`);\n this.callbacks.onTimeout(this.stats, this.context, null);\n }\n\n loadprogress (event) {\n let xhr = event.currentTarget,\n stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n\n let onProgress = this.callbacks.onProgress;\n if (onProgress) {\n // third arg is to provide on progress data\n onProgress(stats, this.context, null, xhr);\n }\n }\n}\n\nexport default XhrLoader;\n","import Event from '../events';\nimport TaskLoop from '../task-loop';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\n/**\n * @class AudioTrackController\n * @implements {EventHandler}\n *\n * Handles main manifest and audio-track metadata loaded,\n * owns and exposes the selectable audio-tracks data-models.\n *\n * Exposes internal interface to select available audio-tracks.\n *\n * Handles errors on loading audio-track playlists. Manages fallback mechanism\n * with redundants tracks (group-IDs).\n *\n * Handles level-loading and group-ID switches for video (fallback on video levels),\n * and eventually adapts the audio-track group-ID to match.\n *\n * @fires AUDIO_TRACK_LOADING\n * @fires AUDIO_TRACK_SWITCHING\n * @fires AUDIO_TRACKS_UPDATED\n * @fires ERROR\n *\n */\nclass AudioTrackController extends TaskLoop {\n constructor (hls) {\n super(hls,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_PARSED,\n Event.AUDIO_TRACK_LOADED,\n Event.AUDIO_TRACK_SWITCHED,\n Event.LEVEL_LOADED,\n Event.ERROR\n );\n\n /**\n * @private\n * Currently selected index in `tracks`\n * @member {number} trackId\n */\n this._trackId = -1;\n\n /**\n * @private\n * If should select tracks according to default track attribute\n * @member {boolean} _selectDefaultTrack\n */\n this._selectDefaultTrack = true;\n\n /**\n * @public\n * All tracks available\n * @member {AudioTrack[]}\n */\n this.tracks = [];\n\n /**\n * @public\n * List of blacklisted audio track IDs (that have caused failure)\n * @member {number[]}\n */\n this.trackIdBlacklist = Object.create(null);\n\n /**\n * @public\n * The currently running group ID for audio\n * (we grab this on manifest-parsed and new level-loaded)\n * @member {string}\n */\n this.audioGroupId = null;\n }\n\n /**\n * Reset audio tracks on new manifest loading.\n */\n onManifestLoading () {\n this.tracks = [];\n this._trackId = -1;\n this._selectDefaultTrack = true;\n }\n\n /**\n * Store tracks data from manifest parsed data.\n *\n * Trigger AUDIO_TRACKS_UPDATED event.\n *\n * @param {*} data\n */\n onManifestParsed (data) {\n const tracks = this.tracks = data.audioTracks || [];\n this.hls.trigger(Event.AUDIO_TRACKS_UPDATED, { audioTracks: tracks });\n\n this._selectAudioGroup(this.hls.nextLoadLevel);\n }\n\n /**\n * Store track details of loaded track in our data-model.\n *\n * Set-up metadata update interval task for live-mode streams.\n *\n * @param {*} data\n */\n onAudioTrackLoaded (data) {\n if (data.id >= this.tracks.length) {\n logger.warn('Invalid audio track id:', data.id);\n return;\n }\n\n logger.log(`audioTrack ${data.id} loaded`);\n\n this.tracks[data.id].details = data.details;\n\n // check if current playlist is a live playlist\n // and if we have already our reload interval setup\n if (data.details.live && !this.hasInterval()) {\n // if live playlist we will have to reload it periodically\n // set reload period to playlist target duration\n const updatePeriodMs = data.details.targetduration * 1000;\n this.setInterval(updatePeriodMs);\n }\n\n if (!data.details.live && this.hasInterval()) {\n // playlist is not live and timer is scheduled: cancel it\n this.clearInterval();\n }\n }\n\n /**\n * Update the internal group ID to any audio-track we may have set manually\n * or because of a failure-handling fallback.\n *\n * Quality-levels should update to that group ID in this case.\n *\n * @param {*} data\n */\n onAudioTrackSwitched (data) {\n const audioGroupId = this.tracks[data.id].groupId;\n if (audioGroupId && (this.audioGroupId !== audioGroupId)) {\n this.audioGroupId = audioGroupId;\n }\n }\n\n /**\n * When a level gets loaded, if it has redundant audioGroupIds (in the same ordinality as it's redundant URLs)\n * we are setting our audio-group ID internally to the one set, if it is different from the group ID currently set.\n *\n * If group-ID got update, we re-select the appropriate audio-track with this group-ID matching the currently\n * selected one (based on NAME property).\n *\n * @param {*} data\n */\n onLevelLoaded (data) {\n this._selectAudioGroup(data.level);\n }\n\n /**\n * Handle network errors loading audio track manifests\n * and also pausing on any netwok errors.\n *\n * @param {ErrorEventData} data\n */\n onError (data) {\n // Only handle network errors\n if (data.type !== ErrorTypes.NETWORK_ERROR) {\n return;\n }\n\n // If fatal network error, cancel update task\n if (data.fatal) {\n this.clearInterval();\n }\n\n // If not an audio-track loading error don't handle further\n if (data.details !== ErrorDetails.AUDIO_TRACK_LOAD_ERROR) {\n return;\n }\n\n logger.warn('Network failure on audio-track id:', data.context.id);\n this._handleLoadError();\n }\n\n /**\n * @type {AudioTrack[]} Audio-track list we own\n */\n get audioTracks () {\n return this.tracks;\n }\n\n /**\n * @type {number} Index into audio-tracks list of currently selected track.\n */\n get audioTrack () {\n return this._trackId;\n }\n\n /**\n * Select current track by index\n */\n set audioTrack (newId) {\n this._setAudioTrack(newId);\n // If audio track is selected from API then don't choose from the manifest default track\n this._selectDefaultTrack = false;\n }\n\n /**\n * @private\n * @param {number} newId\n */\n _setAudioTrack (newId) {\n // noop on same audio track id as already set\n if (this._trackId === newId && this.tracks[this._trackId].details) {\n logger.debug('Same id as current audio-track passed, and track details available -> no-op');\n return;\n }\n\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n logger.warn('Invalid id passed to audio-track controller');\n return;\n }\n\n const audioTrack = this.tracks[newId];\n\n logger.log(`Now switching to audio-track index ${newId}`);\n\n // stopping live reloading timer if any\n this.clearInterval();\n this._trackId = newId;\n\n const { url, type, id } = audioTrack;\n this.hls.trigger(Event.AUDIO_TRACK_SWITCHING, { id, type, url });\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @override\n */\n doTick () {\n this._updateTrack(this._trackId);\n }\n\n /**\n * @param levelId\n * @private\n */\n _selectAudioGroup (levelId) {\n const levelInfo = this.hls.levels[levelId];\n\n if (!levelInfo || !levelInfo.audioGroupIds) {\n return;\n }\n\n const audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.audioGroupId !== audioGroupId) {\n this.audioGroupId = audioGroupId;\n this._selectInitialAudioTrack();\n }\n }\n\n /**\n * Select initial track\n * @private\n */\n _selectInitialAudioTrack () {\n let tracks = this.tracks;\n if (!tracks.length) {\n return;\n }\n\n const currentAudioTrack = this.tracks[this._trackId];\n\n let name = null;\n if (currentAudioTrack) {\n name = currentAudioTrack.name;\n }\n\n // Pre-select default tracks if there are any\n if (this._selectDefaultTrack) {\n const defaultTracks = tracks.filter((track) => track.default);\n if (defaultTracks.length) {\n tracks = defaultTracks;\n } else {\n logger.warn('No default audio tracks defined');\n }\n }\n\n let trackFound = false;\n\n const traverseTracks = () => {\n // Select track with right group ID\n tracks.forEach((track) => {\n if (trackFound) {\n return;\n }\n // We need to match the (pre-)selected group ID\n // and the NAME of the current track.\n if ((!this.audioGroupId || track.groupId === this.audioGroupId) &&\n (!name || name === track.name)) {\n // If there was a previous track try to stay with the same `NAME`.\n // It should be unique across tracks of same group, and consistent through redundant track groups.\n this._setAudioTrack(track.id);\n trackFound = true;\n }\n });\n };\n\n traverseTracks();\n\n if (!trackFound) {\n name = null;\n traverseTracks();\n }\n\n if (!trackFound) {\n logger.error(`No track found for running audio group-ID: ${this.audioGroupId}`);\n\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true\n });\n }\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n * @returns {boolean}\n */\n _needsTrackLoading (audioTrack) {\n const { details, url } = audioTrack;\n\n if (!details || details.live) {\n // check if we face an audio track embedded in main playlist (audio track without URI attribute)\n return !!url;\n }\n\n return false;\n }\n\n /**\n * @private\n * @param {AudioTrack} audioTrack\n */\n _loadTrackDetailsIfNeeded (audioTrack) {\n if (this._needsTrackLoading(audioTrack)) {\n const { url, id } = audioTrack;\n // track not retrieved yet, or live playlist we need to (re)load it\n logger.log(`loading audio-track playlist for id: ${id}`);\n this.hls.trigger(Event.AUDIO_TRACK_LOADING, { url, id });\n }\n }\n\n /**\n * @private\n * @param {number} newId\n */\n _updateTrack (newId) {\n // check if level idx is valid\n if (newId < 0 || newId >= this.tracks.length) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearInterval();\n this._trackId = newId;\n logger.log(`trying to update audio-track ${newId}`);\n const audioTrack = this.tracks[newId];\n this._loadTrackDetailsIfNeeded(audioTrack);\n }\n\n /**\n * @private\n */\n _handleLoadError () {\n // First, let's black list current track id\n this.trackIdBlacklist[this._trackId] = true;\n\n // Let's try to fall back on a functional audio-track with the same group ID\n const previousId = this._trackId;\n const { name, language, groupId } = this.tracks[previousId];\n\n logger.warn(`Loading failed on audio track id: ${previousId}, group-id: ${groupId}, name/language: \"${name}\" / \"${language}\"`);\n\n // Find a non-blacklisted track ID with the same NAME\n // At least a track that is not blacklisted, thus on another group-ID.\n let newId = previousId;\n for (let i = 0; i < this.tracks.length; i++) {\n if (this.trackIdBlacklist[i]) {\n continue;\n }\n const newTrack = this.tracks[i];\n if (newTrack.name === name) {\n newId = i;\n break;\n }\n }\n\n if (newId === previousId) {\n logger.warn(`No fallback audio-track found for name/language: \"${name}\" / \"${language}\"`);\n return;\n }\n\n logger.log('Attempting audio-track fallback id:', newId, 'group-id:', this.tracks[newId].groupId);\n\n this._setAudioTrack(newId);\n }\n}\n\nexport default AudioTrackController;\n","/*\n * Audio Stream Controller\n*/\n\nimport BinarySearch from '../utils/binary-search';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport Demuxer from '../demux/demuxer';\nimport Event from '../events';\nimport * as LevelHelper from './level-helper';\nimport TimeRanges from '../utils/time-ranges';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport { findFragWithCC } from '../utils/discontinuities';\nimport { FragmentState } from './fragment-tracker';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport BaseStreamController, { State } from './base-stream-controller';\nimport { MAX_START_GAP_JUMP } from './gap-controller';\nimport { fragmentWithinToleranceTest } from './fragment-finders';\n\nconst { performance } = window;\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nclass AudioStreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.AUDIO_TRACKS_UPDATED,\n Event.AUDIO_TRACK_SWITCHING,\n Event.AUDIO_TRACK_LOADED,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.FRAG_PARSING_INIT_SEGMENT,\n Event.FRAG_PARSING_DATA,\n Event.FRAG_PARSED,\n Event.ERROR,\n Event.BUFFER_RESET,\n Event.BUFFER_CREATED,\n Event.BUFFER_APPENDED,\n Event.BUFFER_FLUSHED,\n Event.INIT_PTS_FOUND);\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.audioCodecSwap = false;\n this._state = State.STOPPED;\n this.initPTS = [];\n this.waitingFragment = null;\n this.videoTrackCC = null;\n this.waitingVideoCC = null;\n }\n\n // Signal that video PTS was found\n onInitPtsFound (data) {\n let demuxerId = data.id, cc = data.frag.cc, initPTS = data.initPTS;\n if (demuxerId === 'main') {\n // Always update the new INIT PTS\n // Can change due level switch\n this.initPTS[cc] = initPTS;\n this.videoTrackCC = cc;\n logger.log(`InitPTS for cc: ${cc} found from main: ${initPTS}`);\n\n // If we are waiting we need to demux/remux the waiting frag\n // With the new initPTS\n if (this.state === State.WAITING_INIT_PTS) {\n this.tick();\n }\n }\n }\n\n startLoad (startPosition) {\n if (this.tracks) {\n let lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.fragLoadError = 0;\n if (lastCurrentTime > 0 && startPosition === -1) {\n logger.log(`audio:override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(3)}`);\n this.state = State.IDLE;\n } else {\n this.lastCurrentTime = this.startPosition ? this.startPosition : startPosition;\n this.state = State.STARTING;\n }\n this.nextLoadPosition = this.startPosition = this.lastCurrentTime;\n this.tick();\n } else {\n this.startPosition = startPosition;\n this.state = State.STOPPED;\n }\n }\n\n set state (nextState) {\n if (this.state !== nextState) {\n const previousState = this.state;\n this._state = nextState;\n logger.log(`audio stream:${previousState}->${nextState}`);\n }\n }\n\n get state () {\n return this._state;\n }\n\n doTick () {\n let pos, track, trackDetails, hls = this.hls, config = hls.config;\n // logger.log('audioStream:' + this.state);\n switch (this.state) {\n case State.ERROR:\n // don't do anything in error state to avoid breaking further ...\n case State.PAUSED:\n // don't do anything in paused state either ...\n case State.BUFFER_FLUSHING:\n break;\n case State.STARTING:\n this.state = State.WAITING_TRACK;\n this.loadedmetadata = false;\n break;\n case State.IDLE:\n const tracks = this.tracks;\n // audio tracks not received => exit loop\n if (!tracks) {\n break;\n }\n\n // if video not attached AND\n // start fragment already requested OR start frag prefetch disable\n // exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!this.media &&\n (this.startFragRequested || !config.startFragPrefetch)) {\n break;\n }\n\n // determine next candidate fragment to be loaded, based on current position and\n // end of buffer position\n // if we have not yet loaded any fragment, start loading from start position\n if (this.loadedmetadata) {\n pos = this.media.currentTime;\n } else {\n pos = this.nextLoadPosition;\n if (pos === undefined) {\n break;\n }\n }\n let media = this.mediaBuffer ? this.mediaBuffer : this.media;\n const videoBuffer = this.videoBuffer ? this.videoBuffer : this.media;\n const maxBufferHole = pos < config.maxBufferHole ? Math.max(MAX_START_GAP_JUMP, config.maxBufferHole) : config.maxBufferHole;\n const bufferInfo = BufferHelper.bufferInfo(media, pos, maxBufferHole);\n const mainBufferInfo = BufferHelper.bufferInfo(videoBuffer, pos, maxBufferHole);\n const bufferLen = bufferInfo.len;\n let bufferEnd = bufferInfo.end;\n const fragPrevious = this.fragPrevious;\n // ensure we buffer at least config.maxBufferLength (default 30s) or config.maxMaxBufferLength (default: 600s)\n // whichever is smaller.\n // once we reach that threshold, don't buffer more than video (mainBufferInfo.len)\n const maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);\n const maxBufLen = Math.max(maxConfigBuffer, mainBufferInfo.len);\n const audioSwitch = this.audioSwitch;\n const trackId = this.trackId;\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if ((bufferLen < maxBufLen || audioSwitch) && trackId < tracks.length) {\n trackDetails = tracks[trackId].details;\n // if track info not retrieved yet, switch state and wait for track retrieval\n if (typeof trackDetails === 'undefined') {\n this.state = State.WAITING_TRACK;\n break;\n }\n\n if (!audioSwitch && this._streamEnded(bufferInfo, trackDetails)) {\n this.hls.trigger(Event.BUFFER_EOS, { type: 'audio' });\n this.state = State.ENDED;\n return;\n }\n\n // find fragment index, contiguous with end of buffer position\n let fragments = trackDetails.fragments,\n fragLen = fragments.length,\n start = fragments[0].start,\n end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration,\n frag;\n\n // When switching audio track, reload audio as close as possible to currentTime\n if (audioSwitch) {\n if (trackDetails.live && !trackDetails.PTSKnown) {\n logger.log('switching audiotrack, live stream, unknown PTS,load first fragment');\n bufferEnd = 0;\n } else {\n bufferEnd = pos;\n // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n if (trackDetails.PTSKnown && pos < start) {\n // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start\n if (bufferInfo.end > start || bufferInfo.nextStart) {\n logger.log('alt audio track ahead of main track, seek to start of alt audio track');\n this.media.currentTime = start + 0.05;\n } else {\n return;\n }\n }\n }\n }\n if (trackDetails.initSegment && !trackDetails.initSegment.data) {\n frag = trackDetails.initSegment;\n } // eslint-disable-line brace-style\n // if bufferEnd before start of playlist, load first fragment\n else if (bufferEnd <= start) {\n frag = fragments[0];\n if (this.videoTrackCC !== null && frag.cc !== this.videoTrackCC) {\n // Ensure we find a fragment which matches the continuity of the video track\n frag = findFragWithCC(fragments, this.videoTrackCC);\n }\n if (trackDetails.live && frag.loadIdx && frag.loadIdx === this.fragLoadIdx) {\n // we just loaded this first fragment, and we are still lagging behind the start of the live playlist\n // let's force seek to start\n const nextBuffered = bufferInfo.nextStart ? bufferInfo.nextStart : start;\n logger.log(`no alt audio available @currentTime:${this.media.currentTime}, seeking @${nextBuffered + 0.05}`);\n this.media.currentTime = nextBuffered + 0.05;\n return;\n }\n } else {\n let foundFrag;\n let maxFragLookUpTolerance = config.maxFragLookUpTolerance;\n const fragNext = fragPrevious ? fragments[fragPrevious.sn - fragments[0].sn + 1] : undefined;\n\n if (bufferEnd < end) {\n if (bufferEnd > end - maxFragLookUpTolerance) {\n maxFragLookUpTolerance = 0;\n }\n\n // Prefer the next fragment if it's within tolerance\n if (fragNext && !fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext)) {\n foundFrag = fragNext;\n } else {\n foundFrag = BinarySearch.search(fragments, (frag) => fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, frag));\n }\n } else {\n // reach end of playlist\n foundFrag = fragments[fragLen - 1];\n }\n if (foundFrag) {\n frag = foundFrag;\n start = foundFrag.start;\n // logger.log('find SN matching with pos:' + bufferEnd + ':' + frag.sn);\n if (fragPrevious && frag.level === fragPrevious.level && frag.sn === fragPrevious.sn) {\n if (frag.sn < trackDetails.endSN) {\n frag = fragments[frag.sn + 1 - trackDetails.startSN];\n if (this.fragmentTracker.getState(frag) !== FragmentState.OK) {\n logger.log(`SN just loaded, load next one: ${frag.sn}`);\n }\n } else {\n frag = null;\n }\n }\n }\n }\n if (frag) {\n // logger.log(' loading frag ' + i +',pos/bufEnd:' + pos.toFixed(3) + '/' + bufferEnd.toFixed(3));\n if (frag.encrypted) {\n logger.log(`Loading key for ${frag.sn} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}`);\n this.state = State.KEY_LOADING;\n hls.trigger(Event.KEY_LOADING, { frag: frag });\n } else {\n // only load if fragment is not loaded or if in audio switch\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n this.fragCurrent = frag;\n if (audioSwitch || this.fragmentTracker.getState(frag) === FragmentState.NOT_LOADED) {\n logger.log(`Loading ${frag.sn}, cc: ${frag.cc} of [${trackDetails.startSN} ,${trackDetails.endSN}],track ${trackId}, ${\n this.loadedmetadata ? 'currentTime' : 'nextLoadPosition'\n }: ${pos}, bufferEnd: ${bufferEnd.toFixed(3)}`);\n\n if (frag.sn !== 'initSegment') {\n this.startFragRequested = true;\n }\n if (Number.isFinite(frag.sn)) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n\n hls.trigger(Event.FRAG_LOADING, { frag });\n this.state = State.FRAG_LOADING;\n }\n }\n }\n }\n break;\n case State.WAITING_TRACK:\n track = this.tracks[this.trackId];\n // check if playlist is already loaded\n if (track && track.details) {\n this.state = State.IDLE;\n }\n\n break;\n case State.FRAG_LOADING_WAITING_RETRY:\n var now = performance.now();\n var retryDate = this.retryDate;\n media = this.media;\n var isSeeking = media && media.seeking;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || (now >= retryDate) || isSeeking) {\n logger.log('audioStreamController: retryDate reached, switch back to IDLE state');\n this.state = State.IDLE;\n }\n break;\n case State.WAITING_INIT_PTS:\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingFrag = this.waitingFragment;\n if (waitingFrag) {\n const waitingFragCC = waitingFrag.frag.cc;\n if (this.initPTS[waitingFragCC] !== undefined) {\n this.waitingFragment = null;\n this.state = State.FRAG_LOADING;\n this.onFragLoaded(waitingFrag);\n } else if (this.videoTrackCC !== this.waitingVideoCC) {\n // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found\n logger.log(`Waiting fragment cc (${waitingFragCC}) cancelled because video is at cc ${this.videoTrackCC}`);\n this.clearWaitingFragment();\n } else {\n // Drop waiting fragment if an earlier fragment is needed\n const bufferInfo = BufferHelper.bufferInfo(this.mediaBuffer, this.media.currentTime, config.maxBufferHole);\n const waitingFragmentAtPosition = fragmentWithinToleranceTest(bufferInfo.end, config.maxFragLookUpTolerance, waitingFrag.frag);\n if (waitingFragmentAtPosition < 0) {\n logger.log(`Waiting fragment cc (${waitingFragCC}) @ ${waitingFrag.frag.start} cancelled because another fragment at ${bufferInfo.end} is needed`);\n this.clearWaitingFragment();\n }\n }\n } else {\n this.state = State.IDLE;\n }\n\n break;\n case State.STOPPED:\n case State.FRAG_LOADING:\n case State.PARSING:\n case State.PARSED:\n case State.ENDED:\n break;\n default:\n break;\n }\n }\n\n clearWaitingFragment () {\n const waitingFrag = this.waitingFragment;\n if (waitingFrag) {\n this.fragmentTracker.removeFragment(waitingFrag.frag);\n this.waitingFragment = null;\n this.waitingVideoCC = null;\n this.state = State.IDLE;\n }\n }\n\n onMediaAttached (data) {\n let media = this.media = this.mediaBuffer = data.media;\n this.onvseeking = this.onMediaSeeking.bind(this);\n this.onvended = this.onMediaEnded.bind(this);\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('ended', this.onvended);\n let config = this.config;\n if (this.tracks && config.autoStartLoad) {\n this.startLoad(config.startPosition);\n }\n }\n\n onMediaDetaching () {\n let media = this.media;\n if (media && media.ended) {\n logger.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // remove video listeners\n if (media) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvseeked = this.onvended = null;\n }\n this.media = this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n this.fragmentTracker.removeAllFragments();\n this.stopLoad();\n }\n\n onAudioTracksUpdated (data) {\n logger.log('audio tracks updated');\n this.tracks = data.audioTracks;\n }\n\n onAudioTrackSwitching (data) {\n // if any URL found on new audio track, it is an alternate audio track\n let altAudio = !!data.url;\n this.trackId = data.id;\n\n this.fragCurrent = null;\n this.clearWaitingFragment();\n this.state = State.PAUSED;\n // destroy useless demuxer when switching audio to main\n if (!altAudio) {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = null;\n }\n } else {\n // switching to audio track, start timer if not already started\n this.setInterval(TICK_INTERVAL);\n }\n\n // should we switch tracks ?\n if (altAudio) {\n this.audioSwitch = true;\n // main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.state = State.IDLE;\n }\n this.tick();\n }\n\n onAudioTrackLoaded (data) {\n let newDetails = data.details,\n trackId = data.id,\n track = this.tracks[trackId],\n curDetails = track.details,\n duration = newDetails.totalduration,\n sliding = 0;\n\n logger.log(`track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}],duration:${duration}`);\n\n if (newDetails.live || (curDetails && curDetails.live)) {\n if (curDetails && newDetails.fragments.length > 0) {\n // we already have details for that level, merge them\n LevelHelper.mergeDetails(curDetails, newDetails);\n sliding = newDetails.fragments[0].start;\n // TODO\n // this.liveSyncPosition = this.computeLivePosition(sliding, curDetails);\n if (newDetails.PTSKnown) {\n logger.log(`live audio playlist sliding:${sliding.toFixed(3)}`);\n } else {\n logger.log('live audio playlist - outdated PTS, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n logger.log('live audio playlist - first load, unknown sliding');\n }\n } else {\n newDetails.PTSKnown = false;\n }\n track.details = newDetails;\n\n // compute start position\n if (!this.startFragRequested) {\n // compute start position if set to -1. use it straight away if value is defined\n if (this.startPosition === -1) {\n // first, check if start time offset has been set in playlist, if yes, use this value\n let startTimeOffset = newDetails.startTimeOffset;\n if (Number.isFinite(startTimeOffset)) {\n logger.log(`start time offset found in playlist, adjust startPosition to ${startTimeOffset}`);\n this.startPosition = startTimeOffset;\n } else {\n if (newDetails.live) {\n this.startPosition = this.computeLivePosition(sliding, newDetails);\n logger.log(`compute startPosition for audio-track to ${this.startPosition}`);\n } else {\n this.startPosition = 0;\n }\n }\n }\n this.nextLoadPosition = this.startPosition;\n }\n // only switch batck to IDLE state if we were waiting for track to start downloading a new fragment\n if (this.state === State.WAITING_TRACK) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n this.tick();\n }\n }\n\n onFragLoaded (data) {\n let fragCurrent = this.fragCurrent,\n fragLoaded = data.frag;\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n fragLoaded.type === 'audio' &&\n fragLoaded.level === fragCurrent.level &&\n fragLoaded.sn === fragCurrent.sn) {\n let track = this.tracks[this.trackId],\n details = track.details,\n duration = details.totalduration,\n trackId = fragCurrent.level,\n sn = fragCurrent.sn,\n cc = fragCurrent.cc,\n audioCodec = this.config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2',\n stats = this.stats = data.stats;\n if (sn === 'initSegment') {\n this.state = State.IDLE;\n\n stats.tparsed = stats.tbuffered = performance.now();\n details.initSegment.data = data.payload;\n this.hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: fragCurrent, id: 'audio' });\n this.tick();\n } else {\n this.state = State.PARSING;\n // transmux the MPEG-TS data to ISO-BMFF segments\n this.appended = false;\n if (!this.demuxer) {\n this.demuxer = new Demuxer(this.hls, 'audio');\n }\n\n // Check if we have video initPTS\n // If not we need to wait for it\n let initPTS = this.initPTS[cc];\n let initSegmentData = details.initSegment ? details.initSegment.data : [];\n if (initPTS !== undefined) {\n this.pendingBuffering = true;\n logger.log(`Demuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n let accurateTimeOffset = false; // details.PTSKnown || !details.live;\n this.demuxer.push(data.payload, initSegmentData, audioCodec, null, fragCurrent, duration, accurateTimeOffset, initPTS);\n } else {\n logger.log(`Unknown video PTS for cc ${cc}, waiting for video PTS before demuxing audio frag ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n this.waitingFragment = data;\n this.waitingVideoCC = this.videoTrackCC;\n this.state = State.WAITING_INIT_PTS;\n }\n }\n }\n this.fragLoadError = 0;\n }\n\n onFragParsingInitSegment (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let tracks = data.tracks, track;\n\n // delete any video track found on audio demuxer\n if (tracks.video) {\n delete tracks.video;\n }\n\n // include levelCodec in audio and video tracks\n track = tracks.audio;\n if (track) {\n track.levelCodec = track.codec;\n track.id = data.id;\n this.hls.trigger(Event.BUFFER_CODECS, tracks);\n logger.log(`audio track:audio,container:${track.container},codecs[level/parsed]=[${track.levelCodec}/${track.codec}]`);\n let initSegment = track.initSegment;\n if (initSegment) {\n let appendObj = { type: 'audio', data: initSegment, parent: 'audio', content: 'initSegment' };\n if (this.audioSwitch) {\n this.pendingData = [appendObj];\n } else {\n this.appended = true;\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n }\n\n onFragParsingData (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n data.type === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n let trackId = this.trackId,\n track = this.tracks[trackId],\n hls = this.hls;\n\n if (!Number.isFinite(data.endPTS)) {\n data.endPTS = data.startPTS + fragCurrent.duration;\n data.endDTS = data.startDTS + fragCurrent.duration;\n }\n\n fragCurrent.addElementaryStream(ElementaryStreamTypes.AUDIO);\n\n 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}`);\n LevelHelper.updateFragPTSDTS(track.details, fragCurrent, data.startPTS, data.endPTS);\n\n const media = this.media;\n let appendOnBufferFlush = false;\n // Only flush audio from old audio tracks when PTS is known on new audio track\n if (this.audioSwitch) {\n if (media && media.readyState) {\n let currentTime = media.currentTime;\n logger.log('switching audio track : currentTime:' + currentTime);\n if (currentTime >= data.startPTS) {\n logger.log('switching audio track : flushing all audio');\n this.state = State.BUFFER_FLUSHING;\n hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n appendOnBufferFlush = true;\n // Lets announce that the initial audio track switch flush occur\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });\n }\n } else {\n // Lets announce that the initial audio track switch flush occur\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: trackId });\n }\n }\n\n let pendingData = this.pendingData;\n\n if (!pendingData) {\n logger.warn('Apparently attempt to enqueue media payload without codec initialization data upfront');\n hls.trigger(Event.ERROR, { type: ErrorTypes.MEDIA_ERROR, details: null, fatal: true });\n return;\n }\n\n if (!this.audioSwitch) {\n [data.data1, data.data2].forEach(buffer => {\n if (buffer && buffer.length) {\n pendingData.push({ type: data.type, data: buffer, parent: 'audio', content: 'data' });\n }\n });\n if (!appendOnBufferFlush && pendingData.length) {\n pendingData.forEach(appendObj => {\n // only append in PARSING state (rationale is that an appending error could happen synchronously on first segment appending)\n // in that case it is useless to append following segments\n if (this.state === State.PARSING) {\n // arm pending Buffering flag before appending a segment\n this.pendingBuffering = true;\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n }\n });\n this.pendingData = [];\n this.appended = true;\n }\n }\n // trigger handler right now\n this.tick();\n }\n }\n\n onFragParsed (data) {\n const fragCurrent = this.fragCurrent;\n const fragNew = data.frag;\n if (fragCurrent &&\n data.id === 'audio' &&\n fragNew.sn === fragCurrent.sn &&\n fragNew.level === fragCurrent.level &&\n this.state === State.PARSING) {\n this.stats.tparsed = performance.now();\n this.state = State.PARSED;\n this._checkAppendedParsed();\n }\n }\n\n onBufferReset () {\n // reset reference to sourcebuffers\n this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n }\n\n onBufferCreated (data) {\n let audioTrack = data.tracks.audio;\n if (audioTrack) {\n this.mediaBuffer = audioTrack.buffer;\n this.loadedmetadata = true;\n }\n if (data.tracks.video) {\n this.videoBuffer = data.tracks.video.buffer;\n }\n }\n\n onBufferAppended (data) {\n if (data.parent === 'audio') {\n const state = this.state;\n if (state === State.PARSING || state === State.PARSED) {\n // check if all buffers have been appended\n this.pendingBuffering = (data.pending > 0);\n this._checkAppendedParsed();\n }\n }\n }\n\n _checkAppendedParsed () {\n // trigger handler right now\n if (this.state === State.PARSED && (!this.appended || !this.pendingBuffering)) {\n let frag = this.fragCurrent, stats = this.stats, hls = this.hls;\n if (frag) {\n this.fragPrevious = frag;\n stats.tbuffered = performance.now();\n hls.trigger(Event.FRAG_BUFFERED, { stats: stats, frag: frag, id: 'audio' });\n let media = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (media) {\n logger.log(`audio buffered : ${TimeRanges.toString(media.buffered)}`);\n }\n if (this.audioSwitch && this.appended) {\n this.audioSwitch = false;\n hls.trigger(Event.AUDIO_TRACK_SWITCHED, { id: this.trackId });\n }\n this.state = State.IDLE;\n }\n this.tick();\n }\n }\n\n onError (data) {\n let frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n return;\n }\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n const frag = data.frag;\n // don't handle frag error not related to audio fragment\n if (frag && frag.type !== 'audio') {\n break;\n }\n\n if (!data.fatal) {\n let loadError = this.fragLoadError;\n if (loadError) {\n loadError++;\n } else {\n loadError = 1;\n }\n\n const config = this.config;\n if (loadError <= config.fragLoadingMaxRetry) {\n this.fragLoadError = loadError;\n // exponential backoff capped to config.fragLoadingMaxRetryTimeout\n const delay = Math.min(Math.pow(2, loadError - 1) * config.fragLoadingRetryDelay, config.fragLoadingMaxRetryTimeout);\n logger.warn(`AudioStreamController: frag loading failed, retry in ${delay} ms`);\n this.retryDate = performance.now() + delay;\n // retry loading state\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else {\n logger.error(`AudioStreamController: ${data.details} reaches max retry, redispatch as fatal ...`);\n // switch error to fatal\n data.fatal = true;\n this.state = State.ERROR;\n }\n }\n break;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n // when in ERROR state, don't switch back to IDLE state in case a non-fatal error is received\n if (this.state !== State.ERROR) {\n // if fatal error, stop processing, otherwise move to IDLE to retry loading\n this.state = data.fatal ? State.ERROR : State.IDLE;\n logger.warn(`AudioStreamController: ${data.details} while loading frag, now switching to ${this.state} state ...`);\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n // if in appending state\n if (data.parent === 'audio' && (this.state === State.PARSING || this.state === State.PARSED)) {\n const media = this.mediaBuffer,\n currentTime = this.media.currentTime,\n mediaBuffered = media && BufferHelper.isBuffered(media, currentTime) && BufferHelper.isBuffered(media, currentTime + 0.5);\n // reduce max buf len if current position is buffered\n if (mediaBuffered) {\n const config = this.config;\n if (config.maxMaxBufferLength >= config.maxBufferLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n logger.warn(`AudioStreamController: reduce max buffer length to ${config.maxMaxBufferLength}s`);\n }\n this.state = State.IDLE;\n } else {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n logger.warn('AudioStreamController: buffer full error also media.currentTime is not buffered, flush audio buffer');\n this.fragCurrent = null;\n // flush everything\n this.state = State.BUFFER_FLUSHING;\n this.hls.trigger(Event.BUFFER_FLUSHING, { startOffset: 0, endOffset: Number.POSITIVE_INFINITY, type: 'audio' });\n }\n }\n break;\n default:\n break;\n }\n }\n\n onBufferFlushed () {\n let pendingData = this.pendingData;\n if (pendingData && pendingData.length) {\n logger.log('AudioStreamController: appending pending audio data after buffer flushed');\n pendingData.forEach(appendObj => {\n this.hls.trigger(Event.BUFFER_APPENDING, appendObj);\n });\n this.appended = true;\n this.pendingData = [];\n this.state = State.PARSED;\n } else {\n // move to IDLE once flush complete. this should trigger new fragment loading\n this.state = State.IDLE;\n // reset reference to frag\n this.fragPrevious = null;\n this.tick();\n }\n }\n}\nexport default AudioStreamController;\n","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport default (function () {\n if (typeof window !== 'undefined' && window.VTTCue) {\n return window.VTTCue;\n }\n\n let autoKeyword = 'auto';\n let directionSetting = {\n '': true,\n lr: true,\n rl: true\n };\n let alignSetting = {\n start: true,\n middle: true,\n end: true,\n left: true,\n right: true\n };\n\n function findDirectionSetting (value) {\n if (typeof value !== 'string') {\n return false;\n }\n\n let dir = directionSetting[value.toLowerCase()];\n return dir ? value.toLowerCase() : false;\n }\n\n function findAlignSetting (value) {\n if (typeof value !== 'string') {\n return false;\n }\n\n let align = alignSetting[value.toLowerCase()];\n return align ? value.toLowerCase() : false;\n }\n\n function extend (obj) {\n let i = 1;\n for (; i < arguments.length; i++) {\n let cobj = arguments[i];\n for (let p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue (startTime, endTime, text) {\n let cue = this;\n let baseObj = {};\n\n baseObj.enumerable = true;\n\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical = '';\n let _snapToLines = true;\n let _line = 'auto';\n let _lineAlign = 'start';\n let _position = 50;\n let _positionAlign = 'middle';\n let _size = 50;\n let _align = 'middle';\n\n Object.defineProperty(cue, 'id', extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value) {\n _id = '' + value;\n }\n }));\n\n Object.defineProperty(cue, 'pauseOnExit', extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value) {\n _pauseOnExit = !!value;\n }\n }));\n\n Object.defineProperty(cue, 'startTime', extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n\n _startTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'endTime', extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n\n _endTime = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'text', extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value) {\n _text = '' + value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'region', extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value) {\n _region = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'vertical', extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value) {\n let setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _vertical = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'snapToLines', extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'line', extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value) {\n if (typeof value !== 'number' && value !== autoKeyword) {\n throw new SyntaxError('An invalid number or illegal string was specified.');\n }\n\n _line = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'lineAlign', extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _lineAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'position', extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n\n _position = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'positionAlign', extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _positionAlign = setting;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'size', extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n\n _size = value;\n this.hasBeenReset = true;\n }\n }));\n\n Object.defineProperty(cue, 'align', extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value) {\n let setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError('An invalid or illegal string was specified.');\n }\n\n _align = setting;\n this.hasBeenReset = true;\n }\n }));\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = void 0;\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n let WebVTT = window.WebVTT;\n return WebVTT.convertCueToDOMTree(window, this.text);\n };\n\n return VTTCue;\n})();\n","/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js#L1716\n */\n\nimport VTTCue from './vttcue';\n\nconst StringDecoder = function StringDecoder () {\n return {\n decode: function (data) {\n if (!data) {\n return '';\n }\n\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n\n return decodeURIComponent(encodeURIComponent(data));\n }\n };\n};\n\nfunction VTTParser () {\n this.window = window;\n this.state = 'INITIAL';\n this.buffer = '';\n this.decoder = new StringDecoder();\n this.regionList = [];\n}\n\n// Try to parse input as a time stamp.\nfunction parseTimeStamp (input) {\n function computeSeconds (h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + (f | 0) / 1000;\n }\n\n let m = input.match(/^(\\d+):(\\d{2})(:\\d{2})?\\.(\\d{3})/);\n if (!m) {\n return null;\n }\n\n if (m[3]) {\n // Timestamp takes the form of [hours]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3].replace(':', ''), m[4]);\n } else if (m[1] > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[1], m[2], 0, m[4]);\n } else {\n // Timestamp takes the form of [minutes]:[seconds].[milliseconds]\n return computeSeconds(0, m[1], m[2], m[4]);\n }\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nfunction Settings () {\n this.values = Object.create(null);\n}\n\nSettings.prototype = {\n // Only accept the first assignment to any key.\n set: function (k, v) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n },\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get: function (k, dflt, defaultKey) {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n\n return this.has(k) ? this.values[k] : dflt;\n },\n // Check whether we have a value for a key.\n has: function (k) {\n return k in this.values;\n },\n // Accept a setting if its one of the given alternatives.\n alt: function (k, v, a) {\n for (let n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n },\n // Accept a setting if its a valid (signed) integer.\n integer: function (k, v) {\n if (/^-?\\d+$/.test(v)) { // integer\n this.set(k, parseInt(v, 10));\n }\n },\n // Accept a setting if its a valid percentage.\n percent: function (k, v) {\n let m;\n if ((m = v.match(/^([\\d]{1,3})(\\.[\\d]*)?%$/))) {\n v = parseFloat(v);\n if (v >= 0 && v <= 100) {\n this.set(k, v);\n return true;\n }\n }\n return false;\n }\n};\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interprete each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions (input, callback, keyValueDelim, groupDelim) {\n let groups = groupDelim ? input.split(groupDelim) : [input];\n for (let i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n\n let kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n let k = kv[0];\n let v = kv[1];\n callback(k, v);\n }\n}\n\nlet defaults = new VTTCue(0, 0, 0);\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Safari doesn't yet support this change, but FF and Chrome do.\nlet center = defaults.align === 'middle' ? 'middle' : 'center';\n\nfunction parseCue (input, cue, regionList) {\n // Remember the original input if we need to throw an error.\n let oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp () {\n let ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings (input, cue) {\n let settings = new Settings();\n\n parseOptions(input, function (k, v) {\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (let i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n var vals = v.split(','),\n vals0 = vals[0];\n settings.integer(k, vals0);\n if (settings.percent(k, vals0)) {\n settings.set('snapToLines', false);\n }\n\n settings.alt(k, vals0, ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], ['start', center, 'end', 'line-left', 'line-right', 'auto']);\n }\n\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n }, /:/, /\\s/);\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n let line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n let position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position = cue.align === 'start' || cue.align === 'left' ? 0 : cue.align === 'end' || cue.align === 'right' ? 100 : 50;\n }\n cue.position = position;\n }\n\n function skipWhitespace () {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.substr(0, 3) !== '-->') { // (3) next characters must match '-->'\n throw new Error('Malformed time stamp (time stamps must be separated by \\'-->\\'): ' +\n oInput);\n }\n input = input.substr(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\n\nfunction fixLineBreaks (input) {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\n\nVTTParser.prototype = {\n parse: function (data) {\n let self = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n self.buffer += self.decoder.decode(data, { stream: true });\n }\n\n function collectNextLine () {\n let buffer = self.buffer;\n let pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (pos < buffer.length && buffer[pos] !== '\\r' && buffer[pos] !== '\\n') {\n ++pos;\n }\n\n let line = buffer.substr(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n\n self.buffer = buffer.substr(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader (input) {\n parseOptions(input, function (k, v) {\n switch (k) {\n case 'Region':\n // 3.3 WebVTT region metadata header syntax\n // console.log('parse region', v);\n // parseRegion(v);\n break;\n }\n }, /:/);\n }\n\n // 5.1 WebVTT file parsing.\n try {\n let line;\n if (self.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n line = collectNextLine();\n // strip of UTF-8 BOM if any\n // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n let m = line.match(/^()?WEBVTT([ \\t].*)?$/);\n if (!m || !m[0]) {\n throw new Error('Malformed WebVTT signature.');\n }\n\n self.state = 'HEADER';\n }\n\n let alreadyCollectedLine = false;\n while (self.buffer) {\n // We can't parse a line until we have the full line.\n if (!/\\r\\n|\\n/.test(self.buffer)) {\n return this;\n }\n\n if (!alreadyCollectedLine) {\n line = collectNextLine();\n } else {\n alreadyCollectedLine = false;\n }\n\n switch (self.state) {\n case 'HEADER':\n // 13-18 - Allow a header (metadata) under the WEBVTT line.\n if (/:/.test(line)) {\n parseHeader(line);\n } else if (!line) {\n // An empty line terminates the header and starts the body (cues).\n self.state = 'ID';\n }\n continue;\n case 'NOTE':\n // Ignore NOTE blocks.\n if (!line) {\n self.state = 'ID';\n }\n\n continue;\n case 'ID':\n // Check for the start of NOTE blocks.\n if (/^NOTE($|[ \\t])/.test(line)) {\n self.state = 'NOTE';\n break;\n }\n // 19-29 - Allow any number of line terminators, then initialize new cue values.\n if (!line) {\n continue;\n }\n\n self.cue = new VTTCue(0, 0, '');\n self.state = 'CUE';\n // 30-39 - Check if self line contains an optional identifier or timing data.\n if (line.indexOf('-->') === -1) {\n self.cue.id = line;\n continue;\n }\n // Process line as start of a cue.\n /* falls through */\n case 'CUE':\n // 40 - Collect cue timings and settings.\n try {\n parseCue(line, self.cue, self.regionList);\n } catch (e) {\n // In case of an error ignore rest of the cue.\n self.cue = null;\n self.state = 'BADCUE';\n continue;\n }\n self.state = 'CUETEXT';\n continue;\n case 'CUETEXT':\n var hasSubstring = line.indexOf('-->') !== -1;\n // 34 - If we have an empty line then report the cue.\n // 35 - If we have the special substring '-->' then report the cue,\n // but do not collect the line as we need to process the current\n // one as a new cue.\n if (!line || hasSubstring && (alreadyCollectedLine = true)) {\n // We are done parsing self cue.\n if (self.oncue) {\n self.oncue(self.cue);\n }\n\n self.cue = null;\n self.state = 'ID';\n continue;\n }\n if (self.cue.text) {\n self.cue.text += '\\n';\n }\n\n self.cue.text += line;\n continue;\n case 'BADCUE': // BADCUE\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n self.state = 'ID';\n }\n\n continue;\n }\n }\n } catch (e) {\n // If we are currently parsing a cue, report what we have.\n if (self.state === 'CUETEXT' && self.cue && self.oncue) {\n self.oncue(self.cue);\n }\n\n self.cue = null;\n // Enter BADWEBVTT state if header was not parsed correctly otherwise\n // another exception occurred so enter BADCUE state.\n self.state = self.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n }\n return this;\n },\n flush: function () {\n let self = this;\n try {\n // Finish decoding the stream.\n self.buffer += self.decoder.decode();\n // Synthesize the end of the current cue or region.\n if (self.cue || self.state === 'HEADER') {\n self.buffer += '\\n\\n';\n self.parse();\n }\n // If we've flushed, parsed, and we're still on the INITIAL state then\n // that means we don't have enough of the stream to parse the first\n // line.\n if (self.state === 'INITIAL') {\n throw new Error('Malformed WebVTT signature.');\n }\n } catch (e) {\n throw e;\n }\n if (self.onflush) {\n self.onflush();\n }\n\n return this;\n }\n};\n\nexport { fixLineBreaks };\n\nexport default VTTParser;\n","import { fixLineBreaks } from './vttparser';\nimport { CaptionScreen, Row } from './cea-608-parser';\n\nexport interface CuesInterface {\n newCue (track: TextTrack | null, startTime: number, endTime: number, captionScreen: CaptionScreen): VTTCue[]\n}\n\ninterface VTTCue extends TextTrackCue {\n new(start: number, end: number, cueText: string): VTTCue\n line: number\n align: string\n position: number\n}\n\nexport function newCue (track: TextTrack | null, startTime: number, endTime: number, captionScreen: CaptionScreen): VTTCue[] {\n const result: VTTCue[] = [];\n let row: Row;\n // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers\n let cue: VTTCue;\n let indenting: boolean;\n let indent: number;\n let text: string;\n let VTTCue: VTTCue = (window as any).VTTCue as VTTCue || TextTrackCue;\n\n for (let r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty()) {\n for (let c = 0; c < row.chars.length; c++) {\n if (row.chars[c].uchar.match(/\\s/) && indenting) {\n indent++;\n } else {\n text += row.chars[c].uchar;\n indenting = false;\n }\n }\n // To be used for cleaning-up orphaned roll-up captions\n row.cueStartTime = startTime;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n\n cue = new VTTCue(startTime, endTime, fixLineBreaks(text.trim()));\n\n if (indent >= 16) {\n indent--;\n } else {\n indent++;\n }\n\n // VTTCue.line get's flakey when using controls, so let's now include line 13&14\n // also, drop line 1 since it's to close to the top\n if (navigator.userAgent.match(/Firefox\\//)) {\n cue.line = r + 1;\n } else {\n cue.line = (r > 7 ? r - 2 : r + 1);\n }\n\n cue.align = 'left';\n // Clamp the position between 0 and 100 - if out of these bounds, Firefox throws an exception and captions break\n cue.position = Math.max(0, Math.min(100, 100 * (indent / 32)));\n result.push(cue);\n if (track) {\n track.addCue(cue);\n }\n }\n }\n return result;\n}\n","import OutputFilter from './output-filter';\nimport { logger } from '../utils/logger';\n\n/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nconst specialCea608CharsCodes = {\n 0x2a: 0xe1, // lowercase a, acute accent\n 0x5c: 0xe9, // lowercase e, acute accent\n 0x5e: 0xed, // lowercase i, acute accent\n 0x5f: 0xf3, // lowercase o, acute accent\n 0x60: 0xfa, // lowercase u, acute accent\n 0x7b: 0xe7, // lowercase c with cedilla\n 0x7c: 0xf7, // division symbol\n 0x7d: 0xd1, // uppercase N tilde\n 0x7e: 0xf1, // lowercase n tilde\n 0x7f: 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80: 0xae, // Registered symbol (R)\n 0x81: 0xb0, // degree sign\n 0x82: 0xbd, // 1/2 symbol\n 0x83: 0xbf, // Inverted (open) question mark\n 0x84: 0x2122, // Trademark symbol (TM)\n 0x85: 0xa2, // Cents symbol\n 0x86: 0xa3, // Pounds sterling\n 0x87: 0x266a, // Music 8'th note\n 0x88: 0xe0, // lowercase a, grave accent\n 0x89: 0x20, // transparent space (regular)\n 0x8a: 0xe8, // lowercase e, grave accent\n 0x8b: 0xe2, // lowercase a, circumflex accent\n 0x8c: 0xea, // lowercase e, circumflex accent\n 0x8d: 0xee, // lowercase i, circumflex accent\n 0x8e: 0xf4, // lowercase o, circumflex accent\n 0x8f: 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90: 0xc1, // capital letter A with acute\n 0x91: 0xc9, // capital letter E with acute\n 0x92: 0xd3, // capital letter O with acute\n 0x93: 0xda, // capital letter U with acute\n 0x94: 0xdc, // capital letter U with diaresis\n 0x95: 0xfc, // lowercase letter U with diaeresis\n 0x96: 0x2018, // opening single quote\n 0x97: 0xa1, // inverted exclamation mark\n 0x98: 0x2a, // asterisk\n 0x99: 0x2019, // closing single quote\n 0x9a: 0x2501, // box drawings heavy horizontal\n 0x9b: 0xa9, // copyright sign\n 0x9c: 0x2120, // Service mark\n 0x9d: 0x2022, // (round) bullet\n 0x9e: 0x201c, // Left double quotation mark\n 0x9f: 0x201d, // Right double quotation mark\n 0xa0: 0xc0, // uppercase A, grave accent\n 0xa1: 0xc2, // uppercase A, circumflex\n 0xa2: 0xc7, // uppercase C with cedilla\n 0xa3: 0xc8, // uppercase E, grave accent\n 0xa4: 0xca, // uppercase E, circumflex\n 0xa5: 0xcb, // capital letter E with diaresis\n 0xa6: 0xeb, // lowercase letter e with diaresis\n 0xa7: 0xce, // uppercase I, circumflex\n 0xa8: 0xcf, // uppercase I, with diaresis\n 0xa9: 0xef, // lowercase i, with diaresis\n 0xaa: 0xd4, // uppercase O, circumflex\n 0xab: 0xd9, // uppercase U, grave accent\n 0xac: 0xf9, // lowercase u, grave accent\n 0xad: 0xdb, // uppercase U, circumflex\n 0xae: 0xab, // left-pointing double angle quotation mark\n 0xaf: 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0: 0xc3, // Uppercase A, tilde\n 0xb1: 0xe3, // Lowercase a, tilde\n 0xb2: 0xcd, // Uppercase I, acute accent\n 0xb3: 0xcc, // Uppercase I, grave accent\n 0xb4: 0xec, // Lowercase i, grave accent\n 0xb5: 0xd2, // Uppercase O, grave accent\n 0xb6: 0xf2, // Lowercase o, grave accent\n 0xb7: 0xd5, // Uppercase O, tilde\n 0xb8: 0xf5, // Lowercase o, tilde\n 0xb9: 0x7b, // Open curly brace\n 0xba: 0x7d, // Closing curly brace\n 0xbb: 0x5c, // Backslash\n 0xbc: 0x5e, // Caret\n 0xbd: 0x5f, // Underscore\n 0xbe: 0x7c, // Pipe (vertical line)\n 0xbf: 0x223c, // Tilde operator\n 0xc0: 0xc4, // Uppercase A, umlaut\n 0xc1: 0xe4, // Lowercase A, umlaut\n 0xc2: 0xd6, // Uppercase O, umlaut\n 0xc3: 0xf6, // Lowercase o, umlaut\n 0xc4: 0xdf, // Esszett (sharp S)\n 0xc5: 0xa5, // Yen symbol\n 0xc6: 0xa4, // Generic currency sign\n 0xc7: 0x2503, // Box drawings heavy vertical\n 0xc8: 0xc5, // Uppercase A, ring\n 0xc9: 0xe5, // Lowercase A, ring\n 0xca: 0xd8, // Uppercase O, stroke\n 0xcb: 0xf8, // Lowercase o, strok\n 0xcc: 0x250f, // Box drawings heavy down and right\n 0xcd: 0x2513, // Box drawings heavy down and left\n 0xce: 0x2517, // Box drawings heavy up and right\n 0xcf: 0x251b // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nconst getCharForByte = function (byte: number) {\n let charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n\n return String.fromCharCode(charCode);\n};\n\nconst NR_ROWS = 15;\nconst NR_COLS = 100;\n// Tables to look up row from PAC data\nconst rowsLowCh1 = { 0x11: 1, 0x12: 3, 0x15: 5, 0x16: 7, 0x17: 9, 0x10: 11, 0x13: 12, 0x14: 14 };\nconst rowsHighCh1 = { 0x11: 2, 0x12: 4, 0x15: 6, 0x16: 8, 0x17: 10, 0x13: 13, 0x14: 15 };\nconst rowsLowCh2 = { 0x19: 1, 0x1A: 3, 0x1D: 5, 0x1E: 7, 0x1F: 9, 0x18: 11, 0x1B: 12, 0x1C: 14 };\nconst rowsHighCh2 = { 0x19: 2, 0x1A: 4, 0x1D: 6, 0x1E: 8, 0x1F: 10, 0x1B: 13, 0x1C: 15 };\n\nconst backgroundColors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'black', 'transparent'];\n\nenum VerboseLevel {\n ERROR = 0,\n TEXT = 1,\n WARNING = 2,\n INFO = 2,\n DEBUG = 3,\n DATA = 3,\n}\n\nclass CaptionsLogger {\n public time: number | null = null;\n public verboseLevel: VerboseLevel = VerboseLevel.ERROR;\n\n log (severity: VerboseLevel, msg: string): void {\n if (this.verboseLevel >= severity) {\n logger.log(`${this.time} [${severity}] ${msg}`);\n }\n }\n}\n\nconst numArrayToHexArray = function (numArray: number[]): string[] {\n const hexArray: string[] = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\ntype PenStyles = {\n foreground: string | null,\n underline: boolean,\n italics: boolean,\n background: string,\n flash: boolean,\n};\n\nclass PenState {\n public foreground: string;\n public underline: boolean;\n public italics: boolean;\n public background: string;\n public flash: boolean;\n\n constructor (foreground?: string, underline?: boolean, italics?: boolean, background?: string, flash?: boolean) {\n this.foreground = foreground || 'white';\n this.underline = underline || false;\n this.italics = italics || false;\n this.background = background || 'black';\n this.flash = flash || false;\n }\n\n reset () {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n\n setStyles (styles: Partial<PenStyles>) {\n const attribs = ['foreground', 'underline', 'italics', 'background', 'flash'];\n for (let i = 0; i < attribs.length; i++) {\n const style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n\n isDefault () {\n return (this.foreground === 'white' && !this.underline && !this.italics &&\n this.background === 'black' && !this.flash);\n }\n\n equals (other: PenState) {\n return ((this.foreground === other.foreground) &&\n (this.underline === other.underline) &&\n (this.italics === other.italics) &&\n (this.background === other.background) &&\n (this.flash === other.flash));\n }\n\n copy (newPenState: PenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n }\n\n toString (): string {\n return ('color=' + this.foreground + ', underline=' + this.underline + ', italics=' + this.italics +\n ', background=' + this.background + ', flash=' + this.flash);\n }\n}\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\nclass StyledUnicodeChar {\n uchar: string;\n penState: PenState;\n\n constructor (uchar?: string, foreground?: string, underline?: boolean, italics?: boolean, background?: string, flash?: boolean) {\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(foreground, underline, italics, background, flash);\n }\n\n reset () {\n this.uchar = ' ';\n this.penState.reset();\n }\n\n setChar (uchar: string, newPenState: PenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n\n setPenState (newPenState: PenState) {\n this.penState.copy(newPenState);\n }\n\n equals (other: StyledUnicodeChar) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n\n copy (newChar: StyledUnicodeChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n\n isEmpty (): boolean {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n}\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\nexport class Row {\n public chars: StyledUnicodeChar[];\n public pos: number;\n public currPenState: PenState;\n public cueStartTime?: number;\n logger: CaptionsLogger;\n\n constructor (logger: CaptionsLogger) {\n this.chars = [];\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.logger = logger;\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals (other: Row) {\n let equal = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].equals(other.chars[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy (other: Row) {\n for (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty (): boolean {\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor (absPos: number) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n\n if (this.pos < 0) {\n this.logger.log(VerboseLevel.DEBUG, 'Negative cursor position ' + this.pos);\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n this.logger.log(VerboseLevel.DEBUG, 'Too large cursor position ' + this.pos);\n this.pos = NR_COLS;\n }\n }\n\n /**\n * Move the cursor relative to current position.\n */\n moveCursor (relPos: number) {\n const newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let i = this.pos + 1; i < newPos + 1; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n }\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace () {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n\n insertChar (byte: number) {\n if (byte >= 0x90) { // Extended char\n this.backSpace();\n }\n const char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n this.logger.log(VerboseLevel.ERROR, 'Cannot insert ' + byte.toString(16) +\n ' (' + char + ') at position ' + this.pos + '. Skipping it!');\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n }\n\n clearFromPos (startPos: number) {\n let i: number;\n for (i = startPos; i < NR_COLS; i++) {\n this.chars[i].reset();\n }\n }\n\n clear () {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n\n clearToEndOfRow () {\n this.clearFromPos(this.pos);\n }\n\n getTextString () {\n const chars: string[] = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n const char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n\n setPenStyles (styles: Partial<PenStyles>) {\n this.currPenState.setStyles(styles);\n const currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n}\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n */\nexport class CaptionScreen {\n rows: Row[];\n currRow: number;\n nrRollUpRows: number | null;\n lastOutputScreen: CaptionScreen | null;\n logger: CaptionsLogger;\n\n constructor (logger: CaptionsLogger) {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row(logger));\n } // Note that we use zero-based numbering (0-14)\n\n this.logger = logger;\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.lastOutputScreen = null;\n this.reset();\n }\n\n reset () {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n }\n\n equals (other: CaptionScreen): boolean {\n let equal = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy (other: CaptionScreen) {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty (): boolean {\n let empty = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n backSpace () {\n const row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow () {\n const row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar (char: number) {\n const row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen (styles: Partial<PenStyles>) {\n const row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor (relPos: number) {\n const row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor (absPos: number) {\n this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);\n const row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC (pacData: PACData) {\n this.logger.log(VerboseLevel.INFO, 'pacData = ' + JSON.stringify(pacData));\n let newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows - 1;\n }\n\n // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n // clear all rows first\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n // topRowIndex - the start of rows to copy (inclusive index)\n const topRowIndex = this.currRow + 1 - (this.nrRollUpRows);\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n const time = this.logger.time;\n if (prevLineTime && time !== null && prevLineTime < time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow - this.nrRollUpRows + i + 1].copy(lastOutputScreen.rows[topRowIndex + i]);\n }\n }\n }\n }\n\n this.currRow = newRow;\n const row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n const indent = pacData.indent;\n const prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n const styles: PenStyles = { foreground: pacData.color, underline: pacData.underline, italics: pacData.italics, background: 'black', flash: false };\n this.setPen(styles);\n }\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData (bkgData: Partial<PenStyles>) {\n this.logger.log(VerboseLevel.INFO, 'bkgData = ' + JSON.stringify(bkgData));\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); // Space\n }\n\n setRollUpRows (nrRows: number | null) {\n this.nrRollUpRows = nrRows;\n }\n\n rollUp () {\n if (this.nrRollUpRows === null) {\n this.logger.log(VerboseLevel.DEBUG, 'roll_up but nrRollUpRows not set yet');\n return; // Not properly setup\n }\n this.logger.log(VerboseLevel.TEXT, this.getDisplayText());\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n const topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n this.logger.log(VerboseLevel.INFO, 'Rolling up');\n // this.logger.log(VerboseLevel.TEXT, this.get_display_text())\n }\n\n /**\n * Get all non-empty rows with as unicode text.\n */\n getDisplayText (asOneRow?: boolean) {\n asOneRow = asOneRow || false;\n const displayText: string[] = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n const rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i + 1;\n if (asOneRow) {\n displayText.push('Row ' + rowNr + ': \\'' + rowText + '\\'');\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = '[' + displayText.join(' | ') + ']';\n } else {\n text = displayText.join('\\n');\n }\n }\n return text;\n }\n\n getTextAndFormat () {\n return this.rows;\n }\n}\n\n// var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\ntype CaptionModes = 'MODE_ROLL-UP' | 'MODE_POP-ON' | 'MODE_PAINT-ON' | 'MODE_TEXT' | null;\n\nclass Cea608Channel {\n chNr: number;\n outputFilter: OutputFilter;\n mode: CaptionModes;\n verbose: number;\n displayedMemory: CaptionScreen;\n nonDisplayedMemory: CaptionScreen;\n lastOutputScreen: CaptionScreen;\n currRollUpRow: Row;\n writeScreen: CaptionScreen;\n cueStartTime: number | null;\n logger: CaptionsLogger;\n\n constructor (channelNumber: number, outputFilter: OutputFilter, logger: CaptionsLogger) {\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen(logger);\n this.nonDisplayedMemory = new CaptionScreen(logger);\n this.lastOutputScreen = new CaptionScreen(logger);\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n this.logger = logger;\n }\n\n reset () {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.outputFilter.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n }\n\n getHandler (): OutputFilter {\n return this.outputFilter;\n }\n\n setHandler (newHandler: OutputFilter) {\n this.outputFilter = newHandler;\n }\n\n setPAC (pacData: PACData) {\n this.writeScreen.setPAC(pacData);\n }\n\n setBkgData (bkgData: Partial<PenStyles>) {\n this.writeScreen.setBkgData(bkgData);\n }\n\n setMode (newMode: CaptionModes) {\n if (newMode === this.mode) {\n return;\n }\n\n this.mode = newMode;\n this.logger.log(VerboseLevel.INFO, 'MODE=' + newMode);\n if (this.mode === 'MODE_POP-ON') {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n }\n if (this.mode !== 'MODE_ROLL-UP') {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n }\n\n insertChars (chars: number[]) {\n for (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n\n const screen = this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n this.logger.log(VerboseLevel.INFO, screen + ': ' + this.writeScreen.getDisplayText(true));\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n this.logger.log(VerboseLevel.TEXT, 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true));\n this.outputDataUpdate();\n }\n }\n\n ccRCL () { // Resume Caption Loading (switch mode to Pop On)\n this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS () { // BackSpace\n this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF () { // Reserved (formerly Alarm Off)\n\n }\n\n ccAON () { // Reserved (formerly Alarm On)\n\n }\n\n ccDER () { // Delete to End of Row\n this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n\n ccRU (nrRows: number | null) { // Roll-Up Captions-2,3,or 4 Rows\n this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');\n this.writeScreen = this.displayedMemory;\n this.setMode('MODE_ROLL-UP');\n this.writeScreen.setRollUpRows(nrRows);\n }\n\n ccFON () { // Flash On\n this.logger.log(VerboseLevel.INFO, 'FON - Flash On');\n this.writeScreen.setPen({ flash: true });\n }\n\n ccRDC () { // Resume Direct Captioning (switch mode to PaintOn)\n this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR () { // Text Restart in text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD () { // Resume Text Display in Text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM () { // Erase Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n\n ccCR () { // Carriage Return\n this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n\n ccENM () { // Erase Non-Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC () { // End of Caption (Flip Memories)\n this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n const tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n this.logger.log(VerboseLevel.TEXT, 'DISP: ' + this.displayedMemory.getDisplayText());\n }\n this.outputDataUpdate(true);\n }\n\n ccTO (nrCols: number) { // Tab Offset 1,2, or 3 columns\n this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW (secondByte: number) { // Parse MIDROW command\n const styles: Partial<PenStyles> = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n const colorIndex = Math.floor(secondByte / 2) - 0x10;\n const colors = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta'];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n }\n\n outputDataUpdate (dispatch: boolean = false) {\n const time = this.logger.time;\n if (time === null) {\n return;\n }\n\n if (this.outputFilter) {\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) { // Start of a new cue\n this.cueStartTime = time;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n this.outputFilter.newCue(this.cueStartTime!, time, this.lastOutputScreen);\n if (dispatch && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n\n cueSplitAtTime (t: number) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime!, t, this.displayedMemory);\n }\n\n this.cueStartTime = t;\n }\n }\n }\n}\n\ninterface PACData {\n row: number;\n indent: number | null;\n color: string | null;\n underline: boolean;\n italics: boolean;\n}\n\ntype SupportedField = 1 | 3;\n\ntype Channels = 0 | 1 | 2; // Will be 1 or 2 when parsing captions\n\ntype CmdHistory = {\n a: number | null,\n b: number | null\n};\n\nclass Cea608Parser {\n channels: Array<Cea608Channel | null>;\n currentChannel: Channels = 0;\n cmdHistory: CmdHistory;\n logger: CaptionsLogger;\n\n constructor (field: SupportedField, out1: OutputFilter, out2: OutputFilter) {\n const logger = new CaptionsLogger();\n this.channels = [\n null,\n new Cea608Channel(field, out1, logger),\n new Cea608Channel(field + 1, out2, logger)\n ];\n this.cmdHistory = createCmdHistory();\n this.logger = logger;\n }\n\n getHandler (channel: number) {\n return (this.channels[channel] as Cea608Channel).getHandler();\n }\n\n setHandler (channel: number, newHandler: OutputFilter) {\n (this.channels[channel] as Cea608Channel).setHandler(newHandler);\n }\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData (time: number | null, byteList: number[]) {\n let cmdFound: boolean;\n let a: number;\n let b: number;\n let charsFound: number[] | boolean | null = false;\n\n this.logger.time = time;\n\n for (let i = 0; i < byteList.length; i += 2) {\n a = byteList[i] & 0x7f;\n b = byteList[i + 1] & 0x7f;\n if (a === 0 && b === 0) {\n continue;\n } else {\n this.logger.log(VerboseLevel.DATA, '[' + numArrayToHexArray([byteList[i], byteList[i + 1]]) + '] -> (' + numArrayToHexArray([a, b]) + ')');\n }\n\n cmdFound = this.parseCmd(a, b);\n\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n const currChNr = this.currentChannel;\n if (currChNr && currChNr > 0) {\n const channel = this.channels[currChNr] as Cea608Channel;\n channel.insertChars(charsFound);\n } else {\n this.logger.log(VerboseLevel.WARNING, 'No channel found yet. TEXT-MODE?');\n }\n }\n }\n if (!cmdFound && !charsFound) {\n this.logger.log(VerboseLevel.WARNING, 'Couldn\\'t parse cleaned data ' + numArrayToHexArray([a, b]) +\n ' orig: ' + numArrayToHexArray([byteList[i], byteList[i + 1]]));\n }\n }\n }\n\n /**\n * Parse Command.\n * @returns {Boolean} Tells if a command was found\n */\n parseCmd (a: number, b: number) {\n const { cmdHistory } = this;\n const cond1 = (a === 0x14 || a === 0x1C || a === 0x15 || a === 0x1D) && (b >= 0x20 && b <= 0x2F);\n const cond2 = (a === 0x17 || a === 0x1F) && (b >= 0x21 && b <= 0x23);\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n this.logger.log(VerboseLevel.DEBUG, 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped');\n return true;\n }\n\n const chNr = (a === 0x14 || a === 0x15 || a === 0x17) ? 1 : 2;\n const channel = this.channels[chNr] as Cea608Channel;\n\n if (a === 0x14 || a === 0x15 || a === 0x1C || a === 0x1D) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2A) {\n channel.ccTR();\n } else if (b === 0x2B) {\n channel.ccRTD();\n } else if (b === 0x2C) {\n channel.ccEDM();\n } else if (b === 0x2D) {\n channel.ccCR();\n } else if (b === 0x2E) {\n channel.ccENM();\n } else if (b === 0x2F) {\n channel.ccEOC();\n }\n } else { // a == 0x17 || a == 0x1F\n channel.ccTO(b - 0x20);\n }\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n * @returns {Boolean}\n */\n parseMidrow (a: number, b: number) {\n let chNr: number = 0;\n\n if (((a === 0x11) || (a === 0x19)) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n\n if (chNr !== this.currentChannel) {\n this.logger.log(VerboseLevel.ERROR, 'Mismatch channel in midrow parsing');\n return false;\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.ccMIDROW(b);\n this.logger.log(VerboseLevel.DEBUG, 'MIDROW (' + numArrayToHexArray([a, b]) + ')');\n return true;\n }\n return false;\n }\n\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC (a: number, b: number): boolean {\n let row: number;\n const cmdHistory = this.cmdHistory;\n\n const case1 = ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1F)) && (b >= 0x40 && b <= 0x7F);\n const case2 = (a === 0x10 || a === 0x18) && (b >= 0x40 && b <= 0x5F);\n if (!(case1 || case2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n return true; // Repeated commands are dropped (once)\n }\n\n const chNr: Channels = (a <= 0x17) ? 1 : 2;\n\n if (b >= 0x40 && b <= 0x5F) {\n row = (chNr === 1) ? rowsLowCh1[a] : rowsLowCh2[a];\n } else { // 0x60 <= b <= 0x7F\n row = (chNr === 1) ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.setPAC(this.interpretPAC(row, b));\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns {Object} pacData with style parameters.\n */\n interpretPAC (row: number, byte: number): PACData {\n let pacIndex = byte;\n const pacData: PACData = { color: null, italics: false, indent: null, underline: false, row: row };\n\n if (byte > 0x5F) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = ['white', 'green', 'blue', 'cyan', 'red', 'yellow', 'magenta', 'white'][Math.floor(pacIndex / 2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = (Math.floor((pacIndex - 0x10) / 2)) * 4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n }\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars (a: number, b: number): number[] | null {\n let channelNr: Channels;\n let charCodes: number[] | null = null;\n let charCode1: number | null = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let oneCode = b;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n\n this.logger.log(VerboseLevel.INFO, 'Special char \\'' + getCharForByte(oneCode) + '\\' in channel ' + channelNr);\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = (b === 0) ? [a] : [a, b];\n }\n if (charCodes) {\n const hexCodes = numArrayToHexArray(charCodes);\n this.logger.log(VerboseLevel.DEBUG, 'Char codes = ' + hexCodes.join(','));\n setLastCmd(a, b, this.cmdHistory);\n }\n return charCodes;\n }\n\n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns {Boolean} Tells if background attributes are found\n */\n parseBackgroundAttributes (a: number, b: number): boolean {\n const case1 = (a === 0x10 || a === 0x18) && (b >= 0x20 && b <= 0x2f);\n const case2 = (a === 0x17 || a === 0x1f) && (b >= 0x2d && b <= 0x2f);\n if (!(case1 || case2)) {\n return false;\n }\n let index: number;\n const bkgData: Partial<PenStyles> = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b - 0x20) / 2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + '_semi';\n }\n } else if (b === 0x2d) {\n bkgData.background = 'transparent';\n } else {\n bkgData.foreground = 'black';\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n const chNr: Channels = (a <= 0x17) ? 1 : 2;\n const channel: Cea608Channel = this.channels[chNr] as Cea608Channel;\n channel.setBkgData(bkgData);\n setLastCmd(a, b, this.cmdHistory);\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset () {\n for (let i = 0; i < Object.keys(this.channels).length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.reset();\n }\n }\n this.cmdHistory = createCmdHistory();\n }\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime (t: number) {\n for (let i = 0; i < this.channels.length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.cueSplitAtTime(t);\n }\n }\n }\n}\n\nfunction setLastCmd (a: number | null, b: number | null, cmdHistory: CmdHistory) {\n cmdHistory.a = a;\n cmdHistory.b = b;\n}\n\nfunction hasCmdRepeated (a: number, b: number, cmdHistory: CmdHistory) {\n return cmdHistory.a === a && cmdHistory.b === b;\n}\n\nfunction createCmdHistory (): CmdHistory {\n return {\n a: null,\n b: null\n };\n}\n\nexport default Cea608Parser;\n","import { CaptionScreen } from './cea-608-parser';\nimport type TimelineController from '../controller/timeline-controller';\n\nexport default class OutputFilter {\n private timelineController: TimelineController;\n private cueRanges: Array<[number, number]> = [];\n private trackName: string;\n private startTime: number | null = null;\n private endTime: number | null = null;\n private screen: CaptionScreen | null = null;\n\n constructor (timelineController: TimelineController, trackName: string) {\n this.timelineController = timelineController;\n this.trackName = trackName;\n }\n\n dispatchCue () {\n if (this.startTime === null) {\n return;\n }\n\n this.timelineController.addCues(this.trackName, this.startTime, this.endTime as number, this.screen as CaptionScreen, this.cueRanges);\n this.startTime = null;\n }\n\n newCue (startTime: number, endTime: number, screen: CaptionScreen) {\n if (this.startTime === null || this.startTime > startTime) {\n this.startTime = startTime;\n }\n\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\n }\n\n reset () {\n this.cueRanges = [];\n }\n}\n","import VTTParser from './vttparser';\nimport { utf8ArrayToStr } from '../demux/id3';\n\n// String.prototype.startsWith is not supported in IE11\nconst startsWith = function (inputString, searchString, position) {\n return inputString.substr(position || 0, searchString.length) === searchString;\n};\n\nconst cueString2millis = function (timeString) {\n let ts = parseInt(timeString.substr(-3));\n let secs = parseInt(timeString.substr(-6, 2));\n let mins = parseInt(timeString.substr(-9, 2));\n let hours = timeString.length > 9 ? parseInt(timeString.substr(0, timeString.indexOf(':'))) : 0;\n\n if (!Number.isFinite(ts) || !Number.isFinite(secs) || !Number.isFinite(mins) || !Number.isFinite(hours)) {\n throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);\n }\n\n ts += 1000 * secs;\n ts += 60 * 1000 * mins;\n ts += 60 * 60 * 1000 * hours;\n\n return ts;\n};\n\n// From https://github.com/darkskyapp/string-hash\nconst hash = function (text) {\n let hash = 5381;\n let i = text.length;\n while (i) {\n hash = (hash * 33) ^ text.charCodeAt(--i);\n }\n\n return (hash >>> 0).toString();\n};\n\nconst calculateOffset = function (vttCCs, cc, presentationTime) {\n let currCC = vttCCs[cc];\n let prevCC = vttCCs[currCC.prevCC];\n\n // This is the first discontinuity or cues have been processed since the last discontinuity\n // Offset = current discontinuity time\n if (!prevCC || (!prevCC.new && currCC.new)) {\n vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n currCC.new = false;\n return;\n }\n\n // There have been discontinuities since cues were last parsed.\n // Offset = time elapsed\n while (prevCC && prevCC.new) {\n vttCCs.ccOffset += currCC.start - prevCC.start;\n currCC.new = false;\n currCC = prevCC;\n prevCC = vttCCs[currCC.prevCC];\n }\n\n vttCCs.presentationOffset = presentationTime;\n};\n\nconst WebVTTParser = {\n parse: function (vttByteArray, syncPTS, vttCCs, cc, callBack, errorCallBack) {\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n let re = /\\r\\n|\\n\\r|\\n|\\r/g;\n // Uint8Array.prototype.reduce is not implemented in IE11\n let vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray)).trim().replace(re, '\\n').split('\\n');\n\n let cueTime = '00:00.000';\n let mpegTs = 0;\n let localTime = 0;\n let presentationTime = 0;\n let cues = [];\n let parsingError;\n let inHeader = true;\n let timestampMap = false;\n // let VTTCue = VTTCue || window.TextTrackCue;\n\n // Create parser object using VTTCue with TextTrackCue fallback on certain browsers.\n let parser = new VTTParser();\n\n parser.oncue = function (cue) {\n // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n let currCC = vttCCs[cc];\n let cueOffset = vttCCs.ccOffset;\n\n // Update offsets for new discontinuities\n if (currCC && currCC.new) {\n if (localTime !== undefined) {\n // When local time is provided, offset = discontinuity start time - local time\n cueOffset = vttCCs.ccOffset = currCC.start;\n } else {\n calculateOffset(vttCCs, cc, presentationTime);\n }\n }\n\n if (presentationTime) {\n // If we have MPEGTS, offset = presentation time + discontinuity offset\n cueOffset = presentationTime - vttCCs.presentationOffset;\n }\n\n if (timestampMap) {\n cue.startTime += cueOffset - localTime;\n cue.endTime += cueOffset - localTime;\n }\n\n // Create a unique hash id for a cue based on start/end times and text.\n // This helps timeline-controller to avoid showing repeated captions.\n cue.id = hash(cue.startTime.toString()) + hash(cue.endTime.toString()) + hash(cue.text);\n\n // Fix encoding of special characters. TODO: Test with all sorts of weird characters.\n cue.text = decodeURIComponent(encodeURIComponent(cue.text));\n if (cue.endTime > 0) {\n cues.push(cue);\n }\n };\n\n parser.onparsingerror = function (e) {\n parsingError = e;\n };\n\n parser.onflush = function () {\n if (parsingError && errorCallBack) {\n errorCallBack(parsingError);\n return;\n }\n callBack(cues);\n };\n\n // Go through contents line by line.\n vttLines.forEach(line => {\n if (inHeader) {\n // Look for X-TIMESTAMP-MAP in header.\n if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n // Once found, no more are allowed anyway, so stop searching.\n inHeader = false;\n timestampMap = true;\n // Extract LOCAL and MPEGTS.\n line.substr(16).split(',').forEach(timestamp => {\n if (startsWith(timestamp, 'LOCAL:')) {\n cueTime = timestamp.substr(6);\n } else if (startsWith(timestamp, 'MPEGTS:')) {\n mpegTs = parseInt(timestamp.substr(7));\n }\n });\n try {\n // Calculate subtitle offset in milliseconds.\n if (syncPTS + ((vttCCs[cc].start * 90000) || 0) < 0) {\n syncPTS += 8589934592;\n }\n // Adjust MPEGTS by sync PTS.\n mpegTs -= syncPTS;\n // Convert cue time to seconds\n localTime = cueString2millis(cueTime) / 1000;\n // Convert MPEGTS to seconds from 90kHz.\n presentationTime = mpegTs / 90000;\n } catch (e) {\n timestampMap = false;\n parsingError = e;\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line + '\\n');\n });\n\n parser.flush();\n }\n};\n\nexport default WebVTTParser;\n","import Event from '../events';\nimport EventHandler from '../event-handler';\nimport Cea608Parser, { CaptionScreen } from '../utils/cea-608-parser';\nimport OutputFilter from '../utils/output-filter';\nimport WebVTTParser from '../utils/webvtt-parser';\nimport { logger } from '../utils/logger';\nimport { sendAddTrackEvent, clearCurrentCues } from '../utils/texttrack-utils';\nimport Fragment from '../loader/fragment';\nimport { HlsConfig } from '../config';\nimport { CuesInterface } from '../utils/cues';\nimport { MediaPlaylist } from '../types/media-playlist';\n\ntype TrackProperties = {\n label: string,\n languageCode: string,\n media?: MediaPlaylist\n};\n\ntype NonNativeCaptionsTrack = {\n _id?: string,\n label: string,\n kind: string,\n default: boolean,\n closedCaptions?: MediaPlaylist,\n subtitleTrack?: MediaPlaylist\n};\n\ntype VTTCCs = {\n ccOffset: number,\n presentationOffset: number,\n [key: number]: {\n start: number,\n prevCC: number,\n new: boolean\n }\n};\n\nclass TimelineController extends EventHandler {\n private media: HTMLMediaElement | null = null;\n private config: HlsConfig;\n private enabled: boolean = true;\n private Cues: CuesInterface;\n private textTracks: Array<TextTrack> = [];\n private tracks: Array<MediaPlaylist> = [];\n private initPTS: Array<number> = [];\n private unparsedVttFrags: Array<{ frag: Fragment, payload: ArrayBuffer }> = [];\n private captionsTracks: Record<string, TextTrack> = {};\n private nonNativeCaptionsTracks: Record<string, NonNativeCaptionsTrack> = {};\n private captionsProperties: {\n textTrack1: TrackProperties\n textTrack2: TrackProperties\n textTrack3: TrackProperties\n textTrack4: TrackProperties\n };\n private readonly cea608Parser1!: Cea608Parser;\n private readonly cea608Parser2!: Cea608Parser;\n private lastSn: number = -1;\n private prevCC: number = -1;\n private vttCCs: VTTCCs = newVTTCCs();\n\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHING,\n Event.MEDIA_DETACHING,\n Event.FRAG_PARSING_USERDATA,\n Event.FRAG_DECRYPTED,\n Event.MANIFEST_LOADING,\n Event.MANIFEST_LOADED,\n Event.FRAG_LOADED,\n Event.INIT_PTS_FOUND);\n\n this.hls = hls;\n this.config = hls.config;\n this.Cues = hls.config.cueHandler;\n\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode\n },\n textTrack3: {\n label: this.config.captionsTextTrack3Label,\n languageCode: this.config.captionsTextTrack3LanguageCode\n },\n textTrack4: {\n label: this.config.captionsTextTrack4Label,\n languageCode: this.config.captionsTextTrack4LanguageCode\n }\n };\n\n if (this.config.enableCEA708Captions) {\n const channel1 = new OutputFilter(this, 'textTrack1');\n const channel2 = new OutputFilter(this, 'textTrack2');\n const channel3 = new OutputFilter(this, 'textTrack3');\n const channel4 = new OutputFilter(this, 'textTrack4');\n this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);\n this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);\n }\n }\n\n addCues (trackName: string, startTime: number, endTime: number, screen: CaptionScreen, cueRanges: Array<[number, number]>) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n let merged = false;\n for (let i = cueRanges.length; i--;) {\n let cueRange = cueRanges[i];\n let overlap = intersection(cueRange[0], cueRange[1], startTime, endTime);\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if ((overlap / (endTime - startTime)) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n cueRanges.push([startTime, endTime]);\n }\n\n if (this.config.renderTextTracksNatively) {\n this.Cues.newCue(this.captionsTracks[trackName], startTime, endTime, screen);\n } else {\n const cues = this.Cues.newCue(null, startTime, endTime, screen);\n this.hls.trigger(Event.CUES_PARSED, { type: 'captions', cues, track: trackName });\n }\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n onInitPtsFound (data: { id: string, frag: Fragment, initPTS: number}) {\n const { frag, id, initPTS } = data;\n const { unparsedVttFrags } = this;\n if (id === 'main') {\n this.initPTS[frag.cc] = initPTS;\n }\n\n // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (unparsedVttFrags.length) {\n this.unparsedVttFrags = [];\n unparsedVttFrags.forEach(frag => {\n this.onFragLoaded(frag);\n });\n }\n }\n\n getExistingTrack (trackName: string): TextTrack | null {\n const { media } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n let textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n createCaptionsTrack (trackName: string) {\n if (this.config.renderTextTracksNatively) {\n this.createNativeTrack(trackName);\n } else {\n this.createNonNativeTrack(trackName);\n }\n }\n\n createNativeTrack (trackName: string) {\n if (this.captionsTracks[trackName]) {\n return;\n }\n const { captionsProperties, captionsTracks, media } = this;\n const { label, languageCode } = captionsProperties[trackName];\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], media as HTMLMediaElement);\n }\n }\n\n createNonNativeTrack (trackName: string) {\n if (this.nonNativeCaptionsTracks[trackName]) {\n return;\n }\n // Create a list of a single track for the provider to consume\n const trackProperties: TrackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n const label = trackProperties.label as string;\n const track = {\n _id: trackName,\n label,\n kind: 'captions',\n default: trackProperties.media ? !!trackProperties.media.default : false,\n closedCaptions: trackProperties.media\n };\n this.nonNativeCaptionsTracks[trackName] = track;\n this.hls.trigger(Event.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: [track] });\n }\n createTextTrack (kind: TextTrackKind, label: string, lang?: string): TextTrack | undefined {\n const media = this.media;\n if (!media) {\n return;\n }\n return media.addTextTrack(kind, label, lang);\n }\n\n destroy () {\n super.destroy();\n }\n\n onMediaAttaching (data: { media: HTMLMediaElement }) {\n this.media = data.media;\n this._cleanTracks();\n }\n\n onMediaDetaching () {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach(trackName => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n this.nonNativeCaptionsTracks = {};\n }\n\n onManifestLoading () {\n this.lastSn = -1; // Detect discontiguity in fragment parsing\n this.prevCC = -1;\n this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests\n this._cleanTracks();\n this.tracks = [];\n this.captionsTracks = {};\n this.nonNativeCaptionsTracks = {};\n }\n\n _cleanTracks () {\n // clear outdated subtitles\n const { media } = this;\n if (!media) {\n return;\n }\n const textTracks = media.textTracks;\n if (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n clearCurrentCues(textTracks[i]);\n }\n }\n }\n\n onManifestLoaded (data: { subtitles: Array<MediaPlaylist>, captions: Array<MediaPlaylist> }) {\n this.textTracks = [];\n this.unparsedVttFrags = this.unparsedVttFrags || [];\n this.initPTS = [];\n if (this.cea608Parser1 && this.cea608Parser2) {\n this.cea608Parser1.reset();\n this.cea608Parser2.reset();\n }\n\n if (this.config.enableWebVTT) {\n const tracks = data.subtitles || [];\n const sameTracks = this.tracks && tracks && this.tracks.length === tracks.length;\n this.tracks = data.subtitles || [];\n\n if (this.config.renderTextTracksNatively) {\n const inUseTracks = this.media ? this.media.textTracks : [];\n\n this.tracks.forEach((track, index) => {\n let textTrack;\n if (index < inUseTracks.length) {\n let inUseTrack: TextTrack | null = null;\n\n for (let i = 0; i < inUseTracks.length; i++) {\n if (canReuseVttTextTrack(inUseTracks[i], track)) {\n inUseTrack = inUseTracks[i];\n break;\n }\n }\n\n // Reuse tracks with the same label, but do not reuse 608/708 tracks\n if (inUseTrack) {\n textTrack = inUseTrack;\n }\n }\n if (!textTrack) {\n textTrack = this.createTextTrack('subtitles', track.name, track.lang);\n }\n\n if (track.default) {\n textTrack.mode = this.hls.subtitleDisplay ? 'showing' : 'hidden';\n } else {\n textTrack.mode = 'disabled';\n }\n\n this.textTracks.push(textTrack);\n });\n } else if (!sameTracks && this.tracks && this.tracks.length) {\n // Create a list of tracks for the provider to consume\n const tracksList = this.tracks.map((track) => {\n return {\n label: track.name,\n kind: track.type.toLowerCase(),\n default: track.default,\n subtitleTrack: track\n };\n });\n this.hls.trigger(Event.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: tracksList });\n }\n }\n\n if (this.config.enableCEA708Captions && data.captions) {\n data.captions.forEach(captionsTrack => {\n const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(captionsTrack.instreamId as string);\n if (!instreamIdMatch) {\n return;\n }\n const trackName = `textTrack${instreamIdMatch[1]}`;\n const trackProperties: TrackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n trackProperties.label = captionsTrack.name;\n if (captionsTrack.lang) { // optional attribute\n trackProperties.languageCode = captionsTrack.lang;\n }\n trackProperties.media = captionsTrack;\n });\n }\n }\n\n onFragLoaded (data: { frag: Fragment, payload: ArrayBuffer }) {\n const { frag, payload } = data;\n const { cea608Parser1, cea608Parser2, initPTS, lastSn, unparsedVttFrags } = this;\n if (frag.type === 'main') {\n const sn = frag.sn;\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (frag.sn !== lastSn + 1) {\n if (cea608Parser1 && cea608Parser2) {\n cea608Parser1.reset();\n cea608Parser2.reset();\n }\n }\n this.lastSn = sn as number;\n } // eslint-disable-line brace-style\n // If fragment is subtitle type, parse as WebVTT.\n else if (frag.type === 'subtitle') {\n if (payload.byteLength) {\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived.\n if (!Number.isFinite(initPTS[frag.cc])) {\n unparsedVttFrags.push(data);\n if (initPTS.length) {\n // finish unsuccessfully, otherwise the subtitle-stream-controller could be blocked from loading new frags.\n this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag });\n }\n return;\n }\n\n let decryptData = frag.decryptdata;\n // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.\n if ((decryptData == null) || (decryptData.key == null) || (decryptData.method !== 'AES-128')) {\n this._parseVTTs(frag, payload);\n }\n } else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag });\n }\n }\n }\n\n _parseVTTs (frag: Fragment, payload: ArrayBuffer) {\n const { hls, prevCC, textTracks, vttCCs } = this;\n if (!vttCCs[frag.cc]) {\n vttCCs[frag.cc] = { start: frag.start, prevCC, new: true };\n this.prevCC = frag.cc;\n }\n // Parse the WebVTT file contents.\n WebVTTParser.parse(payload, this.initPTS[frag.cc], vttCCs, frag.cc, (cues) => {\n if (this.config.renderTextTracksNatively) {\n const currentTrack = textTracks[frag.level];\n // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n // Because we check if the mode is diabled, we can force check `cues` below. They can't be null.\n if (currentTrack.mode === 'disabled') {\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n return;\n }\n\n // Add cues and trigger event with success true.\n cues.forEach(cue => {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n if (!currentTrack.cues!.getCueById(cue.id)) {\n try {\n currentTrack.addCue(cue);\n if (!currentTrack.cues!.getCueById(cue.id)) {\n throw new Error(`addCue is failed for: ${cue}`);\n }\n } catch (err) {\n logger.debug(`Failed occurred on adding cues: ${err}`);\n const textTrackCue = new (window as any).TextTrackCue(cue.startTime, cue.endTime, cue.text);\n textTrackCue.id = cue.id;\n currentTrack.addCue(textTrackCue);\n }\n }\n });\n } else {\n let trackId = this.tracks[frag.level].default ? 'default' : 'subtitles' + frag.level;\n hls.trigger(Event.CUES_PARSED, { type: 'subtitles', cues: cues, track: trackId });\n }\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: true, frag: frag });\n },\n function (e) {\n // Something went wrong while parsing. Trigger event with success false.\n logger.log(`Failed to parse VTT cue: ${e}`);\n hls.trigger(Event.SUBTITLE_FRAG_PROCESSED, { success: false, frag: frag });\n });\n }\n\n onFragDecrypted (data: { frag: Fragment, payload: any}) {\n const { frag, payload } = data;\n if (frag.type === 'subtitle') {\n if (!Number.isFinite(this.initPTS[frag.cc])) {\n this.unparsedVttFrags.push(data);\n return;\n }\n\n this._parseVTTs(frag, payload);\n }\n }\n\n onFragParsingUserdata (data: { samples: Array<any> }) {\n const { cea608Parser1, cea608Parser2 } = this;\n if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n return;\n }\n\n // If the event contains captions (found in the bytes property), push all bytes into the parser immediately\n // It will create the proper timestamps based on the PTS value\n for (let i = 0; i < data.samples.length; i++) {\n const ccBytes = data.samples[i].bytes;\n if (ccBytes) {\n const ccdatas = this.extractCea608Data(ccBytes);\n cea608Parser1.addData(data.samples[i].pts, ccdatas[0]);\n cea608Parser2.addData(data.samples[i].pts, ccdatas[1]);\n }\n }\n }\n\n extractCea608Data (byteArray: Uint8Array): number[][] {\n const count = byteArray[0] & 31;\n let position = 2;\n const actualCCBytes: number[][] = [[], []];\n\n for (let j = 0; j < count; j++) {\n const tmpByte = byteArray[position++];\n const ccbyte1 = 0x7F & byteArray[position++];\n const ccbyte2 = 0x7F & byteArray[position++];\n const ccValid = (4 & tmpByte) !== 0;\n const ccType = 3 & tmpByte;\n\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n\n if (ccValid) {\n if (ccType === 0 || ccType === 1) {\n actualCCBytes[ccType].push(ccbyte1);\n actualCCBytes[ccType].push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\n\nfunction canReuseVttTextTrack (inUseTrack, manifestTrack): boolean {\n return inUseTrack && inUseTrack.label === manifestTrack.name && !(inUseTrack.textTrack1 || inUseTrack.textTrack2);\n}\n\nfunction intersection (x1: number, x2: number, y1: number, y2: number): number {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\n\nfunction newVTTCCs (): VTTCCs {\n return {\n ccOffset: 0,\n presentationOffset: 0,\n 0: {\n start: 0,\n prevCC: -1,\n new: false\n }\n };\n}\n\nexport default TimelineController;\n","import Event from '../events';\nimport EventHandler from '../event-handler';\nimport { logger } from '../utils/logger';\nimport { computeReloadInterval } from './level-helper';\nimport { clearCurrentCues } from '../utils/texttrack-utils';\n\nclass SubtitleTrackController extends EventHandler {\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.MANIFEST_LOADED,\n Event.SUBTITLE_TRACK_LOADED);\n this.tracks = [];\n this.trackId = -1;\n this.media = null;\n this.stopped = true;\n\n /**\n * @member {boolean} subtitleDisplay Enable/disable subtitle display rendering\n */\n this.subtitleDisplay = true;\n\n /**\n * Keeps reference to a default track id when media has not been attached yet\n * @member {number}\n */\n this.queuedDefaultTrack = null;\n }\n\n destroy () {\n EventHandler.prototype.destroy.call(this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n onMediaAttached (data) {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n if (Number.isFinite(this.queuedDefaultTrack)) {\n this.subtitleTrack = this.queuedDefaultTrack;\n this.queuedDefaultTrack = null;\n }\n\n this.trackChangeListener = this._onTextTracksChanged.bind(this);\n\n this.useTextTrackPolling = !(this.media.textTracks && 'onchange' in this.media.textTracks);\n if (this.useTextTrackPolling) {\n this.subtitlePollingInterval = setInterval(() => {\n this.trackChangeListener();\n }, 500);\n } else {\n this.media.textTracks.addEventListener('change', this.trackChangeListener);\n }\n }\n\n onMediaDetaching () {\n if (!this.media) {\n return;\n }\n\n if (this.useTextTrackPolling) {\n clearInterval(this.subtitlePollingInterval);\n } else {\n this.media.textTracks.removeEventListener('change', this.trackChangeListener);\n }\n\n if (Number.isFinite(this.subtitleTrack)) {\n this.queuedDefaultTrack = this.subtitleTrack;\n }\n\n const textTracks = filterSubtitleTracks(this.media.textTracks);\n // Clear loaded cues on media detachment from tracks\n textTracks.forEach((track) => {\n clearCurrentCues(track);\n });\n // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.\n this.subtitleTrack = -1;\n this.media = null;\n }\n\n // Fired whenever a new manifest is loaded.\n onManifestLoaded (data) {\n let tracks = data.subtitles || [];\n this.tracks = tracks;\n this.hls.trigger(Event.SUBTITLE_TRACKS_UPDATED, { subtitleTracks: tracks });\n\n // loop through available subtitle tracks and autoselect default if needed\n // TODO: improve selection logic to handle forced, etc\n tracks.forEach(track => {\n if (track.default) {\n // setting this.subtitleTrack will trigger internal logic\n // if media has not been attached yet, it will fail\n // we keep a reference to the default track id\n // and we'll set subtitleTrack when onMediaAttached is triggered\n if (this.media) {\n this.subtitleTrack = track.id;\n } else {\n this.queuedDefaultTrack = track.id;\n }\n }\n });\n }\n\n onSubtitleTrackLoaded (data) {\n const { id, details } = data;\n const { trackId, tracks } = this;\n const currentTrack = tracks[trackId];\n if (id >= tracks.length || id !== trackId || !currentTrack || this.stopped) {\n this._clearReloadTimer();\n return;\n }\n\n logger.log(`subtitle track ${id} loaded`);\n if (details.live) {\n const reloadInterval = computeReloadInterval(currentTrack.details, details, data.stats.trequest);\n logger.log(`Reloading live subtitle playlist in ${reloadInterval}ms`);\n this.timer = setTimeout(() => {\n this._loadCurrentTrack();\n }, reloadInterval);\n } else {\n this._clearReloadTimer();\n }\n }\n\n startLoad () {\n this.stopped = false;\n this._loadCurrentTrack();\n }\n\n stopLoad () {\n this.stopped = true;\n this._clearReloadTimer();\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks () {\n return this.tracks;\n }\n\n /** get index of the selected subtitle track (index in subtitle track lists) **/\n get subtitleTrack () {\n return this.trackId;\n }\n\n /** select a subtitle track, based on its index in subtitle track lists**/\n set subtitleTrack (subtitleTrackId) {\n if (this.trackId !== subtitleTrackId) {\n this._toggleTrackModes(subtitleTrackId);\n this._setSubtitleTrackInternal(subtitleTrackId);\n }\n }\n\n _clearReloadTimer () {\n if (this.timer) {\n clearTimeout(this.timer);\n this.timer = null;\n }\n }\n\n _loadCurrentTrack () {\n const { trackId, tracks, hls } = this;\n const currentTrack = tracks[trackId];\n if (trackId < 0 || !currentTrack || (currentTrack.details && !currentTrack.details.live)) {\n return;\n }\n logger.log(`Loading subtitle track ${trackId}`);\n hls.trigger(Event.SUBTITLE_TRACK_LOADING, { url: currentTrack.url, id: trackId });\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n * @param newId - The id of the next track to enable\n * @private\n */\n _toggleTrackModes (newId) {\n const { media, subtitleDisplay, trackId } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n if (newId === -1) {\n [].slice.call(textTracks).forEach(track => {\n track.mode = 'disabled';\n });\n } else {\n const oldTrack = textTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n const nextTrack = textTracks[newId];\n if (nextTrack) {\n nextTrack.mode = subtitleDisplay ? 'showing' : 'hidden';\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n * @param newId - The id of the subtitle track to activate.\n */\n _setSubtitleTrackInternal (newId) {\n const { hls, tracks } = this;\n if (!Number.isFinite(newId) || newId < -1 || newId >= tracks.length) {\n return;\n }\n\n this.trackId = newId;\n logger.log(`Switching to subtitle track ${newId}`);\n hls.trigger(Event.SUBTITLE_TRACK_SWITCH, { id: newId });\n this._loadCurrentTrack();\n }\n\n _onTextTracksChanged () {\n // Media is undefined when switching streams via loadSource()\n if (!this.media || !this.hls.config.renderTextTracksNatively) {\n return;\n }\n\n let trackId = -1;\n let tracks = filterSubtitleTracks(this.media.textTracks);\n for (let id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n this.subtitleTrack = trackId;\n }\n}\n\nfunction filterSubtitleTracks (textTrackList) {\n let tracks = [];\n for (let i = 0; i < textTrackList.length; i++) {\n const track = textTrackList[i];\n // Edge adds a track without a label; we don't want to use it\n if (track.kind === 'subtitles' && track.label) {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nexport default SubtitleTrackController;\n","/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nexport enum KeySystems {\n WIDEVINE = 'com.widevine.alpha',\n PLAYREADY = 'com.microsoft.playready',\n}\n\nexport type MediaKeyFunc = (keySystem: KeySystems, supportedConfigurations: MediaKeySystemConfiguration[]) => Promise<MediaKeySystemAccess>;\nconst requestMediaKeySystemAccess = (function (): MediaKeyFunc | null {\n if (typeof window !== 'undefined' && window.navigator && window.navigator.requestMediaKeySystemAccess) {\n return window.navigator.requestMediaKeySystemAccess.bind(window.navigator);\n } else {\n return null;\n }\n})();\n\nexport {\n requestMediaKeySystemAccess\n};\n","/**\n * @class SubtitleStreamController\n */\n\nimport Event from '../events';\nimport { logger } from '../utils/logger';\nimport Decrypter from '../crypt/decrypter';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { findFragmentByPDT, findFragmentByPTS } from './fragment-finders';\nimport { FragmentState } from './fragment-tracker';\nimport BaseStreamController, { State } from './base-stream-controller';\nimport { mergeSubtitlePlaylists } from './level-helper';\n\nconst { performance } = window;\nconst TICK_INTERVAL = 500; // how often to tick in ms\n\nexport class SubtitleStreamController extends BaseStreamController {\n constructor (hls, fragmentTracker) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHING,\n Event.ERROR,\n Event.KEY_LOADED,\n Event.FRAG_LOADED,\n Event.SUBTITLE_TRACKS_UPDATED,\n Event.SUBTITLE_TRACK_SWITCH,\n Event.SUBTITLE_TRACK_LOADED,\n Event.SUBTITLE_FRAG_PROCESSED,\n Event.LEVEL_UPDATED);\n\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.state = State.STOPPED;\n this.tracks = [];\n this.tracksBuffered = [];\n this.currentTrackId = -1;\n this.decrypter = new Decrypter(hls, hls.config);\n // lastAVStart stores the time in seconds for the start time of a level load\n this.lastAVStart = 0;\n this._onMediaSeeking = this.onMediaSeeking.bind(this);\n }\n\n startLoad () {\n this.stopLoad();\n this.state = State.IDLE;\n\n // Check if we already have a track with necessary details to load fragments\n const currentTrack = this.tracks[this.currentTrackId];\n if (currentTrack && currentTrack.details) {\n this.setInterval(TICK_INTERVAL);\n this.tick();\n }\n }\n\n onSubtitleFragProcessed (data) {\n const { frag, success } = data;\n this.fragPrevious = frag;\n this.state = State.IDLE;\n if (!success) {\n return;\n }\n\n const buffered = this.tracksBuffered[this.currentTrackId];\n if (!buffered) {\n return;\n }\n\n // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo\n // so we can re-use the logic used to detect how much have been buffered\n let timeRange;\n const fragStart = frag.start;\n for (let i = 0; i < buffered.length; i++) {\n if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {\n timeRange = buffered[i];\n break;\n }\n }\n\n const fragEnd = frag.start + frag.duration;\n if (timeRange) {\n timeRange.end = fragEnd;\n } else {\n timeRange = {\n start: fragStart,\n end: fragEnd\n };\n buffered.push(timeRange);\n }\n }\n\n onMediaAttached ({ media }) {\n this.media = media;\n media.addEventListener('seeking', this._onMediaSeeking);\n this.state = State.IDLE;\n }\n\n onMediaDetaching () {\n if (!this.media) {\n return;\n }\n this.media.removeEventListener('seeking', this._onMediaSeeking);\n this.fragmentTracker.removeAllFragments();\n this.currentTrackId = -1;\n this.tracks.forEach((track) => {\n this.tracksBuffered[track.id] = [];\n });\n this.media = null;\n this.state = State.STOPPED;\n }\n\n // If something goes wrong, proceed to next frag, if we were processing one.\n onError (data) {\n let frag = data.frag;\n // don't handle error not related to subtitle fragment\n if (!frag || frag.type !== 'subtitle') {\n return;\n }\n\n if (this.fragCurrent && this.fragCurrent.loader) {\n this.fragCurrent.loader.abort();\n }\n\n this.state = State.IDLE;\n }\n\n // Got all new subtitle tracks.\n onSubtitleTracksUpdated (data) {\n logger.log('subtitle tracks updated');\n this.tracksBuffered = [];\n this.tracks = data.subtitleTracks;\n this.tracks.forEach((track) => {\n this.tracksBuffered[track.id] = [];\n });\n }\n\n onSubtitleTrackSwitch (data) {\n this.currentTrackId = data.id;\n\n if (!this.tracks || !this.tracks.length || this.currentTrackId === -1) {\n this.clearInterval();\n return;\n }\n\n // Check if track has the necessary details to load fragments\n const currentTrack = this.tracks[this.currentTrackId];\n if (currentTrack && currentTrack.details) {\n this.setInterval(TICK_INTERVAL);\n }\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded (data) {\n const { id, details } = data;\n const { currentTrackId, tracks } = this;\n const currentTrack = tracks[currentTrackId];\n if (id >= tracks.length || id !== currentTrackId || !currentTrack) {\n return;\n }\n\n if (details.live) {\n mergeSubtitlePlaylists(currentTrack.details, details, this.lastAVStart);\n }\n currentTrack.details = details;\n this.setInterval(TICK_INTERVAL);\n }\n\n onKeyLoaded () {\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n }\n }\n\n onFragLoaded (data) {\n const fragCurrent = this.fragCurrent;\n const decryptData = data.frag.decryptdata;\n const fragLoaded = data.frag;\n const hls = this.hls;\n\n if (this.state === State.FRAG_LOADING &&\n fragCurrent &&\n data.frag.type === 'subtitle' &&\n fragCurrent.sn === data.frag.sn) {\n // check to see if the payload needs to be decrypted\n if (data.payload.byteLength > 0 && (decryptData && decryptData.key && decryptData.method === 'AES-128')) {\n let startTime = performance.now();\n\n // decrypt the subtitles\n this.decrypter.decrypt(data.payload, decryptData.key.buffer, decryptData.iv.buffer, function (decryptedData) {\n let endTime = performance.now();\n hls.trigger(Event.FRAG_DECRYPTED, { frag: fragLoaded, payload: decryptedData, stats: { tstart: startTime, tdecrypt: endTime } });\n });\n }\n }\n }\n\n onLevelUpdated ({ details }) {\n const frags = details.fragments;\n this.lastAVStart = frags.length ? frags[0].start : 0;\n }\n\n doTick () {\n if (!this.media) {\n this.state = State.IDLE;\n return;\n }\n\n switch (this.state) {\n case State.IDLE: {\n const { config, currentTrackId, fragmentTracker, media, tracks } = this;\n if (!tracks || !tracks[currentTrackId] || !tracks[currentTrackId].details) {\n break;\n }\n\n const { maxBufferHole, maxFragLookUpTolerance } = config;\n const maxConfigBuffer = Math.min(config.maxBufferLength, config.maxMaxBufferLength);\n const bufferedInfo = BufferHelper.bufferedInfo(this._getBuffered(), media.currentTime, maxBufferHole);\n const { end: bufferEnd, len: bufferLen } = bufferedInfo;\n\n const trackDetails = tracks[currentTrackId].details;\n const fragments = trackDetails.fragments;\n const fragLen = fragments.length;\n const end = fragments[fragLen - 1].start + fragments[fragLen - 1].duration;\n\n if (bufferLen > maxConfigBuffer) {\n return;\n }\n\n let foundFrag;\n const fragPrevious = this.fragPrevious;\n if (bufferEnd < end) {\n if (fragPrevious && trackDetails.hasProgramDateTime) {\n foundFrag = findFragmentByPDT(fragments, fragPrevious.endProgramDateTime, maxFragLookUpTolerance);\n }\n if (!foundFrag) {\n foundFrag = findFragmentByPTS(fragPrevious, fragments, bufferEnd, maxFragLookUpTolerance);\n }\n } else {\n foundFrag = fragments[fragLen - 1];\n }\n\n if (foundFrag && foundFrag.encrypted) {\n logger.log(`Loading key for ${foundFrag.sn}`);\n this.state = State.KEY_LOADING;\n this.hls.trigger(Event.KEY_LOADING, { frag: foundFrag });\n } else if (foundFrag && fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED) {\n // only load if fragment is not loaded\n this.fragCurrent = foundFrag;\n this.state = State.FRAG_LOADING;\n this.hls.trigger(Event.FRAG_LOADING, { frag: foundFrag });\n }\n }\n }\n }\n\n stopLoad () {\n this.lastAVStart = 0;\n this.fragPrevious = null;\n super.stopLoad();\n }\n\n _getBuffered () {\n return this.tracksBuffered[this.currentTrackId] || [];\n }\n\n onMediaSeeking () {\n if (this.fragCurrent) {\n const currentTime = this.media ? this.media.currentTime : 0;\n const tolerance = this.config.maxFragLookUpTolerance;\n const fragStartOffset = this.fragCurrent.start - tolerance;\n const fragEndOffset = this.fragCurrent.start + this.fragCurrent.duration + tolerance;\n\n // check if position will be out of currently loaded frag range after seeking : if out, cancel frag load, if in, don't do anything\n if (currentTime < fragStartOffset || currentTime > fragEndOffset) {\n if (this.fragCurrent.loader) {\n this.fragCurrent.loader.abort();\n }\n\n this.fragmentTracker.removeFragment(this.fragCurrent);\n this.fragCurrent = null;\n this.fragPrevious = null;\n\n // switch to IDLE state to load new fragment\n this.state = State.IDLE;\n\n // speed up things\n this.tick();\n }\n }\n }\n}\n","/**\n * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n *\n * DRM support for Hls.js\n */\n\nimport EventHandler from '../event-handler';\nimport Event from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\n\nimport { logger } from '../utils/logger';\nimport { DRMSystemOptions, EMEControllerConfig } from '../config';\nimport { KeySystems, MediaKeyFunc } from '../utils/mediakeys-helper';\n\nconst MAX_LICENSE_REQUEST_FAILURES = 3;\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @param {object} drmSystemOptions Optional parameters/requirements for the key-system\n * @returns {Array<MediaSystemConfiguration>} An array of supported configurations\n */\n\nconst createWidevineMediaKeySystemConfigurations = function (\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] { /* jshint ignore:line */\n const baseConfig: MediaKeySystemConfiguration = {\n // initDataTypes: ['keyids', 'mp4'],\n // label: \"\",\n // persistentState: \"not-allowed\", // or \"required\" ?\n // distinctiveIdentifier: \"not-allowed\", // or \"required\" ?\n // sessionTypes: ['temporary'],\n audioCapabilities: [], // { contentType: 'audio/mp4; codecs=\"mp4a.40.2\"' }\n videoCapabilities: [] // { contentType: 'video/mp4; codecs=\"avc1.42E01E\"' }\n };\n\n audioCodecs.forEach((codec) => {\n baseConfig.audioCapabilities!.push({\n contentType: `audio/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.audioRobustness || ''\n });\n });\n videoCodecs.forEach((codec) => {\n baseConfig.videoCapabilities!.push({\n contentType: `video/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.videoRobustness || ''\n });\n });\n\n return [\n baseConfig\n ];\n};\n\n/**\n * The idea here is to handle key-system (and their respective platforms) specific configuration differences\n * in order to work with the local requestMediaKeySystemAccess method.\n *\n * We can also rule-out platform-related key-system support at this point by throwing an error.\n *\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @throws will throw an error if a unknown key system is passed\n * @returns {Array<MediaSystemConfiguration>} A non-empty Array of MediaKeySystemConfiguration objects\n */\nconst getSupportedMediaKeySystemConfigurations = function (\n keySystem: KeySystems,\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n return createWidevineMediaKeySystemConfigurations(audioCodecs, videoCodecs, drmSystemOptions);\n default:\n throw new Error(`Unknown key-system: ${keySystem}`);\n }\n};\n\ninterface MediaKeysListItem {\n mediaKeys?: MediaKeys,\n mediaKeysSession?: MediaKeySession,\n mediaKeysSessionInitialized: boolean;\n mediaKeySystemAccess: MediaKeySystemAccess;\n mediaKeySystemDomain: KeySystems;\n}\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\nclass EMEController extends EventHandler {\n private _widevineLicenseUrl?: string;\n private _licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void;\n private _emeEnabled: boolean;\n private _requestMediaKeySystemAccess: MediaKeyFunc | null;\n private _drmSystemOptions: DRMSystemOptions;\n\n private _config: EMEControllerConfig;\n private _mediaKeysList: MediaKeysListItem[] = [];\n private _media: HTMLMediaElement | null = null;\n private _hasSetMediaKeys: boolean = false;\n private _requestLicenseFailureCount: number = 0;\n\n private mediaKeysPromise: Promise<MediaKeys> | null = null;\n\n /**\n * @constructs\n * @param {Hls} hls Our Hls.js instance\n */\n constructor (hls) {\n super(hls,\n Event.MEDIA_ATTACHED,\n Event.MEDIA_DETACHED,\n Event.MANIFEST_PARSED\n );\n this._config = hls.config;\n\n this._widevineLicenseUrl = this._config.widevineLicenseUrl;\n this._licenseXhrSetup = this._config.licenseXhrSetup;\n this._emeEnabled = this._config.emeEnabled;\n this._requestMediaKeySystemAccess = this._config.requestMediaKeySystemAccessFunc;\n this._drmSystemOptions = hls.config.drmSystemOptions;\n }\n\n /**\n * @param {string} keySystem Identifier for the key-system, see `KeySystems` enum\n * @returns {string} License server URL for key-system (if any configured, otherwise causes error)\n * @throws if a unsupported keysystem is passed\n */\n getLicenseServerUrl (keySystem: KeySystems): string {\n switch (keySystem) {\n case KeySystems.WIDEVINE:\n if (!this._widevineLicenseUrl) {\n break;\n }\n return this._widevineLicenseUrl;\n }\n\n throw new Error(`no license server URL configured for key-system \"${keySystem}\"`);\n }\n\n /**\n * Requests access object and adds it to our list upon success\n * @private\n * @param {string} keySystem System ID (see `KeySystems`)\n * @param {Array<string>} audioCodecs List of required audio codecs to support\n * @param {Array<string>} videoCodecs List of required video codecs to support\n * @throws When a unsupported KeySystem is passed\n */\n private _attemptKeySystemAccess (keySystem: KeySystems, audioCodecs: string[], videoCodecs: string[]) {\n // This can throw, but is caught in event handler callpath\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(keySystem, audioCodecs, videoCodecs, this._drmSystemOptions);\n\n logger.log('Requesting encrypted media key-system access');\n\n // expecting interface like window.navigator.requestMediaKeySystemAccess\n const keySystemAccessPromise = this.requestMediaKeySystemAccess(keySystem, mediaKeySystemConfigs);\n\n this.mediaKeysPromise = keySystemAccessPromise.then((mediaKeySystemAccess) =>\n this._onMediaKeySystemAccessObtained(keySystem, mediaKeySystemAccess));\n\n keySystemAccessPromise.catch((err) => {\n logger.error(`Failed to obtain key-system \"${keySystem}\" access:`, err);\n });\n }\n\n get requestMediaKeySystemAccess () {\n if (!this._requestMediaKeySystemAccess) {\n throw new Error('No requestMediaKeySystemAccess function configured');\n }\n\n return this._requestMediaKeySystemAccess;\n }\n\n /**\n * Handles obtaining access to a key-system\n * @private\n * @param {string} keySystem\n * @param {MediaKeySystemAccess} mediaKeySystemAccess https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemAccess\n */\n private _onMediaKeySystemAccessObtained (keySystem: KeySystems, mediaKeySystemAccess: MediaKeySystemAccess): Promise<MediaKeys> {\n logger.log(`Access for key-system \"${keySystem}\" obtained`);\n\n const mediaKeysListItem: MediaKeysListItem = {\n mediaKeysSessionInitialized: false,\n mediaKeySystemAccess: mediaKeySystemAccess,\n mediaKeySystemDomain: keySystem\n };\n\n this._mediaKeysList.push(mediaKeysListItem);\n\n const mediaKeysPromise = Promise.resolve().then(() => mediaKeySystemAccess.createMediaKeys())\n .then((mediaKeys) => {\n mediaKeysListItem.mediaKeys = mediaKeys;\n\n logger.log(`Media-keys created for key-system \"${keySystem}\"`);\n\n this._onMediaKeysCreated();\n\n return mediaKeys;\n });\n\n mediaKeysPromise.catch((err) => {\n logger.error('Failed to create media-keys:', err);\n });\n\n return mediaKeysPromise;\n }\n\n /**\n * Handles key-creation (represents access to CDM). We are going to create key-sessions upon this\n * for all existing keys where no session exists yet.\n *\n * @private\n */\n private _onMediaKeysCreated () {\n // check for all key-list items if a session exists, otherwise, create one\n this._mediaKeysList.forEach((mediaKeysListItem) => {\n if (!mediaKeysListItem.mediaKeysSession) {\n // mediaKeys is definitely initialized here\n mediaKeysListItem.mediaKeysSession = mediaKeysListItem.mediaKeys!.createSession();\n this._onNewMediaKeySession(mediaKeysListItem.mediaKeysSession);\n }\n });\n }\n\n /**\n * @private\n * @param {*} keySession\n */\n private _onNewMediaKeySession (keySession: MediaKeySession) {\n logger.log(`New key-system session ${keySession.sessionId}`);\n\n keySession.addEventListener('message', (event: MediaKeyMessageEvent) => {\n this._onKeySessionMessage(keySession, event.message);\n }, false);\n }\n\n /**\n * @private\n * @param {MediaKeySession} keySession\n * @param {ArrayBuffer} message\n */\n private _onKeySessionMessage (keySession: MediaKeySession, message: ArrayBuffer) {\n logger.log('Got EME message event, creating license request');\n\n this._requestLicense(message, (data: ArrayBuffer) => {\n logger.log(`Received license data (length: ${data ? data.byteLength : data}), updating key-session`);\n keySession.update(data);\n });\n }\n\n /**\n * @private\n * @param e {MediaEncryptedEvent}\n */\n private _onMediaEncrypted = (e: MediaEncryptedEvent) => {\n logger.log(`Media is encrypted using \"${e.initDataType}\" init data type`);\n\n if (!this.mediaKeysPromise) {\n logger.error('Fatal: Media is encrypted but no CDM access or no keys have been requested');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n fatal: true\n });\n return;\n }\n\n const finallySetKeyAndStartSession = (mediaKeys) => {\n if (!this._media) {\n return;\n }\n this._attemptSetMediaKeys(mediaKeys);\n this._generateRequestWithPreferredKeySession(e.initDataType, e.initData);\n };\n\n // Could use `Promise.finally` but some Promise polyfills are missing it\n this.mediaKeysPromise.then(finallySetKeyAndStartSession).catch(finallySetKeyAndStartSession);\n }\n\n /**\n * @private\n */\n private _attemptSetMediaKeys (mediaKeys?: MediaKeys) {\n if (!this._media) {\n throw new Error('Attempted to set mediaKeys without first attaching a media element');\n }\n\n if (!this._hasSetMediaKeys) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem || !keysListItem.mediaKeys) {\n logger.error('Fatal: Media is encrypted but no CDM access or no keys have been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n fatal: true\n });\n return;\n }\n\n logger.log('Setting keys for encrypted media');\n\n this._media.setMediaKeys(keysListItem.mediaKeys);\n this._hasSetMediaKeys = true;\n }\n }\n\n /**\n * @private\n */\n private _generateRequestWithPreferredKeySession (initDataType: string, initData: ArrayBuffer | null) {\n // FIXME: see if we can/want/need-to really to deal with several potential key-sessions?\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal: Media is encrypted but not any key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n if (keysListItem.mediaKeysSessionInitialized) {\n logger.warn('Key-Session already initialized but requested again');\n return;\n }\n\n const keySession = keysListItem.mediaKeysSession;\n if (!keySession) {\n logger.error('Fatal: Media is encrypted but no key-session existing');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: true\n });\n return;\n }\n\n // initData is null if the media is not CORS-same-origin\n if (!initData) {\n logger.warn('Fatal: initData required for generating a key session is null');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_INIT_DATA,\n fatal: true\n });\n return;\n }\n\n logger.log(`Generating key-session request for \"${initDataType}\" init data type`);\n keysListItem.mediaKeysSessionInitialized = true;\n\n keySession.generateRequest(initDataType, initData)\n .then(() => {\n logger.debug('Key-session generation succeeded');\n })\n .catch((err) => {\n logger.error('Error generating key-session request:', err);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n fatal: false\n });\n });\n }\n\n /**\n * @private\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n * @returns {XMLHttpRequest} Unsent (but opened state) XHR object\n * @throws if XMLHttpRequest construction failed\n */\n private _createLicenseXhr (url: string, keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void): XMLHttpRequest {\n const xhr = new XMLHttpRequest();\n const licenseXhrSetup = this._licenseXhrSetup;\n\n try {\n if (licenseXhrSetup) {\n try {\n licenseXhrSetup(xhr, url);\n } catch (e) {\n // let's try to open before running setup\n xhr.open('POST', url, true);\n licenseXhrSetup(xhr, url);\n }\n }\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n } catch (e) {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n throw new Error(`issue setting up KeySystem license XHR ${e}`);\n }\n\n // Because we set responseType to ArrayBuffer here, callback is typed as handling only array buffers\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange =\n this._onLicenseRequestReadyStageChange.bind(this, xhr, url, keyMessage, callback);\n return xhr;\n }\n\n /**\n * @private\n * @param {XMLHttpRequest} xhr\n * @param {string} url License server URL\n * @param {ArrayBuffer} keyMessage Message data issued by key-system\n * @param {function} callback Called when XHR has succeeded\n */\n private _onLicenseRequestReadyStageChange (xhr: XMLHttpRequest, url: string, keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void) {\n switch (xhr.readyState) {\n case 4:\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n logger.log('License request succeeded');\n\n if (xhr.responseType !== 'arraybuffer') {\n logger.warn('xhr response type was not set to the expected arraybuffer for license request');\n }\n callback(xhr.response);\n } else {\n logger.error(`License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`);\n this._requestLicenseFailureCount++;\n if (this._requestLicenseFailureCount > MAX_LICENSE_REQUEST_FAILURES) {\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n return;\n }\n\n const attemptsLeft = MAX_LICENSE_REQUEST_FAILURES - this._requestLicenseFailureCount + 1;\n logger.warn(`Retrying license request, ${attemptsLeft} attempts left`);\n this._requestLicense(keyMessage, callback);\n }\n break;\n }\n }\n\n /**\n * @private\n * @param {MediaKeysListItem} keysListItem\n * @param {ArrayBuffer} keyMessage\n * @returns {ArrayBuffer} Challenge data posted to license server\n * @throws if KeySystem is unsupported\n */\n private _generateLicenseRequestChallenge (keysListItem: MediaKeysListItem, keyMessage: ArrayBuffer): ArrayBuffer {\n switch (keysListItem.mediaKeySystemDomain) {\n // case KeySystems.PLAYREADY:\n // from https://github.com/MicrosoftEdge/Demos/blob/master/eme/scripts/demo.js\n /*\n if (this.licenseType !== this.LICENSE_TYPE_WIDEVINE) {\n // For PlayReady CDMs, we need to dig the Challenge out of the XML.\n var keyMessageXml = new DOMParser().parseFromString(String.fromCharCode.apply(null, new Uint16Array(keyMessage)), 'application/xml');\n if (keyMessageXml.getElementsByTagName('Challenge')[0]) {\n challenge = atob(keyMessageXml.getElementsByTagName('Challenge')[0].childNodes[0].nodeValue);\n } else {\n throw 'Cannot find <Challenge> in key message';\n }\n var headerNames = keyMessageXml.getElementsByTagName('name');\n var headerValues = keyMessageXml.getElementsByTagName('value');\n if (headerNames.length !== headerValues.length) {\n throw 'Mismatched header <name>/<value> pair in key message';\n }\n for (var i = 0; i < headerNames.length; i++) {\n xhr.setRequestHeader(headerNames[i].childNodes[0].nodeValue, headerValues[i].childNodes[0].nodeValue);\n }\n }\n break;\n */\n case KeySystems.WIDEVINE:\n // For Widevine CDMs, the challenge is the keyMessage.\n return keyMessage;\n }\n\n throw new Error(`unsupported key-system: ${keysListItem.mediaKeySystemDomain}`);\n }\n\n /**\n * @private\n * @param keyMessage\n * @param callback\n */\n private _requestLicense (keyMessage: ArrayBuffer, callback: (data: ArrayBuffer) => void) {\n logger.log('Requesting content license for key-system');\n\n const keysListItem = this._mediaKeysList[0];\n if (!keysListItem) {\n logger.error('Fatal error: Media is encrypted but no key-system access has been obtained yet');\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n fatal: true\n });\n return;\n }\n\n try {\n const url = this.getLicenseServerUrl(keysListItem.mediaKeySystemDomain);\n const xhr = this._createLicenseXhr(url, keyMessage, callback);\n logger.log(`Sending license request to URL: ${url}`);\n const challenge = this._generateLicenseRequestChallenge(keysListItem, keyMessage);\n xhr.send(challenge);\n } catch (e) {\n logger.error(`Failure requesting DRM license: ${e}`);\n this.hls.trigger(Event.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true\n });\n }\n }\n\n onMediaAttached (data: { media: HTMLMediaElement; }) {\n if (!this._emeEnabled) {\n return;\n }\n\n const media = data.media;\n\n // keep reference of media\n this._media = media;\n\n media.addEventListener('encrypted', this._onMediaEncrypted);\n }\n\n onMediaDetached () {\n const media = this._media;\n const mediaKeysList = this._mediaKeysList;\n if (!media) {\n return;\n }\n media.removeEventListener('encrypted', this._onMediaEncrypted);\n this._media = null;\n this._mediaKeysList = [];\n // Close all sessions and remove media keys from the video element.\n Promise.all(mediaKeysList.map((mediaKeysListItem) => {\n if (mediaKeysListItem.mediaKeysSession) {\n return mediaKeysListItem.mediaKeysSession.close().catch(() => {\n // Ignore errors when closing the sessions. Closing a session that\n // generated no key requests will throw an error.\n });\n }\n })).then(() => {\n return media.setMediaKeys(null);\n }).catch(() => {\n // Ignore any failures while removing media keys from the video element.\n });\n }\n\n // TODO: Use manifest types here when they are defined\n onManifestParsed (data: any) {\n if (!this._emeEnabled) {\n return;\n }\n\n const audioCodecs = data.levels.map((level) => level.audioCodec);\n const videoCodecs = data.levels.map((level) => level.videoCodec);\n\n this._attemptKeySystemAccess(KeySystems.WIDEVINE, audioCodecs, videoCodecs);\n }\n}\n\nexport default EMEController;\n","/**\n * HLS config\n */\n\nimport AbrController from './controller/abr-controller';\nimport BufferController from './controller/buffer-controller';\nimport CapLevelController from './controller/cap-level-controller';\nimport FPSController from './controller/fps-controller';\nimport XhrLoader from './utils/xhr-loader';\n// import FetchLoader from './utils/fetch-loader';\n\nimport AudioTrackController from './controller/audio-track-controller';\nimport AudioStreamController from './controller/audio-stream-controller';\n\nimport * as Cues from './utils/cues';\nimport TimelineController from './controller/timeline-controller';\nimport SubtitleTrackController from './controller/subtitle-track-controller';\nimport { SubtitleStreamController } from './controller/subtitle-stream-controller';\nimport EMEController from './controller/eme-controller';\nimport { requestMediaKeySystemAccess, MediaKeyFunc } from './utils/mediakeys-helper';\n\ntype ABRControllerConfig = {\n abrEwmaFastLive: number,\n abrEwmaSlowLive: number,\n abrEwmaFastVoD: number,\n abrEwmaSlowVoD: number,\n abrEwmaDefaultEstimate: number,\n abrBandWidthFactor: number,\n abrBandWidthUpFactor: number,\n abrMaxWithRealBitrate: boolean,\n maxStarvationDelay: number,\n maxLoadingDelay: number,\n};\n\nexport type BufferControllerConfig = {\n appendErrorMaxRetry: number,\n liveDurationInfinity: boolean,\n liveBackBufferLength: number,\n};\n\ntype CapLevelControllerConfig = {\n capLevelToPlayerSize: boolean\n};\n\nexport type DRMSystemOptions = {\n audioRobustness?: string,\n videoRobustness?: string,\n}\n\nexport type EMEControllerConfig = {\n licenseXhrSetup?: (xhr: XMLHttpRequest, url: string) => void,\n emeEnabled: boolean,\n widevineLicenseUrl?: string,\n drmSystemOptions: DRMSystemOptions,\n requestMediaKeySystemAccessFunc: MediaKeyFunc | null,\n};\n\ntype FragmentLoaderConfig = {\n fLoader: any, // TODO(typescript-loader): Once Loader is typed fill this in\n\n fragLoadingTimeOut: number,\n fragLoadingMaxRetry: number,\n fragLoadingRetryDelay: number,\n fragLoadingMaxRetryTimeout: number,\n};\n\ntype FPSControllerConfig = {\n capLevelOnFPSDrop: boolean,\n fpsDroppedMonitoringPeriod: number,\n fpsDroppedMonitoringThreshold: number,\n};\n\ntype LevelControllerConfig = {\n startLevel?: number\n};\n\ntype MP4RemuxerConfig = {\n stretchShortVideoTrack: boolean,\n maxAudioFramesDrift: number,\n};\n\ntype PlaylistLoaderConfig = {\n pLoader: any, // TODO(typescript-loader): Once Loader is typed fill this in\n\n manifestLoadingTimeOut: number,\n manifestLoadingMaxRetry: number,\n manifestLoadingRetryDelay: number,\n manifestLoadingMaxRetryTimeout: number,\n\n levelLoadingTimeOut: number,\n levelLoadingMaxRetry: number,\n levelLoadingRetryDelay: number,\n levelLoadingMaxRetryTimeout: number\n};\n\ntype StreamControllerConfig = {\n autoStartLoad: boolean,\n startPosition: number,\n defaultAudioCodec?: string,\n initialLiveManifestSize: number,\n maxBufferLength: number,\n maxBufferSize: number,\n maxBufferHole: number,\n\n lowBufferWatchdogPeriod: number,\n highBufferWatchdogPeriod: number,\n nudgeOffset: number,\n nudgeMaxRetry: number,\n maxFragLookUpTolerance: number,\n liveSyncDurationCount: number,\n liveMaxLatencyDurationCount: number,\n liveSyncDuration?: number,\n liveMaxLatencyDuration?: number,\n maxMaxBufferLength: number,\n\n startFragPrefetch: boolean,\n testBandwidth: boolean\n};\n\ntype TimelineControllerConfig = {\n cueHandler: Cues.CuesInterface,\n enableCEA708Captions: boolean,\n enableWebVTT: boolean,\n captionsTextTrack1Label: string,\n captionsTextTrack1LanguageCode: string,\n captionsTextTrack2Label: string,\n captionsTextTrack2LanguageCode: string,\n captionsTextTrack3Label: string,\n captionsTextTrack3LanguageCode: string,\n captionsTextTrack4Label: string,\n captionsTextTrack4LanguageCode: string,\n renderTextTracksNatively: boolean,\n};\n\ntype TSDemuxerConfig = {\n forceKeyFrameOnDiscontinuity: boolean,\n};\n\nexport type HlsConfig =\n {\n debug: boolean,\n enableWorker: boolean,\n enableSoftwareAES: boolean,\n minAutoBitrate: number,\n loader: any, // TODO(typescript-xhrloader): Type once XHR is done\n xhrSetup?: (xhr: XMLHttpRequest, url: string) => void,\n\n // Alt Audio\n audioStreamController?: any, // TODO(typescript-audiostreamcontroller): Type once file is done\n audioTrackController?: any, // TODO(typescript-audiotrackcontroller): Type once file is done\n // Subtitle\n subtitleStreamController?: any, // TODO(typescript-subtitlestreamcontroller): Type once file is done\n subtitleTrackController?: any, // TODO(typescript-subtitletrackcontroller): Type once file is done\n timelineController?: any, // TODO(typescript-timelinecontroller): Type once file is done\n // EME\n emeController?: typeof EMEController,\n\n abrController: any, // TODO(typescript-abrcontroller): Type once file is done\n bufferController: typeof BufferController,\n capLevelController: any, // TODO(typescript-caplevelcontroller): Type once file is done\n fpsController: any, // TODO(typescript-fpscontroller): Type once file is done\n } &\n ABRControllerConfig &\n BufferControllerConfig &\n CapLevelControllerConfig &\n EMEControllerConfig &\n FPSControllerConfig &\n FragmentLoaderConfig &\n LevelControllerConfig &\n MP4RemuxerConfig &\n PlaylistLoaderConfig &\n StreamControllerConfig &\n TimelineControllerConfig &\n TSDemuxerConfig;\n\n// If possible, keep hlsDefaultConfig shallow\n// It is cloned whenever a new Hls instance is created, by keeping the config\n// shallow the properties are cloned, and we don't end up manipulating the default\nexport const hlsDefaultConfig: HlsConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: void 0, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.5, // used by stream-controller\n\n lowBufferWatchdogPeriod: 0.5, // used by stream-controller\n highBufferWatchdogPeriod: 3, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry: 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount: 3, // used by stream-controller\n liveMaxLatencyDurationCount: Infinity, // used by stream-controller\n liveSyncDuration: void 0, // used by stream-controller\n liveMaxLatencyDuration: void 0, // used by stream-controller\n liveDurationInfinity: false, // used by buffer-controller\n liveBackBufferLength: Infinity, // used by buffer-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by demuxer\n enableSoftwareAES: true, // used by decrypter\n manifestLoadingTimeOut: 10000, // used by playlist-loader\n manifestLoadingMaxRetry: 1, // used by playlist-loader\n manifestLoadingRetryDelay: 1000, // used by playlist-loader\n manifestLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n startLevel: void 0, // used by level-controller\n levelLoadingTimeOut: 10000, // used by playlist-loader\n levelLoadingMaxRetry: 4, // used by playlist-loader\n levelLoadingRetryDelay: 1000, // used by playlist-loader\n levelLoadingMaxRetryTimeout: 64000, // used by playlist-loader\n fragLoadingTimeOut: 20000, // used by fragment-loader\n fragLoadingMaxRetry: 6, // used by fragment-loader\n fragLoadingRetryDelay: 1000, // used by fragment-loader\n fragLoadingMaxRetryTimeout: 64000, // used by fragment-loader\n startFragPrefetch: false, // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000, // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller\n appendErrorMaxRetry: 3, // used by buffer-controller\n loader: XhrLoader,\n // loader: FetchLoader,\n fLoader: void 0, // used by fragment-loader\n pLoader: void 0, // used by playlist-loader\n xhrSetup: void 0, // used by xhr-loader\n licenseXhrSetup: void 0, // used by eme-controller\n // fetchSetup: void 0,\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n fpsController: FPSController,\n stretchShortVideoTrack: false, // used by mp4-remuxer\n maxAudioFramesDrift: 1, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrBandWidthFactor: 0.95, // used by abr-controller\n abrBandWidthUpFactor: 0.7, // used by abr-controller\n abrMaxWithRealBitrate: false, // used by abr-controller\n maxStarvationDelay: 4, // used by abr-controller\n maxLoadingDelay: 4, // used by abr-controller\n minAutoBitrate: 0, // used by hls\n emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: void 0, // used by eme-controller\n drmSystemOptions: {}, // used by eme-controller\n requestMediaKeySystemAccessFunc: requestMediaKeySystemAccess, // used by eme-controller\n testBandwidth: true,\n\n // Dynamic Modules\n ...timelineConfig(),\n subtitleStreamController: (__USE_SUBTITLES__) ? SubtitleStreamController : void 0,\n subtitleTrackController: (__USE_SUBTITLES__) ? SubtitleTrackController : void 0,\n timelineController: (__USE_SUBTITLES__) ? TimelineController : void 0,\n audioStreamController: (__USE_ALT_AUDIO__) ? AudioStreamController : void 0,\n audioTrackController: (__USE_ALT_AUDIO__) ? AudioTrackController : void 0,\n emeController: (__USE_EME_DRM__) ? EMEController : void 0\n};\n\nfunction timelineConfig (): TimelineControllerConfig {\n return {\n cueHandler: Cues, // used by timeline-controller\n enableCEA708Captions: __USE_SUBTITLES__, // used by timeline-controller\n enableWebVTT: __USE_SUBTITLES__, // used by timeline-controller\n captionsTextTrack1Label: 'English', // used by timeline-controller\n captionsTextTrack1LanguageCode: 'en', // used by timeline-controller\n captionsTextTrack2Label: 'Spanish', // used by timeline-controller\n captionsTextTrack2LanguageCode: 'es', // used by timeline-controller\n captionsTextTrack3Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack3LanguageCode: '', // used by timeline-controller\n captionsTextTrack4Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack4LanguageCode: '', // used by timeline-controller\n renderTextTracksNatively: true\n };\n}\n","import * as URLToolkit from 'url-toolkit';\n\nimport {\n ErrorTypes,\n ErrorDetails\n} from './errors';\n\nimport PlaylistLoader from './loader/playlist-loader';\nimport FragmentLoader from './loader/fragment-loader';\nimport KeyLoader from './loader/key-loader';\n\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport StreamController from './controller/stream-controller';\nimport LevelController from './controller/level-controller';\nimport ID3TrackController from './controller/id3-track-controller';\n\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { hlsDefaultConfig, HlsConfig } from './config';\n\nimport HlsEvents from './events';\n\nimport { Observer } from './observer';\n\n/**\n * @module Hls\n * @class\n * @constructor\n */\nexport default class Hls extends Observer {\n public static defaultConfig?: HlsConfig;\n public config: HlsConfig;\n\n private _autoLevelCapping: number;\n private abrController: any;\n private capLevelController: any;\n private levelController: LevelController;\n private streamController: StreamController;\n private networkControllers: any[];\n private audioTrackController: any;\n private subtitleTrackController: any;\n private emeController: any;\n private coreComponents: any[];\n private media: HTMLMediaElement | null = null;\n private url: string | null = null;\n\n /**\n * @type {string}\n */\n static get version (): string {\n return __VERSION__;\n }\n\n /**\n * @type {boolean}\n */\n static isSupported (): boolean {\n return isSupported();\n }\n\n /**\n * @type {HlsEvents}\n */\n static get Events () {\n return HlsEvents;\n }\n\n /**\n * @type {HlsErrorTypes}\n */\n static get ErrorTypes () {\n return ErrorTypes;\n }\n\n /**\n * @type {HlsErrorDetails}\n */\n static get ErrorDetails () {\n return ErrorDetails;\n }\n\n /**\n * @type {HlsConfig}\n */\n static get DefaultConfig (): HlsConfig {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * @type {HlsConfig}\n */\n static set DefaultConfig (defaultConfig: HlsConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n *\n * @constructs Hls\n * @param {HlsConfig} config\n */\n constructor (userConfig: Partial<HlsConfig> = {}) {\n super();\n\n const defaultConfig = Hls.DefaultConfig;\n\n if ((userConfig.liveSyncDurationCount || userConfig.liveMaxLatencyDurationCount) && (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)) {\n throw new Error('Illegal hls.js config: don\\'t mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration');\n }\n\n // Shallow clone\n this.config = {\n ...defaultConfig,\n ...userConfig\n };\n\n const { config } = this;\n\n if (config.liveMaxLatencyDurationCount !== void 0 && config.liveMaxLatencyDurationCount <= config.liveSyncDurationCount) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be gt \"liveSyncDurationCount\"');\n }\n\n if (config.liveMaxLatencyDuration !== void 0 && (config.liveSyncDuration === void 0 || config.liveMaxLatencyDuration <= config.liveSyncDuration)) {\n throw new Error('Illegal hls.js config: \"liveMaxLatencyDuration\" must be gt \"liveSyncDuration\"');\n }\n\n enableLogs(config.debug);\n\n this._autoLevelCapping = -1;\n\n // core controllers and network loaders\n\n /**\n * @member {AbrController} abrController\n */\n const abrController = this.abrController = new config.abrController(this); // eslint-disable-line new-cap\n const bufferController = new config.bufferController(this); // eslint-disable-line new-cap\n const capLevelController = this.capLevelController = new config.capLevelController(this); // eslint-disable-line new-cap\n const fpsController = new config.fpsController(this); // eslint-disable-line new-cap\n const playListLoader = new PlaylistLoader(this);\n const fragmentLoader = new FragmentLoader(this);\n const keyLoader = new KeyLoader(this);\n const id3TrackController = new ID3TrackController(this);\n\n // network controllers\n\n /**\n * @member {LevelController} levelController\n */\n const levelController = this.levelController = new LevelController(this);\n\n // FIXME: FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n\n /**\n * @member {StreamController} streamController\n */\n const streamController = this.streamController = new StreamController(this, fragmentTracker);\n\n let networkControllers = [levelController, streamController];\n\n // optional audio stream controller\n /**\n * @var {ICoreComponent | Controller}\n */\n let Controller = config.audioStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n\n /**\n * @member {INetworkController[]} networkControllers\n */\n this.networkControllers = networkControllers;\n\n /**\n * @var {ICoreComponent[]}\n */\n const coreComponents = [\n playListLoader,\n fragmentLoader,\n keyLoader,\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker\n ];\n\n // optional audio track and subtitle controller\n Controller = config.audioTrackController;\n if (Controller) {\n const audioTrackController = new Controller(this);\n\n /**\n * @member {AudioTrackController} audioTrackController\n */\n this.audioTrackController = audioTrackController;\n coreComponents.push(audioTrackController);\n }\n\n Controller = config.subtitleTrackController;\n if (Controller) {\n const subtitleTrackController = new Controller(this);\n\n /**\n * @member {SubtitleTrackController} subtitleTrackController\n */\n this.subtitleTrackController = subtitleTrackController;\n networkControllers.push(subtitleTrackController);\n }\n\n Controller = config.emeController;\n if (Controller) {\n const emeController = new Controller(this);\n\n /**\n * @member {EMEController} emeController\n */\n this.emeController = emeController;\n coreComponents.push(emeController);\n }\n\n // optional subtitle controllers\n Controller = config.subtitleStreamController;\n if (Controller) {\n networkControllers.push(new Controller(this, fragmentTracker));\n }\n Controller = config.timelineController;\n if (Controller) {\n coreComponents.push(new Controller(this));\n }\n\n /**\n * @member {ICoreComponent[]}\n */\n this.coreComponents = coreComponents;\n }\n\n /**\n * Dispose of the instance\n */\n destroy () {\n logger.log('destroy');\n this.trigger(HlsEvents.DESTROYING);\n this.detachMedia();\n this.coreComponents.concat(this.networkControllers).forEach(component => {\n component.destroy();\n });\n this.url = null;\n this.removeAllListeners();\n this._autoLevelCapping = -1;\n }\n\n /**\n * Attach a media element\n * @param {HTMLMediaElement} media\n */\n attachMedia (media: HTMLMediaElement) {\n logger.log('attachMedia');\n this.media = media;\n this.trigger(HlsEvents.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach from the media\n */\n detachMedia () {\n logger.log('detachMedia');\n this.trigger(HlsEvents.MEDIA_DETACHING);\n this.media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n * @param {string} url\n */\n loadSource (url: string) {\n url = URLToolkit.buildAbsoluteURL(window.location.href, url, { alwaysNormalize: true });\n logger.log(`loadSource:${url}`);\n this.url = url;\n // when attaching to a source URL, trigger a playlist load\n this.trigger(HlsEvents.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param {number} startPosition Set the start position to stream from\n * @default -1 None (from earliest point)\n */\n startLoad (startPosition: number = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach(controller => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad () {\n logger.log('stopLoad');\n this.networkControllers.forEach(controller => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec () {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError () {\n logger.log('recoverMediaError');\n let media = this.media;\n this.detachMedia();\n if (media) {\n this.attachMedia(media);\n }\n }\n\n /**\n * Remove a loaded level from the list of levels, or a level url in from a list of redundant level urls.\n * This can be used to remove a rendition or playlist url that errors frequently from the list of levels that a user\n * or hls.js can choose from.\n *\n * @param levelIndex {number} The quality level index to of the level to remove\n * @param urlId {number} The quality level url index in the case that fallback levels are available. Defaults to 0.\n */\n removeLevel (levelIndex, urlId = 0) {\n this.levelController.removeLevel(levelIndex, urlId);\n }\n\n /**\n * @type {QualityLevel[]}\n */\n // todo(typescript-levelController)\n get levels (): any[] {\n return this.levelController.levels;\n }\n\n /**\n * Index of quality level currently played\n * @type {number}\n */\n get currentLevel (): number {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately .\n * This will flush the current buffer to replace the quality asap.\n * That means playback will interrupt at least shortly to re-buffer and re-sync eventually.\n * @param newLevel {number} -1 for automatic level selection\n */\n set currentLevel (newLevel: number) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n * @type {number}\n */\n get nextLevel (): number {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @type {number} -1 for automatic level selection\n */\n set nextLevel (newLevel: number) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n * @type {number}\n */\n get loadLevel (): number {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @type {number} newLevel -1 for automatic level selection\n */\n set loadLevel (newLevel: number) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n * @type {number}\n */\n get nextLoadLevel (): number {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n * @type {number} level\n */\n set nextLoadLevel (level: number) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n * @type {number}\n */\n get firstLevel (): number {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n * @type {number}\n */\n set firstLevel (newLevel: number) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /**\n * Return start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n * @type {number}\n */\n get startLevel (): number {\n return this.levelController.startLevel;\n }\n\n /**\n * set start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n * @type {number} newLevel\n */\n set startLevel (newLevel: number) {\n logger.log(`set startLevel:${newLevel}`);\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, this.minAutoLevel);\n }\n\n this.levelController.startLevel = newLevel;\n }\n\n /**\n * set dynamically set capLevelToPlayerSize against (`CapLevelController`)\n *\n * @type {boolean}\n */\n set capLevelToPlayerSize (shouldStartCapping: boolean) {\n const newCapLevelToPlayerSize = !!shouldStartCapping;\n\n if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {\n if (newCapLevelToPlayerSize) {\n this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.\n } else {\n this.capLevelController.stopCapping();\n this.autoLevelCapping = -1;\n this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.\n }\n\n this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;\n }\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n get autoLevelCapping (): number {\n return this._autoLevelCapping;\n }\n\n /**\n * get bandwidth estimate\n * @type {number}\n */\n get bandwidthEstimate (): number {\n const bwEstimator = this.abrController._bwEstimator;\n return bwEstimator ? bwEstimator.getEstimate() : NaN;\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n * @type {number}\n */\n set autoLevelCapping (newLevel: number) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n\n /**\n * True when automatic level selection enabled\n * @type {boolean}\n */\n get autoLevelEnabled (): boolean {\n return (this.levelController.manualLevel === -1);\n }\n\n /**\n * Level set manually (if any)\n * @type {number}\n */\n get manualLevel (): number {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n * @type {number}\n */\n get minAutoLevel (): number {\n const { levels, config: { minAutoBitrate } } = this;\n const len = levels ? levels.length : 0;\n\n for (let i = 0; i < len; i++) {\n const levelNextBitrate = levels[i].realBitrate\n ? Math.max(levels[i].realBitrate, levels[i].bitrate)\n : levels[i].bitrate;\n\n if (levelNextBitrate > minAutoBitrate) {\n return i;\n }\n }\n\n return 0;\n }\n\n /**\n * max level selectable in auto mode according to autoLevelCapping\n * @type {number}\n */\n get maxAutoLevel (): number {\n const { levels, autoLevelCapping } = this;\n\n let maxAutoLevel;\n if (autoLevelCapping === -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n * @type {number}\n */\n get nextAutoLevel (): number {\n // ensure next auto level is between min and max auto level\n return Math.min(Math.max(this.abrController.nextAutoLevel, this.minAutoLevel), this.maxAutoLevel);\n }\n\n /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n * forced value is valid for one fragment. upon succesful frag loading at forced level,\n * this value will be resetted to -1 by ABR controller.\n * @type {number}\n */\n set nextAutoLevel (nextLevel: number) {\n this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);\n }\n\n /**\n * @type {AudioTrack[]}\n */\n // todo(typescript-audioTrackController)\n get audioTracks (): any[] {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n * @type {number}\n */\n get audioTrack (): number {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n * @type {number}\n */\n set audioTrack (audioTrackId: number) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * @type {Seconds}\n */\n get liveSyncPosition (): number {\n return this.streamController.liveSyncPosition;\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n * @type {SubtitleTrack[]}\n */\n // todo(typescript-subtitleTrackController)\n get subtitleTracks (): any[] {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTracks : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n * @type {number}\n */\n get subtitleTrack (): number {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n * @type {number}\n */\n set subtitleTrack (subtitleTrackId: number) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * @type {boolean}\n */\n get subtitleDisplay (): boolean {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleDisplay : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n * @type {boolean}\n */\n set subtitleDisplay (value: boolean) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n}\n","import { getMediaSource } from './utils/mediasource-helper';\n\nexport function isSupported (): boolean {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n const sourceBuffer = self.SourceBuffer || (self as any).WebKitSourceBuffer as SourceBuffer;\n const isTypeSupported = mediaSource &&\n typeof mediaSource.isTypeSupported === 'function' &&\n mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\n\n // if SourceBuffer is exposed ensure its API is valid\n // safari and old version of Chrome doe not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBufferValidAPI = !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function');\n return !!isTypeSupported && !!sourceBufferValidAPI;\n}\n"],"sourceRoot":""} \ No newline at end of file +{"version":3,"file":"hls.js.min.map","sources":["node_modules/url-toolkit/src/url-toolkit.js","src/polyfills/number.ts","src/events.ts","src/errors.ts","src/utils/logger.ts","src/utils/attr-list.ts","src/loader/date-range.ts","src/loader/load-stats.ts","src/loader/fragment.ts","src/loader/level-details.ts","src/utils/numeric-encoding-utils.ts","src/utils/keysystem-util.ts","src/utils/mediakeys-helper.ts","src/utils/typed-array.ts","src/demux/id3.ts","src/utils/hex.ts","src/utils/mp4-tools.ts","src/loader/level-key.ts","src/utils/variable-substitution.ts","src/utils/mediasource-helper.ts","src/utils/codecs.ts","src/loader/m3u8-parser.ts","src/types/loader.ts","src/loader/playlist-loader.ts","src/utils/texttrack-utils.ts","src/types/demuxer.ts","src/controller/id3-track-controller.ts","src/controller/latency-controller.ts","src/types/level.ts","src/controller/level-helper.ts","src/utils/error-helper.ts","src/utils/binary-search.ts","src/controller/fragment-finders.ts","src/controller/error-controller.ts","src/controller/level-controller.ts","src/controller/base-playlist-controller.ts","src/controller/fragment-tracker.ts","src/loader/fragment-loader.ts","src/loader/key-loader.ts","src/task-loop.ts","src/utils/buffer-helper.ts","src/types/transmuxer.ts","src/utils/discontinuities.ts","src/crypt/aes-crypto.ts","src/crypt/fast-aes-key.ts","src/crypt/aes-decryptor.ts","src/crypt/decrypter.ts","src/utils/time-ranges.ts","src/controller/base-stream-controller.ts","src/is-supported.ts","src/demux/dummy-demuxed-track.ts","src/demux/base-audio-demuxer.ts","src/demux/adts.ts","src/demux/aacdemuxer.ts","src/demux/mp4demuxer.ts","src/demux/mpegaudio.ts","src/demux/exp-golomb.ts","src/demux/sample-aes.ts","src/demux/tsdemuxer.ts","src/demux/mp3demuxer.ts","src/remux/aac-helper.ts","src/remux/mp4-generator.ts","src/utils/timescale-conversion.ts","src/remux/mp4-remuxer.ts","src/demux/transmuxer.ts","src/remux/passthrough-remuxer.ts","node_modules/eventemitter3/index.js","src/demux/transmuxer-worker.ts","src/demux/transmuxer-interface.ts","src/demux/inject-worker.ts","src/controller/gap-controller.ts","src/controller/stream-controller.ts","src/utils/ewma.ts","src/utils/ewma-bandwidth-estimator.ts","src/controller/abr-controller.ts","src/demux/chunk-cache.ts","src/controller/audio-stream-controller.ts","src/controller/audio-track-controller.ts","src/utils/media-option-attributes.ts","src/controller/subtitle-stream-controller.ts","src/controller/subtitle-track-controller.ts","src/controller/buffer-operation-queue.ts","src/controller/buffer-controller.ts","src/utils/cea-608-parser.ts","src/utils/output-filter.ts","src/utils/vttcue.ts","src/utils/vttparser.ts","src/utils/webvtt-parser.ts","src/utils/imsc1-ttml-parser.ts","src/controller/timeline-controller.ts","src/controller/cap-level-controller.ts","src/controller/fps-controller.ts","src/controller/eme-controller.ts","src/types/cmcd.ts","src/controller/cmcd-controller.ts","src/controller/content-steering-controller.ts","src/utils/xhr-loader.ts","src/utils/fetch-loader.ts","src/utils/cues.ts","src/config.ts","src/hls.ts"],"sourcesContent":["// see https://tools.ietf.org/html/rfc1808\n\n(function (root) {\n var URL_REGEX =\n /^(?=((?:[a-zA-Z0-9+\\-.]+:)?))\\1(?=((?:\\/\\/[^\\/?#]*)?))\\2(?=((?:(?:[^?#\\/]*\\/)*[^;?#\\/]*)?))\\3((?:;[^?#]*)?)(\\?[^#]*)?(#[^]*)?$/;\n var FIRST_SEGMENT_REGEX = /^(?=([^\\/?#]*))\\1([^]*)$/;\n var SLASH_DOT_REGEX = /(?:\\/|^)\\.(?=\\/)/g;\n var SLASH_DOT_DOT_REGEX = /(?:\\/|^)\\.\\.\\/(?!\\.\\.\\/)[^\\/]*(?=\\/)/g;\n\n var URLToolkit = {\n // If opts.alwaysNormalize is true then the path will always be normalized even when it starts with / or //\n // E.g\n // With opts.alwaysNormalize = false (default, spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/f/../g\n // With opts.alwaysNormalize = true (not spec compliant)\n // http://a.com/b/cd + /e/f/../g => http://a.com/e/g\n buildAbsoluteURL: function (baseURL, relativeURL, opts) {\n opts = opts || {};\n // remove any remaining space and CRLF\n baseURL = baseURL.trim();\n relativeURL = relativeURL.trim();\n if (!relativeURL) {\n // 2a) If the embedded URL is entirely empty, it inherits the\n // entire base URL (i.e., is set equal to the base URL)\n // and we are done.\n if (!opts.alwaysNormalize) {\n return baseURL;\n }\n var basePartsForNormalise = URLToolkit.parseURL(baseURL);\n if (!basePartsForNormalise) {\n throw new Error('Error trying to parse base URL.');\n }\n basePartsForNormalise.path = URLToolkit.normalizePath(\n basePartsForNormalise.path\n );\n return URLToolkit.buildURLFromParts(basePartsForNormalise);\n }\n var relativeParts = URLToolkit.parseURL(relativeURL);\n if (!relativeParts) {\n throw new Error('Error trying to parse relative URL.');\n }\n if (relativeParts.scheme) {\n // 2b) If the embedded URL starts with a scheme name, it is\n // interpreted as an absolute URL and we are done.\n if (!opts.alwaysNormalize) {\n return relativeURL;\n }\n relativeParts.path = URLToolkit.normalizePath(relativeParts.path);\n return URLToolkit.buildURLFromParts(relativeParts);\n }\n var baseParts = URLToolkit.parseURL(baseURL);\n if (!baseParts) {\n throw new Error('Error trying to parse base URL.');\n }\n if (!baseParts.netLoc && baseParts.path && baseParts.path[0] !== '/') {\n // If netLoc missing and path doesn't start with '/', assume everthing before the first '/' is the netLoc\n // This causes 'example.com/a' to be handled as '//example.com/a' instead of '/example.com/a'\n var pathParts = FIRST_SEGMENT_REGEX.exec(baseParts.path);\n baseParts.netLoc = pathParts[1];\n baseParts.path = pathParts[2];\n }\n if (baseParts.netLoc && !baseParts.path) {\n baseParts.path = '/';\n }\n var builtParts = {\n // 2c) Otherwise, the embedded URL inherits the scheme of\n // the base URL.\n scheme: baseParts.scheme,\n netLoc: relativeParts.netLoc,\n path: null,\n params: relativeParts.params,\n query: relativeParts.query,\n fragment: relativeParts.fragment,\n };\n if (!relativeParts.netLoc) {\n // 3) If the embedded URL's <net_loc> is non-empty, we skip to\n // Step 7. Otherwise, the embedded URL inherits the <net_loc>\n // (if any) of the base URL.\n builtParts.netLoc = baseParts.netLoc;\n // 4) If the embedded URL path is preceded by a slash \"/\", the\n // path is not relative and we skip to Step 7.\n if (relativeParts.path[0] !== '/') {\n if (!relativeParts.path) {\n // 5) If the embedded URL path is empty (and not preceded by a\n // slash), then the embedded URL inherits the base URL path\n builtParts.path = baseParts.path;\n // 5a) if the embedded URL's <params> is non-empty, we skip to\n // step 7; otherwise, it inherits the <params> of the base\n // URL (if any) and\n if (!relativeParts.params) {\n builtParts.params = baseParts.params;\n // 5b) if the embedded URL's <query> is non-empty, we skip to\n // step 7; otherwise, it inherits the <query> of the base\n // URL (if any) and we skip to step 7.\n if (!relativeParts.query) {\n builtParts.query = baseParts.query;\n }\n }\n } else {\n // 6) The last segment of the base URL's path (anything\n // following the rightmost slash \"/\", or the entire path if no\n // slash is present) is removed and the embedded URL's path is\n // appended in its place.\n var baseURLPath = baseParts.path;\n var newPath =\n baseURLPath.substring(0, baseURLPath.lastIndexOf('/') + 1) +\n relativeParts.path;\n builtParts.path = URLToolkit.normalizePath(newPath);\n }\n }\n }\n if (builtParts.path === null) {\n builtParts.path = opts.alwaysNormalize\n ? URLToolkit.normalizePath(relativeParts.path)\n : relativeParts.path;\n }\n return URLToolkit.buildURLFromParts(builtParts);\n },\n parseURL: function (url) {\n var parts = URL_REGEX.exec(url);\n if (!parts) {\n return null;\n }\n return {\n scheme: parts[1] || '',\n netLoc: parts[2] || '',\n path: parts[3] || '',\n params: parts[4] || '',\n query: parts[5] || '',\n fragment: parts[6] || '',\n };\n },\n normalizePath: function (path) {\n // The following operations are\n // then applied, in order, to the new path:\n // 6a) All occurrences of \"./\", where \".\" is a complete path\n // segment, are removed.\n // 6b) If the path ends with \".\" as a complete path segment,\n // that \".\" is removed.\n path = path.split('').reverse().join('').replace(SLASH_DOT_REGEX, '');\n // 6c) All occurrences of \"<segment>/../\", where <segment> is a\n // complete path segment not equal to \"..\", are removed.\n // Removal of these path segments is performed iteratively,\n // removing the leftmost matching pattern on each iteration,\n // until no matching pattern remains.\n // 6d) If the path ends with \"<segment>/..\", where <segment> is a\n // complete path segment not equal to \"..\", that\n // \"<segment>/..\" is removed.\n while (\n path.length !== (path = path.replace(SLASH_DOT_DOT_REGEX, '')).length\n ) {}\n return path.split('').reverse().join('');\n },\n buildURLFromParts: function (parts) {\n return (\n parts.scheme +\n parts.netLoc +\n parts.path +\n parts.params +\n parts.query +\n parts.fragment\n );\n },\n };\n\n if (typeof exports === 'object' && typeof module === 'object')\n module.exports = URLToolkit;\n else if (typeof define === 'function' && define.amd)\n define([], function () {\n return URLToolkit;\n });\n else if (typeof exports === 'object') exports['URLToolkit'] = URLToolkit;\n else root['URLToolkit'] = URLToolkit;\n})(this);\n","// https://caniuse.com/mdn-javascript_builtins_number_isfinite\nexport const isFiniteNumber =\n Number.isFinite ||\n function (value) {\n return typeof value === 'number' && isFinite(value);\n };\n\n// https://caniuse.com/mdn-javascript_builtins_number_issafeinteger\nexport const isSafeInteger =\n Number.isSafeInteger ||\n function (value) {\n return typeof value === 'number' && Math.abs(value) <= MAX_SAFE_INTEGER;\n };\n\nexport const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991;\n","import {\n ManifestLoadedData,\n ManifestLoadingData,\n MediaAttachedData,\n MediaAttachingData,\n LevelLoadingData,\n LevelLoadedData,\n ManifestParsedData,\n LevelUpdatedData,\n LevelsUpdatedData,\n FragParsingUserdataData,\n FragDecryptedData,\n FragLoadedData,\n InitPTSFoundData,\n CuesParsedData,\n SubtitleFragProcessedData,\n NonNativeTextTracksData,\n FragLoadingData,\n AudioTrackLoadedData,\n SubtitleTrackLoadedData,\n ErrorData,\n AudioTrackSwitchingData,\n AudioTrackSwitchedData,\n KeyLoadedData,\n KeyLoadingData,\n SubtitleTrackSwitchData,\n SubtitleTracksUpdatedData,\n LevelSwitchedData,\n FragChangedData,\n BufferAppendingData,\n BufferCodecsData,\n FragParsingMetadataData,\n FragParsingInitSegmentData,\n FragBufferedData,\n BufferFlushingData,\n BufferEOSData,\n LevelSwitchingData,\n FPSDropLevelCappingData,\n FPSDropData,\n BufferCreatedData,\n BufferAppendedData,\n LevelPTSUpdatedData,\n FragParsedData,\n AudioTracksUpdatedData,\n FragLoadEmergencyAbortedData,\n BackBufferData,\n LiveBackBufferData,\n TrackLoadingData,\n BufferFlushedData,\n} from './types/events';\n\nexport enum Events {\n // Fired before MediaSource is attaching to media element\n MEDIA_ATTACHING = 'hlsMediaAttaching',\n // Fired when MediaSource has been successfully attached to media element\n MEDIA_ATTACHED = 'hlsMediaAttached',\n // Fired before detaching MediaSource from media element\n MEDIA_DETACHING = 'hlsMediaDetaching',\n // Fired when MediaSource has been detached from media element\n MEDIA_DETACHED = 'hlsMediaDetached',\n // Fired when the buffer is going to be reset\n BUFFER_RESET = 'hlsBufferReset',\n // Fired when we know about the codecs that we need buffers for to push into - data: {tracks : { container, codec, levelCodec, initSegment, metadata }}\n BUFFER_CODECS = 'hlsBufferCodecs',\n // fired when sourcebuffers have been created - data: { tracks : tracks }\n BUFFER_CREATED = 'hlsBufferCreated',\n // fired when we append a segment to the buffer - data: { segment: segment object }\n BUFFER_APPENDING = 'hlsBufferAppending',\n // 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}\n BUFFER_APPENDED = 'hlsBufferAppended',\n // fired when the stream is finished and we want to notify the media buffer that there will be no more data - data: { }\n BUFFER_EOS = 'hlsBufferEos',\n // fired when the media buffer should be flushed - data { startOffset, endOffset }\n BUFFER_FLUSHING = 'hlsBufferFlushing',\n // fired when the media buffer has been flushed - data: { }\n BUFFER_FLUSHED = 'hlsBufferFlushed',\n // fired to signal that a manifest loading starts - data: { url : manifestURL}\n MANIFEST_LOADING = 'hlsManifestLoading',\n // fired after manifest has been loaded - data: { levels : [available quality levels], audioTracks : [ available audio tracks ], url : manifestURL, stats : LoaderStats }\n MANIFEST_LOADED = 'hlsManifestLoaded',\n // fired after manifest has been parsed - data: { levels : [available quality levels], firstLevel : index of first quality level appearing in Manifest}\n MANIFEST_PARSED = 'hlsManifestParsed',\n // fired when a level switch is requested - data: { level : id of new level }\n LEVEL_SWITCHING = 'hlsLevelSwitching',\n // fired when a level switch is effective - data: { level : id of new level }\n LEVEL_SWITCHED = 'hlsLevelSwitched',\n // fired when a level playlist loading starts - data: { url : level URL, level : id of level being loaded}\n LEVEL_LOADING = 'hlsLevelLoading',\n // fired when a level playlist loading finishes - data: { details : levelDetails object, level : id of loaded level, stats : LoaderStats }\n LEVEL_LOADED = 'hlsLevelLoaded',\n // 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 }\n LEVEL_UPDATED = 'hlsLevelUpdated',\n // 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 }\n LEVEL_PTS_UPDATED = 'hlsLevelPtsUpdated',\n // fired to notify that levels have changed after removing a level - data: { levels : [available quality levels] }\n LEVELS_UPDATED = 'hlsLevelsUpdated',\n // fired to notify that audio track lists has been updated - data: { audioTracks : audioTracks }\n AUDIO_TRACKS_UPDATED = 'hlsAudioTracksUpdated',\n // fired when an audio track switching is requested - data: { id : audio track id }\n AUDIO_TRACK_SWITCHING = 'hlsAudioTrackSwitching',\n // fired when an audio track switch actually occurs - data: { id : audio track id }\n AUDIO_TRACK_SWITCHED = 'hlsAudioTrackSwitched',\n // fired when an audio track loading starts - data: { url : audio track URL, id : audio track id }\n AUDIO_TRACK_LOADING = 'hlsAudioTrackLoading',\n // fired when an audio track loading finishes - data: { details : levelDetails object, id : audio track id, stats : LoaderStats }\n AUDIO_TRACK_LOADED = 'hlsAudioTrackLoaded',\n // fired to notify that subtitle track lists has been updated - data: { subtitleTracks : subtitleTracks }\n SUBTITLE_TRACKS_UPDATED = 'hlsSubtitleTracksUpdated',\n // fired to notify that subtitle tracks were cleared as a result of stopping the media\n SUBTITLE_TRACKS_CLEARED = 'hlsSubtitleTracksCleared',\n // fired when an subtitle track switch occurs - data: { id : subtitle track id }\n SUBTITLE_TRACK_SWITCH = 'hlsSubtitleTrackSwitch',\n // fired when a subtitle track loading starts - data: { url : subtitle track URL, id : subtitle track id }\n SUBTITLE_TRACK_LOADING = 'hlsSubtitleTrackLoading',\n // fired when a subtitle track loading finishes - data: { details : levelDetails object, id : subtitle track id, stats : LoaderStats }\n SUBTITLE_TRACK_LOADED = 'hlsSubtitleTrackLoaded',\n // fired when a subtitle fragment has been processed - data: { success : boolean, frag : the processed frag }\n SUBTITLE_FRAG_PROCESSED = 'hlsSubtitleFragProcessed',\n // fired when a set of VTTCues to be managed externally has been parsed - data: { type: string, track: string, cues: [ VTTCue ] }\n CUES_PARSED = 'hlsCuesParsed',\n // fired when a text track to be managed externally is found - data: { tracks: [ { label: string, kind: string, default: boolean } ] }\n NON_NATIVE_TEXT_TRACKS_FOUND = 'hlsNonNativeTextTracksFound',\n // fired when the first timestamp is found - data: { id : demuxer id, initPTS: initPTS, timescale: timescale, frag : fragment object }\n INIT_PTS_FOUND = 'hlsInitPtsFound',\n // fired when a fragment loading starts - data: { frag : fragment object }\n FRAG_LOADING = 'hlsFragLoading',\n // fired when a fragment loading is progressing - data: { frag : fragment object, { trequest, tfirst, loaded } }\n // FRAG_LOAD_PROGRESS = 'hlsFragLoadProgress',\n // Identifier for fragment load aborting for emergency switch down - data: { frag : fragment object }\n FRAG_LOAD_EMERGENCY_ABORTED = 'hlsFragLoadEmergencyAborted',\n // fired when a fragment loading is completed - data: { frag : fragment object, payload : fragment payload, stats : LoaderStats }\n FRAG_LOADED = 'hlsFragLoaded',\n // fired when a fragment has finished decrypting - data: { id : demuxer id, frag: fragment object, payload : fragment payload, stats : { tstart, tdecrypt } }\n FRAG_DECRYPTED = 'hlsFragDecrypted',\n // 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 }\n FRAG_PARSING_INIT_SEGMENT = 'hlsFragParsingInitSegment',\n // fired when parsing sei text is completed - data: { id : demuxer id, frag: fragment object, samples : [ sei samples pes ] }\n FRAG_PARSING_USERDATA = 'hlsFragParsingUserdata',\n // fired when parsing id3 is completed - data: { id : demuxer id, frag: fragment object, samples : [ id3 samples pes ] }\n FRAG_PARSING_METADATA = 'hlsFragParsingMetadata',\n // 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}\n // FRAG_PARSING_DATA = 'hlsFragParsingData',\n // fired when fragment parsing is completed - data: { id : demuxer id, frag: fragment object }\n FRAG_PARSED = 'hlsFragParsed',\n // fired when fragment remuxed MP4 boxes have all been appended into SourceBuffer - data: { id : demuxer id, frag : fragment object, stats : LoaderStats }\n FRAG_BUFFERED = 'hlsFragBuffered',\n // fired when fragment matching with current media position is changing - data : { id : demuxer id, frag : fragment object }\n FRAG_CHANGED = 'hlsFragChanged',\n // Identifier for a FPS drop event - data: { currentDropped, currentDecoded, totalDroppedFrames }\n FPS_DROP = 'hlsFpsDrop',\n // triggered when FPS drop triggers auto level capping - data: { level, droppedLevel }\n FPS_DROP_LEVEL_CAPPING = 'hlsFpsDropLevelCapping',\n // 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 }\n ERROR = 'hlsError',\n // 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: { }\n DESTROYING = 'hlsDestroying',\n // fired when a decrypt key loading starts - data: { frag : fragment object }\n KEY_LOADING = 'hlsKeyLoading',\n // fired when a decrypt key loading is completed - data: { frag : fragment object, keyInfo : KeyLoaderInfo }\n KEY_LOADED = 'hlsKeyLoaded',\n // deprecated; please use BACK_BUFFER_REACHED - data : { bufferEnd: number }\n LIVE_BACK_BUFFER_REACHED = 'hlsLiveBackBufferReached',\n // fired when the back buffer is reached as defined by the backBufferLength config option - data : { bufferEnd: number }\n BACK_BUFFER_REACHED = 'hlsBackBufferReached',\n}\n\n/**\n * Defines each Event type and payload by Event name. Used in {@link hls.js#HlsEventEmitter} to strongly type the event listener API.\n */\nexport interface HlsListeners {\n [Events.MEDIA_ATTACHING]: (\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) => void;\n [Events.MEDIA_ATTACHED]: (\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) => void;\n [Events.MEDIA_DETACHING]: (event: Events.MEDIA_DETACHING) => void;\n [Events.MEDIA_DETACHED]: (event: Events.MEDIA_DETACHED) => void;\n [Events.BUFFER_RESET]: (event: Events.BUFFER_RESET) => void;\n [Events.BUFFER_CODECS]: (\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData\n ) => void;\n [Events.BUFFER_CREATED]: (\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData\n ) => void;\n [Events.BUFFER_APPENDING]: (\n event: Events.BUFFER_APPENDING,\n data: BufferAppendingData\n ) => void;\n [Events.BUFFER_APPENDED]: (\n event: Events.BUFFER_APPENDED,\n data: BufferAppendedData\n ) => void;\n [Events.BUFFER_EOS]: (event: Events.BUFFER_EOS, data: BufferEOSData) => void;\n [Events.BUFFER_FLUSHING]: (\n event: Events.BUFFER_FLUSHING,\n data: BufferFlushingData\n ) => void;\n [Events.BUFFER_FLUSHED]: (\n event: Events.BUFFER_FLUSHED,\n data: BufferFlushedData\n ) => void;\n [Events.MANIFEST_LOADING]: (\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData\n ) => void;\n [Events.MANIFEST_LOADED]: (\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ) => void;\n [Events.MANIFEST_PARSED]: (\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) => void;\n [Events.LEVEL_SWITCHING]: (\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ) => void;\n [Events.LEVEL_SWITCHED]: (\n event: Events.LEVEL_SWITCHED,\n data: LevelSwitchedData\n ) => void;\n [Events.LEVEL_LOADING]: (\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData\n ) => void;\n [Events.LEVEL_LOADED]: (\n event: Events.LEVEL_LOADED,\n data: LevelLoadedData\n ) => void;\n [Events.LEVEL_UPDATED]: (\n event: Events.LEVEL_UPDATED,\n data: LevelUpdatedData\n ) => void;\n [Events.LEVEL_PTS_UPDATED]: (\n event: Events.LEVEL_PTS_UPDATED,\n data: LevelPTSUpdatedData\n ) => void;\n [Events.LEVELS_UPDATED]: (\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData\n ) => void;\n [Events.AUDIO_TRACKS_UPDATED]: (\n event: Events.AUDIO_TRACKS_UPDATED,\n data: AudioTracksUpdatedData\n ) => void;\n [Events.AUDIO_TRACK_SWITCHING]: (\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData\n ) => void;\n [Events.AUDIO_TRACK_SWITCHED]: (\n event: Events.AUDIO_TRACK_SWITCHED,\n data: AudioTrackSwitchedData\n ) => void;\n [Events.AUDIO_TRACK_LOADING]: (\n event: Events.AUDIO_TRACK_LOADING,\n data: TrackLoadingData\n ) => void;\n [Events.AUDIO_TRACK_LOADED]: (\n event: Events.AUDIO_TRACK_LOADED,\n data: AudioTrackLoadedData\n ) => void;\n [Events.SUBTITLE_TRACKS_UPDATED]: (\n event: Events.SUBTITLE_TRACKS_UPDATED,\n data: SubtitleTracksUpdatedData\n ) => void;\n [Events.SUBTITLE_TRACKS_CLEARED]: (\n event: Events.SUBTITLE_TRACKS_CLEARED\n ) => void;\n [Events.SUBTITLE_TRACK_SWITCH]: (\n event: Events.SUBTITLE_TRACK_SWITCH,\n data: SubtitleTrackSwitchData\n ) => void;\n [Events.SUBTITLE_TRACK_LOADING]: (\n event: Events.SUBTITLE_TRACK_LOADING,\n data: TrackLoadingData\n ) => void;\n [Events.SUBTITLE_TRACK_LOADED]: (\n event: Events.SUBTITLE_TRACK_LOADED,\n data: SubtitleTrackLoadedData\n ) => void;\n [Events.SUBTITLE_FRAG_PROCESSED]: (\n event: Events.SUBTITLE_FRAG_PROCESSED,\n data: SubtitleFragProcessedData\n ) => void;\n [Events.CUES_PARSED]: (\n event: Events.CUES_PARSED,\n data: CuesParsedData\n ) => void;\n [Events.NON_NATIVE_TEXT_TRACKS_FOUND]: (\n event: Events.NON_NATIVE_TEXT_TRACKS_FOUND,\n data: NonNativeTextTracksData\n ) => void;\n [Events.INIT_PTS_FOUND]: (\n event: Events.INIT_PTS_FOUND,\n data: InitPTSFoundData\n ) => void;\n [Events.FRAG_LOADING]: (\n event: Events.FRAG_LOADING,\n data: FragLoadingData\n ) => void;\n // [Events.FRAG_LOAD_PROGRESS]: TodoEventType\n [Events.FRAG_LOAD_EMERGENCY_ABORTED]: (\n event: Events.FRAG_LOAD_EMERGENCY_ABORTED,\n data: FragLoadEmergencyAbortedData\n ) => void;\n [Events.FRAG_LOADED]: (\n event: Events.FRAG_LOADED,\n data: FragLoadedData\n ) => void;\n [Events.FRAG_DECRYPTED]: (\n event: Events.FRAG_DECRYPTED,\n data: FragDecryptedData\n ) => void;\n [Events.FRAG_PARSING_INIT_SEGMENT]: (\n event: Events.FRAG_PARSING_INIT_SEGMENT,\n data: FragParsingInitSegmentData\n ) => void;\n [Events.FRAG_PARSING_USERDATA]: (\n event: Events.FRAG_PARSING_USERDATA,\n data: FragParsingUserdataData\n ) => void;\n [Events.FRAG_PARSING_METADATA]: (\n event: Events.FRAG_PARSING_METADATA,\n data: FragParsingMetadataData\n ) => void;\n // [Events.FRAG_PARSING_DATA]: TodoEventType\n [Events.FRAG_PARSED]: (\n event: Events.FRAG_PARSED,\n data: FragParsedData\n ) => void;\n [Events.FRAG_BUFFERED]: (\n event: Events.FRAG_BUFFERED,\n data: FragBufferedData\n ) => void;\n [Events.FRAG_CHANGED]: (\n event: Events.FRAG_CHANGED,\n data: FragChangedData\n ) => void;\n [Events.FPS_DROP]: (event: Events.FPS_DROP, data: FPSDropData) => void;\n [Events.FPS_DROP_LEVEL_CAPPING]: (\n event: Events.FPS_DROP_LEVEL_CAPPING,\n data: FPSDropLevelCappingData\n ) => void;\n [Events.ERROR]: (event: Events.ERROR, data: ErrorData) => void;\n [Events.DESTROYING]: (event: Events.DESTROYING) => void;\n [Events.KEY_LOADING]: (\n event: Events.KEY_LOADING,\n data: KeyLoadingData\n ) => void;\n [Events.KEY_LOADED]: (event: Events.KEY_LOADED, data: KeyLoadedData) => void;\n [Events.LIVE_BACK_BUFFER_REACHED]: (\n event: Events.LIVE_BACK_BUFFER_REACHED,\n data: LiveBackBufferData\n ) => void;\n [Events.BACK_BUFFER_REACHED]: (\n event: Events.BACK_BUFFER_REACHED,\n data: BackBufferData\n ) => void;\n}\nexport interface HlsEventEmitter {\n on<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context?: Context\n ): void;\n once<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context?: Context\n ): void;\n\n removeAllListeners<E extends keyof HlsListeners>(event?: E): void;\n off<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener?: HlsListeners[E],\n context?: Context,\n once?: boolean\n ): void;\n\n listeners<E extends keyof HlsListeners>(event: E): HlsListeners[E][];\n emit<E extends keyof HlsListeners>(\n event: E,\n name: E,\n eventObject: Parameters<HlsListeners[E]>[1]\n ): boolean;\n listenerCount<E extends keyof HlsListeners>(event: E): number;\n}\n","export enum ErrorTypes {\n // Identifier for a network error (loading error / timeout ...)\n NETWORK_ERROR = 'networkError',\n // Identifier for a media Error (video/parsing/mediasource error)\n MEDIA_ERROR = 'mediaError',\n // EME (encrypted media extensions) errors\n KEY_SYSTEM_ERROR = 'keySystemError',\n // Identifier for a mux Error (demuxing/remuxing)\n MUX_ERROR = 'muxError',\n // Identifier for all other errors\n OTHER_ERROR = 'otherError',\n}\n\nexport enum ErrorDetails {\n KEY_SYSTEM_NO_KEYS = 'keySystemNoKeys',\n KEY_SYSTEM_NO_ACCESS = 'keySystemNoAccess',\n KEY_SYSTEM_NO_SESSION = 'keySystemNoSession',\n KEY_SYSTEM_NO_CONFIGURED_LICENSE = 'keySystemNoConfiguredLicense',\n KEY_SYSTEM_LICENSE_REQUEST_FAILED = 'keySystemLicenseRequestFailed',\n KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED = 'keySystemServerCertificateRequestFailed',\n KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED = 'keySystemServerCertificateUpdateFailed',\n KEY_SYSTEM_SESSION_UPDATE_FAILED = 'keySystemSessionUpdateFailed',\n KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED = 'keySystemStatusOutputRestricted',\n KEY_SYSTEM_STATUS_INTERNAL_ERROR = 'keySystemStatusInternalError',\n // Identifier for a manifest load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_ERROR = 'manifestLoadError',\n // Identifier for a manifest load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n MANIFEST_LOAD_TIMEOUT = 'manifestLoadTimeOut',\n // Identifier for a manifest parsing error - data: { url : faulty URL, reason : error reason}\n MANIFEST_PARSING_ERROR = 'manifestParsingError',\n // Identifier for a manifest with only incompatible codecs error - data: { url : faulty URL, reason : error reason}\n MANIFEST_INCOMPATIBLE_CODECS_ERROR = 'manifestIncompatibleCodecsError',\n // Identifier for a level which contains no fragments - data: { url: faulty URL, reason: \"no fragments found in level\", level: index of the bad level }\n LEVEL_EMPTY_ERROR = 'levelEmptyError',\n // Identifier for a level load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_ERROR = 'levelLoadError',\n // Identifier for a level load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n LEVEL_LOAD_TIMEOUT = 'levelLoadTimeOut',\n // Identifier for a level parse error - data: { url : faulty URL, error: Error, reason: error message }\n LEVEL_PARSING_ERROR = 'levelParsingError',\n // Identifier for a level switch error - data: { level : faulty level Id, event : error description}\n LEVEL_SWITCH_ERROR = 'levelSwitchError',\n // Identifier for an audio track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_ERROR = 'audioTrackLoadError',\n // Identifier for an audio track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n AUDIO_TRACK_LOAD_TIMEOUT = 'audioTrackLoadTimeOut',\n // Identifier for a subtitle track load error - data: { url : faulty URL, response : { code: error code, text: error text }}\n SUBTITLE_LOAD_ERROR = 'subtitleTrackLoadError',\n // Identifier for a subtitle track load timeout - data: { url : faulty URL, response : { code: error code, text: error text }}\n SUBTITLE_TRACK_LOAD_TIMEOUT = 'subtitleTrackLoadTimeOut',\n // Identifier for fragment load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n FRAG_LOAD_ERROR = 'fragLoadError',\n // Identifier for fragment load timeout error - data: { frag : fragment object}\n FRAG_LOAD_TIMEOUT = 'fragLoadTimeOut',\n // Identifier for a fragment decryption error event - data: {id : demuxer Id,frag: fragment object, reason : parsing error description }\n FRAG_DECRYPT_ERROR = 'fragDecryptError',\n // Identifier for a fragment parsing error event - data: { id : demuxer Id, reason : parsing error description }\n // will be renamed DEMUX_PARSING_ERROR and switched to MUX_ERROR in the next major release\n FRAG_PARSING_ERROR = 'fragParsingError',\n // Identifier for a fragment or part load skipped because of a GAP tag or attribute\n FRAG_GAP = 'fragGap',\n // 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 }\n REMUX_ALLOC_ERROR = 'remuxAllocError',\n // Identifier for decrypt key load error - data: { frag : fragment object, response : { code: error code, text: error text }}\n KEY_LOAD_ERROR = 'keyLoadError',\n // Identifier for decrypt key load timeout error - data: { frag : fragment object}\n KEY_LOAD_TIMEOUT = 'keyLoadTimeOut',\n // Triggered when an exception occurs while adding a sourceBuffer to MediaSource - data : { error : exception , mimeType : mimeType }\n BUFFER_ADD_CODEC_ERROR = 'bufferAddCodecError',\n // Triggered when source buffer(s) could not be created using level (manifest CODECS attribute), parsed media, or best guess codec(s) - data: { reason : error reason }\n BUFFER_INCOMPATIBLE_CODECS_ERROR = 'bufferIncompatibleCodecsError',\n // Identifier for a buffer append error - data: append error description\n BUFFER_APPEND_ERROR = 'bufferAppendError',\n // Identifier for a buffer appending error event - data: appending error description\n BUFFER_APPENDING_ERROR = 'bufferAppendingError',\n // Identifier for a buffer stalled error event\n BUFFER_STALLED_ERROR = 'bufferStalledError',\n // Identifier for a buffer full event\n BUFFER_FULL_ERROR = 'bufferFullError',\n // Identifier for a buffer seek over hole event\n BUFFER_SEEK_OVER_HOLE = 'bufferSeekOverHole',\n // Identifier for a buffer nudge on stall (playback is stuck although currentTime is in a buffered area)\n BUFFER_NUDGE_ON_STALL = 'bufferNudgeOnStall',\n // Identifier for an internal exception happening inside hls.js while handling an event\n INTERNAL_EXCEPTION = 'internalException',\n // Identifier for an internal call to abort a loader\n INTERNAL_ABORTED = 'aborted',\n // Uncategorized error\n UNKNOWN = 'unknown',\n}\n","export interface ILogFunction {\n (message?: any, ...optionalParams: any[]): void;\n}\n\nexport interface ILogger {\n trace: ILogFunction;\n debug: ILogFunction;\n log: ILogFunction;\n warn: ILogFunction;\n info: ILogFunction;\n error: ILogFunction;\n}\n\nconst noop: ILogFunction = function () {};\n\nconst fakeLogger: ILogger = {\n trace: noop,\n debug: noop,\n log: noop,\n warn: noop,\n info: noop,\n error: noop,\n};\n\nlet exportedLogger: ILogger = fakeLogger;\n\n// let lastCallTime;\n// function formatMsgWithTimeInfo(type, msg) {\n// const now = Date.now();\n// const diff = lastCallTime ? '+' + (now - lastCallTime) : '0';\n// lastCallTime = now;\n// msg = (new Date(now)).toISOString() + ' | [' + type + '] > ' + msg + ' ( ' + diff + ' ms )';\n// return msg;\n// }\n\nfunction consolePrintFn(type: string): ILogFunction {\n const func: ILogFunction = self.console[type];\n if (func) {\n return func.bind(self.console, `[${type}] >`);\n }\n return noop;\n}\n\nfunction exportLoggerFunctions(\n debugConfig: boolean | ILogger,\n ...functions: string[]\n): void {\n functions.forEach(function (type) {\n exportedLogger[type] = debugConfig[type]\n ? debugConfig[type].bind(debugConfig)\n : consolePrintFn(type);\n });\n}\n\nexport function enableLogs(debugConfig: boolean | ILogger, id: string): void {\n // check that console is available\n if (\n (self.console && debugConfig === true) ||\n typeof debugConfig === 'object'\n ) {\n exportLoggerFunctions(\n debugConfig,\n // Remove out from list here to hard-disable a log-level\n // 'trace',\n 'debug',\n 'log',\n 'info',\n 'warn',\n 'error'\n );\n // Some browsers don't allow to use bind on console object anyway\n // fallback to default if needed\n try {\n exportedLogger.log(\n `Debug logs enabled for \"${id}\" in hls.js version ${__VERSION__}`\n );\n } catch (e) {\n exportedLogger = fakeLogger;\n }\n } else {\n exportedLogger = fakeLogger;\n }\n}\n\nexport const logger: ILogger = exportedLogger;\n","const DECIMAL_RESOLUTION_REGEX = /^(\\d+)x(\\d+)$/;\nconst ATTR_LIST_REGEX = /(.+?)=(\".*?\"|.*?)(?:,|$)/g;\n\n// adapted from https://github.com/kanongil/node-m3u8parse/blob/master/attrlist.js\nexport class AttrList {\n [key: string]: any;\n\n constructor(attrs: string | Record<string, any>) {\n if (typeof attrs === 'string') {\n attrs = AttrList.parseAttrList(attrs);\n }\n\n for (const attr in attrs) {\n if (attrs.hasOwnProperty(attr)) {\n if (attr.substring(0, 2) === 'X-') {\n this.clientAttrs = this.clientAttrs || [];\n this.clientAttrs.push(attr);\n }\n this[attr] = attrs[attr];\n }\n }\n }\n\n decimalInteger(attrName: string): number {\n const intValue = parseInt(this[attrName], 10);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n hexadecimalInteger(attrName: string) {\n if (this[attrName]) {\n let stringValue = (this[attrName] || '0x').slice(2);\n stringValue = (stringValue.length & 1 ? '0' : '') + stringValue;\n\n const value = new Uint8Array(stringValue.length / 2);\n for (let i = 0; i < stringValue.length / 2; i++) {\n value[i] = parseInt(stringValue.slice(i * 2, i * 2 + 2), 16);\n }\n\n return value;\n } else {\n return null;\n }\n }\n\n hexadecimalIntegerAsNumber(attrName: string): number {\n const intValue = parseInt(this[attrName], 16);\n if (intValue > Number.MAX_SAFE_INTEGER) {\n return Infinity;\n }\n\n return intValue;\n }\n\n decimalFloatingPoint(attrName: string): number {\n return parseFloat(this[attrName]);\n }\n\n optionalFloat(attrName: string, defaultValue: number): number {\n const value = this[attrName];\n return value ? parseFloat(value) : defaultValue;\n }\n\n enumeratedString(attrName: string): string | undefined {\n return this[attrName];\n }\n\n bool(attrName: string): boolean {\n return this[attrName] === 'YES';\n }\n\n decimalResolution(attrName: string):\n | {\n width: number;\n height: number;\n }\n | undefined {\n const res = DECIMAL_RESOLUTION_REGEX.exec(this[attrName]);\n if (res === null) {\n return undefined;\n }\n\n return {\n width: parseInt(res[1], 10),\n height: parseInt(res[2], 10),\n };\n }\n\n static parseAttrList(input: string): Record<string, any> {\n let match;\n const attrs = {};\n const quote = '\"';\n ATTR_LIST_REGEX.lastIndex = 0;\n while ((match = ATTR_LIST_REGEX.exec(input)) !== null) {\n let value = match[2];\n\n if (\n value.indexOf(quote) === 0 &&\n value.lastIndexOf(quote) === value.length - 1\n ) {\n value = value.slice(1, -1);\n }\n const name = match[1].trim();\n attrs[name] = value;\n }\n return attrs;\n }\n}\n","import { AttrList } from '../utils/attr-list';\nimport { logger } from '../utils/logger';\n\n// Avoid exporting const enum so that these values can be inlined\nconst enum DateRangeAttribute {\n ID = 'ID',\n CLASS = 'CLASS',\n START_DATE = 'START-DATE',\n DURATION = 'DURATION',\n END_DATE = 'END-DATE',\n END_ON_NEXT = 'END-ON-NEXT',\n PLANNED_DURATION = 'PLANNED-DURATION',\n SCTE35_OUT = 'SCTE35-OUT',\n SCTE35_IN = 'SCTE35-IN',\n}\n\nexport function isDateRangeCueAttribute(attrName: string): boolean {\n return (\n attrName !== DateRangeAttribute.ID &&\n attrName !== DateRangeAttribute.CLASS &&\n attrName !== DateRangeAttribute.START_DATE &&\n attrName !== DateRangeAttribute.DURATION &&\n attrName !== DateRangeAttribute.END_DATE &&\n attrName !== DateRangeAttribute.END_ON_NEXT\n );\n}\n\nexport function isSCTE35Attribute(attrName: string): boolean {\n return (\n attrName === DateRangeAttribute.SCTE35_OUT ||\n attrName === DateRangeAttribute.SCTE35_IN\n );\n}\n\nexport class DateRange {\n public attr: AttrList;\n private _startDate: Date;\n private _endDate?: Date;\n private _badValueForSameId?: string;\n\n constructor(dateRangeAttr: AttrList, dateRangeWithSameId?: DateRange) {\n if (dateRangeWithSameId) {\n const previousAttr = dateRangeWithSameId.attr;\n for (const key in previousAttr) {\n if (\n Object.prototype.hasOwnProperty.call(dateRangeAttr, key) &&\n dateRangeAttr[key] !== previousAttr[key]\n ) {\n logger.warn(\n `DATERANGE tag attribute: \"${key}\" does not match for tags with ID: \"${dateRangeAttr.ID}\"`\n );\n this._badValueForSameId = key;\n break;\n }\n }\n // Merge DateRange tags with the same ID\n dateRangeAttr = Object.assign(\n new AttrList({}),\n previousAttr,\n dateRangeAttr\n );\n }\n this.attr = dateRangeAttr;\n this._startDate = new Date(dateRangeAttr[DateRangeAttribute.START_DATE]);\n if (DateRangeAttribute.END_DATE in this.attr) {\n const endDate = new Date(this.attr[DateRangeAttribute.END_DATE]);\n if (Number.isFinite(endDate.getTime())) {\n this._endDate = endDate;\n }\n }\n }\n\n get id(): string {\n return this.attr.ID;\n }\n\n get class(): string {\n return this.attr.CLASS;\n }\n\n get startDate(): Date {\n return this._startDate;\n }\n\n get endDate(): Date | null {\n if (this._endDate) {\n return this._endDate;\n }\n const duration = this.duration;\n if (duration !== null) {\n return new Date(this._startDate.getTime() + duration * 1000);\n }\n return null;\n }\n\n get duration(): number | null {\n if (DateRangeAttribute.DURATION in this.attr) {\n const duration = this.attr.decimalFloatingPoint(\n DateRangeAttribute.DURATION\n );\n if (Number.isFinite(duration)) {\n return duration;\n }\n } else if (this._endDate) {\n return (this._endDate.getTime() - this._startDate.getTime()) / 1000;\n }\n return null;\n }\n\n get plannedDuration(): number | null {\n if (DateRangeAttribute.PLANNED_DURATION in this.attr) {\n return this.attr.decimalFloatingPoint(\n DateRangeAttribute.PLANNED_DURATION\n );\n }\n return null;\n }\n\n get endOnNext(): boolean {\n return this.attr.bool(DateRangeAttribute.END_ON_NEXT);\n }\n\n get isValid(): boolean {\n return (\n !!this.id &&\n !this._badValueForSameId &&\n Number.isFinite(this.startDate.getTime()) &&\n (this.duration === null || this.duration >= 0) &&\n (!this.endOnNext || !!this.class)\n );\n }\n}\n","import type {\n HlsPerformanceTiming,\n HlsProgressivePerformanceTiming,\n LoaderStats,\n} from '../types/loader';\n\nexport class LoadStats implements LoaderStats {\n aborted: boolean = false;\n loaded: number = 0;\n retry: number = 0;\n total: number = 0;\n chunkCount: number = 0;\n bwEstimate: number = 0;\n loading: HlsProgressivePerformanceTiming = { start: 0, first: 0, end: 0 };\n parsing: HlsPerformanceTiming = { start: 0, end: 0 };\n buffering: HlsProgressivePerformanceTiming = { start: 0, first: 0, end: 0 };\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport { LevelKey } from './level-key';\nimport { LoadStats } from './load-stats';\nimport { AttrList } from '../utils/attr-list';\nimport type {\n FragmentLoaderContext,\n KeyLoaderContext,\n Loader,\n PlaylistLevelType,\n} from '../types/loader';\nimport type { KeySystemFormats } from '../utils/mediakeys-helper';\n\nexport const enum ElementaryStreamTypes {\n AUDIO = 'audio',\n VIDEO = 'video',\n AUDIOVIDEO = 'audiovideo',\n}\n\nexport interface ElementaryStreamInfo {\n startPTS: number;\n endPTS: number;\n startDTS: number;\n endDTS: number;\n partial?: boolean;\n}\n\nexport type ElementaryStreams = Record<\n ElementaryStreamTypes,\n ElementaryStreamInfo | null\n>;\n\nexport class BaseSegment {\n private _byteRange: number[] | null = null;\n private _url: string | null = null;\n\n // baseurl is the URL to the playlist\n public readonly baseurl: string;\n // relurl is the portion of the URL that comes from inside the playlist.\n public relurl?: string;\n // Holds the types of data this fragment supports\n public elementaryStreams: ElementaryStreams = {\n [ElementaryStreamTypes.AUDIO]: null,\n [ElementaryStreamTypes.VIDEO]: null,\n [ElementaryStreamTypes.AUDIOVIDEO]: null,\n };\n\n constructor(baseurl: string) {\n this.baseurl = baseurl;\n }\n\n // setByteRange converts a EXT-X-BYTERANGE attribute into a two element array\n setByteRange(value: string, previous?: BaseSegment) {\n const params = value.split('@', 2);\n const byteRange: number[] = [];\n if (params.length === 1) {\n byteRange[0] = previous ? previous.byteRangeEndOffset : 0;\n } else {\n byteRange[0] = parseInt(params[1]);\n }\n byteRange[1] = parseInt(params[0]) + byteRange[0];\n this._byteRange = byteRange;\n }\n\n get byteRange(): number[] {\n if (!this._byteRange) {\n return [];\n }\n\n return this._byteRange;\n }\n\n get byteRangeStartOffset(): number {\n return this.byteRange[0];\n }\n\n get byteRangeEndOffset(): number {\n return this.byteRange[1];\n }\n\n get url(): string {\n if (!this._url && this.baseurl && this.relurl) {\n this._url = buildAbsoluteURL(this.baseurl, this.relurl, {\n alwaysNormalize: true,\n });\n }\n return this._url || '';\n }\n\n set url(value: string) {\n this._url = value;\n }\n}\n\n/**\n * Object representing parsed data from an HLS Segment. Found in {@link hls.js#LevelDetails.fragments}.\n */\nexport class Fragment extends BaseSegment {\n private _decryptdata: LevelKey | null = null;\n\n public rawProgramDateTime: string | null = null;\n public programDateTime: number | null = null;\n public tagList: Array<string[]> = [];\n\n // EXTINF has to be present for a m3u8 to be considered valid\n public duration: number = 0;\n // sn notates the sequence number for a segment, and if set to a string can be 'initSegment'\n public sn: number | 'initSegment' = 0;\n // levelkeys are the EXT-X-KEY tags that apply to this segment for decryption\n // core difference from the private field _decryptdata is the lack of the initialized IV\n // _decryptdata will set the IV for this segment based on the segment number in the fragment\n public levelkeys?: { [key: string]: LevelKey };\n // A string representing the fragment type\n public readonly type: PlaylistLevelType;\n // A reference to the loader. Set while the fragment is loading, and removed afterwards. Used to abort fragment loading\n public loader: Loader<FragmentLoaderContext> | null = null;\n // A reference to the key loader. Set while the key is loading, and removed afterwards. Used to abort key loading\n public keyLoader: Loader<KeyLoaderContext> | null = null;\n // The level/track index to which the fragment belongs\n public level: number = -1;\n // The continuity counter of the fragment\n public cc: number = 0;\n // The starting Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n public startPTS?: number;\n // The ending Presentation Time Stamp (PTS) of the fragment. Set after transmux complete.\n public endPTS?: number;\n // The starting Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n public startDTS!: number;\n // The ending Decode Time Stamp (DTS) of the fragment. Set after transmux complete.\n public endDTS!: number;\n // The start time of the fragment, as listed in the manifest. Updated after transmux complete.\n public start: number = 0;\n // Set by `updateFragPTSDTS` in level-helper\n public deltaPTS?: number;\n // The maximum starting Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n public maxStartPTS?: number;\n // The minimum ending Presentation Time Stamp (audio/video PTS) of the fragment. Set after transmux complete.\n public minEndPTS?: number;\n // Load/parse timing information\n public stats: LoadStats = new LoadStats();\n public urlId: number = 0;\n public data?: Uint8Array;\n // A flag indicating whether the segment was downloaded in order to test bitrate, and was not buffered\n public bitrateTest: boolean = false;\n // #EXTINF segment title\n public title: string | null = null;\n // The Media Initialization Section for this segment\n public initSegment: Fragment | null = null;\n // Fragment is the last fragment in the media playlist\n public endList?: boolean;\n // Fragment is marked by an EXT-X-GAP tag indicating that it does not contain media data and should not be loaded\n public gap?: boolean;\n\n constructor(type: PlaylistLevelType, baseurl: string) {\n super(baseurl);\n this.type = type;\n }\n\n get decryptdata(): LevelKey | null {\n const { levelkeys } = this;\n if (!levelkeys && !this._decryptdata) {\n return null;\n }\n\n if (!this._decryptdata && this.levelkeys && !this.levelkeys.NONE) {\n const key = this.levelkeys.identity;\n if (key) {\n this._decryptdata = key.getDecryptData(this.sn);\n } else {\n const keyFormats = Object.keys(this.levelkeys);\n if (keyFormats.length === 1) {\n return (this._decryptdata = this.levelkeys[\n keyFormats[0]\n ].getDecryptData(this.sn));\n } else {\n // Multiple keys. key-loader to call Fragment.setKeyFormat based on selected key-system.\n }\n }\n }\n\n return this._decryptdata;\n }\n\n get end(): number {\n return this.start + this.duration;\n }\n\n get endProgramDateTime() {\n if (this.programDateTime === null) {\n return null;\n }\n\n if (!Number.isFinite(this.programDateTime)) {\n return null;\n }\n\n const duration = !Number.isFinite(this.duration) ? 0 : this.duration;\n\n return this.programDateTime + duration * 1000;\n }\n\n get encrypted() {\n // At the m3u8-parser level we need to add support for manifest signalled keyformats\n // when we want the fragment to start reporting that it is encrypted.\n // Currently, keyFormat will only be set for identity keys\n if (this._decryptdata?.encrypted) {\n return true;\n } else if (this.levelkeys) {\n const keyFormats = Object.keys(this.levelkeys);\n const len = keyFormats.length;\n if (len > 1 || (len === 1 && this.levelkeys[keyFormats[0]].encrypted)) {\n return true;\n }\n }\n\n return false;\n }\n\n setKeyFormat(keyFormat: KeySystemFormats) {\n if (this.levelkeys) {\n const key = this.levelkeys[keyFormat];\n if (key && !this._decryptdata) {\n this._decryptdata = key.getDecryptData(this.sn);\n }\n }\n }\n\n abortRequests(): void {\n this.loader?.abort();\n this.keyLoader?.abort();\n }\n\n setElementaryStreamInfo(\n type: ElementaryStreamTypes,\n startPTS: number,\n endPTS: number,\n startDTS: number,\n endDTS: number,\n partial: boolean = false\n ) {\n const { elementaryStreams } = this;\n const info = elementaryStreams[type];\n if (!info) {\n elementaryStreams[type] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n partial,\n };\n return;\n }\n\n info.startPTS = Math.min(info.startPTS, startPTS);\n info.endPTS = Math.max(info.endPTS, endPTS);\n info.startDTS = Math.min(info.startDTS, startDTS);\n info.endDTS = Math.max(info.endDTS, endDTS);\n }\n\n clearElementaryStreamInfo() {\n const { elementaryStreams } = this;\n elementaryStreams[ElementaryStreamTypes.AUDIO] = null;\n elementaryStreams[ElementaryStreamTypes.VIDEO] = null;\n elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO] = null;\n }\n}\n\n/**\n * Object representing parsed data from an HLS Partial Segment. Found in {@link hls.js#LevelDetails.partList}.\n */\nexport class Part extends BaseSegment {\n public readonly fragOffset: number = 0;\n public readonly duration: number = 0;\n public readonly gap: boolean = false;\n public readonly independent: boolean = false;\n public readonly relurl: string;\n public readonly fragment: Fragment;\n public readonly index: number;\n public stats: LoadStats = new LoadStats();\n\n constructor(\n partAttrs: AttrList,\n frag: Fragment,\n baseurl: string,\n index: number,\n previous?: Part\n ) {\n super(baseurl);\n this.duration = partAttrs.decimalFloatingPoint('DURATION');\n this.gap = partAttrs.bool('GAP');\n this.independent = partAttrs.bool('INDEPENDENT');\n this.relurl = partAttrs.enumeratedString('URI') as string;\n this.fragment = frag;\n this.index = index;\n const byteRange = partAttrs.enumeratedString('BYTERANGE');\n if (byteRange) {\n this.setByteRange(byteRange, previous);\n }\n if (previous) {\n this.fragOffset = previous.fragOffset + previous.duration;\n }\n }\n\n get start(): number {\n return this.fragment.start + this.fragOffset;\n }\n\n get end(): number {\n return this.start + this.duration;\n }\n\n get loaded(): boolean {\n const { elementaryStreams } = this;\n return !!(\n elementaryStreams.audio ||\n elementaryStreams.video ||\n elementaryStreams.audiovideo\n );\n }\n}\n","import { Part } from './fragment';\nimport type { Fragment } from './fragment';\nimport type { AttrList } from '../utils/attr-list';\nimport type { DateRange } from './date-range';\nimport type { VariableMap } from '../types/level';\n\nconst DEFAULT_TARGET_DURATION = 10;\n\n/**\n * Object representing parsed data from an HLS Media Playlist. Found in {@link hls.js#Level.details}.\n */\nexport class LevelDetails {\n public PTSKnown: boolean = false;\n public alignedSliding: boolean = false;\n public averagetargetduration?: number;\n public endCC: number = 0;\n public endSN: number = 0;\n public fragments: Fragment[];\n public fragmentHint?: Fragment;\n public partList: Part[] | null = null;\n public dateRanges: Record<string, DateRange>;\n public live: boolean = true;\n public ageHeader: number = 0;\n public advancedDateTime?: number;\n public updated: boolean = true;\n public advanced: boolean = true;\n public availabilityDelay?: number; // Manifest reload synchronization\n public misses: number = 0;\n public startCC: number = 0;\n public startSN: number = 0;\n public startTimeOffset: number | null = null;\n public targetduration: number = 0;\n public totalduration: number = 0;\n public type: string | null = null;\n public url: string;\n public m3u8: string = '';\n public version: number | null = null;\n public canBlockReload: boolean = false;\n public canSkipUntil: number = 0;\n public canSkipDateRanges: boolean = false;\n public skippedSegments: number = 0;\n public recentlyRemovedDateranges?: string[];\n public partHoldBack: number = 0;\n public holdBack: number = 0;\n public partTarget: number = 0;\n public preloadHint?: AttrList;\n public renditionReports?: AttrList[];\n public tuneInGoal: number = 0;\n public deltaUpdateFailed?: boolean;\n public driftStartTime: number = 0;\n public driftEndTime: number = 0;\n public driftStart: number = 0;\n public driftEnd: number = 0;\n public encryptedFragments: Fragment[];\n public playlistParsingError: Error | null = null;\n public variableList: VariableMap | null = null;\n public hasVariableRefs = false;\n\n constructor(baseUrl) {\n this.fragments = [];\n this.encryptedFragments = [];\n this.dateRanges = {};\n this.url = baseUrl;\n }\n\n reloaded(previous: LevelDetails | undefined) {\n if (!previous) {\n this.advanced = true;\n this.updated = true;\n return;\n }\n const partSnDiff = this.lastPartSn - previous.lastPartSn;\n const partIndexDiff = this.lastPartIndex - previous.lastPartIndex;\n this.updated =\n this.endSN !== previous.endSN ||\n !!partIndexDiff ||\n !!partSnDiff ||\n !this.live;\n this.advanced =\n this.endSN > previous.endSN ||\n partSnDiff > 0 ||\n (partSnDiff === 0 && partIndexDiff > 0);\n if (this.updated || this.advanced) {\n this.misses = Math.floor(previous.misses * 0.6);\n } else {\n this.misses = previous.misses + 1;\n }\n this.availabilityDelay = previous.availabilityDelay;\n }\n\n get hasProgramDateTime(): boolean {\n if (this.fragments.length) {\n return Number.isFinite(\n this.fragments[this.fragments.length - 1].programDateTime as number\n );\n }\n return false;\n }\n\n get levelTargetDuration(): number {\n return (\n this.averagetargetduration ||\n this.targetduration ||\n DEFAULT_TARGET_DURATION\n );\n }\n\n get drift(): number {\n const runTime = this.driftEndTime - this.driftStartTime;\n if (runTime > 0) {\n const runDuration = this.driftEnd - this.driftStart;\n return (runDuration * 1000) / runTime;\n }\n return 1;\n }\n\n get edge(): number {\n return this.partEnd || this.fragmentEnd;\n }\n\n get partEnd(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].end;\n }\n return this.fragmentEnd;\n }\n\n get fragmentEnd(): number {\n if (this.fragments?.length) {\n return this.fragments[this.fragments.length - 1].end;\n }\n return 0;\n }\n\n get age(): number {\n if (this.advancedDateTime) {\n return Math.max(Date.now() - this.advancedDateTime, 0) / 1000;\n }\n return 0;\n }\n\n get lastPartIndex(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].index;\n }\n return -1;\n }\n\n get lastPartSn(): number {\n if (this.partList?.length) {\n return this.partList[this.partList.length - 1].fragment.sn as number;\n }\n return this.endSN;\n }\n}\n","export function base64ToBase64Url(base64encodedStr: string): string {\n return base64encodedStr\n .replace(/\\+/g, '-')\n .replace(/\\//g, '_')\n .replace(/=+$/, '');\n}\n\nexport function strToBase64Encode(str: string): string {\n return btoa(str);\n}\n\nexport function base64DecodeToStr(str: string): string {\n return atob(str);\n}\n\nexport function base64Encode(input: Uint8Array): string {\n return btoa(String.fromCharCode(...input));\n}\n\nexport function base64UrlEncode(input: Uint8Array): string {\n return base64ToBase64Url(base64Encode(input));\n}\n\nexport function base64Decode(base64encodedStr: string): Uint8Array {\n return Uint8Array.from(atob(base64encodedStr), (c) => c.charCodeAt(0));\n}\n","import { base64Decode } from './numeric-encoding-utils';\n\nfunction getKeyIdBytes(str: string): Uint8Array {\n const keyIdbytes = strToUtf8array(str).subarray(0, 16);\n const paddedkeyIdbytes = new Uint8Array(16);\n paddedkeyIdbytes.set(keyIdbytes, 16 - keyIdbytes.length);\n return paddedkeyIdbytes;\n}\n\nexport function changeEndianness(keyId: Uint8Array) {\n const swap = function (array: Uint8Array, from: number, to: number) {\n const cur = array[from];\n array[from] = array[to];\n array[to] = cur;\n };\n\n swap(keyId, 0, 3);\n swap(keyId, 1, 2);\n swap(keyId, 4, 5);\n swap(keyId, 6, 7);\n}\n\nexport function convertDataUriToArrayBytes(uri: string): Uint8Array | null {\n // data:[<media type][;attribute=value][;base64],<data>\n const colonsplit = uri.split(':');\n let keydata: Uint8Array | null = null;\n if (colonsplit[0] === 'data' && colonsplit.length === 2) {\n const semicolonsplit = colonsplit[1].split(';');\n const commasplit = semicolonsplit[semicolonsplit.length - 1].split(',');\n if (commasplit.length === 2) {\n const isbase64 = commasplit[0] === 'base64';\n const data = commasplit[1];\n if (isbase64) {\n semicolonsplit.splice(-1, 1); // remove from processing\n keydata = base64Decode(data);\n } else {\n keydata = getKeyIdBytes(data);\n }\n }\n }\n return keydata;\n}\n\nexport function strToUtf8array(str: string): Uint8Array {\n return Uint8Array.from(unescape(encodeURIComponent(str)), (c) =>\n c.charCodeAt(0)\n );\n}\n","import type { DRMSystemOptions, EMEControllerConfig } from '../config';\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Navigator/requestMediaKeySystemAccess\n */\nexport const enum KeySystems {\n CLEARKEY = 'org.w3.clearkey',\n FAIRPLAY = 'com.apple.fps',\n PLAYREADY = 'com.microsoft.playready',\n WIDEVINE = 'com.widevine.alpha',\n}\n\n// Playlist #EXT-X-KEY KEYFORMAT values\nexport const enum KeySystemFormats {\n CLEARKEY = 'org.w3.clearkey',\n FAIRPLAY = 'com.apple.streamingkeydelivery',\n PLAYREADY = 'com.microsoft.playready',\n WIDEVINE = 'urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed',\n}\n\nexport function keySystemFormatToKeySystemDomain(\n format: KeySystemFormats\n): KeySystems | undefined {\n switch (format) {\n case KeySystemFormats.FAIRPLAY:\n return KeySystems.FAIRPLAY;\n case KeySystemFormats.PLAYREADY:\n return KeySystems.PLAYREADY;\n case KeySystemFormats.WIDEVINE:\n return KeySystems.WIDEVINE;\n case KeySystemFormats.CLEARKEY:\n return KeySystems.CLEARKEY;\n }\n}\n\n// System IDs for which we can extract a key ID from \"encrypted\" event PSSH\nexport const enum KeySystemIds {\n // CENC = '1077efecc0b24d02ace33c1e52e2fb4b'\n // CLEARKEY = 'e2719d58a985b3c9781ab030af78d30e',\n // FAIRPLAY = '94ce86fb07ff4f43adb893d2fa968ca2',\n // PLAYREADY = '9a04f07998404286ab92e65be0885f95',\n WIDEVINE = 'edef8ba979d64acea3c827dcd51d21ed',\n}\n\nexport function keySystemIdToKeySystemDomain(\n systemId: KeySystemIds\n): KeySystems | undefined {\n if (systemId === KeySystemIds.WIDEVINE) {\n return KeySystems.WIDEVINE;\n // } else if (systemId === KeySystemIds.PLAYREADY) {\n // return KeySystems.PLAYREADY;\n // } else if (systemId === KeySystemIds.CENC || systemId === KeySystemIds.CLEARKEY) {\n // return KeySystems.CLEARKEY;\n }\n}\n\nexport function keySystemDomainToKeySystemFormat(\n keySystem: KeySystems\n): KeySystemFormats | undefined {\n switch (keySystem) {\n case KeySystems.FAIRPLAY:\n return KeySystemFormats.FAIRPLAY;\n case KeySystems.PLAYREADY:\n return KeySystemFormats.PLAYREADY;\n case KeySystems.WIDEVINE:\n return KeySystemFormats.WIDEVINE;\n case KeySystems.CLEARKEY:\n return KeySystemFormats.CLEARKEY;\n }\n}\n\nexport function getKeySystemsForConfig(\n config: EMEControllerConfig\n): KeySystems[] {\n const { drmSystems, widevineLicenseUrl } = config;\n const keySystemsToAttempt: KeySystems[] = drmSystems\n ? [\n KeySystems.FAIRPLAY,\n KeySystems.WIDEVINE,\n KeySystems.PLAYREADY,\n KeySystems.CLEARKEY,\n ].filter((keySystem) => !!drmSystems[keySystem])\n : [];\n if (!keySystemsToAttempt[KeySystems.WIDEVINE] && widevineLicenseUrl) {\n keySystemsToAttempt.push(KeySystems.WIDEVINE);\n }\n return keySystemsToAttempt;\n}\n\nexport type MediaKeyFunc = (\n keySystem: KeySystems,\n supportedConfigurations: MediaKeySystemConfiguration[]\n) => Promise<MediaKeySystemAccess>;\n\nexport const requestMediaKeySystemAccess = (function (): MediaKeyFunc | null {\n if (\n typeof self !== 'undefined' &&\n self.navigator &&\n self.navigator.requestMediaKeySystemAccess\n ) {\n return self.navigator.requestMediaKeySystemAccess.bind(self.navigator);\n } else {\n return null;\n }\n})();\n\n/**\n * @see https://developer.mozilla.org/en-US/docs/Web/API/MediaKeySystemConfiguration\n */\nexport function getSupportedMediaKeySystemConfigurations(\n keySystem: KeySystems,\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] {\n let initDataTypes: string[];\n switch (keySystem) {\n case KeySystems.FAIRPLAY:\n initDataTypes = ['cenc', 'sinf'];\n break;\n case KeySystems.WIDEVINE:\n case KeySystems.PLAYREADY:\n initDataTypes = ['cenc'];\n break;\n case KeySystems.CLEARKEY:\n initDataTypes = ['cenc', 'keyids'];\n break;\n default:\n throw new Error(`Unknown key-system: ${keySystem}`);\n }\n return createMediaKeySystemConfigurations(\n initDataTypes,\n audioCodecs,\n videoCodecs,\n drmSystemOptions\n );\n}\n\nfunction createMediaKeySystemConfigurations(\n initDataTypes: string[],\n audioCodecs: string[],\n videoCodecs: string[],\n drmSystemOptions: DRMSystemOptions\n): MediaKeySystemConfiguration[] {\n const baseConfig: MediaKeySystemConfiguration = {\n initDataTypes: initDataTypes,\n persistentState: drmSystemOptions.persistentState || 'not-allowed',\n distinctiveIdentifier:\n drmSystemOptions.distinctiveIdentifier || 'not-allowed',\n sessionTypes: drmSystemOptions.sessionTypes || [\n drmSystemOptions.sessionType || 'temporary',\n ],\n audioCapabilities: audioCodecs.map((codec) => ({\n contentType: `audio/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.audioRobustness || '',\n encryptionScheme: drmSystemOptions.audioEncryptionScheme || null,\n })),\n videoCapabilities: videoCodecs.map((codec) => ({\n contentType: `video/mp4; codecs=\"${codec}\"`,\n robustness: drmSystemOptions.videoRobustness || '',\n encryptionScheme: drmSystemOptions.videoEncryptionScheme || null,\n })),\n };\n\n return [baseConfig];\n}\n","export function sliceUint8(\n array: Uint8Array,\n start?: number,\n end?: number\n): Uint8Array {\n // @ts-expect-error This polyfills IE11 usage of Uint8Array slice.\n // It always exists in the TypeScript definition so fails, but it fails at runtime on IE11.\n return Uint8Array.prototype.slice\n ? array.slice(start, end)\n : new Uint8Array(Array.prototype.slice.call(array, start, end));\n}\n","type RawFrame = { type: string; size: number; data: Uint8Array };\n\n// breaking up those two types in order to clarify what is happening in the decoding path.\ntype DecodedFrame<T> = { key: string; data: T; info?: any };\nexport type Frame = DecodedFrame<ArrayBuffer | string>;\n\n/**\n * Returns true if an ID3 header can be found at offset in data\n * @param data - The data to search\n * @param offset - The offset at which to start searching\n */\nexport const isHeader = (data: Uint8Array, offset: number): boolean => {\n /*\n * http://id3.org/id3v2.3.0\n * [0] = 'I'\n * [1] = 'D'\n * [2] = '3'\n * [3,4] = {Version}\n * [5] = {Flags}\n * [6-9] = {ID3 Size}\n *\n * An ID3v2 tag can be detected with the following pattern:\n * $49 44 33 yy yy xx zz zz zz zz\n * Where yy is less than $FF, xx is the 'flags' byte and zz is less than $80\n */\n if (offset + 10 <= data.length) {\n // look for 'ID3' identifier\n if (\n data[offset] === 0x49 &&\n data[offset + 1] === 0x44 &&\n data[offset + 2] === 0x33\n ) {\n // check version is within range\n if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {\n // check size is within range\n if (\n data[offset + 6] < 0x80 &&\n data[offset + 7] < 0x80 &&\n data[offset + 8] < 0x80 &&\n data[offset + 9] < 0x80\n ) {\n return true;\n }\n }\n }\n }\n\n return false;\n};\n\n/**\n * Returns true if an ID3 footer can be found at offset in data\n * @param data - The data to search\n * @param offset - The offset at which to start searching\n */\nexport const isFooter = (data: Uint8Array, offset: number): boolean => {\n /*\n * The footer is a copy of the header, but with a different identifier\n */\n if (offset + 10 <= data.length) {\n // look for '3DI' identifier\n if (\n data[offset] === 0x33 &&\n data[offset + 1] === 0x44 &&\n data[offset + 2] === 0x49\n ) {\n // check version is within range\n if (data[offset + 3] < 0xff && data[offset + 4] < 0xff) {\n // check size is within range\n if (\n data[offset + 6] < 0x80 &&\n data[offset + 7] < 0x80 &&\n data[offset + 8] < 0x80 &&\n data[offset + 9] < 0x80\n ) {\n return true;\n }\n }\n }\n }\n\n return false;\n};\n\n/**\n * Returns any adjacent ID3 tags found in data starting at offset, as one block of data\n * @param data - The data to search in\n * @param offset - The offset at which to start searching\n * @returns the block of data containing any ID3 tags found\n * or *undefined* if no header is found at the starting offset\n */\nexport const getID3Data = (\n data: Uint8Array,\n offset: number\n): Uint8Array | undefined => {\n const front = offset;\n let length = 0;\n\n while (isHeader(data, offset)) {\n // ID3 header is 10 bytes\n length += 10;\n\n const size = readSize(data, offset + 6);\n length += size;\n\n if (isFooter(data, offset + 10)) {\n // ID3 footer is 10 bytes\n length += 10;\n }\n\n offset += length;\n }\n\n if (length > 0) {\n return data.subarray(front, front + length);\n }\n\n return undefined;\n};\n\nconst readSize = (data: Uint8Array, offset: number): number => {\n let size = 0;\n size = (data[offset] & 0x7f) << 21;\n size |= (data[offset + 1] & 0x7f) << 14;\n size |= (data[offset + 2] & 0x7f) << 7;\n size |= data[offset + 3] & 0x7f;\n return size;\n};\n\nexport const canParse = (data: Uint8Array, offset: number): boolean => {\n return (\n isHeader(data, offset) &&\n readSize(data, offset + 6) + 10 <= data.length - offset\n );\n};\n\n/**\n * Searches for the Elementary Stream timestamp found in the ID3 data chunk\n * @param data - Block of data containing one or more ID3 tags\n */\nexport const getTimeStamp = (data: Uint8Array): number | undefined => {\n const frames: Frame[] = getID3Frames(data);\n\n for (let i = 0; i < frames.length; i++) {\n const frame = frames[i];\n\n if (isTimeStampFrame(frame)) {\n return readTimeStamp(frame as DecodedFrame<ArrayBuffer>);\n }\n }\n\n return undefined;\n};\n\n/**\n * Returns true if the ID3 frame is an Elementary Stream timestamp frame\n */\nexport const isTimeStampFrame = (frame: Frame): boolean => {\n return (\n frame &&\n frame.key === 'PRIV' &&\n frame.info === 'com.apple.streaming.transportStreamTimestamp'\n );\n};\n\nconst getFrameData = (data: Uint8Array): RawFrame => {\n /*\n Frame ID $xx xx xx xx (four characters)\n Size $xx xx xx xx\n Flags $xx xx\n */\n const type: string = String.fromCharCode(data[0], data[1], data[2], data[3]);\n const size: number = readSize(data, 4);\n\n // skip frame id, size, and flags\n const offset = 10;\n\n return { type, size, data: data.subarray(offset, offset + size) };\n};\n\n/**\n * Returns an array of ID3 frames found in all the ID3 tags in the id3Data\n * @param id3Data - The ID3 data containing one or more ID3 tags\n */\nexport const getID3Frames = (id3Data: Uint8Array): Frame[] => {\n let offset = 0;\n const frames: Frame[] = [];\n\n while (isHeader(id3Data, offset)) {\n const size = readSize(id3Data, offset + 6);\n // skip past ID3 header\n offset += 10;\n const end = offset + size;\n // loop through frames in the ID3 tag\n while (offset + 8 < end) {\n const frameData: RawFrame = getFrameData(id3Data.subarray(offset));\n const frame: Frame | undefined = decodeFrame(frameData);\n if (frame) {\n frames.push(frame);\n }\n\n // skip frame header and frame data\n offset += frameData.size + 10;\n }\n\n if (isFooter(id3Data, offset)) {\n offset += 10;\n }\n }\n\n return frames;\n};\n\nexport const decodeFrame = (frame: RawFrame): Frame | undefined => {\n if (frame.type === 'PRIV') {\n return decodePrivFrame(frame);\n } else if (frame.type[0] === 'W') {\n return decodeURLFrame(frame);\n }\n\n return decodeTextFrame(frame);\n};\n\nconst decodePrivFrame = (\n frame: RawFrame\n): DecodedFrame<ArrayBuffer> | undefined => {\n /*\n Format: <text string>\\0<binary data>\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n const owner = utf8ArrayToStr(frame.data, true);\n const privateData = new Uint8Array(frame.data.subarray(owner.length + 1));\n\n return { key: frame.type, info: owner, data: privateData.buffer };\n};\n\nconst decodeTextFrame = (frame: RawFrame): DecodedFrame<string> | undefined => {\n if (frame.size < 2) {\n return undefined;\n }\n\n if (frame.type === 'TXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{Value}\n */\n let index = 1;\n const description = utf8ArrayToStr(frame.data.subarray(index), true);\n\n index += description.length + 1;\n const value = utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n }\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Value}\n */\n const text = utf8ArrayToStr(frame.data.subarray(1));\n return { key: frame.type, data: text };\n};\n\nconst decodeURLFrame = (frame: RawFrame): DecodedFrame<string> | undefined => {\n if (frame.type === 'WXXX') {\n /*\n Format:\n [0] = {Text Encoding}\n [1-?] = {Description}\\0{URL}\n */\n if (frame.size < 2) {\n return undefined;\n }\n\n let index = 1;\n const description: string = utf8ArrayToStr(\n frame.data.subarray(index),\n true\n );\n\n index += description.length + 1;\n const value: string = utf8ArrayToStr(frame.data.subarray(index));\n\n return { key: frame.type, info: description, data: value };\n }\n /*\n Format:\n [0-?] = {URL}\n */\n const url: string = utf8ArrayToStr(frame.data);\n return { key: frame.type, data: url };\n};\n\nconst readTimeStamp = (\n timeStampFrame: DecodedFrame<ArrayBuffer>\n): number | undefined => {\n if (timeStampFrame.data.byteLength === 8) {\n const data = new Uint8Array(timeStampFrame.data);\n // timestamp is 33 bit expressed as a big-endian eight-octet number,\n // with the upper 31 bits set to zero.\n const pts33Bit = data[3] & 0x1;\n let timestamp =\n (data[4] << 23) + (data[5] << 15) + (data[6] << 7) + data[7];\n timestamp /= 45;\n\n if (pts33Bit) {\n timestamp += 47721858.84;\n } // 2^32 / 90\n\n return Math.round(timestamp);\n }\n\n return undefined;\n};\n\n// http://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript/22373197\n// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt\n/* utf.js - UTF-8 <=> UTF-16 convertion\n *\n * Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>\n * Version: 1.0\n * LastModified: Dec 25 1999\n * This library is free. You can redistribute it and/or modify it.\n */\nexport const utf8ArrayToStr = (\n array: Uint8Array,\n exitOnNull: boolean = false\n): string => {\n const decoder = getTextDecoder();\n if (decoder) {\n const decoded = decoder.decode(array);\n\n if (exitOnNull) {\n // grab up to the first null\n const idx = decoded.indexOf('\\0');\n return idx !== -1 ? decoded.substring(0, idx) : decoded;\n }\n\n // remove any null characters\n return decoded.replace(/\\0/g, '');\n }\n\n const len = array.length;\n let c;\n let char2;\n let char3;\n let out = '';\n let i = 0;\n while (i < len) {\n c = array[i++];\n if (c === 0x00 && exitOnNull) {\n return out;\n } else if (c === 0x00 || c === 0x03) {\n // If the character is 3 (END_OF_TEXT) or 0 (NULL) then skip it\n continue;\n }\n switch (c >> 4) {\n case 0:\n case 1:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n // 0xxxxxxx\n out += String.fromCharCode(c);\n break;\n case 12:\n case 13:\n // 110x xxxx 10xx xxxx\n char2 = array[i++];\n out += String.fromCharCode(((c & 0x1f) << 6) | (char2 & 0x3f));\n break;\n case 14:\n // 1110 xxxx 10xx xxxx 10xx xxxx\n char2 = array[i++];\n char3 = array[i++];\n out += String.fromCharCode(\n ((c & 0x0f) << 12) | ((char2 & 0x3f) << 6) | ((char3 & 0x3f) << 0)\n );\n break;\n default:\n }\n }\n return out;\n};\n\nexport const testables = {\n decodeTextFrame: decodeTextFrame,\n};\n\nlet decoder: TextDecoder;\n\nfunction getTextDecoder() {\n // On Play Station 4, TextDecoder is defined but partially implemented.\n // Manual decoding option is preferable\n if (navigator.userAgent.includes('PlayStation 4')) {\n return;\n }\n\n if (!decoder && typeof self.TextDecoder !== 'undefined') {\n decoder = new self.TextDecoder('utf-8');\n }\n\n return decoder;\n}\n","/**\n * hex dump helper class\n */\n\nconst Hex = {\n hexDump: function (array: Uint8Array) {\n let str = '';\n for (let i = 0; i < array.length; i++) {\n let h = array[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n str += h;\n }\n return str;\n },\n};\n\nexport default Hex;\n","import { ElementaryStreamTypes } from '../loader/fragment';\nimport { sliceUint8 } from './typed-array';\nimport { utf8ArrayToStr } from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport Hex from './hex';\nimport type { PassthroughTrack, UserdataSample } from '../types/demuxer';\nimport type { DecryptData } from '../loader/level-key';\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\nconst push = [].push;\n\n// We are using fixed track IDs for driving the MP4 remuxer\n// instead of following the TS PIDs.\n// There is no reason not to do this and some browsers/SourceBuffer-demuxers\n// may not like if there are TrackID \"switches\"\n// See https://github.com/video-dev/hls.js/issues/1331\n// Here we are mapping our internal track types to constant MP4 track IDs\n// With MSE currently one can only have one track of each, and we are muxing\n// whatever video/audio rendition in them.\nexport const RemuxerTrackIdConfig = {\n video: 1,\n audio: 2,\n id3: 3,\n text: 4,\n};\n\nexport function bin2str(data: Uint8Array): string {\n return String.fromCharCode.apply(null, data);\n}\n\nexport function readUint16(buffer: Uint8Array, offset: number): number {\n const val = (buffer[offset] << 8) | buffer[offset + 1];\n return val < 0 ? 65536 + val : val;\n}\n\nexport function readUint32(buffer: Uint8Array, offset: number): number {\n const val = readSint32(buffer, offset);\n return val < 0 ? 4294967296 + val : val;\n}\n\nexport function readSint32(buffer: Uint8Array, offset: number): number {\n return (\n (buffer[offset] << 24) |\n (buffer[offset + 1] << 16) |\n (buffer[offset + 2] << 8) |\n buffer[offset + 3]\n );\n}\n\nexport function writeUint32(buffer: Uint8Array, offset: number, value: number) {\n buffer[offset] = value >> 24;\n buffer[offset + 1] = (value >> 16) & 0xff;\n buffer[offset + 2] = (value >> 8) & 0xff;\n buffer[offset + 3] = value & 0xff;\n}\n\n// Find the data for a box specified by its path\nexport function findBox(data: Uint8Array, path: string[]): Uint8Array[] {\n const results = [] as Uint8Array[];\n if (!path.length) {\n // short-circuit the search for empty paths\n return results;\n }\n const end = data.byteLength;\n\n for (let i = 0; i < end; ) {\n const size = readUint32(data, i);\n const type = bin2str(data.subarray(i + 4, i + 8));\n const endbox = size > 1 ? i + size : end;\n\n if (type === path[0]) {\n if (path.length === 1) {\n // this is the end of the path and we've found the box we were\n // looking for\n results.push(data.subarray(i + 8, endbox));\n } else {\n // recursively search for the next box along the path\n const subresults = findBox(data.subarray(i + 8, endbox), path.slice(1));\n if (subresults.length) {\n push.apply(results, subresults);\n }\n }\n }\n i = endbox;\n }\n\n // we've finished searching all of data\n return results;\n}\n\ntype SidxInfo = {\n earliestPresentationTime: number;\n timescale: number;\n version: number;\n referencesCount: number;\n references: any[];\n};\n\nexport function parseSegmentIndex(sidx: Uint8Array): SidxInfo | null {\n const references: any[] = [];\n\n const version = sidx[0];\n\n // set initial offset, we skip the reference ID (not needed)\n let index = 8;\n\n const timescale = readUint32(sidx, index);\n index += 4;\n\n // TODO: parse earliestPresentationTime and firstOffset\n // usually zero in our case\n const earliestPresentationTime = 0;\n const firstOffset = 0;\n\n if (version === 0) {\n index += 8;\n } else {\n index += 16;\n }\n\n // skip reserved\n index += 2;\n\n let startByte = sidx.length + firstOffset;\n\n const referencesCount = readUint16(sidx, index);\n index += 2;\n\n for (let i = 0; i < referencesCount; i++) {\n let referenceIndex = index;\n\n const referenceInfo = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n const referenceSize = referenceInfo & 0x7fffffff;\n const referenceType = (referenceInfo & 0x80000000) >>> 31;\n\n if (referenceType === 1) {\n logger.warn('SIDX has hierarchical references (not supported)');\n return null;\n }\n\n const subsegmentDuration = readUint32(sidx, referenceIndex);\n referenceIndex += 4;\n\n references.push({\n referenceSize,\n subsegmentDuration, // unscaled\n info: {\n duration: subsegmentDuration / timescale,\n start: startByte,\n end: startByte + referenceSize - 1,\n },\n });\n\n startByte += referenceSize;\n\n // Skipping 1 bit for |startsWithSap|, 3 bits for |sapType|, and 28 bits\n // for |sapDelta|.\n referenceIndex += 4;\n\n // skip to next ref\n index = referenceIndex;\n }\n\n return {\n earliestPresentationTime,\n timescale,\n version,\n referencesCount,\n references,\n };\n}\n\n/**\n * Parses an MP4 initialization segment and extracts stream type and\n * timescale values for any declared tracks. Timescale values indicate the\n * number of clock ticks per second to assume for time-based values\n * elsewhere in the MP4.\n *\n * To determine the start time of an MP4, you need two pieces of\n * information: the timescale unit and the earliest base media decode\n * time. Multiple timescales can be specified within an MP4 but the\n * base media decode time is always expressed in the timescale from\n * the media header box for the track:\n * ```\n * moov > trak > mdia > mdhd.timescale\n * moov > trak > mdia > hdlr\n * ```\n * @param initSegment the bytes of the init segment\n * @returns a hash of track type to timescale values or null if\n * the init segment is malformed.\n */\n\nexport interface InitDataTrack {\n timescale: number;\n id: number;\n codec: string;\n}\n\ntype HdlrType = ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO;\n\nexport interface InitData extends Array<any> {\n [index: number]:\n | {\n timescale: number;\n type: HdlrType;\n default?: {\n duration: number;\n flags: number;\n };\n }\n | undefined;\n audio?: InitDataTrack;\n video?: InitDataTrack;\n caption?: InitDataTrack;\n}\n\nexport function parseInitSegment(initSegment: Uint8Array): InitData {\n const result: InitData = [];\n const traks = findBox(initSegment, ['moov', 'trak']);\n for (let i = 0; i < traks.length; i++) {\n const trak = traks[i];\n const tkhd = findBox(trak, ['tkhd'])[0];\n if (tkhd) {\n let version = tkhd[0];\n let index = version === 0 ? 12 : 20;\n const trackId = readUint32(tkhd, index);\n const mdhd = findBox(trak, ['mdia', 'mdhd'])[0];\n if (mdhd) {\n version = mdhd[0];\n index = version === 0 ? 12 : 20;\n const timescale = readUint32(mdhd, index);\n const hdlr = findBox(trak, ['mdia', 'hdlr'])[0];\n if (hdlr) {\n const hdlrType = bin2str(hdlr.subarray(8, 12));\n const type: HdlrType | undefined = {\n soun: ElementaryStreamTypes.AUDIO as const,\n vide: ElementaryStreamTypes.VIDEO as const,\n }[hdlrType];\n if (type) {\n // Parse codec details\n const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n let codec;\n if (stsd) {\n codec = bin2str(stsd.subarray(12, 16));\n // TODO: Parse codec details to be able to build MIME type.\n // stsd.start += 8;\n // const codecBox = findBox(stsd, [codec])[0];\n // if (codecBox) {\n // TODO: Codec parsing support for avc1, mp4a, hevc, av01...\n // }\n }\n result[trackId] = { timescale, type };\n result[type] = { timescale, id: trackId, codec };\n }\n }\n }\n }\n }\n\n const trex = findBox(initSegment, ['moov', 'mvex', 'trex']);\n trex.forEach((trex) => {\n const trackId = readUint32(trex, 4);\n const track = result[trackId];\n if (track) {\n track.default = {\n duration: readUint32(trex, 12),\n flags: readUint32(trex, 20),\n };\n }\n });\n\n return result;\n}\n\nexport function patchEncyptionData(\n initSegment: Uint8Array | undefined,\n decryptdata: DecryptData | null\n): Uint8Array | undefined {\n if (!initSegment || !decryptdata) {\n return initSegment;\n }\n const keyId = decryptdata.keyId;\n if (keyId && decryptdata.isCommonEncryption) {\n const traks = findBox(initSegment, ['moov', 'trak']);\n traks.forEach((trak) => {\n const stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];\n\n // skip the sample entry count\n const sampleEntries = stsd.subarray(8);\n let encBoxes = findBox(sampleEntries, ['enca']);\n const isAudio = encBoxes.length > 0;\n if (!isAudio) {\n encBoxes = findBox(sampleEntries, ['encv']);\n }\n encBoxes.forEach((enc) => {\n const encBoxChildren = isAudio ? enc.subarray(28) : enc.subarray(78);\n const sinfBoxes = findBox(encBoxChildren, ['sinf']);\n sinfBoxes.forEach((sinf) => {\n const tenc = parseSinf(sinf);\n if (tenc) {\n // Look for default key id (keyID offset is always 8 within the tenc box):\n const tencKeyId = tenc.subarray(8, 24);\n if (!tencKeyId.some((b) => b !== 0)) {\n logger.log(\n `[eme] Patching keyId in 'enc${\n isAudio ? 'a' : 'v'\n }>sinf>>tenc' box: ${Hex.hexDump(tencKeyId)} -> ${Hex.hexDump(\n keyId\n )}`\n );\n tenc.set(keyId, 8);\n }\n }\n });\n });\n });\n }\n\n return initSegment;\n}\n\nexport function parseSinf(sinf: Uint8Array): Uint8Array | null {\n const schm = findBox(sinf, ['schm'])[0];\n if (schm) {\n const scheme = bin2str(schm.subarray(4, 8));\n if (scheme === 'cbcs' || scheme === 'cenc') {\n return findBox(sinf, ['schi', 'tenc'])[0];\n }\n }\n logger.error(`[eme] missing 'schm' box`);\n return null;\n}\n\n/**\n * Determine the base media decode start time, in seconds, for an MP4\n * fragment. If multiple fragments are specified, the earliest time is\n * returned.\n *\n * The base media decode time can be parsed from track fragment\n * metadata:\n * ```\n * moof > traf > tfdt.baseMediaDecodeTime\n * ```\n * It requires the timescale value from the mdhd to interpret.\n *\n * @param initData - a hash of track type to timescale values\n * @param fmp4 - the bytes of the mp4 fragment\n * @returns the earliest base media decode start time for the\n * fragment, in seconds\n */\nexport function getStartDTS(\n initData: InitData,\n fmp4: Uint8Array\n): number | null {\n // we need info from two children of each track fragment box\n return findBox(fmp4, ['moof', 'traf']).reduce(\n (result: number | null, traf) => {\n const tfdt = findBox(traf, ['tfdt'])[0];\n const version = tfdt[0];\n const start = findBox(traf, ['tfhd']).reduce(\n (result: number | null, tfhd) => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (track) {\n let baseTime = readUint32(tfdt, 4);\n if (version === 1) {\n // If value is too large, assume signed 64-bit. Negative track fragment decode times are invalid, but they exist in the wild.\n // This prevents large values from being used for initPTS, which can cause playlist sync issues.\n // https://github.com/video-dev/hls.js/issues/5303\n if (baseTime === UINT32_MAX) {\n logger.warn(\n `[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`\n );\n return result;\n }\n baseTime *= UINT32_MAX + 1;\n baseTime += readUint32(tfdt, 8);\n }\n // assume a 90kHz clock if no timescale was specified\n const scale = track.timescale || 90e3;\n // convert base time to seconds\n const startTime = baseTime / scale;\n if (\n Number.isFinite(startTime) &&\n (result === null || startTime < result)\n ) {\n return startTime;\n }\n }\n return result;\n },\n null\n );\n if (\n start !== null &&\n Number.isFinite(start) &&\n (result === null || start < result)\n ) {\n return start;\n }\n return result;\n },\n null\n );\n}\n\n/*\n For Reference:\n aligned(8) class TrackFragmentHeaderBox\n extends FullBox(‘tfhd’, 0, tf_flags){\n unsigned int(32) track_ID;\n // all the following are optional fields\n unsigned int(64) base_data_offset;\n unsigned int(32) sample_description_index;\n unsigned int(32) default_sample_duration;\n unsigned int(32) default_sample_size;\n unsigned int(32) default_sample_flags\n }\n */\nexport function getDuration(data: Uint8Array, initData: InitData) {\n let rawDuration = 0;\n let videoDuration = 0;\n let audioDuration = 0;\n const trafs = findBox(data, ['moof', 'traf']);\n for (let i = 0; i < trafs.length; i++) {\n const traf = trafs[i];\n // There is only one tfhd & trun per traf\n // This is true for CMAF style content, and we should perhaps check the ftyp\n // and only look for a single trun then, but for ISOBMFF we should check\n // for multiple track runs.\n const tfhd = findBox(traf, ['tfhd'])[0];\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n continue;\n }\n const trackDefault = track.default;\n const tfhdFlags = readUint32(tfhd, 0) | trackDefault?.flags!;\n let sampleDuration: number | undefined = trackDefault?.duration;\n if (tfhdFlags & 0x000008) {\n // 0x000008 indicates the presence of the default_sample_duration field\n if (tfhdFlags & 0x000002) {\n // 0x000002 indicates the presence of the sample_description_index field, which precedes default_sample_duration\n // If present, the default_sample_duration exists at byte offset 12\n sampleDuration = readUint32(tfhd, 12);\n } else {\n // Otherwise, the duration is at byte offset 8\n sampleDuration = readUint32(tfhd, 8);\n }\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n const truns = findBox(traf, ['trun']);\n for (let j = 0; j < truns.length; j++) {\n rawDuration = computeRawDurationFromSamples(truns[j]);\n if (!rawDuration && sampleDuration) {\n const sampleCount = readUint32(truns[j], 4);\n rawDuration = sampleDuration * sampleCount;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n videoDuration += rawDuration / timescale;\n } else if (track.type === ElementaryStreamTypes.AUDIO) {\n audioDuration += rawDuration / timescale;\n }\n }\n }\n if (videoDuration === 0 && audioDuration === 0) {\n // If duration samples are not available in the traf use sidx subsegment_duration\n let sidxDuration = 0;\n const sidxs = findBox(data, ['sidx']);\n for (let i = 0; i < sidxs.length; i++) {\n const sidx = parseSegmentIndex(sidxs[i]);\n if (sidx?.references) {\n sidxDuration += sidx.references.reduce(\n (dur, ref) => dur + ref.info.duration || 0,\n 0\n );\n }\n }\n\n return sidxDuration;\n }\n if (videoDuration) {\n return videoDuration;\n }\n return audioDuration;\n}\n\n/*\n For Reference:\n aligned(8) class TrackRunBox\n extends FullBox(‘trun’, version, tr_flags) {\n unsigned int(32) sample_count;\n // the following are optional fields\n signed int(32) data_offset;\n unsigned int(32) first_sample_flags;\n // all fields in the following array are optional\n {\n unsigned int(32) sample_duration;\n unsigned int(32) sample_size;\n unsigned int(32) sample_flags\n if (version == 0)\n { unsigned int(32)\n else\n { signed int(32)\n }[ sample_count ]\n }\n */\nexport function computeRawDurationFromSamples(trun): number {\n const flags = readUint32(trun, 0);\n // Flags are at offset 0, non-optional sample_count is at offset 4. Therefore we start 8 bytes in.\n // Each field is an int32, which is 4 bytes\n let offset = 8;\n // data-offset-present flag\n if (flags & 0x000001) {\n offset += 4;\n }\n // first-sample-flags-present flag\n if (flags & 0x000004) {\n offset += 4;\n }\n\n let duration = 0;\n const sampleCount = readUint32(trun, 4);\n for (let i = 0; i < sampleCount; i++) {\n // sample-duration-present flag\n if (flags & 0x000100) {\n const sampleDuration = readUint32(trun, offset);\n duration += sampleDuration;\n offset += 4;\n }\n // sample-size-present flag\n if (flags & 0x000200) {\n offset += 4;\n }\n // sample-flags-present flag\n if (flags & 0x000400) {\n offset += 4;\n }\n // sample-composition-time-offsets-present flag\n if (flags & 0x000800) {\n offset += 4;\n }\n }\n return duration;\n}\n\nexport function offsetStartDTS(\n initData: InitData,\n fmp4: Uint8Array,\n timeOffset: number\n) {\n findBox(fmp4, ['moof', 'traf']).forEach((traf) => {\n findBox(traf, ['tfhd']).forEach((tfhd) => {\n // get the track id from the tfhd\n const id = readUint32(tfhd, 4);\n const track = initData[id];\n if (!track) {\n return;\n }\n // assume a 90kHz clock if no timescale was specified\n const timescale = track.timescale || 90e3;\n // get the base media decode time from the tfdt\n findBox(traf, ['tfdt']).forEach((tfdt) => {\n const version = tfdt[0];\n let baseMediaDecodeTime = readUint32(tfdt, 4);\n\n if (version === 0) {\n baseMediaDecodeTime -= timeOffset * timescale;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n writeUint32(tfdt, 4, baseMediaDecodeTime);\n } else {\n baseMediaDecodeTime *= Math.pow(2, 32);\n baseMediaDecodeTime += readUint32(tfdt, 8);\n baseMediaDecodeTime -= timeOffset * timescale;\n baseMediaDecodeTime = Math.max(baseMediaDecodeTime, 0);\n const upper = Math.floor(baseMediaDecodeTime / (UINT32_MAX + 1));\n const lower = Math.floor(baseMediaDecodeTime % (UINT32_MAX + 1));\n writeUint32(tfdt, 4, upper);\n writeUint32(tfdt, 8, lower);\n }\n });\n });\n });\n}\n\n// TODO: Check if the last moof+mdat pair is part of the valid range\nexport function segmentValidRange(data: Uint8Array): SegmentedRange {\n const segmentedRange: SegmentedRange = {\n valid: null,\n remainder: null,\n };\n\n const moofs = findBox(data, ['moof']);\n if (!moofs) {\n return segmentedRange;\n } else if (moofs.length < 2) {\n segmentedRange.remainder = data;\n return segmentedRange;\n }\n const last = moofs[moofs.length - 1];\n // Offset by 8 bytes; findBox offsets the start by as much\n segmentedRange.valid = sliceUint8(data, 0, last.byteOffset - 8);\n segmentedRange.remainder = sliceUint8(data, last.byteOffset - 8);\n return segmentedRange;\n}\n\nexport interface SegmentedRange {\n valid: Uint8Array | null;\n remainder: Uint8Array | null;\n}\n\nexport function appendUint8Array(\n data1: Uint8Array,\n data2: Uint8Array\n): Uint8Array {\n const temp = new Uint8Array(data1.length + data2.length);\n temp.set(data1);\n temp.set(data2, data1.length);\n\n return temp;\n}\n\nexport interface IEmsgParsingData {\n schemeIdUri: string;\n value: string;\n timeScale: number;\n presentationTimeDelta?: number;\n presentationTime?: number;\n eventDuration: number;\n id: number;\n payload: Uint8Array;\n}\n\nexport function parseSamples(\n timeOffset: number,\n track: PassthroughTrack\n): UserdataSample[] {\n const seiSamples = [] as UserdataSample[];\n const videoData = track.samples;\n const timescale = track.timescale;\n const trackId = track.id;\n let isHEVCFlavor = false;\n\n const moofs = findBox(videoData, ['moof']);\n moofs.map((moof) => {\n const moofOffset = moof.byteOffset - 8;\n const trafs = findBox(moof, ['traf']);\n trafs.map((traf) => {\n // get the base media decode time from the tfdt\n const baseTime = findBox(traf, ['tfdt']).map((tfdt) => {\n const version = tfdt[0];\n let result = readUint32(tfdt, 4);\n if (version === 1) {\n result *= Math.pow(2, 32);\n result += readUint32(tfdt, 8);\n }\n return result / timescale;\n })[0];\n\n if (baseTime !== undefined) {\n timeOffset = baseTime;\n }\n\n return findBox(traf, ['tfhd']).map((tfhd) => {\n const id = readUint32(tfhd, 4);\n const tfhdFlags = readUint32(tfhd, 0) & 0xffffff;\n const baseDataOffsetPresent = (tfhdFlags & 0x000001) !== 0;\n const sampleDescriptionIndexPresent = (tfhdFlags & 0x000002) !== 0;\n const defaultSampleDurationPresent = (tfhdFlags & 0x000008) !== 0;\n let defaultSampleDuration = 0;\n const defaultSampleSizePresent = (tfhdFlags & 0x000010) !== 0;\n let defaultSampleSize = 0;\n const defaultSampleFlagsPresent = (tfhdFlags & 0x000020) !== 0;\n let tfhdOffset = 8;\n\n if (id === trackId) {\n if (baseDataOffsetPresent) {\n tfhdOffset += 8;\n }\n if (sampleDescriptionIndexPresent) {\n tfhdOffset += 4;\n }\n if (defaultSampleDurationPresent) {\n defaultSampleDuration = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleSizePresent) {\n defaultSampleSize = readUint32(tfhd, tfhdOffset);\n tfhdOffset += 4;\n }\n if (defaultSampleFlagsPresent) {\n tfhdOffset += 4;\n }\n if (track.type === 'video') {\n isHEVCFlavor = isHEVC(track.codec);\n }\n\n findBox(traf, ['trun']).map((trun) => {\n const version = trun[0];\n const flags = readUint32(trun, 0) & 0xffffff;\n const dataOffsetPresent = (flags & 0x000001) !== 0;\n let dataOffset = 0;\n const firstSampleFlagsPresent = (flags & 0x000004) !== 0;\n const sampleDurationPresent = (flags & 0x000100) !== 0;\n let sampleDuration = 0;\n const sampleSizePresent = (flags & 0x000200) !== 0;\n let sampleSize = 0;\n const sampleFlagsPresent = (flags & 0x000400) !== 0;\n const sampleCompositionOffsetsPresent = (flags & 0x000800) !== 0;\n let compositionOffset = 0;\n const sampleCount = readUint32(trun, 4);\n let trunOffset = 8; // past version, flags, and sample count\n\n if (dataOffsetPresent) {\n dataOffset = readUint32(trun, trunOffset);\n trunOffset += 4;\n }\n if (firstSampleFlagsPresent) {\n trunOffset += 4;\n }\n\n let sampleOffset = dataOffset + moofOffset;\n\n for (let ix = 0; ix < sampleCount; ix++) {\n if (sampleDurationPresent) {\n sampleDuration = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleDuration = defaultSampleDuration;\n }\n if (sampleSizePresent) {\n sampleSize = readUint32(trun, trunOffset);\n trunOffset += 4;\n } else {\n sampleSize = defaultSampleSize;\n }\n if (sampleFlagsPresent) {\n trunOffset += 4;\n }\n if (sampleCompositionOffsetsPresent) {\n if (version === 0) {\n compositionOffset = readUint32(trun, trunOffset);\n } else {\n compositionOffset = readSint32(trun, trunOffset);\n }\n trunOffset += 4;\n }\n if (track.type === ElementaryStreamTypes.VIDEO) {\n let naluTotalSize = 0;\n while (naluTotalSize < sampleSize) {\n const naluSize = readUint32(videoData, sampleOffset);\n sampleOffset += 4;\n if (isSEIMessage(isHEVCFlavor, videoData[sampleOffset])) {\n const data = videoData.subarray(\n sampleOffset,\n sampleOffset + naluSize\n );\n parseSEIMessageFromNALu(\n data,\n isHEVCFlavor ? 2 : 1,\n timeOffset + compositionOffset / timescale,\n seiSamples\n );\n }\n sampleOffset += naluSize;\n naluTotalSize += naluSize + 4;\n }\n }\n\n timeOffset += sampleDuration / timescale;\n }\n });\n }\n });\n });\n });\n return seiSamples;\n}\n\nfunction isHEVC(codec: string) {\n if (!codec) {\n return false;\n }\n const delimit = codec.indexOf('.');\n const baseCodec = delimit < 0 ? codec : codec.substring(0, delimit);\n return (\n baseCodec === 'hvc1' ||\n baseCodec === 'hev1' ||\n // Dolby Vision\n baseCodec === 'dvh1' ||\n baseCodec === 'dvhe'\n );\n}\n\nfunction isSEIMessage(isHEVCFlavor: boolean, naluHeader: number) {\n if (isHEVCFlavor) {\n const naluType = (naluHeader >> 1) & 0x3f;\n return naluType === 39 || naluType === 40;\n } else {\n const naluType = naluHeader & 0x1f;\n return naluType === 6;\n }\n}\n\nexport function parseSEIMessageFromNALu(\n unescapedData: Uint8Array,\n headerSize: number,\n pts: number,\n samples: UserdataSample[]\n) {\n const data = discardEPB(unescapedData);\n let seiPtr = 0;\n // skip nal header\n seiPtr += headerSize;\n let payloadType = 0;\n let payloadSize = 0;\n let endOfCaptions = false;\n let b = 0;\n\n while (seiPtr < data.length) {\n payloadType = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadType += b;\n } while (b === 0xff);\n\n // Parse payload size.\n payloadSize = 0;\n do {\n if (seiPtr >= data.length) {\n break;\n }\n b = data[seiPtr++];\n payloadSize += b;\n } while (b === 0xff);\n\n const leftOver = data.length - seiPtr;\n\n if (!endOfCaptions && payloadType === 4 && seiPtr < data.length) {\n endOfCaptions = true;\n\n const countryCode = data[seiPtr++];\n if (countryCode === 181) {\n const providerCode = readUint16(data, seiPtr);\n seiPtr += 2;\n\n if (providerCode === 49) {\n const userStructure = readUint32(data, seiPtr);\n seiPtr += 4;\n\n if (userStructure === 0x47413934) {\n const userDataType = data[seiPtr++];\n\n // Raw CEA-608 bytes wrapped in CEA-708 packet\n if (userDataType === 3) {\n const firstByte = data[seiPtr++];\n const totalCCs = 0x1f & firstByte;\n const enabled = 0x40 & firstByte;\n const totalBytes = enabled ? 2 + totalCCs * 3 : 0;\n const byteArray = new Uint8Array(totalBytes);\n if (enabled) {\n byteArray[0] = firstByte;\n for (let i = 1; i < totalBytes; i++) {\n byteArray[i] = data[seiPtr++];\n }\n }\n\n samples.push({\n type: userDataType,\n payloadType,\n pts,\n bytes: byteArray,\n });\n }\n }\n }\n }\n } else if (payloadType === 5 && payloadSize < leftOver) {\n endOfCaptions = true;\n\n if (payloadSize > 16) {\n const uuidStrArray: Array<string> = [];\n for (let i = 0; i < 16; i++) {\n const b = data[seiPtr++].toString(16);\n uuidStrArray.push(b.length == 1 ? '0' + b : b);\n\n if (i === 3 || i === 5 || i === 7 || i === 9) {\n uuidStrArray.push('-');\n }\n }\n const length = payloadSize - 16;\n const userDataBytes = new Uint8Array(length);\n for (let i = 0; i < length; i++) {\n userDataBytes[i] = data[seiPtr++];\n }\n\n samples.push({\n payloadType,\n pts,\n uuid: uuidStrArray.join(''),\n userData: utf8ArrayToStr(userDataBytes),\n userDataBytes,\n });\n }\n } else if (payloadSize < leftOver) {\n seiPtr += payloadSize;\n } else if (payloadSize > leftOver) {\n break;\n }\n }\n}\n\n/**\n * remove Emulation Prevention bytes from a RBSP\n */\nexport function discardEPB(data: Uint8Array): Uint8Array {\n const length = data.byteLength;\n const EPBPositions = [] as Array<number>;\n let i = 1;\n\n // Find all `Emulation Prevention Bytes`\n while (i < length - 2) {\n if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {\n EPBPositions.push(i + 2);\n i += 2;\n } else {\n i++;\n }\n }\n\n // If no Emulation Prevention Bytes were found just return the original\n // array\n if (EPBPositions.length === 0) {\n return data;\n }\n\n // Create a new array to hold the NAL unit data\n const newLength = length - EPBPositions.length;\n const newData = new Uint8Array(newLength);\n let sourceIndex = 0;\n\n for (i = 0; i < newLength; sourceIndex++, i++) {\n if (sourceIndex === EPBPositions[0]) {\n // Skip this byte\n sourceIndex++;\n // Remove this position index\n EPBPositions.shift();\n }\n newData[i] = data[sourceIndex];\n }\n return newData;\n}\n\nexport function parseEmsg(data: Uint8Array): IEmsgParsingData {\n const version = data[0];\n let schemeIdUri: string = '';\n let value: string = '';\n let timeScale: number = 0;\n let presentationTimeDelta: number = 0;\n let presentationTime: number = 0;\n let eventDuration: number = 0;\n let id: number = 0;\n let offset: number = 0;\n\n if (version === 0) {\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n timeScale = readUint32(data, 12);\n presentationTimeDelta = readUint32(data, 16);\n eventDuration = readUint32(data, 20);\n id = readUint32(data, 24);\n offset = 28;\n } else if (version === 1) {\n offset += 4;\n timeScale = readUint32(data, offset);\n offset += 4;\n const leftPresentationTime = readUint32(data, offset);\n offset += 4;\n const rightPresentationTime = readUint32(data, offset);\n offset += 4;\n presentationTime = 2 ** 32 * leftPresentationTime + rightPresentationTime;\n if (!Number.isSafeInteger(presentationTime)) {\n presentationTime = Number.MAX_SAFE_INTEGER;\n logger.warn(\n 'Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box'\n );\n }\n\n eventDuration = readUint32(data, offset);\n offset += 4;\n id = readUint32(data, offset);\n offset += 4;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n schemeIdUri += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n\n while (bin2str(data.subarray(offset, offset + 1)) !== '\\0') {\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n\n value += bin2str(data.subarray(offset, offset + 1));\n offset += 1;\n }\n const payload = data.subarray(offset, data.byteLength);\n\n return {\n schemeIdUri,\n value,\n timeScale,\n presentationTime,\n presentationTimeDelta,\n eventDuration,\n id,\n payload,\n };\n}\n\nexport function mp4Box(type: ArrayLike<number>, ...payload: Uint8Array[]) {\n const len = payload.length;\n let size = 8;\n let i = len;\n while (i--) {\n size += payload[i].byteLength;\n }\n const result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n for (i = 0, size = 8; i < len; i++) {\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n}\n\nexport function mp4pssh(\n systemId: Uint8Array,\n keyids: Array<Uint8Array> | null,\n data: Uint8Array\n) {\n if (systemId.byteLength !== 16) {\n throw new RangeError('Invalid system id');\n }\n let version;\n let kids;\n if (keyids) {\n version = 1;\n kids = new Uint8Array(keyids.length * 16);\n for (let ix = 0; ix < keyids.length; ix++) {\n const k = keyids[ix]; // uint8array\n if (k.byteLength !== 16) {\n throw new RangeError('Invalid key');\n }\n kids.set(k, ix * 16);\n }\n } else {\n version = 0;\n kids = new Uint8Array();\n }\n let kidCount;\n if (version > 0) {\n kidCount = new Uint8Array(4);\n if (keyids!.length > 0) {\n new DataView(kidCount.buffer).setUint32(0, keyids!.length, false);\n }\n } else {\n kidCount = new Uint8Array();\n }\n const dataSize = new Uint8Array(4);\n if (data && data.byteLength > 0) {\n new DataView(dataSize.buffer).setUint32(0, data.byteLength, false);\n }\n return mp4Box(\n [112, 115, 115, 104],\n new Uint8Array([\n version,\n 0x00,\n 0x00,\n 0x00, // Flags\n ]),\n systemId, // 16 bytes\n kidCount,\n kids,\n dataSize,\n data || new Uint8Array()\n );\n}\n\nexport function parsePssh(initData: ArrayBuffer) {\n if (!(initData instanceof ArrayBuffer) || initData.byteLength < 32) {\n return null;\n }\n const result = {\n version: 0,\n systemId: '',\n kids: null as null | Uint8Array[],\n data: null as null | Uint8Array,\n };\n const view = new DataView(initData);\n const boxSize = view.getUint32(0);\n if (initData.byteLength !== boxSize && boxSize > 44) {\n return null;\n }\n const type = view.getUint32(4);\n if (type !== 0x70737368) {\n return null;\n }\n result.version = view.getUint32(8) >>> 24;\n if (result.version > 1) {\n return null;\n }\n result.systemId = Hex.hexDump(new Uint8Array(initData, 12, 16));\n const dataSizeOrKidCount = view.getUint32(28);\n if (result.version === 0) {\n if (boxSize - 32 < dataSizeOrKidCount) {\n return null;\n }\n result.data = new Uint8Array(initData, 32, dataSizeOrKidCount);\n } else if (result.version === 1) {\n result.kids = [];\n for (let i = 0; i < dataSizeOrKidCount; i++) {\n result.kids.push(new Uint8Array(initData, 32 + i * 16, 16));\n }\n }\n return result;\n}\n","import {\n changeEndianness,\n convertDataUriToArrayBytes,\n} from '../utils/keysystem-util';\nimport { KeySystemFormats } from '../utils/mediakeys-helper';\nimport { mp4pssh } from '../utils/mp4-tools';\nimport { logger } from '../utils/logger';\nimport { base64Decode } from '../utils/numeric-encoding-utils';\n\nlet keyUriToKeyIdMap: { [uri: string]: Uint8Array } = {};\n\nexport interface DecryptData {\n uri: string;\n method: string;\n keyFormat: string;\n keyFormatVersions: number[];\n iv: Uint8Array | null;\n key: Uint8Array | null;\n keyId: Uint8Array | null;\n pssh: Uint8Array | null;\n encrypted: boolean;\n isCommonEncryption: boolean;\n}\n\nexport class LevelKey implements DecryptData {\n public readonly uri: string;\n public readonly method: string;\n public readonly keyFormat: string;\n public readonly keyFormatVersions: number[];\n public readonly encrypted: boolean;\n public readonly isCommonEncryption: boolean;\n public iv: Uint8Array | null = null;\n public key: Uint8Array | null = null;\n public keyId: Uint8Array | null = null;\n public pssh: Uint8Array | null = null;\n\n static clearKeyUriToKeyIdMap() {\n keyUriToKeyIdMap = {};\n }\n\n constructor(\n method: string,\n uri: string,\n format: string,\n formatversions: number[] = [1],\n iv: Uint8Array | null = null\n ) {\n this.method = method;\n this.uri = uri;\n this.keyFormat = format;\n this.keyFormatVersions = formatversions;\n this.iv = iv;\n this.encrypted = method ? method !== 'NONE' : false;\n this.isCommonEncryption = this.encrypted && method !== 'AES-128';\n }\n\n public isSupported(): boolean {\n // If it's Segment encryption or No encryption, just select that key system\n if (this.method) {\n if (this.method === 'AES-128' || this.method === 'NONE') {\n return true;\n }\n if (this.keyFormat === 'identity') {\n // Maintain support for clear SAMPLE-AES with MPEG-3 TS\n return this.method === 'SAMPLE-AES';\n } else if (__USE_EME_DRM__) {\n switch (this.keyFormat) {\n case KeySystemFormats.FAIRPLAY:\n case KeySystemFormats.WIDEVINE:\n case KeySystemFormats.PLAYREADY:\n case KeySystemFormats.CLEARKEY:\n return (\n [\n 'ISO-23001-7',\n 'SAMPLE-AES',\n 'SAMPLE-AES-CENC',\n 'SAMPLE-AES-CTR',\n ].indexOf(this.method) !== -1\n );\n }\n }\n }\n return false;\n }\n\n public getDecryptData(sn: number | 'initSegment'): LevelKey | null {\n if (!this.encrypted || !this.uri) {\n return null;\n }\n\n if (this.method === 'AES-128' && this.uri && !this.iv) {\n if (typeof sn !== 'number') {\n // We are fetching decryption data for a initialization segment\n // If the segment was encrypted with AES-128\n // It must have an IV defined. We cannot substitute the Segment Number in.\n if (this.method === 'AES-128' && !this.iv) {\n logger.warn(\n `missing IV for initialization segment with method=\"${this.method}\" - compliance issue`\n );\n }\n // Explicitly set sn to resulting value from implicit conversions 'initSegment' values for IV generation.\n sn = 0;\n }\n const iv = createInitializationVector(sn);\n const decryptdata = new LevelKey(\n this.method,\n this.uri,\n 'identity',\n this.keyFormatVersions,\n iv\n );\n return decryptdata;\n }\n\n if (!__USE_EME_DRM__) {\n return this;\n }\n\n // Initialize keyId if possible\n const keyBytes = convertDataUriToArrayBytes(this.uri);\n if (keyBytes) {\n switch (this.keyFormat) {\n case KeySystemFormats.WIDEVINE:\n this.pssh = keyBytes;\n // In case of widevine keyID is embedded in PSSH box. Read Key ID.\n if (keyBytes.length >= 22) {\n this.keyId = keyBytes.subarray(\n keyBytes.length - 22,\n keyBytes.length - 6\n );\n }\n break;\n case KeySystemFormats.PLAYREADY: {\n const PlayReadyKeySystemUUID = new Uint8Array([\n 0x9a, 0x04, 0xf0, 0x79, 0x98, 0x40, 0x42, 0x86, 0xab, 0x92, 0xe6,\n 0x5b, 0xe0, 0x88, 0x5f, 0x95,\n ]);\n\n this.pssh = mp4pssh(PlayReadyKeySystemUUID, null, keyBytes);\n\n const keyBytesUtf16 = new Uint16Array(\n keyBytes.buffer,\n keyBytes.byteOffset,\n keyBytes.byteLength / 2\n );\n const keyByteStr = String.fromCharCode.apply(\n null,\n Array.from(keyBytesUtf16)\n );\n\n // Parse Playready WRMHeader XML\n const xmlKeyBytes = keyByteStr.substring(\n keyByteStr.indexOf('<'),\n keyByteStr.length\n );\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(xmlKeyBytes, 'text/xml');\n const keyData = xmlDoc.getElementsByTagName('KID')[0];\n if (keyData) {\n const keyId = keyData.childNodes[0]\n ? keyData.childNodes[0].nodeValue\n : keyData.getAttribute('VALUE');\n if (keyId) {\n const keyIdArray = base64Decode(keyId).subarray(0, 16);\n // KID value in PRO is a base64-encoded little endian GUID interpretation of UUID\n // KID value in ‘tenc’ is a big endian UUID GUID interpretation of UUID\n changeEndianness(keyIdArray);\n this.keyId = keyIdArray;\n }\n }\n break;\n }\n default: {\n let keydata = keyBytes.subarray(0, 16);\n if (keydata.length !== 16) {\n const padded = new Uint8Array(16);\n padded.set(keydata, 16 - keydata.length);\n keydata = padded;\n }\n this.keyId = keydata;\n break;\n }\n }\n }\n\n // Default behavior: assign a new keyId for each uri\n if (!this.keyId || this.keyId.byteLength !== 16) {\n let keyId = keyUriToKeyIdMap[this.uri];\n if (!keyId) {\n const val =\n Object.keys(keyUriToKeyIdMap).length % Number.MAX_SAFE_INTEGER;\n keyId = new Uint8Array(16);\n const dv = new DataView(keyId.buffer, 12, 4); // Just set the last 4 bytes\n dv.setUint32(0, val);\n keyUriToKeyIdMap[this.uri] = keyId;\n }\n this.keyId = keyId;\n }\n\n return this;\n }\n}\n\nfunction createInitializationVector(segmentNumber: number): Uint8Array {\n const uint8View = new Uint8Array(16);\n for (let i = 12; i < 16; i++) {\n uint8View[i] = (segmentNumber >> (8 * (15 - i))) & 0xff;\n }\n return uint8View;\n}\n","import type { AttrList } from './attr-list';\nimport type { ParsedMultivariantPlaylist } from '../loader/m3u8-parser';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { VariableMap } from '../types/level';\n\nconst VARIABLE_REPLACEMENT_REGEX = /\\{\\$([a-zA-Z0-9-_]+)\\}/g;\n\nexport function hasVariableReferences(str: string): boolean {\n return VARIABLE_REPLACEMENT_REGEX.test(str);\n}\n\nexport function substituteVariablesInAttributes(\n parsed: Pick<\n ParsedMultivariantPlaylist | LevelDetails,\n 'variableList' | 'hasVariableRefs' | 'playlistParsingError'\n >,\n attr: AttrList,\n attributeNames: string[]\n) {\n if (parsed.variableList !== null || parsed.hasVariableRefs) {\n for (let i = attributeNames.length; i--; ) {\n const name = attributeNames[i];\n const value = attr[name];\n if (value) {\n attr[name] = substituteVariables(parsed, value);\n }\n }\n }\n}\n\nexport function substituteVariables(\n parsed: Pick<\n ParsedMultivariantPlaylist | LevelDetails,\n 'variableList' | 'hasVariableRefs' | 'playlistParsingError'\n >,\n value: string\n): string {\n if (parsed.variableList !== null || parsed.hasVariableRefs) {\n const variableList = parsed.variableList;\n return value.replace(\n VARIABLE_REPLACEMENT_REGEX,\n (variableReference: string) => {\n const variableName = variableReference.substring(\n 2,\n variableReference.length - 1\n );\n const variableValue = variableList?.[variableName];\n if (variableValue === undefined) {\n parsed.playlistParsingError ||= new Error(\n `Missing preceding EXT-X-DEFINE tag for Variable Reference: \"${variableName}\"`\n );\n return variableReference;\n }\n return variableValue;\n }\n );\n }\n return value;\n}\n\nexport function addVariableDefinition(\n parsed: Pick<\n ParsedMultivariantPlaylist | LevelDetails,\n 'variableList' | 'playlistParsingError'\n >,\n attr: AttrList,\n parentUrl: string\n) {\n let variableList = parsed.variableList;\n if (!variableList) {\n parsed.variableList = variableList = {};\n }\n let NAME: string;\n let VALUE;\n if ('QUERYPARAM' in attr) {\n NAME = attr.QUERYPARAM;\n try {\n const searchParams = new self.URL(parentUrl).searchParams;\n if (searchParams.has(NAME)) {\n VALUE = searchParams.get(NAME);\n } else {\n throw new Error(\n `\"${NAME}\" does not match any query parameter in URI: \"${parentUrl}\"`\n );\n }\n } catch (error) {\n parsed.playlistParsingError ||= new Error(\n `EXT-X-DEFINE QUERYPARAM: ${error.message}`\n );\n }\n } else {\n NAME = attr.NAME;\n VALUE = attr.VALUE;\n }\n if (NAME in variableList) {\n parsed.playlistParsingError ||= new Error(\n `EXT-X-DEFINE duplicate Variable Name declarations: \"${NAME}\"`\n );\n } else {\n variableList[NAME] = VALUE || '';\n }\n}\n\nexport function importVariableDefinition(\n parsed: Pick<\n ParsedMultivariantPlaylist | LevelDetails,\n 'variableList' | 'playlistParsingError'\n >,\n attr: AttrList,\n sourceVariableList: VariableMap | null\n) {\n const IMPORT = attr.IMPORT;\n if (sourceVariableList && IMPORT in sourceVariableList) {\n let variableList = parsed.variableList;\n if (!variableList) {\n parsed.variableList = variableList = {};\n }\n variableList[IMPORT] = sourceVariableList[IMPORT];\n } else {\n parsed.playlistParsingError ||= new Error(\n `EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: \"${IMPORT}\"`\n );\n }\n}\n","/**\n * MediaSource helper\n */\n\nexport function getMediaSource(): typeof MediaSource | undefined {\n if (typeof self === 'undefined') return undefined;\n return self.MediaSource || ((self as any).WebKitMediaSource as MediaSource);\n}\n","import { getMediaSource } from './mediasource-helper';\n\n// from http://mp4ra.org/codecs.html\nconst sampleEntryCodesISO = {\n audio: {\n a3ds: true,\n 'ac-3': true,\n 'ac-4': true,\n alac: true,\n alaw: true,\n dra1: true,\n 'dts+': true,\n 'dts-': true,\n dtsc: true,\n dtse: true,\n dtsh: true,\n 'ec-3': true,\n enca: true,\n g719: true,\n g726: true,\n m4ae: true,\n mha1: true,\n mha2: true,\n mhm1: true,\n mhm2: true,\n mlpa: true,\n mp4a: true,\n 'raw ': true,\n Opus: true,\n opus: true, // browsers expect this to be lowercase despite MP4RA says 'Opus'\n samr: true,\n sawb: true,\n sawp: true,\n sevc: true,\n sqcp: true,\n ssmv: true,\n twos: true,\n ulaw: true,\n },\n video: {\n avc1: true,\n avc2: true,\n avc3: true,\n avc4: true,\n avcp: true,\n av01: true,\n drac: true,\n dva1: true,\n dvav: true,\n dvh1: true,\n dvhe: true,\n encv: true,\n hev1: true,\n hvc1: true,\n mjp2: true,\n mp4v: true,\n mvc1: true,\n mvc2: true,\n mvc3: true,\n mvc4: true,\n resv: true,\n rv60: true,\n s263: true,\n svc1: true,\n svc2: true,\n 'vc-1': true,\n vp08: true,\n vp09: true,\n },\n text: {\n stpp: true,\n wvtt: true,\n },\n};\n\nconst MediaSource = getMediaSource();\n\nexport type CodecType = 'audio' | 'video';\n\nexport function isCodecType(codec: string, type: CodecType): boolean {\n const typeCodes = sampleEntryCodesISO[type];\n return !!typeCodes && typeCodes[codec.slice(0, 4)] === true;\n}\n\nexport function isCodecSupportedInMp4(codec: string, type: CodecType): boolean {\n return (\n MediaSource?.isTypeSupported(`${type || 'video'}/mp4;codecs=\"${codec}\"`) ??\n false\n );\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport { DateRange } from './date-range';\nimport { Fragment, Part } from './fragment';\nimport { LevelDetails } from './level-details';\nimport { LevelKey } from './level-key';\nimport { AttrList } from '../utils/attr-list';\nimport { logger } from '../utils/logger';\nimport {\n addVariableDefinition,\n hasVariableReferences,\n importVariableDefinition,\n substituteVariables,\n substituteVariablesInAttributes,\n} from '../utils/variable-substitution';\nimport { isCodecType } from '../utils/codecs';\nimport type { CodecType } from '../utils/codecs';\nimport type {\n MediaPlaylist,\n AudioGroup,\n MediaPlaylistType,\n MediaAttributes,\n} from '../types/media-playlist';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { LevelAttributes, LevelParsed, VariableMap } from '../types/level';\nimport type { ContentSteeringOptions } from '../types/events';\n\ntype M3U8ParserFragments = Array<Fragment | null>;\n\nexport type ParsedMultivariantPlaylist = {\n contentSteering: ContentSteeringOptions | null;\n levels: LevelParsed[];\n playlistParsingError: Error | null;\n sessionData: Record<string, AttrList> | null;\n sessionKeys: LevelKey[] | null;\n startTimeOffset: number | null;\n variableList: VariableMap | null;\n hasVariableRefs: boolean;\n};\n\ntype ParsedMultivariantMediaOptions = {\n AUDIO?: MediaPlaylist[];\n SUBTITLES?: MediaPlaylist[];\n 'CLOSED-CAPTIONS'?: MediaPlaylist[];\n};\n\nconst MASTER_PLAYLIST_REGEX =\n /#EXT-X-STREAM-INF:([^\\r\\n]*)(?:[\\r\\n](?:#[^\\r\\n]*)?)*([^\\r\\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\\r\\n]*)[\\r\\n]+/g;\nconst MASTER_PLAYLIST_MEDIA_REGEX = /#EXT-X-MEDIA:(.*)/g;\n\nconst IS_MEDIA_PLAYLIST = /^#EXT(?:INF|-X-TARGETDURATION):/m; // Handle empty Media Playlist (first EXTINF not signaled, but TARGETDURATION present)\n\nconst LEVEL_PLAYLIST_REGEX_FAST = new RegExp(\n [\n /#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?/.source, // duration (#EXTINF:<duration>,<title>), group 1 => duration, group 2 => title\n /(?!#) *(\\S[\\S ]*)/.source, // segment URI, group 3 => the URI (note newline is not eaten)\n /#EXT-X-BYTERANGE:*(.+)/.source, // next segment's byterange, group 4 => range spec (x@y)\n /#EXT-X-PROGRAM-DATE-TIME:(.+)/.source, // next segment's program date/time group 5 => the datetime spec\n /#.*/.source, // All other non-segment oriented tags will match with all groups empty\n ].join('|'),\n 'g'\n);\n\nconst LEVEL_PLAYLIST_REGEX_SLOW = new RegExp(\n [\n /#(EXTM3U)/.source,\n /#EXT-X-(DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/\n .source,\n /#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)/\n .source,\n /#EXT-X-(DISCONTINUITY|ENDLIST|GAP)/.source,\n /(#)([^:]*):(.*)/.source,\n /(#)(.*)(?:.*)\\r?\\n?/.source,\n ].join('|')\n);\n\nexport default class M3U8Parser {\n static findGroup(\n groups: Array<AudioGroup>,\n mediaGroupId: string\n ): AudioGroup | undefined {\n for (let i = 0; i < groups.length; i++) {\n const group = groups[i];\n if (group.id === mediaGroupId) {\n return group;\n }\n }\n }\n\n static convertAVC1ToAVCOTI(codec) {\n // Convert avc1 codec string from RFC-4281 to RFC-6381 for MediaSource.isTypeSupported\n const avcdata = codec.split('.');\n if (avcdata.length > 2) {\n let result = avcdata.shift() + '.';\n result += parseInt(avcdata.shift()).toString(16);\n result += ('000' + parseInt(avcdata.shift()).toString(16)).slice(-4);\n return result;\n }\n return codec;\n }\n\n static resolve(url, baseUrl) {\n return buildAbsoluteURL(baseUrl, url, { alwaysNormalize: true });\n }\n\n static isMediaPlaylist(str: string): boolean {\n return IS_MEDIA_PLAYLIST.test(str);\n }\n\n static parseMasterPlaylist(\n string: string,\n baseurl: string\n ): ParsedMultivariantPlaylist {\n const hasVariableRefs = __USE_VARIABLE_SUBSTITUTION__\n ? hasVariableReferences(string)\n : false;\n const parsed: ParsedMultivariantPlaylist = {\n contentSteering: null,\n levels: [],\n playlistParsingError: null,\n sessionData: null,\n sessionKeys: null,\n startTimeOffset: null,\n variableList: null,\n hasVariableRefs,\n };\n const levelsWithKnownCodecs: LevelParsed[] = [];\n\n MASTER_PLAYLIST_REGEX.lastIndex = 0;\n\n let result: RegExpExecArray | null;\n while ((result = MASTER_PLAYLIST_REGEX.exec(string)) != null) {\n if (result[1]) {\n // '#EXT-X-STREAM-INF' is found, parse level tag in group 1\n const attrs = new AttrList(result[1]) as LevelAttributes;\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, attrs, [\n 'CODECS',\n 'SUPPLEMENTAL-CODECS',\n 'ALLOWED-CPC',\n 'PATHWAY-ID',\n 'STABLE-VARIANT-ID',\n 'AUDIO',\n 'VIDEO',\n 'SUBTITLES',\n 'CLOSED-CAPTIONS',\n 'NAME',\n ]);\n }\n const uri = __USE_VARIABLE_SUBSTITUTION__\n ? substituteVariables(parsed, result[2])\n : result[2];\n const level: LevelParsed = {\n attrs,\n bitrate:\n attrs.decimalInteger('AVERAGE-BANDWIDTH') ||\n attrs.decimalInteger('BANDWIDTH'),\n name: attrs.NAME,\n url: M3U8Parser.resolve(uri, baseurl),\n };\n\n const resolution = attrs.decimalResolution('RESOLUTION');\n if (resolution) {\n level.width = resolution.width;\n level.height = resolution.height;\n }\n\n setCodecs(\n ((attrs.CODECS as string) || '').split(/[ ,]+/).filter((c) => c),\n level\n );\n\n if (level.videoCodec && level.videoCodec.indexOf('avc1') !== -1) {\n level.videoCodec = M3U8Parser.convertAVC1ToAVCOTI(level.videoCodec);\n }\n\n if (!level.unknownCodecs?.length) {\n levelsWithKnownCodecs.push(level);\n }\n\n parsed.levels.push(level);\n } else if (result[3]) {\n const tag = result[3];\n const attributes = result[4];\n switch (tag) {\n case 'SESSION-DATA': {\n // #EXT-X-SESSION-DATA\n const sessionAttrs = new AttrList(attributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, sessionAttrs, [\n 'DATA-ID',\n 'LANGUAGE',\n 'VALUE',\n 'URI',\n ]);\n }\n const dataId = sessionAttrs['DATA-ID'];\n if (dataId) {\n if (parsed.sessionData === null) {\n parsed.sessionData = {};\n }\n parsed.sessionData[dataId] = sessionAttrs;\n }\n break;\n }\n case 'SESSION-KEY': {\n // #EXT-X-SESSION-KEY\n const sessionKey = parseKey(attributes, baseurl, parsed);\n if (sessionKey.encrypted && sessionKey.isSupported()) {\n if (parsed.sessionKeys === null) {\n parsed.sessionKeys = [];\n }\n parsed.sessionKeys.push(sessionKey);\n } else {\n logger.warn(\n `[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: \"${attributes}\"`\n );\n }\n break;\n }\n case 'DEFINE': {\n // #EXT-X-DEFINE\n if (__USE_VARIABLE_SUBSTITUTION__) {\n const variableAttributes = new AttrList(attributes);\n substituteVariablesInAttributes(parsed, variableAttributes, [\n 'NAME',\n 'VALUE',\n 'QUERYPARAM',\n ]);\n addVariableDefinition(parsed, variableAttributes, baseurl);\n }\n break;\n }\n case 'CONTENT-STEERING': {\n // #EXT-X-CONTENT-STEERING\n const contentSteeringAttributes = new AttrList(attributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(\n parsed,\n contentSteeringAttributes,\n ['SERVER-URI', 'PATHWAY-ID']\n );\n }\n parsed.contentSteering = {\n uri: M3U8Parser.resolve(\n contentSteeringAttributes['SERVER-URI'],\n baseurl\n ),\n pathwayId: contentSteeringAttributes['PATHWAY-ID'] || '.',\n };\n break;\n }\n case 'START': {\n // #EXT-X-START\n parsed.startTimeOffset = parseStartTimeOffset(attributes);\n break;\n }\n default:\n break;\n }\n }\n }\n // Filter out levels with unknown codecs if it does not remove all levels\n const stripUnknownCodecLevels =\n levelsWithKnownCodecs.length > 0 &&\n levelsWithKnownCodecs.length < parsed.levels.length;\n\n parsed.levels = stripUnknownCodecLevels\n ? levelsWithKnownCodecs\n : parsed.levels;\n if (parsed.levels.length === 0) {\n parsed.playlistParsingError = new Error('no levels found in manifest');\n }\n\n return parsed;\n }\n\n static parseMasterPlaylistMedia(\n string: string,\n baseurl: string,\n parsed: ParsedMultivariantPlaylist\n ): ParsedMultivariantMediaOptions {\n let result: RegExpExecArray | null;\n const results: ParsedMultivariantMediaOptions = {};\n const levels = parsed.levels;\n const groupsByType = {\n AUDIO: levels.map((level: LevelParsed) => ({\n id: level.attrs.AUDIO,\n audioCodec: level.audioCodec,\n })),\n SUBTITLES: levels.map((level: LevelParsed) => ({\n id: level.attrs.SUBTITLES,\n textCodec: level.textCodec,\n })),\n 'CLOSED-CAPTIONS': [],\n };\n let id = 0;\n MASTER_PLAYLIST_MEDIA_REGEX.lastIndex = 0;\n while ((result = MASTER_PLAYLIST_MEDIA_REGEX.exec(string)) !== null) {\n const attrs = new AttrList(result[1]) as MediaAttributes;\n const type: MediaPlaylistType | undefined = attrs.TYPE as\n | MediaPlaylistType\n | undefined;\n if (type) {\n const groups = groupsByType[type];\n const medias: MediaPlaylist[] = results[type] || [];\n results[type] = medias;\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, attrs, [\n 'URI',\n 'GROUP-ID',\n 'LANGUAGE',\n 'ASSOC-LANGUAGE',\n 'STABLE-RENDITION-ID',\n 'NAME',\n 'INSTREAM-ID',\n 'CHARACTERISTICS',\n 'CHANNELS',\n ]);\n }\n const media: MediaPlaylist = {\n attrs,\n bitrate: 0,\n id: id++,\n groupId: attrs['GROUP-ID'] || '',\n instreamId: attrs['INSTREAM-ID'],\n name: attrs.NAME || attrs.LANGUAGE || '',\n type,\n default: attrs.bool('DEFAULT'),\n autoselect: attrs.bool('AUTOSELECT'),\n forced: attrs.bool('FORCED'),\n lang: attrs.LANGUAGE,\n url: attrs.URI ? M3U8Parser.resolve(attrs.URI, baseurl) : '',\n };\n\n if (groups?.length) {\n // If there are audio or text groups signalled in the manifest, let's look for a matching codec string for this track\n // If we don't find the track signalled, lets use the first audio groups codec we have\n // Acting as a best guess\n const groupCodec =\n M3U8Parser.findGroup(groups, media.groupId as string) || groups[0];\n assignCodec(media, groupCodec, 'audioCodec');\n assignCodec(media, groupCodec, 'textCodec');\n }\n\n medias.push(media);\n }\n }\n return results;\n }\n\n static parseLevelPlaylist(\n string: string,\n baseurl: string,\n id: number,\n type: PlaylistLevelType,\n levelUrlId: number,\n multivariantVariableList: VariableMap | null\n ): LevelDetails {\n const level = new LevelDetails(baseurl);\n const fragments: M3U8ParserFragments = level.fragments;\n // The most recent init segment seen (applies to all subsequent segments)\n let currentInitSegment: Fragment | null = null;\n let currentSN = 0;\n let currentPart = 0;\n let totalduration = 0;\n let discontinuityCounter = 0;\n let prevFrag: Fragment | null = null;\n let frag: Fragment = new Fragment(type, baseurl);\n let result: RegExpExecArray | RegExpMatchArray | null;\n let i: number;\n let levelkeys: { [key: string]: LevelKey } | undefined;\n let firstPdtIndex = -1;\n let createNextFrag = false;\n\n LEVEL_PLAYLIST_REGEX_FAST.lastIndex = 0;\n level.m3u8 = string;\n level.hasVariableRefs = __USE_VARIABLE_SUBSTITUTION__\n ? hasVariableReferences(string)\n : false;\n\n while ((result = LEVEL_PLAYLIST_REGEX_FAST.exec(string)) !== null) {\n if (createNextFrag) {\n createNextFrag = false;\n frag = new Fragment(type, baseurl);\n // setup the next fragment for part loading\n frag.start = totalduration;\n frag.sn = currentSN;\n frag.cc = discontinuityCounter;\n frag.level = id;\n if (currentInitSegment) {\n frag.initSegment = currentInitSegment;\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n currentInitSegment.rawProgramDateTime = null;\n }\n }\n\n const duration = result[1];\n if (duration) {\n // INF\n frag.duration = parseFloat(duration);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const title = (' ' + result[2]).slice(1);\n frag.title = title || null;\n frag.tagList.push(title ? ['INF', duration, title] : ['INF', duration]);\n } else if (result[3]) {\n // url\n if (Number.isFinite(frag.duration)) {\n frag.start = totalduration;\n if (levelkeys) {\n setFragLevelKeys(frag, levelkeys, level);\n }\n frag.sn = currentSN;\n frag.level = id;\n frag.cc = discontinuityCounter;\n frag.urlId = levelUrlId;\n fragments.push(frag);\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const uri = (' ' + result[3]).slice(1);\n frag.relurl = __USE_VARIABLE_SUBSTITUTION__\n ? substituteVariables(level, uri)\n : uri;\n assignProgramDateTime(frag, prevFrag);\n prevFrag = frag;\n totalduration += frag.duration;\n currentSN++;\n currentPart = 0;\n createNextFrag = true;\n }\n } else if (result[4]) {\n // X-BYTERANGE\n const data = (' ' + result[4]).slice(1);\n if (prevFrag) {\n frag.setByteRange(data, prevFrag);\n } else {\n frag.setByteRange(data);\n }\n } else if (result[5]) {\n // PROGRAM-DATE-TIME\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n frag.rawProgramDateTime = (' ' + result[5]).slice(1);\n frag.tagList.push(['PROGRAM-DATE-TIME', frag.rawProgramDateTime]);\n if (firstPdtIndex === -1) {\n firstPdtIndex = fragments.length;\n }\n } else {\n result = result[0].match(LEVEL_PLAYLIST_REGEX_SLOW);\n if (!result) {\n logger.warn('No matches on slow regex match for level playlist!');\n continue;\n }\n for (i = 1; i < result.length; i++) {\n if (typeof result[i] !== 'undefined') {\n break;\n }\n }\n\n // avoid sliced strings https://github.com/video-dev/hls.js/issues/939\n const tag = (' ' + result[i]).slice(1);\n const value1 = (' ' + result[i + 1]).slice(1);\n const value2 = result[i + 2] ? (' ' + result[i + 2]).slice(1) : '';\n\n switch (tag) {\n case 'PLAYLIST-TYPE':\n level.type = value1.toUpperCase();\n break;\n case 'MEDIA-SEQUENCE':\n currentSN = level.startSN = parseInt(value1);\n break;\n case 'SKIP': {\n const skipAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, skipAttrs, [\n 'RECENTLY-REMOVED-DATERANGES',\n ]);\n }\n const skippedSegments =\n skipAttrs.decimalInteger('SKIPPED-SEGMENTS');\n if (Number.isFinite(skippedSegments)) {\n level.skippedSegments = skippedSegments;\n // This will result in fragments[] containing undefined values, which we will fill in with `mergeDetails`\n for (let i = skippedSegments; i--; ) {\n fragments.unshift(null);\n }\n currentSN += skippedSegments;\n }\n const recentlyRemovedDateranges = skipAttrs.enumeratedString(\n 'RECENTLY-REMOVED-DATERANGES'\n );\n if (recentlyRemovedDateranges) {\n level.recentlyRemovedDateranges =\n recentlyRemovedDateranges.split('\\t');\n }\n break;\n }\n case 'TARGETDURATION':\n level.targetduration = Math.max(parseInt(value1), 1);\n break;\n case 'VERSION':\n level.version = parseInt(value1);\n break;\n case 'EXTM3U':\n break;\n case 'ENDLIST':\n level.live = false;\n break;\n case '#':\n if (value1 || value2) {\n frag.tagList.push(value2 ? [value1, value2] : [value1]);\n }\n break;\n case 'DISCONTINUITY':\n discontinuityCounter++;\n frag.tagList.push(['DIS']);\n break;\n case 'GAP':\n frag.gap = true;\n frag.tagList.push([tag]);\n break;\n case 'BITRATE':\n frag.tagList.push([tag, value1]);\n break;\n case 'DATERANGE': {\n const dateRangeAttr = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, dateRangeAttr, [\n 'ID',\n 'CLASS',\n 'START-DATE',\n 'END-DATE',\n 'SCTE35-CMD',\n 'SCTE35-OUT',\n 'SCTE35-IN',\n ]);\n substituteVariablesInAttributes(\n level,\n dateRangeAttr,\n dateRangeAttr.clientAttrs\n );\n }\n const dateRange = new DateRange(\n dateRangeAttr,\n level.dateRanges[dateRangeAttr.ID]\n );\n if (dateRange.isValid || level.skippedSegments) {\n level.dateRanges[dateRange.id] = dateRange;\n } else {\n logger.warn(`Ignoring invalid DATERANGE tag: \"${value1}\"`);\n }\n // Add to fragment tag list for backwards compatibility (< v1.2.0)\n frag.tagList.push(['EXT-X-DATERANGE', value1]);\n break;\n }\n case 'DEFINE': {\n if (__USE_VARIABLE_SUBSTITUTION__) {\n const variableAttributes = new AttrList(value1);\n substituteVariablesInAttributes(level, variableAttributes, [\n 'NAME',\n 'VALUE',\n 'IMPORT',\n 'QUERYPARAM',\n ]);\n if ('IMPORT' in variableAttributes) {\n importVariableDefinition(\n level,\n variableAttributes,\n multivariantVariableList\n );\n } else {\n addVariableDefinition(level, variableAttributes, baseurl);\n }\n }\n break;\n }\n\n case 'DISCONTINUITY-SEQUENCE':\n discontinuityCounter = parseInt(value1);\n break;\n case 'KEY': {\n const levelKey = parseKey(value1, baseurl, level);\n if (levelKey.isSupported()) {\n if (levelKey.method === 'NONE') {\n levelkeys = undefined;\n break;\n }\n if (!levelkeys) {\n levelkeys = {};\n }\n if (levelkeys[levelKey.keyFormat]) {\n levelkeys = Object.assign({}, levelkeys);\n }\n levelkeys[levelKey.keyFormat] = levelKey;\n } else {\n logger.warn(`[Keys] Ignoring invalid EXT-X-KEY tag: \"${value1}\"`);\n }\n break;\n }\n case 'START':\n level.startTimeOffset = parseStartTimeOffset(value1);\n break;\n case 'MAP': {\n const mapAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, mapAttrs, [\n 'BYTERANGE',\n 'URI',\n ]);\n }\n if (frag.duration) {\n // Initial segment tag is after segment duration tag.\n // #EXTINF: 6.0\n // #EXT-X-MAP:URI=\"init.mp4\n const init = new Fragment(type, baseurl);\n setInitSegment(init, mapAttrs, id, levelkeys);\n currentInitSegment = init;\n frag.initSegment = currentInitSegment;\n if (\n currentInitSegment.rawProgramDateTime &&\n !frag.rawProgramDateTime\n ) {\n frag.rawProgramDateTime = currentInitSegment.rawProgramDateTime;\n }\n } else {\n // Initial segment tag is before segment duration tag\n setInitSegment(frag, mapAttrs, id, levelkeys);\n currentInitSegment = frag;\n createNextFrag = true;\n }\n break;\n }\n case 'SERVER-CONTROL': {\n const serverControlAttrs = new AttrList(value1);\n level.canBlockReload = serverControlAttrs.bool('CAN-BLOCK-RELOAD');\n level.canSkipUntil = serverControlAttrs.optionalFloat(\n 'CAN-SKIP-UNTIL',\n 0\n );\n level.canSkipDateRanges =\n level.canSkipUntil > 0 &&\n serverControlAttrs.bool('CAN-SKIP-DATERANGES');\n level.partHoldBack = serverControlAttrs.optionalFloat(\n 'PART-HOLD-BACK',\n 0\n );\n level.holdBack = serverControlAttrs.optionalFloat('HOLD-BACK', 0);\n break;\n }\n case 'PART-INF': {\n const partInfAttrs = new AttrList(value1);\n level.partTarget = partInfAttrs.decimalFloatingPoint('PART-TARGET');\n break;\n }\n case 'PART': {\n let partList = level.partList;\n if (!partList) {\n partList = level.partList = [];\n }\n const previousFragmentPart =\n currentPart > 0 ? partList[partList.length - 1] : undefined;\n const index = currentPart++;\n const partAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, partAttrs, [\n 'BYTERANGE',\n 'URI',\n ]);\n }\n const part = new Part(\n partAttrs,\n frag,\n baseurl,\n index,\n previousFragmentPart\n );\n partList.push(part);\n frag.duration += part.duration;\n break;\n }\n case 'PRELOAD-HINT': {\n const preloadHintAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, preloadHintAttrs, ['URI']);\n }\n level.preloadHint = preloadHintAttrs;\n break;\n }\n case 'RENDITION-REPORT': {\n const renditionReportAttrs = new AttrList(value1);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(level, renditionReportAttrs, [\n 'URI',\n ]);\n }\n level.renditionReports = level.renditionReports || [];\n level.renditionReports.push(renditionReportAttrs);\n break;\n }\n default:\n logger.warn(`line parsed but not handled: ${result}`);\n break;\n }\n }\n }\n if (prevFrag && !prevFrag.relurl) {\n fragments.pop();\n totalduration -= prevFrag.duration;\n if (level.partList) {\n level.fragmentHint = prevFrag;\n }\n } else if (level.partList) {\n assignProgramDateTime(frag, prevFrag);\n frag.cc = discontinuityCounter;\n level.fragmentHint = frag;\n if (levelkeys) {\n setFragLevelKeys(frag, levelkeys, level);\n }\n }\n const fragmentLength = fragments.length;\n const firstFragment = fragments[0];\n const lastFragment = fragments[fragmentLength - 1];\n totalduration += level.skippedSegments * level.targetduration;\n if (totalduration > 0 && fragmentLength && lastFragment) {\n level.averagetargetduration = totalduration / fragmentLength;\n const lastSn = lastFragment.sn;\n level.endSN = lastSn !== 'initSegment' ? lastSn : 0;\n if (!level.live) {\n lastFragment.endList = true;\n }\n if (firstFragment) {\n level.startCC = firstFragment.cc;\n }\n } else {\n level.endSN = 0;\n level.startCC = 0;\n }\n if (level.fragmentHint) {\n totalduration += level.fragmentHint.duration;\n }\n level.totalduration = totalduration;\n level.endCC = discontinuityCounter;\n\n /**\n * Backfill any missing PDT values\n * \"If the first EXT-X-PROGRAM-DATE-TIME tag in a Playlist appears after\n * one or more Media Segment URIs, the client SHOULD extrapolate\n * backward from that tag (using EXTINF durations and/or media\n * timestamps) to associate dates with those segments.\"\n * We have already extrapolated forward, but all fragments up to the first instance of PDT do not have their PDTs\n * computed.\n */\n if (firstPdtIndex > 0) {\n backfillProgramDateTimes(fragments, firstPdtIndex);\n }\n\n return level;\n }\n}\n\nfunction parseKey(\n keyTagAttributes: string,\n baseurl: string,\n parsed: ParsedMultivariantPlaylist | LevelDetails\n): LevelKey {\n // https://tools.ietf.org/html/rfc8216#section-4.3.2.4\n const keyAttrs = new AttrList(keyTagAttributes);\n if (__USE_VARIABLE_SUBSTITUTION__) {\n substituteVariablesInAttributes(parsed, keyAttrs, [\n 'KEYFORMAT',\n 'KEYFORMATVERSIONS',\n 'URI',\n 'IV',\n 'URI',\n ]);\n }\n const decryptmethod = keyAttrs.METHOD ?? '';\n const decrypturi = keyAttrs.URI;\n const decryptiv = keyAttrs.hexadecimalInteger('IV');\n const decryptkeyformatversions = keyAttrs.KEYFORMATVERSIONS;\n // From RFC: This attribute is OPTIONAL; its absence indicates an implicit value of \"identity\".\n const decryptkeyformat = keyAttrs.KEYFORMAT ?? 'identity';\n\n if (decrypturi && keyAttrs.IV && !decryptiv) {\n logger.error(`Invalid IV: ${keyAttrs.IV}`);\n }\n // If decrypturi is a URI with a scheme, then baseurl will be ignored\n // No uri is allowed when METHOD is NONE\n const resolvedUri = decrypturi ? M3U8Parser.resolve(decrypturi, baseurl) : '';\n const keyFormatVersions = (\n decryptkeyformatversions ? decryptkeyformatversions : '1'\n )\n .split('/')\n .map(Number)\n .filter(Number.isFinite);\n\n return new LevelKey(\n decryptmethod,\n resolvedUri,\n decryptkeyformat,\n keyFormatVersions,\n decryptiv\n );\n}\n\nfunction parseStartTimeOffset(startAttributes: string): number | null {\n const startAttrs = new AttrList(startAttributes);\n const startTimeOffset = startAttrs.decimalFloatingPoint('TIME-OFFSET');\n if (Number.isFinite(startTimeOffset)) {\n return startTimeOffset;\n }\n return null;\n}\n\nfunction setCodecs(codecs: Array<string>, level: LevelParsed) {\n ['video', 'audio', 'text'].forEach((type: CodecType) => {\n const filtered = codecs.filter((codec) => isCodecType(codec, type));\n if (filtered.length) {\n const preferred = filtered.filter((codec) => {\n return (\n codec.lastIndexOf('avc1', 0) === 0 ||\n codec.lastIndexOf('mp4a', 0) === 0\n );\n });\n level[`${type}Codec`] = preferred.length > 0 ? preferred[0] : filtered[0];\n\n // remove from list\n codecs = codecs.filter((codec) => filtered.indexOf(codec) === -1);\n }\n });\n\n level.unknownCodecs = codecs;\n}\n\nfunction assignCodec(media, groupItem, codecProperty) {\n const codecValue = groupItem[codecProperty];\n if (codecValue) {\n media[codecProperty] = codecValue;\n }\n}\n\nfunction backfillProgramDateTimes(\n fragments: M3U8ParserFragments,\n firstPdtIndex: number\n) {\n let fragPrev = fragments[firstPdtIndex] as Fragment;\n for (let i = firstPdtIndex; i--; ) {\n const frag = fragments[i];\n // Exit on delta-playlist skipped segments\n if (!frag) {\n return;\n }\n frag.programDateTime =\n (fragPrev.programDateTime as number) - frag.duration * 1000;\n fragPrev = frag;\n }\n}\n\nfunction assignProgramDateTime(frag, prevFrag) {\n if (frag.rawProgramDateTime) {\n frag.programDateTime = Date.parse(frag.rawProgramDateTime);\n } else if (prevFrag?.programDateTime) {\n frag.programDateTime = prevFrag.endProgramDateTime;\n }\n\n if (!Number.isFinite(frag.programDateTime)) {\n frag.programDateTime = null;\n frag.rawProgramDateTime = null;\n }\n}\n\nfunction setInitSegment(\n frag: Fragment,\n mapAttrs: AttrList,\n id: number,\n levelkeys: { [key: string]: LevelKey } | undefined\n) {\n frag.relurl = mapAttrs.URI;\n if (mapAttrs.BYTERANGE) {\n frag.setByteRange(mapAttrs.BYTERANGE);\n }\n frag.level = id;\n frag.sn = 'initSegment';\n if (levelkeys) {\n frag.levelkeys = levelkeys;\n }\n frag.initSegment = null;\n}\n\nfunction setFragLevelKeys(\n frag: Fragment,\n levelkeys: { [key: string]: LevelKey },\n level: LevelDetails\n) {\n frag.levelkeys = levelkeys;\n const { encryptedFragments } = level;\n if (\n (!encryptedFragments.length ||\n encryptedFragments[encryptedFragments.length - 1].levelkeys !==\n levelkeys) &&\n Object.keys(levelkeys).some(\n (format) => levelkeys![format].isCommonEncryption\n )\n ) {\n encryptedFragments.push(frag);\n }\n}\n","import type { LoaderConfig } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\nimport type { KeyLoaderInfo } from '../loader/key-loader';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { HlsUrlParameters } from './level';\n\nexport interface LoaderContext {\n // target URL\n url: string;\n // loader response type (arraybuffer or default response type for playlist)\n responseType: string;\n // headers\n headers?: Record<string, string>;\n // start byte range offset\n rangeStart?: number;\n // end byte range offset\n rangeEnd?: number;\n // true if onProgress should report partial chunk of loaded content\n progressData?: boolean;\n}\n\nexport interface FragmentLoaderContext extends LoaderContext {\n frag: Fragment;\n part: Part | null;\n resetIV?: boolean;\n}\n\nexport interface KeyLoaderContext extends LoaderContext {\n keyInfo: KeyLoaderInfo;\n frag: Fragment;\n}\n\nexport interface LoaderConfiguration {\n // LoaderConfig policy that overrides required settings\n loadPolicy: LoaderConfig;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry maxNumRetry\n */\n // Max number of load retries\n maxRetry: number;\n /**\n * @deprecated use LoaderConfig maxTimeToFirstByteMs and maxLoadTimeMs\n */\n // Timeout after which `onTimeOut` callback will be triggered\n // when loading has not finished after that delay\n timeout: number;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry retryDelayMs\n */\n // Delay between an I/O error and following connection retry (ms).\n // This to avoid spamming the server\n retryDelay: number;\n /**\n * @deprecated use LoaderConfig timeoutRetry and errorRetry maxRetryDelayMs\n */\n // max connection retry delay (ms)\n maxRetryDelay: number;\n // When streaming progressively, this is the minimum chunk size required to emit a PROGRESS event\n highWaterMark?: number;\n}\n\nexport interface LoaderResponse {\n url: string;\n data?: string | ArrayBuffer | Object;\n // Errors can include HTTP status code and error message\n // Successful responses should include status code 200\n code?: number;\n text?: string;\n}\n\nexport interface LoaderStats {\n aborted: boolean;\n loaded: number;\n retry: number;\n total: number;\n chunkCount: number;\n bwEstimate: number;\n loading: HlsProgressivePerformanceTiming;\n parsing: HlsPerformanceTiming;\n buffering: HlsProgressivePerformanceTiming;\n}\n\nexport interface HlsPerformanceTiming {\n start: number;\n end: number;\n}\n\nexport interface HlsChunkPerformanceTiming extends HlsPerformanceTiming {\n executeStart: number;\n executeEnd: number;\n}\n\nexport interface HlsProgressivePerformanceTiming extends HlsPerformanceTiming {\n first: number;\n}\n\nexport type LoaderOnSuccess<T extends LoaderContext> = (\n response: LoaderResponse,\n stats: LoaderStats,\n context: T,\n networkDetails: any\n) => void;\n\nexport type LoaderOnProgress<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n data: string | ArrayBuffer,\n networkDetails: any\n) => void;\n\nexport type LoaderOnError<T extends LoaderContext> = (\n error: {\n // error status code\n code: number;\n // error description\n text: string;\n },\n context: T,\n networkDetails: any,\n stats: LoaderStats\n) => void;\n\nexport type LoaderOnTimeout<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n networkDetails: any\n) => void;\n\nexport type LoaderOnAbort<T extends LoaderContext> = (\n stats: LoaderStats,\n context: T,\n networkDetails: any\n) => void;\n\nexport interface LoaderCallbacks<T extends LoaderContext> {\n onSuccess: LoaderOnSuccess<T>;\n onError: LoaderOnError<T>;\n onTimeout: LoaderOnTimeout<T>;\n onAbort?: LoaderOnAbort<T>;\n onProgress?: LoaderOnProgress<T>;\n}\n\nexport interface Loader<T extends LoaderContext> {\n destroy(): void;\n abort(): void;\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<T>\n ): void;\n /**\n * `getCacheAge()` is called by hls.js to get the duration that a given object\n * has been sitting in a cache proxy when playing live. If implemented,\n * this should return a value in seconds.\n *\n * For HTTP based loaders, this should return the contents of the \"age\" header.\n *\n * @returns time object being lodaded\n */\n getCacheAge?: () => number | null;\n getResponseHeader?: (name: string) => string | null;\n context: T;\n stats: LoaderStats;\n}\n\nexport const enum PlaylistContextType {\n MANIFEST = 'manifest',\n LEVEL = 'level',\n AUDIO_TRACK = 'audioTrack',\n SUBTITLE_TRACK = 'subtitleTrack',\n}\n\nexport const enum PlaylistLevelType {\n MAIN = 'main',\n AUDIO = 'audio',\n SUBTITLE = 'subtitle',\n}\n\nexport interface PlaylistLoaderContext extends LoaderContext {\n type: PlaylistContextType;\n // the level index to load\n level: number | null;\n // level or track id from LevelLoadingData / TrackLoadingData\n id: number | null;\n // track group id\n groupId?: string;\n // internal representation of a parsed m3u8 level playlist\n levelDetails?: LevelDetails;\n // Blocking playlist request delivery directives (or null id none were added to playlist url\n deliveryDirectives: HlsUrlParameters | null;\n}\n","/**\n * PlaylistLoader - delegate for media manifest/playlist loading tasks. Takes care of parsing media to internal data-models.\n *\n * Once loaded, dispatches events with parsed data-models of manifest/levels/audio/subtitle tracks.\n *\n * Uses loader(s) set in config to do actual internal loading of resource tasks.\n */\n\nimport { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { logger } from '../utils/logger';\nimport M3U8Parser from './m3u8-parser';\nimport type { LevelParsed, VariableMap } from '../types/level';\nimport type {\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n LoaderResponse,\n LoaderStats,\n PlaylistLoaderContext,\n} from '../types/loader';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport { LevelDetails } from './level-details';\nimport { AttrList } from '../utils/attr-list';\nimport type Hls from '../hls';\nimport type {\n ErrorData,\n LevelLoadingData,\n ManifestLoadingData,\n TrackLoadingData,\n} from '../types/events';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { MediaAttributes } from '../types/media-playlist';\nimport type { LoaderConfig, RetryConfig } from '../config';\n\nfunction mapContextToLevelType(\n context: PlaylistLoaderContext\n): PlaylistLevelType {\n const { type } = context;\n\n switch (type) {\n case PlaylistContextType.AUDIO_TRACK:\n return PlaylistLevelType.AUDIO;\n case PlaylistContextType.SUBTITLE_TRACK:\n return PlaylistLevelType.SUBTITLE;\n default:\n return PlaylistLevelType.MAIN;\n }\n}\n\nfunction getResponseUrl(\n response: LoaderResponse,\n context: PlaylistLoaderContext\n): string {\n let url = response.url;\n // responseURL not supported on some browsers (it is used to detect URL redirection)\n // data-uri mode also not supported (but no need to detect redirection)\n if (url === undefined || url.indexOf('data:') === 0) {\n // fallback to initial URL\n url = context.url;\n }\n return url;\n}\n\nclass PlaylistLoader implements NetworkComponentAPI {\n private readonly hls: Hls;\n private readonly loaders: {\n [key: string]: Loader<LoaderContext>;\n } = Object.create(null);\n private variableList: VariableMap | null = null;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.registerListeners();\n }\n\n public startLoad(startPosition: number): void {}\n\n public stopLoad(): void {\n this.destroyInternalLoaders();\n }\n\n private registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n hls.on(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n }\n\n private unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.AUDIO_TRACK_LOADING, this.onAudioTrackLoading, this);\n hls.off(Events.SUBTITLE_TRACK_LOADING, this.onSubtitleTrackLoading, this);\n }\n\n /**\n * Returns defaults or configured loader-type overloads (pLoader and loader config params)\n */\n private createInternalLoader(\n context: PlaylistLoaderContext\n ): Loader<LoaderContext> {\n const config = this.hls.config;\n const PLoader = config.pLoader;\n const Loader = config.loader;\n const InternalLoader = PLoader || Loader;\n const loader = new InternalLoader(config) as Loader<PlaylistLoaderContext>;\n\n this.loaders[context.type] = loader;\n return loader;\n }\n\n private getInternalLoader(\n context: PlaylistLoaderContext\n ): Loader<LoaderContext> | undefined {\n return this.loaders[context.type];\n }\n\n private resetInternalLoader(contextType): void {\n if (this.loaders[contextType]) {\n delete this.loaders[contextType];\n }\n }\n\n /**\n * Call `destroy` on all internal loader instances mapped (one per context type)\n */\n private destroyInternalLoaders(): void {\n for (const contextType in this.loaders) {\n const loader = this.loaders[contextType];\n if (loader) {\n loader.destroy();\n }\n\n this.resetInternalLoader(contextType);\n }\n }\n\n public destroy(): void {\n this.variableList = null;\n this.unregisterListeners();\n this.destroyInternalLoaders();\n }\n\n private onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData\n ) {\n const { url } = data;\n this.variableList = null;\n this.load({\n id: null,\n level: 0,\n responseType: 'text',\n type: PlaylistContextType.MANIFEST,\n url,\n deliveryDirectives: null,\n });\n }\n\n private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {\n const { id, level, url, deliveryDirectives } = data;\n this.load({\n id,\n level,\n responseType: 'text',\n type: PlaylistContextType.LEVEL,\n url,\n deliveryDirectives,\n });\n }\n\n private onAudioTrackLoading(\n event: Events.AUDIO_TRACK_LOADING,\n data: TrackLoadingData\n ) {\n const { id, groupId, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.AUDIO_TRACK,\n url,\n deliveryDirectives,\n });\n }\n\n private onSubtitleTrackLoading(\n event: Events.SUBTITLE_TRACK_LOADING,\n data: TrackLoadingData\n ) {\n const { id, groupId, url, deliveryDirectives } = data;\n this.load({\n id,\n groupId,\n level: null,\n responseType: 'text',\n type: PlaylistContextType.SUBTITLE_TRACK,\n url,\n deliveryDirectives,\n });\n }\n\n private load(context: PlaylistLoaderContext): void {\n const config = this.hls.config;\n\n // logger.debug(`[playlist-loader]: Loading playlist of type ${context.type}, level: ${context.level}, id: ${context.id}`);\n\n // Check if a loader for this context already exists\n let loader = this.getInternalLoader(context);\n if (loader) {\n const loaderContext = loader.context;\n if (loaderContext && loaderContext.url === context.url) {\n // same URL can't overlap\n logger.trace('[playlist-loader]: playlist request ongoing');\n return;\n }\n logger.log(\n `[playlist-loader]: aborting previous loader for type: ${context.type}`\n );\n loader.abort();\n }\n\n // apply different configs for retries depending on\n // context (manifest, level, audio/subs playlist)\n let loadPolicy: LoaderConfig;\n if (context.type === PlaylistContextType.MANIFEST) {\n loadPolicy = config.manifestLoadPolicy.default;\n } else {\n loadPolicy = Object.assign({}, config.playlistLoadPolicy.default, {\n timeoutRetry: null,\n errorRetry: null,\n });\n }\n loader = this.createInternalLoader(context);\n\n // Override level/track timeout for LL-HLS requests\n // (the default of 10000ms is counter productive to blocking playlist reload requests)\n if (context.deliveryDirectives?.part) {\n let levelDetails: LevelDetails | undefined;\n if (\n context.type === PlaylistContextType.LEVEL &&\n context.level !== null\n ) {\n levelDetails = this.hls.levels[context.level].details;\n } else if (\n context.type === PlaylistContextType.AUDIO_TRACK &&\n context.id !== null\n ) {\n levelDetails = this.hls.audioTracks[context.id].details;\n } else if (\n context.type === PlaylistContextType.SUBTITLE_TRACK &&\n context.id !== null\n ) {\n levelDetails = this.hls.subtitleTracks[context.id].details;\n }\n if (levelDetails) {\n const partTarget = levelDetails.partTarget;\n const targetDuration = levelDetails.targetduration;\n if (partTarget && targetDuration) {\n const maxLowLatencyPlaylistRefresh =\n Math.max(partTarget * 3, targetDuration * 0.8) * 1000;\n loadPolicy = Object.assign({}, loadPolicy, {\n maxTimeToFirstByteMs: Math.min(\n maxLowLatencyPlaylistRefresh,\n loadPolicy.maxTimeToFirstByteMs\n ),\n maxLoadTimeMs: Math.min(\n maxLowLatencyPlaylistRefresh,\n loadPolicy.maxTimeToFirstByteMs\n ),\n });\n }\n }\n }\n\n const legacyRetryCompatibility: RetryConfig | Record<string, void> =\n loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: legacyRetryCompatibility.maxNumRetry || 0,\n retryDelay: legacyRetryCompatibility.retryDelayMs || 0,\n maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0,\n };\n\n const loaderCallbacks: LoaderCallbacks<PlaylistLoaderContext> = {\n onSuccess: (response, stats, context, networkDetails) => {\n const loader = this.getInternalLoader(context) as\n | Loader<PlaylistLoaderContext>\n | undefined;\n this.resetInternalLoader(context.type);\n\n const string = response.data as string;\n\n // Validate if it is an M3U8 at all\n if (string.indexOf('#EXTM3U') !== 0) {\n this.handleManifestParsingError(\n response,\n context,\n new Error('no EXTM3U delimiter'),\n networkDetails || null,\n stats\n );\n return;\n }\n\n stats.parsing.start = performance.now();\n if (M3U8Parser.isMediaPlaylist(string)) {\n this.handleTrackOrLevelPlaylist(\n response,\n stats,\n context,\n networkDetails || null,\n loader\n );\n } else {\n this.handleMasterPlaylist(response, stats, context, networkDetails);\n }\n },\n onError: (response, context, networkDetails, stats) => {\n this.handleNetworkError(\n context,\n networkDetails,\n false,\n response,\n stats\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.handleNetworkError(\n context,\n networkDetails,\n true,\n undefined,\n stats\n );\n },\n };\n\n // logger.debug(`[playlist-loader]: Calling internal loader delegate for URL: ${context.url}`);\n\n loader.load(context, loaderConfig, loaderCallbacks);\n }\n\n private handleMasterPlaylist(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any\n ): void {\n const hls = this.hls;\n const string = response.data as string;\n\n const url = getResponseUrl(response, context);\n\n const parsedResult = M3U8Parser.parseMasterPlaylist(string, url);\n\n if (parsedResult.playlistParsingError) {\n this.handleManifestParsingError(\n response,\n context,\n parsedResult.playlistParsingError,\n networkDetails,\n stats\n );\n return;\n }\n\n const {\n contentSteering,\n levels,\n sessionData,\n sessionKeys,\n startTimeOffset,\n variableList,\n } = parsedResult;\n\n this.variableList = variableList;\n\n const {\n AUDIO: audioTracks = [],\n SUBTITLES: subtitles,\n 'CLOSED-CAPTIONS': captions,\n } = M3U8Parser.parseMasterPlaylistMedia(string, url, parsedResult);\n\n if (audioTracks.length) {\n // check if we have found an audio track embedded in main playlist (audio track without URI attribute)\n const embeddedAudioFound: boolean = audioTracks.some(\n (audioTrack) => !audioTrack.url\n );\n\n // if no embedded audio track defined, but audio codec signaled in quality level,\n // we need to signal this main audio track this could happen with playlists with\n // alt audio rendition in which quality levels (main)\n // contains both audio+video. but with mixed audio track not signaled\n if (\n !embeddedAudioFound &&\n levels[0].audioCodec &&\n !levels[0].attrs.AUDIO\n ) {\n logger.log(\n '[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one'\n );\n audioTracks.unshift({\n type: 'main',\n name: 'main',\n groupId: 'main',\n default: false,\n autoselect: false,\n forced: false,\n id: -1,\n attrs: new AttrList({}) as MediaAttributes,\n bitrate: 0,\n url: '',\n });\n }\n }\n\n hls.trigger(Events.MANIFEST_LOADED, {\n levels,\n audioTracks,\n subtitles,\n captions,\n contentSteering,\n url,\n stats,\n networkDetails,\n sessionData,\n sessionKeys,\n startTimeOffset,\n variableList,\n });\n }\n\n private handleTrackOrLevelPlaylist(\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any,\n loader: Loader<PlaylistLoaderContext> | undefined\n ): void {\n const hls = this.hls;\n const { id, level, type } = context;\n\n const url = getResponseUrl(response, context);\n const levelUrlId = Number.isFinite(id as number) ? (id as number) : 0;\n const levelId = Number.isFinite(level as number)\n ? (level as number)\n : levelUrlId;\n const levelType = mapContextToLevelType(context);\n const levelDetails: LevelDetails = M3U8Parser.parseLevelPlaylist(\n response.data as string,\n url,\n levelId,\n levelType,\n levelUrlId,\n this.variableList\n );\n\n // We have done our first request (Manifest-type) and receive\n // not a master playlist but a chunk-list (track/level)\n // We fire the manifest-loaded event anyway with the parsed level-details\n // by creating a single-level structure for it.\n if (type === PlaylistContextType.MANIFEST) {\n const singleLevel: LevelParsed = {\n attrs: new AttrList({}),\n bitrate: 0,\n details: levelDetails,\n name: '',\n url,\n };\n\n hls.trigger(Events.MANIFEST_LOADED, {\n levels: [singleLevel],\n audioTracks: [],\n url,\n stats,\n networkDetails,\n sessionData: null,\n sessionKeys: null,\n contentSteering: null,\n startTimeOffset: null,\n variableList: null,\n });\n }\n\n // save parsing time\n stats.parsing.end = performance.now();\n\n // extend the context with the new levelDetails property\n context.levelDetails = levelDetails;\n\n this.handlePlaylistLoaded(\n levelDetails,\n response,\n stats,\n context,\n networkDetails,\n loader\n );\n }\n\n private handleManifestParsingError(\n response: LoaderResponse,\n context: PlaylistLoaderContext,\n error: Error,\n networkDetails: any,\n stats: LoaderStats\n ): void {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.MANIFEST_PARSING_ERROR,\n fatal: context.type === PlaylistContextType.MANIFEST,\n url: response.url,\n err: error,\n error,\n reason: error.message,\n response,\n context,\n networkDetails,\n stats,\n });\n }\n\n private handleNetworkError(\n context: PlaylistLoaderContext,\n networkDetails: any,\n timeout = false,\n response: { code: number; text: string } | undefined,\n stats: LoaderStats\n ): void {\n let message = `A network ${\n timeout\n ? 'timeout'\n : 'error' + (response ? ' (status ' + response.code + ')' : '')\n } occurred while loading ${context.type}`;\n if (context.type === PlaylistContextType.LEVEL) {\n message += `: ${context.level} id: ${context.id}`;\n } else if (\n context.type === PlaylistContextType.AUDIO_TRACK ||\n context.type === PlaylistContextType.SUBTITLE_TRACK\n ) {\n message += ` id: ${context.id} group-id: \"${context.groupId}\"`;\n }\n const error = new Error(message);\n logger.warn(`[playlist-loader]: ${message}`);\n let details = ErrorDetails.UNKNOWN;\n let fatal = false;\n\n const loader = this.getInternalLoader(context);\n\n switch (context.type) {\n case PlaylistContextType.MANIFEST:\n details = timeout\n ? ErrorDetails.MANIFEST_LOAD_TIMEOUT\n : ErrorDetails.MANIFEST_LOAD_ERROR;\n fatal = true;\n break;\n case PlaylistContextType.LEVEL:\n details = timeout\n ? ErrorDetails.LEVEL_LOAD_TIMEOUT\n : ErrorDetails.LEVEL_LOAD_ERROR;\n fatal = false;\n break;\n case PlaylistContextType.AUDIO_TRACK:\n details = timeout\n ? ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT\n : ErrorDetails.AUDIO_TRACK_LOAD_ERROR;\n fatal = false;\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n details = timeout\n ? ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT\n : ErrorDetails.SUBTITLE_LOAD_ERROR;\n fatal = false;\n break;\n }\n\n if (loader) {\n this.resetInternalLoader(context.type);\n }\n\n const errorData: ErrorData = {\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal,\n url: context.url,\n loader,\n context,\n error,\n networkDetails,\n stats,\n };\n\n if (response) {\n const url = networkDetails?.url || context.url;\n errorData.response = { url, data: undefined as any, ...response };\n }\n\n this.hls.trigger(Events.ERROR, errorData);\n }\n\n private handlePlaylistLoaded(\n levelDetails: LevelDetails,\n response: LoaderResponse,\n stats: LoaderStats,\n context: PlaylistLoaderContext,\n networkDetails: any,\n loader: Loader<PlaylistLoaderContext> | undefined\n ): void {\n const hls = this.hls;\n const { type, level, id, groupId, deliveryDirectives } = context;\n const url = getResponseUrl(response, context);\n const parent = mapContextToLevelType(context);\n const levelIndex =\n typeof context.level === 'number' && parent === PlaylistLevelType.MAIN\n ? (level as number)\n : undefined;\n if (!levelDetails.fragments.length) {\n const error = new Error('No Segments found in Playlist');\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_EMPTY_ERROR,\n fatal: false,\n url,\n error,\n reason: error.message,\n response,\n context,\n level: levelIndex,\n parent,\n networkDetails,\n stats,\n });\n return;\n }\n if (!levelDetails.targetduration) {\n levelDetails.playlistParsingError = new Error('Missing Target Duration');\n }\n const error = levelDetails.playlistParsingError;\n if (error) {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.LEVEL_PARSING_ERROR,\n fatal: false,\n url,\n error,\n reason: error.message,\n response,\n context,\n level: levelIndex,\n parent,\n networkDetails,\n stats,\n });\n return;\n }\n\n if (levelDetails.live && loader) {\n if (loader.getCacheAge) {\n levelDetails.ageHeader = loader.getCacheAge() || 0;\n }\n if (!loader.getCacheAge || isNaN(levelDetails.ageHeader)) {\n levelDetails.ageHeader = 0;\n }\n }\n\n switch (type) {\n case PlaylistContextType.MANIFEST:\n case PlaylistContextType.LEVEL:\n hls.trigger(Events.LEVEL_LOADED, {\n details: levelDetails,\n level: levelIndex || 0,\n id: id || 0,\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n case PlaylistContextType.AUDIO_TRACK:\n hls.trigger(Events.AUDIO_TRACK_LOADED, {\n details: levelDetails,\n id: id || 0,\n groupId: groupId || '',\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n case PlaylistContextType.SUBTITLE_TRACK:\n hls.trigger(Events.SUBTITLE_TRACK_LOADED, {\n details: levelDetails,\n id: id || 0,\n groupId: groupId || '',\n stats,\n networkDetails,\n deliveryDirectives,\n });\n break;\n }\n }\n}\n\nexport default PlaylistLoader;\n","import { logger } from './logger';\n\nexport function sendAddTrackEvent(track: TextTrack, videoEl: HTMLMediaElement) {\n let event: Event;\n try {\n event = new Event('addtrack');\n } catch (err) {\n // for IE11\n event = document.createEvent('Event');\n event.initEvent('addtrack', false, false);\n }\n (event as any).track = track;\n videoEl.dispatchEvent(event);\n}\n\nexport function addCueToTrack(track: TextTrack, cue: VTTCue) {\n // Sometimes there are cue overlaps on segmented vtts so the same\n // cue can appear more than once in different vtt files.\n // This avoid showing duplicated cues with same timecode and text.\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues && !track.cues.getCueById(cue.id)) {\n try {\n track.addCue(cue);\n if (!track.cues.getCueById(cue.id)) {\n throw new Error(`addCue is failed for: ${cue}`);\n }\n } catch (err) {\n logger.debug(`[texttrack-utils]: ${err}`);\n try {\n const textTrackCue = new (self.TextTrackCue as any)(\n cue.startTime,\n cue.endTime,\n cue.text\n );\n textTrackCue.id = cue.id;\n track.addCue(textTrackCue);\n } catch (err2) {\n logger.debug(\n `[texttrack-utils]: Legacy TextTrackCue fallback failed: ${err2}`\n );\n }\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\nexport function clearCurrentCues(track: TextTrack) {\n // When track.mode is disabled, track.cues will be null.\n // To guarantee the removal of cues, we need to temporarily\n // change the mode to hidden\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n if (track.cues) {\n for (let i = track.cues.length; i--; ) {\n track.removeCue(track.cues[i]);\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\nexport function removeCuesInRange(\n track: TextTrack,\n start: number,\n end: number,\n predicate?: (cue: TextTrackCue) => boolean\n) {\n const mode = track.mode;\n if (mode === 'disabled') {\n track.mode = 'hidden';\n }\n\n if (track.cues && track.cues.length > 0) {\n const cues = getCuesInRange(track.cues, start, end);\n for (let i = 0; i < cues.length; i++) {\n if (!predicate || predicate(cues[i])) {\n track.removeCue(cues[i]);\n }\n }\n }\n if (mode === 'disabled') {\n track.mode = mode;\n }\n}\n\n// Find first cue starting after given time.\n// Modified version of binary search O(log(n)).\nfunction getFirstCueIndexAfterTime(\n cues: TextTrackCueList | TextTrackCue[],\n time: number\n): number {\n // If first cue starts after time, start there\n if (time < cues[0].startTime) {\n return 0;\n }\n // If the last cue ends before time there is no overlap\n const len = cues.length - 1;\n if (time > cues[len].endTime) {\n return -1;\n }\n\n let left = 0;\n let right = len;\n\n while (left <= right) {\n const mid = Math.floor((right + left) / 2);\n\n if (time < cues[mid].startTime) {\n right = mid - 1;\n } else if (time > cues[mid].startTime && left < len) {\n left = mid + 1;\n } else {\n // If it's not lower or higher, it must be equal.\n return mid;\n }\n }\n // At this point, left and right have swapped.\n // No direct match was found, left or right element must be the closest. Check which one has the smallest diff.\n return cues[left].startTime - time < time - cues[right].startTime\n ? left\n : right;\n}\n\nexport function getCuesInRange(\n cues: TextTrackCueList | TextTrackCue[],\n start: number,\n end: number\n): TextTrackCue[] {\n const cuesFound: TextTrackCue[] = [];\n const firstCueInRange = getFirstCueIndexAfterTime(cues, start);\n if (firstCueInRange > -1) {\n for (let i = firstCueInRange, len = cues.length; i < len; i++) {\n const cue = cues[i];\n if (cue.startTime >= start && cue.endTime <= end) {\n cuesFound.push(cue);\n } else if (cue.startTime > end) {\n return cuesFound;\n }\n }\n }\n return cuesFound;\n}\n","import type { RationalTimestamp } from '../utils/timescale-conversion';\n\nexport interface Demuxer {\n demux(\n data: Uint8Array,\n timeOffset: number,\n isSampleAes?: boolean,\n flush?: boolean\n ): DemuxerResult;\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number\n ): Promise<DemuxerResult>;\n flush(timeOffset?: number): DemuxerResult | Promise<DemuxerResult>;\n destroy(): void;\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number\n );\n resetTimeStamp(defaultInitPTS?: RationalTimestamp | null): void;\n resetContiguity(): void;\n}\n\nexport interface DemuxerResult {\n audioTrack: DemuxedAudioTrack;\n videoTrack: DemuxedVideoTrack;\n id3Track: DemuxedMetadataTrack;\n textTrack: DemuxedUserdataTrack;\n}\n\nexport interface DemuxedTrack {\n type: string;\n id: number;\n pid: number;\n inputTimeScale: number;\n sequenceNumber: number;\n samples:\n | AudioSample[]\n | AvcSample[]\n | MetadataSample[]\n | UserdataSample[]\n | Uint8Array;\n timescale?: number;\n container?: string;\n dropped: number;\n duration?: number;\n pesData?: ElementaryStreamData | null;\n codec?: string;\n}\n\nexport interface PassthroughTrack extends DemuxedTrack {\n sampleDuration: number;\n samples: Uint8Array;\n timescale: number;\n duration: number;\n codec: string;\n}\nexport interface DemuxedAudioTrack extends DemuxedTrack {\n config?: number[];\n samplerate?: number;\n segmentCodec?: string;\n channelCount?: number;\n manifestCodec?: string;\n samples: AudioSample[];\n}\n\nexport interface DemuxedVideoTrack extends DemuxedTrack {\n width?: number;\n height?: number;\n pixelRatio?: [number, number];\n audFound?: boolean;\n pps?: Uint8Array[];\n sps?: Uint8Array[];\n naluState?: number;\n samples: AvcSample[] | Uint8Array;\n}\n\nexport interface DemuxedAvcTrack extends DemuxedVideoTrack {\n samples: AvcSample[];\n}\n\nexport interface DemuxedMetadataTrack extends DemuxedTrack {\n samples: MetadataSample[];\n}\n\nexport interface DemuxedUserdataTrack extends DemuxedTrack {\n samples: UserdataSample[];\n}\n\nexport const enum MetadataSchema {\n audioId3 = 'org.id3',\n dateRange = 'com.apple.quicktime.HLS',\n emsg = 'https://aomedia.org/emsg/ID3',\n}\nexport interface MetadataSample {\n pts: number;\n dts: number;\n duration: number;\n len?: number;\n data: Uint8Array;\n type: MetadataSchema;\n}\n\nexport interface UserdataSample {\n pts: number;\n bytes?: Uint8Array;\n type?: number;\n payloadType?: number;\n uuid?: string;\n userData?: string;\n userDataBytes?: Uint8Array;\n}\n\nexport interface AvcSample {\n dts: number;\n pts: number;\n key: boolean;\n frame: boolean;\n units: AvcSampleUnit[];\n debug: string;\n length: number;\n}\n\nexport interface AvcSampleUnit {\n data: Uint8Array;\n type: number;\n}\n\nexport type AudioSample = {\n unit: Uint8Array;\n pts: number;\n};\n\nexport type AudioFrame = {\n sample: AudioSample;\n length: number;\n missing: number;\n};\n\nexport interface ElementaryStreamData {\n data: Uint8Array[];\n size: number;\n}\n\nexport interface KeyData {\n method: string;\n key: Uint8Array;\n iv: Uint8Array;\n}\n","import { Events } from '../events';\nimport {\n sendAddTrackEvent,\n clearCurrentCues,\n removeCuesInRange,\n} from '../utils/texttrack-utils';\nimport * as ID3 from '../demux/id3';\nimport {\n DateRange,\n isDateRangeCueAttribute,\n isSCTE35Attribute,\n} from '../loader/date-range';\nimport { MetadataSchema } from '../types/demuxer';\nimport type {\n BufferFlushingData,\n FragParsingMetadataData,\n LevelUpdatedData,\n MediaAttachedData,\n} from '../types/events';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\n\ndeclare global {\n interface Window {\n WebKitDataCue: VTTCue | void;\n }\n}\n\nconst MIN_CUE_DURATION = 0.25;\n\nfunction getCueClass(): typeof VTTCue | typeof TextTrackCue | undefined {\n if (typeof self === 'undefined') return undefined;\n return self.VTTCue || self.TextTrackCue;\n}\n\nfunction createCueWithDataFields(\n Cue: typeof VTTCue | typeof TextTrackCue,\n startTime: number,\n endTime: number,\n data: Object,\n type?: string\n): VTTCue | TextTrackCue | undefined {\n let cue = new Cue(startTime, endTime, '');\n try {\n (cue as any).value = data;\n if (type) {\n (cue as any).type = type;\n }\n } catch (e) {\n cue = new Cue(\n startTime,\n endTime,\n JSON.stringify(type ? { type, ...data } : data)\n );\n }\n return cue;\n}\n\n// VTTCue latest draft allows an infinite duration, fallback\n// to MAX_VALUE if necessary\nconst MAX_CUE_ENDTIME = (() => {\n const Cue = getCueClass();\n try {\n Cue && new Cue(0, Number.POSITIVE_INFINITY, '');\n } catch (e) {\n return Number.MAX_VALUE;\n }\n return Number.POSITIVE_INFINITY;\n})();\n\nfunction dateRangeDateToTimelineSeconds(date: Date, offset: number): number {\n return date.getTime() / 1000 - offset;\n}\n\nfunction hexToArrayBuffer(str): ArrayBuffer {\n return Uint8Array.from(\n str\n .replace(/^0x/, '')\n .replace(/([\\da-fA-F]{2}) ?/g, '0x$1 ')\n .replace(/ +$/, '')\n .split(' ')\n ).buffer;\n}\nclass ID3TrackController implements ComponentAPI {\n private hls: Hls;\n private id3Track: TextTrack | null = null;\n private media: HTMLMediaElement | null = null;\n private dateRangeCuesAppended: Record<\n string,\n {\n cues: Record<string, VTTCue | TextTrackCue>;\n dateRange: DateRange;\n durationKnown: boolean;\n }\n > = {};\n\n constructor(hls) {\n this.hls = hls;\n this._registerListeners();\n }\n\n destroy() {\n this._unregisterListeners();\n this.id3Track = null;\n this.media = null;\n this.dateRangeCuesAppended = {};\n // @ts-ignore\n this.hls = null;\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.FRAG_PARSING_METADATA, this.onFragParsingMetadata, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n // Add ID3 metatadata text track.\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ): void {\n this.media = data.media;\n }\n\n protected onMediaDetaching(): void {\n if (!this.id3Track) {\n return;\n }\n clearCurrentCues(this.id3Track);\n this.id3Track = null;\n this.media = null;\n this.dateRangeCuesAppended = {};\n }\n\n private onManifestLoading() {\n this.dateRangeCuesAppended = {};\n }\n\n createTrack(media: HTMLMediaElement): TextTrack {\n const track = this.getID3Track(media.textTracks) as TextTrack;\n track.mode = 'hidden';\n return track;\n }\n\n getID3Track(textTracks: TextTrackList): TextTrack | void {\n if (!this.media) {\n return;\n }\n for (let i = 0; i < textTracks.length; i++) {\n const textTrack: TextTrack = textTracks[i];\n if (textTrack.kind === 'metadata' && textTrack.label === 'id3') {\n // send 'addtrack' when reusing the textTrack for metadata,\n // same as what we do for captions\n sendAddTrackEvent(textTrack, this.media);\n\n return textTrack;\n }\n }\n return this.media.addTextTrack('metadata', 'id3');\n }\n\n onFragParsingMetadata(\n event: Events.FRAG_PARSING_METADATA,\n data: FragParsingMetadataData\n ) {\n if (!this.media) {\n return;\n }\n\n const {\n hls: {\n config: { enableEmsgMetadataCues, enableID3MetadataCues },\n },\n } = this;\n if (!enableEmsgMetadataCues && !enableID3MetadataCues) {\n return;\n }\n\n const { samples } = data;\n\n // create track dynamically\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n\n const Cue = getCueClass();\n if (!Cue) {\n return;\n }\n\n for (let i = 0; i < samples.length; i++) {\n const type = samples[i].type;\n if (\n (type === MetadataSchema.emsg && !enableEmsgMetadataCues) ||\n !enableID3MetadataCues\n ) {\n continue;\n }\n\n const frames = ID3.getID3Frames(samples[i].data);\n if (frames) {\n const startTime = samples[i].pts;\n let endTime: number = startTime + samples[i].duration;\n\n if (endTime > MAX_CUE_ENDTIME) {\n endTime = MAX_CUE_ENDTIME;\n }\n\n const timeDiff = endTime - startTime;\n if (timeDiff <= 0) {\n endTime = startTime + MIN_CUE_DURATION;\n }\n\n for (let j = 0; j < frames.length; j++) {\n const frame = frames[j];\n // Safari doesn't put the timestamp frame in the TextTrack\n if (!ID3.isTimeStampFrame(frame)) {\n // add a bounds to any unbounded cues\n this.updateId3CueEnds(startTime, type);\n const cue = createCueWithDataFields(\n Cue,\n startTime,\n endTime,\n frame,\n type\n );\n if (cue) {\n this.id3Track.addCue(cue);\n }\n }\n }\n }\n }\n }\n\n updateId3CueEnds(startTime: number, type: MetadataSchema) {\n const cues = this.id3Track?.cues;\n if (cues) {\n for (let i = cues.length; i--; ) {\n const cue = cues[i] as any;\n if (\n cue.type === type &&\n cue.startTime < startTime &&\n cue.endTime === MAX_CUE_ENDTIME\n ) {\n cue.endTime = startTime;\n }\n }\n }\n }\n\n onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n { startOffset, endOffset, type }: BufferFlushingData\n ) {\n const { id3Track, hls } = this;\n if (!hls) {\n return;\n }\n\n const {\n config: { enableEmsgMetadataCues, enableID3MetadataCues },\n } = hls;\n if (id3Track && (enableEmsgMetadataCues || enableID3MetadataCues)) {\n let predicate;\n\n if (type === 'audio') {\n predicate = (cue) =>\n (cue as any).type === MetadataSchema.audioId3 &&\n enableID3MetadataCues;\n } else if (type === 'video') {\n predicate = (cue) =>\n (cue as any).type === MetadataSchema.emsg && enableEmsgMetadataCues;\n } else {\n predicate = (cue) =>\n ((cue as any).type === MetadataSchema.audioId3 &&\n enableID3MetadataCues) ||\n ((cue as any).type === MetadataSchema.emsg && enableEmsgMetadataCues);\n }\n removeCuesInRange(id3Track, startOffset, endOffset, predicate);\n }\n }\n\n onLevelUpdated(event: Events.LEVEL_UPDATED, { details }: LevelUpdatedData) {\n if (\n !this.media ||\n !details.hasProgramDateTime ||\n !this.hls.config.enableDateRangeMetadataCues\n ) {\n return;\n }\n const { dateRangeCuesAppended, id3Track } = this;\n const { dateRanges } = details;\n const ids = Object.keys(dateRanges);\n // Remove cues from track not found in details.dateRanges\n if (id3Track) {\n const idsToRemove = Object.keys(dateRangeCuesAppended).filter(\n (id) => !ids.includes(id)\n );\n for (let i = idsToRemove.length; i--; ) {\n const id = idsToRemove[i];\n Object.keys(dateRangeCuesAppended[id].cues).forEach((key) => {\n id3Track.removeCue(dateRangeCuesAppended[id].cues[key]);\n });\n delete dateRangeCuesAppended[id];\n }\n }\n // Exit if the playlist does not have Date Ranges or does not have Program Date Time\n const lastFragment = details.fragments[details.fragments.length - 1];\n if (ids.length === 0 || !Number.isFinite(lastFragment?.programDateTime)) {\n return;\n }\n\n if (!this.id3Track) {\n this.id3Track = this.createTrack(this.media);\n }\n\n const dateTimeOffset =\n (lastFragment.programDateTime as number) / 1000 - lastFragment.start;\n const Cue = getCueClass();\n\n for (let i = 0; i < ids.length; i++) {\n const id = ids[i];\n const dateRange = dateRanges[id];\n const appendedDateRangeCues = dateRangeCuesAppended[id];\n const cues = appendedDateRangeCues?.cues || {};\n let durationKnown = appendedDateRangeCues?.durationKnown || false;\n const startTime = dateRangeDateToTimelineSeconds(\n dateRange.startDate,\n dateTimeOffset\n );\n let endTime = MAX_CUE_ENDTIME;\n const endDate = dateRange.endDate;\n if (endDate) {\n endTime = dateRangeDateToTimelineSeconds(endDate, dateTimeOffset);\n durationKnown = true;\n } else if (dateRange.endOnNext && !durationKnown) {\n const nextDateRangeWithSameClass = ids\n .reduce((filterMapArray, id) => {\n const candidate = dateRanges[id];\n if (\n candidate.class === dateRange.class &&\n candidate.id !== id &&\n candidate.startDate > dateRange.startDate\n ) {\n filterMapArray.push(candidate);\n }\n return filterMapArray;\n }, [] as DateRange[])\n .sort((a, b) => a.startDate.getTime() - b.startDate.getTime())[0];\n if (nextDateRangeWithSameClass) {\n endTime = dateRangeDateToTimelineSeconds(\n nextDateRangeWithSameClass.startDate,\n dateTimeOffset\n );\n durationKnown = true;\n }\n }\n\n const attributes = Object.keys(dateRange.attr);\n for (let j = 0; j < attributes.length; j++) {\n const key = attributes[j];\n if (!isDateRangeCueAttribute(key)) {\n continue;\n }\n const cue = cues[key];\n if (cue) {\n if (durationKnown && !appendedDateRangeCues.durationKnown) {\n cue.endTime = endTime;\n }\n } else if (Cue) {\n let data = dateRange.attr[key];\n if (isSCTE35Attribute(key)) {\n data = hexToArrayBuffer(data);\n }\n const cue = createCueWithDataFields(\n Cue,\n startTime,\n endTime,\n { key, data },\n MetadataSchema.dateRange\n );\n if (cue) {\n cue.id = id;\n this.id3Track.addCue(cue);\n cues[key] = cue;\n }\n }\n }\n dateRangeCuesAppended[id] = {\n cues,\n dateRange,\n durationKnown,\n };\n }\n }\n}\n\nexport default ID3TrackController;\n","import { LevelDetails } from '../loader/level-details';\nimport { ErrorDetails } from '../errors';\nimport { Events } from '../events';\nimport type {\n ErrorData,\n LevelUpdatedData,\n MediaAttachingData,\n} from '../types/events';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\n\nexport default class LatencyController implements ComponentAPI {\n private hls: Hls;\n private readonly config: HlsConfig;\n private media: HTMLMediaElement | null = null;\n private levelDetails: LevelDetails | null = null;\n private currentTime: number = 0;\n private stallCount: number = 0;\n private _latency: number | null = null;\n private timeupdateHandler = () => this.timeupdate();\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.registerListeners();\n }\n\n get latency(): number {\n return this._latency || 0;\n }\n\n get maxLatency(): number {\n const { config, levelDetails } = this;\n if (config.liveMaxLatencyDuration !== undefined) {\n return config.liveMaxLatencyDuration;\n }\n return levelDetails\n ? config.liveMaxLatencyDurationCount * levelDetails.targetduration\n : 0;\n }\n\n get targetLatency(): number | null {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return null;\n }\n const { holdBack, partHoldBack, targetduration } = levelDetails;\n const { liveSyncDuration, liveSyncDurationCount, lowLatencyMode } =\n this.config;\n const userConfig = this.hls.userConfig;\n let targetLatency = lowLatencyMode ? partHoldBack || holdBack : holdBack;\n if (\n userConfig.liveSyncDuration ||\n userConfig.liveSyncDurationCount ||\n targetLatency === 0\n ) {\n targetLatency =\n liveSyncDuration !== undefined\n ? liveSyncDuration\n : liveSyncDurationCount * targetduration;\n }\n const maxLiveSyncOnStallIncrease = targetduration;\n const liveSyncOnStallIncrease = 1.0;\n return (\n targetLatency +\n Math.min(\n this.stallCount * liveSyncOnStallIncrease,\n maxLiveSyncOnStallIncrease\n )\n );\n }\n\n get liveSyncPosition(): number | null {\n const liveEdge = this.estimateLiveEdge();\n const targetLatency = this.targetLatency;\n const levelDetails = this.levelDetails;\n if (liveEdge === null || targetLatency === null || levelDetails === null) {\n return null;\n }\n const edge = levelDetails.edge;\n const syncPosition = liveEdge - targetLatency - this.edgeStalled;\n const min = edge - levelDetails.totalduration;\n const max =\n edge -\n ((this.config.lowLatencyMode && levelDetails.partTarget) ||\n levelDetails.targetduration);\n return Math.min(Math.max(min, syncPosition), max);\n }\n\n get drift(): number {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return 1;\n }\n return levelDetails.drift;\n }\n\n get edgeStalled(): number {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return 0;\n }\n const maxLevelUpdateAge =\n ((this.config.lowLatencyMode && levelDetails.partTarget) ||\n levelDetails.targetduration) * 3;\n return Math.max(levelDetails.age - maxLevelUpdateAge, 0);\n }\n\n private get forwardBufferLength(): number {\n const { media, levelDetails } = this;\n if (!media || !levelDetails) {\n return 0;\n }\n const bufferedRanges = media.buffered.length;\n return (\n (bufferedRanges\n ? media.buffered.end(bufferedRanges - 1)\n : levelDetails.edge) - this.currentTime\n );\n }\n\n public destroy(): void {\n this.unregisterListeners();\n this.onMediaDetaching();\n this.levelDetails = null;\n // @ts-ignore\n this.hls = this.timeupdateHandler = null;\n }\n\n private registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n this.hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n this.hls.off(Events.ERROR, this.onError, this);\n }\n\n private onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachingData\n ) {\n this.media = data.media;\n this.media.addEventListener('timeupdate', this.timeupdateHandler);\n }\n\n private onMediaDetaching() {\n if (this.media) {\n this.media.removeEventListener('timeupdate', this.timeupdateHandler);\n this.media = null;\n }\n }\n\n private onManifestLoading() {\n this.levelDetails = null;\n this._latency = null;\n this.stallCount = 0;\n }\n\n private onLevelUpdated(\n event: Events.LEVEL_UPDATED,\n { details }: LevelUpdatedData\n ) {\n this.levelDetails = details;\n if (details.advanced) {\n this.timeupdate();\n }\n if (!details.live && this.media) {\n this.media.removeEventListener('timeupdate', this.timeupdateHandler);\n }\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.details !== ErrorDetails.BUFFER_STALLED_ERROR) {\n return;\n }\n this.stallCount++;\n if (this.levelDetails?.live) {\n logger.warn(\n '[playback-rate-controller]: Stall detected, adjusting target latency'\n );\n }\n }\n\n private timeupdate() {\n const { media, levelDetails } = this;\n if (!media || !levelDetails) {\n return;\n }\n this.currentTime = media.currentTime;\n\n const latency = this.computeLatency();\n if (latency === null) {\n return;\n }\n this._latency = latency;\n\n // Adapt playbackRate to meet target latency in low-latency mode\n const { lowLatencyMode, maxLiveSyncPlaybackRate } = this.config;\n if (!lowLatencyMode || maxLiveSyncPlaybackRate === 1) {\n return;\n }\n const targetLatency = this.targetLatency;\n if (targetLatency === null) {\n return;\n }\n const distanceFromTarget = latency - targetLatency;\n // Only adjust playbackRate when within one target duration of targetLatency\n // and more than one second from under-buffering.\n // Playback further than one target duration from target can be considered DVR playback.\n const liveMinLatencyDuration = Math.min(\n this.maxLatency,\n targetLatency + levelDetails.targetduration\n );\n const inLiveRange = distanceFromTarget < liveMinLatencyDuration;\n if (\n levelDetails.live &&\n inLiveRange &&\n distanceFromTarget > 0.05 &&\n this.forwardBufferLength > 1\n ) {\n const max = Math.min(2, Math.max(1.0, maxLiveSyncPlaybackRate));\n const rate =\n Math.round(\n (2 / (1 + Math.exp(-0.75 * distanceFromTarget - this.edgeStalled))) *\n 20\n ) / 20;\n media.playbackRate = Math.min(max, Math.max(1, rate));\n } else if (media.playbackRate !== 1 && media.playbackRate !== 0) {\n media.playbackRate = 1;\n }\n }\n\n private estimateLiveEdge(): number | null {\n const { levelDetails } = this;\n if (levelDetails === null) {\n return null;\n }\n return levelDetails.edge + levelDetails.age;\n }\n\n private computeLatency(): number | null {\n const liveEdge = this.estimateLiveEdge();\n if (liveEdge === null) {\n return null;\n }\n return liveEdge - this.currentTime;\n }\n}\n","import { LevelDetails } from '../loader/level-details';\nimport { AttrList } from '../utils/attr-list';\n\nexport interface LevelParsed {\n attrs: LevelAttributes;\n audioCodec?: string;\n bitrate: number;\n details?: LevelDetails;\n height?: number;\n id?: number;\n level?: number;\n name: string;\n textCodec?: string;\n unknownCodecs?: string[];\n url: string;\n videoCodec?: string;\n width?: number;\n}\n\nexport interface LevelAttributes extends AttrList {\n 'ALLOWED-CPC'?: string;\n AUDIO?: string;\n 'AVERAGE-BANDWIDTH'?: string;\n BANDWIDTH?: string;\n 'CLOSED-CAPTIONS'?: string;\n CODECS?: string;\n 'FRAME-RATE'?: string;\n 'HDCP-LEVEL'?: 'TYPE-0' | 'TYPE-1' | 'NONE';\n 'PATHWAY-ID'?: string;\n RESOLUTION?: string;\n SCORE?: string;\n 'STABLE-VARIANT-ID'?: string;\n SUBTITLES?: string;\n 'SUPPLEMENTAL-CODECS'?: string;\n VIDEO?: string;\n 'VIDEO-RANGE'?: 'SDR' | 'HLG' | 'PQ';\n}\n\nexport const HdcpLevels = ['NONE', 'TYPE-0', 'TYPE-1', null] as const;\nexport type HdcpLevel = (typeof HdcpLevels)[number];\n\nexport type VariableMap = Record<string, string>;\n\nexport const enum HlsSkip {\n No = '',\n Yes = 'YES',\n v2 = 'v2',\n}\n\nexport function getSkipValue(details: LevelDetails, msn?: number): HlsSkip {\n const { canSkipUntil, canSkipDateRanges, endSN } = details;\n const snChangeGoal = msn !== undefined ? msn - endSN : 0;\n if (canSkipUntil && snChangeGoal < canSkipUntil) {\n if (canSkipDateRanges) {\n return HlsSkip.v2;\n }\n return HlsSkip.Yes;\n }\n return HlsSkip.No;\n}\n\nexport class HlsUrlParameters {\n msn?: number;\n part?: number;\n skip?: HlsSkip;\n\n constructor(msn?: number, part?: number, skip?: HlsSkip) {\n this.msn = msn;\n this.part = part;\n this.skip = skip;\n }\n\n addDirectives(uri: string): string | never {\n const url: URL = new self.URL(uri);\n if (this.msn !== undefined) {\n url.searchParams.set('_HLS_msn', this.msn.toString());\n }\n if (this.part !== undefined) {\n url.searchParams.set('_HLS_part', this.part.toString());\n }\n if (this.skip) {\n url.searchParams.set('_HLS_skip', this.skip);\n }\n return url.href;\n }\n}\n\nexport class Level {\n public readonly _attrs: LevelAttributes[];\n public readonly audioCodec: string | undefined;\n public readonly bitrate: number;\n public readonly codecSet: string;\n public readonly height: number;\n public readonly id: number;\n public readonly name: string | undefined;\n public readonly videoCodec: string | undefined;\n public readonly width: number;\n public readonly unknownCodecs: string[] | undefined;\n public audioGroupIds?: (string | undefined)[];\n public details?: LevelDetails;\n public fragmentError: number = 0;\n public loadError: number = 0;\n public loaded?: { bytes: number; duration: number };\n public realBitrate: number = 0;\n public textGroupIds?: (string | undefined)[];\n public url: string[];\n private _urlId: number = 0;\n\n constructor(data: LevelParsed) {\n this.url = [data.url];\n this._attrs = [data.attrs];\n this.bitrate = data.bitrate;\n if (data.details) {\n this.details = data.details;\n }\n this.id = data.id || 0;\n this.name = data.name;\n this.width = data.width || 0;\n this.height = data.height || 0;\n this.audioCodec = data.audioCodec;\n this.videoCodec = data.videoCodec;\n this.unknownCodecs = data.unknownCodecs;\n this.codecSet = [data.videoCodec, data.audioCodec]\n .filter((c) => c)\n .join(',')\n .replace(/\\.[^.,]+/g, '');\n }\n\n get maxBitrate(): number {\n return Math.max(this.realBitrate, this.bitrate);\n }\n\n get attrs(): LevelAttributes {\n return this._attrs[this._urlId];\n }\n\n get pathwayId(): string {\n return this.attrs['PATHWAY-ID'] || '.';\n }\n\n get uri(): string {\n return this.url[this._urlId] || '';\n }\n\n get urlId(): number {\n return this._urlId;\n }\n\n set urlId(value: number) {\n const newValue = value % this.url.length;\n if (this._urlId !== newValue) {\n this.fragmentError = 0;\n this.loadError = 0;\n this.details = undefined;\n this._urlId = newValue;\n }\n }\n\n get audioGroupId(): string | undefined {\n return this.audioGroupIds?.[this.urlId];\n }\n\n get textGroupId(): string | undefined {\n return this.textGroupIds?.[this.urlId];\n }\n\n addFallback(data: LevelParsed) {\n this.url.push(data.url);\n this._attrs.push(data.attrs);\n }\n}\n","/**\n * Provides methods dealing with playlist sliding and drift\n */\n\nimport { logger } from '../utils/logger';\nimport { Fragment, Part } from '../loader/fragment';\nimport { LevelDetails } from '../loader/level-details';\nimport type { Level } from '../types/level';\nimport { DateRange } from '../loader/date-range';\n\ntype FragmentIntersection = (oldFrag: Fragment, newFrag: Fragment) => void;\ntype PartIntersection = (oldPart: Part, newPart: Part) => void;\n\nexport function updatePTS(\n fragments: Fragment[],\n fromIdx: number,\n toIdx: number\n): void {\n const fragFrom = fragments[fromIdx];\n const fragTo = fragments[toIdx];\n updateFromToPTS(fragFrom, fragTo);\n}\n\nfunction updateFromToPTS(fragFrom: Fragment, fragTo: Fragment) {\n const fragToPTS = fragTo.startPTS as number;\n // if we know startPTS[toIdx]\n if (Number.isFinite(fragToPTS)) {\n // update fragment duration.\n // it helps to fix drifts between playlist reported duration and fragment real duration\n let duration: number = 0;\n let frag: Fragment;\n if (fragTo.sn > fragFrom.sn) {\n duration = fragToPTS - fragFrom.start;\n frag = fragFrom;\n } else {\n duration = fragFrom.start - fragToPTS;\n frag = fragTo;\n }\n if (frag.duration !== duration) {\n frag.duration = duration;\n }\n // we dont know startPTS[toIdx]\n } else if (fragTo.sn > fragFrom.sn) {\n const contiguous = fragFrom.cc === fragTo.cc;\n // TODO: With part-loading end/durations we need to confirm the whole fragment is loaded before using (or setting) minEndPTS\n if (contiguous && fragFrom.minEndPTS) {\n fragTo.start = fragFrom.start + (fragFrom.minEndPTS - fragFrom.start);\n } else {\n fragTo.start = fragFrom.start + fragFrom.duration;\n }\n } else {\n fragTo.start = Math.max(fragFrom.start - fragTo.duration, 0);\n }\n}\n\nexport function updateFragPTSDTS(\n details: LevelDetails | undefined,\n frag: Fragment,\n startPTS: number,\n endPTS: number,\n startDTS: number,\n endDTS: number\n): number {\n const parsedMediaDuration = endPTS - startPTS;\n if (parsedMediaDuration <= 0) {\n logger.warn('Fragment should have a positive duration', frag);\n endPTS = startPTS + frag.duration;\n endDTS = startDTS + frag.duration;\n }\n let maxStartPTS = startPTS;\n let minEndPTS = endPTS;\n const fragStartPts = frag.startPTS as number;\n const fragEndPts = frag.endPTS as number;\n if (Number.isFinite(fragStartPts)) {\n // delta PTS between audio and video\n const deltaPTS = Math.abs(fragStartPts - startPTS);\n if (!Number.isFinite(frag.deltaPTS as number)) {\n frag.deltaPTS = deltaPTS;\n } else {\n frag.deltaPTS = Math.max(deltaPTS, frag.deltaPTS as number);\n }\n\n maxStartPTS = Math.max(startPTS, fragStartPts);\n startPTS = Math.min(startPTS, fragStartPts);\n startDTS = Math.min(startDTS, frag.startDTS);\n\n minEndPTS = Math.min(endPTS, fragEndPts);\n endPTS = Math.max(endPTS, fragEndPts);\n endDTS = Math.max(endDTS, frag.endDTS);\n }\n\n const drift = startPTS - frag.start;\n if (frag.start !== 0) {\n frag.start = startPTS;\n }\n frag.duration = endPTS - frag.start;\n frag.startPTS = startPTS;\n frag.maxStartPTS = maxStartPTS;\n frag.startDTS = startDTS;\n frag.endPTS = endPTS;\n frag.minEndPTS = minEndPTS;\n frag.endDTS = endDTS;\n\n const sn = frag.sn as number; // 'initSegment'\n // exit if sn out of range\n if (!details || sn < details.startSN || sn > details.endSN) {\n return 0;\n }\n let i;\n const fragIdx = sn - details.startSN;\n const fragments = details.fragments;\n // update frag reference in fragments array\n // rationale is that fragments array might not contain this frag object.\n // this will happen if playlist has been refreshed between frag loading and call to updateFragPTSDTS()\n // if we don't update frag, we won't be able to propagate PTS info on the playlist\n // resulting in invalid sliding computation\n fragments[fragIdx] = frag;\n // adjust fragment PTS/duration from seqnum-1 to frag 0\n for (i = fragIdx; i > 0; i--) {\n updateFromToPTS(fragments[i], fragments[i - 1]);\n }\n\n // adjust fragment PTS/duration from seqnum to last frag\n for (i = fragIdx; i < fragments.length - 1; i++) {\n updateFromToPTS(fragments[i], fragments[i + 1]);\n }\n if (details.fragmentHint) {\n updateFromToPTS(fragments[fragments.length - 1], details.fragmentHint);\n }\n\n details.PTSKnown = details.alignedSliding = true;\n return drift;\n}\n\nexport function mergeDetails(\n oldDetails: LevelDetails,\n newDetails: LevelDetails\n): void {\n // Track the last initSegment processed. Initialize it to the last one on the timeline.\n let currentInitSegment: Fragment | null = null;\n const oldFragments = oldDetails.fragments;\n for (let i = oldFragments.length - 1; i >= 0; i--) {\n const oldInit = oldFragments[i].initSegment;\n if (oldInit) {\n currentInitSegment = oldInit;\n break;\n }\n }\n\n if (oldDetails.fragmentHint) {\n // prevent PTS and duration from being adjusted on the next hint\n delete oldDetails.fragmentHint.endPTS;\n }\n // check if old/new playlists have fragments in common\n // loop through overlapping SN and update startPTS , cc, and duration if any found\n let ccOffset = 0;\n let PTSFrag;\n mapFragmentIntersection(\n oldDetails,\n newDetails,\n (oldFrag: Fragment, newFrag: Fragment) => {\n if (oldFrag.relurl) {\n // Do not compare CC if the old fragment has no url. This is a level.fragmentHint used by LL-HLS parts.\n // It maybe be off by 1 if it was created before any parts or discontinuity tags were appended to the end\n // of the playlist.\n ccOffset = oldFrag.cc - newFrag.cc;\n }\n if (\n Number.isFinite(oldFrag.startPTS) &&\n Number.isFinite(oldFrag.endPTS)\n ) {\n newFrag.start = newFrag.startPTS = oldFrag.startPTS as number;\n newFrag.startDTS = oldFrag.startDTS;\n newFrag.maxStartPTS = oldFrag.maxStartPTS;\n\n newFrag.endPTS = oldFrag.endPTS;\n newFrag.endDTS = oldFrag.endDTS;\n newFrag.minEndPTS = oldFrag.minEndPTS;\n newFrag.duration =\n (oldFrag.endPTS as number) - (oldFrag.startPTS as number);\n\n if (newFrag.duration) {\n PTSFrag = newFrag;\n }\n\n // PTS is known when any segment has startPTS and endPTS\n newDetails.PTSKnown = newDetails.alignedSliding = true;\n }\n newFrag.elementaryStreams = oldFrag.elementaryStreams;\n newFrag.loader = oldFrag.loader;\n newFrag.stats = oldFrag.stats;\n newFrag.urlId = oldFrag.urlId;\n if (oldFrag.initSegment) {\n newFrag.initSegment = oldFrag.initSegment;\n currentInitSegment = oldFrag.initSegment;\n }\n }\n );\n\n if (currentInitSegment) {\n const fragmentsToCheck = newDetails.fragmentHint\n ? newDetails.fragments.concat(newDetails.fragmentHint)\n : newDetails.fragments;\n fragmentsToCheck.forEach((frag) => {\n if (\n !frag.initSegment ||\n frag.initSegment.relurl === currentInitSegment?.relurl\n ) {\n frag.initSegment = currentInitSegment;\n }\n });\n }\n\n if (newDetails.skippedSegments) {\n newDetails.deltaUpdateFailed = newDetails.fragments.some((frag) => !frag);\n if (newDetails.deltaUpdateFailed) {\n logger.warn(\n '[level-helper] Previous playlist missing segments skipped in delta playlist'\n );\n for (let i = newDetails.skippedSegments; i--; ) {\n newDetails.fragments.shift();\n }\n newDetails.startSN = newDetails.fragments[0].sn as number;\n newDetails.startCC = newDetails.fragments[0].cc;\n } else if (newDetails.canSkipDateRanges) {\n newDetails.dateRanges = mergeDateRanges(\n oldDetails.dateRanges,\n newDetails.dateRanges,\n newDetails.recentlyRemovedDateranges\n );\n }\n }\n\n const newFragments = newDetails.fragments;\n if (ccOffset) {\n logger.warn('discontinuity sliding from playlist, take drift into account');\n for (let i = 0; i < newFragments.length; i++) {\n newFragments[i].cc += ccOffset;\n }\n }\n if (newDetails.skippedSegments) {\n newDetails.startCC = newDetails.fragments[0].cc;\n }\n\n // Merge parts\n mapPartIntersection(\n oldDetails.partList,\n newDetails.partList,\n (oldPart: Part, newPart: Part) => {\n newPart.elementaryStreams = oldPart.elementaryStreams;\n newPart.stats = oldPart.stats;\n }\n );\n\n // if at least one fragment contains PTS info, recompute PTS information for all fragments\n if (PTSFrag) {\n updateFragPTSDTS(\n newDetails,\n PTSFrag,\n PTSFrag.startPTS,\n PTSFrag.endPTS,\n PTSFrag.startDTS,\n PTSFrag.endDTS\n );\n } else {\n // ensure that delta is within oldFragments range\n // also adjust sliding in case delta is 0 (we could have old=[50-60] and new=old=[50-61])\n // in that case we also need to adjust start offset of all fragments\n adjustSliding(oldDetails, newDetails);\n }\n\n if (newFragments.length) {\n newDetails.totalduration = newDetails.edge - newFragments[0].start;\n }\n\n newDetails.driftStartTime = oldDetails.driftStartTime;\n newDetails.driftStart = oldDetails.driftStart;\n const advancedDateTime = newDetails.advancedDateTime;\n if (newDetails.advanced && advancedDateTime) {\n const edge = newDetails.edge;\n if (!newDetails.driftStart) {\n newDetails.driftStartTime = advancedDateTime;\n newDetails.driftStart = edge;\n }\n newDetails.driftEndTime = advancedDateTime;\n newDetails.driftEnd = edge;\n } else {\n newDetails.driftEndTime = oldDetails.driftEndTime;\n newDetails.driftEnd = oldDetails.driftEnd;\n newDetails.advancedDateTime = oldDetails.advancedDateTime;\n }\n}\n\nfunction mergeDateRanges(\n oldDateRanges: Record<string, DateRange>,\n deltaDateRanges: Record<string, DateRange>,\n recentlyRemovedDateranges: string[] | undefined\n): Record<string, DateRange> {\n const dateRanges = Object.assign({}, oldDateRanges);\n if (recentlyRemovedDateranges) {\n recentlyRemovedDateranges.forEach((id) => {\n delete dateRanges[id];\n });\n }\n Object.keys(deltaDateRanges).forEach((id) => {\n const dateRange = new DateRange(deltaDateRanges[id].attr, dateRanges[id]);\n if (dateRange.isValid) {\n dateRanges[id] = dateRange;\n } else {\n logger.warn(\n `Ignoring invalid Playlist Delta Update DATERANGE tag: \"${JSON.stringify(\n deltaDateRanges[id].attr\n )}\"`\n );\n }\n });\n return dateRanges;\n}\n\nexport function mapPartIntersection(\n oldParts: Part[] | null,\n newParts: Part[] | null,\n intersectionFn: PartIntersection\n) {\n if (oldParts && newParts) {\n let delta = 0;\n for (let i = 0, len = oldParts.length; i <= len; i++) {\n const oldPart = oldParts[i];\n const newPart = newParts[i + delta];\n if (\n oldPart &&\n newPart &&\n oldPart.index === newPart.index &&\n oldPart.fragment.sn === newPart.fragment.sn\n ) {\n intersectionFn(oldPart, newPart);\n } else {\n delta--;\n }\n }\n }\n}\n\nexport function mapFragmentIntersection(\n oldDetails: LevelDetails,\n newDetails: LevelDetails,\n intersectionFn: FragmentIntersection\n): void {\n const skippedSegments = newDetails.skippedSegments;\n const start =\n Math.max(oldDetails.startSN, newDetails.startSN) - newDetails.startSN;\n const end =\n (oldDetails.fragmentHint ? 1 : 0) +\n (skippedSegments\n ? newDetails.endSN\n : Math.min(oldDetails.endSN, newDetails.endSN)) -\n newDetails.startSN;\n const delta = newDetails.startSN - oldDetails.startSN;\n const newFrags = newDetails.fragmentHint\n ? newDetails.fragments.concat(newDetails.fragmentHint)\n : newDetails.fragments;\n const oldFrags = oldDetails.fragmentHint\n ? oldDetails.fragments.concat(oldDetails.fragmentHint)\n : oldDetails.fragments;\n\n for (let i = start; i <= end; i++) {\n const oldFrag = oldFrags[delta + i];\n let newFrag = newFrags[i];\n if (skippedSegments && !newFrag && i < skippedSegments) {\n // Fill in skipped segments in delta playlist\n newFrag = newDetails.fragments[i] = oldFrag;\n }\n if (oldFrag && newFrag) {\n intersectionFn(oldFrag, newFrag);\n }\n }\n}\n\nexport function adjustSliding(\n oldDetails: LevelDetails,\n newDetails: LevelDetails\n): void {\n const delta =\n newDetails.startSN + newDetails.skippedSegments - oldDetails.startSN;\n const oldFragments = oldDetails.fragments;\n if (delta < 0 || delta >= oldFragments.length) {\n return;\n }\n addSliding(newDetails, oldFragments[delta].start);\n}\n\nexport function addSliding(details: LevelDetails, start: number) {\n if (start) {\n const fragments = details.fragments;\n for (let i = details.skippedSegments; i < fragments.length; i++) {\n fragments[i].start += start;\n }\n if (details.fragmentHint) {\n details.fragmentHint.start += start;\n }\n }\n}\n\nexport function computeReloadInterval(\n newDetails: LevelDetails,\n distanceToLiveEdgeMs: number = Infinity\n): number {\n let reloadInterval = 1000 * newDetails.targetduration;\n\n if (newDetails.updated) {\n // Use last segment duration when shorter than target duration and near live edge\n const fragments = newDetails.fragments;\n const liveEdgeMaxTargetDurations = 4;\n if (\n fragments.length &&\n reloadInterval * liveEdgeMaxTargetDurations > distanceToLiveEdgeMs\n ) {\n const lastSegmentDuration =\n fragments[fragments.length - 1].duration * 1000;\n if (lastSegmentDuration < reloadInterval) {\n reloadInterval = lastSegmentDuration;\n }\n }\n } else {\n // estimate = 'miss half average';\n // follow HLS Spec, If the client reloads a Playlist file and finds that it has not\n // changed then it MUST wait for a period of one-half the target\n // duration before retrying.\n reloadInterval /= 2;\n }\n\n return Math.round(reloadInterval);\n}\n\nexport function getFragmentWithSN(\n level: Level,\n sn: number,\n fragCurrent: Fragment | null\n): Fragment | null {\n if (!level?.details) {\n return null;\n }\n const levelDetails = level.details;\n let fragment: Fragment | undefined =\n levelDetails.fragments[sn - levelDetails.startSN];\n if (fragment) {\n return fragment;\n }\n fragment = levelDetails.fragmentHint;\n if (fragment && fragment.sn === sn) {\n return fragment;\n }\n if (sn < levelDetails.startSN && fragCurrent && fragCurrent.sn === sn) {\n return fragCurrent;\n }\n return null;\n}\n\nexport function getPartWith(\n level: Level,\n sn: number,\n partIndex: number\n): Part | null {\n if (!level?.details) {\n return null;\n }\n return findPart(level.details?.partList, sn, partIndex);\n}\n\nexport function findPart(\n partList: Part[] | null | undefined,\n sn: number,\n partIndex: number\n): Part | null {\n if (partList) {\n for (let i = partList.length; i--; ) {\n const part = partList[i];\n if (part.index === partIndex && part.fragment.sn === sn) {\n return part;\n }\n }\n }\n return null;\n}\n","import { LoadPolicy, LoaderConfig, RetryConfig } from '../config';\nimport { ErrorDetails } from '../errors';\nimport { ErrorData } from '../types/events';\n\nexport function isTimeoutError(error: ErrorData): boolean {\n switch (error.details) {\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n case ErrorDetails.MANIFEST_LOAD_TIMEOUT:\n return true;\n }\n return false;\n}\n\nexport function getRetryConfig(\n loadPolicy: LoadPolicy,\n error: ErrorData\n): RetryConfig | null {\n const isTimeout = isTimeoutError(error);\n return loadPolicy.default[`${isTimeout ? 'timeout' : 'error'}Retry`];\n}\n\nexport function getRetryDelay(\n retryConfig: RetryConfig,\n retryCount: number\n): number {\n // exponential backoff capped to max retry delay\n const backoffFactor =\n retryConfig.backoff === 'linear' ? 1 : Math.pow(2, retryCount);\n return Math.min(\n backoffFactor * retryConfig.retryDelayMs,\n retryConfig.maxRetryDelayMs\n );\n}\n\nexport function getLoaderConfigWithoutReties(\n loderConfig: LoaderConfig\n): LoaderConfig {\n return {\n ...loderConfig,\n ...{\n errorRetry: null,\n timeoutRetry: null,\n },\n };\n}\n\nexport function shouldRetry(\n retryConfig: RetryConfig | null | undefined,\n retryCount: number,\n isTimeout: boolean,\n httpStatus?: number | undefined\n): retryConfig is RetryConfig & boolean {\n return (\n !!retryConfig &&\n retryCount < retryConfig.maxNumRetry &&\n (retryForHttpStatus(httpStatus) || !!isTimeout)\n );\n}\n\nexport function retryForHttpStatus(httpStatus: number | undefined) {\n // Do not retry on status 4xx, status 0 (CORS error), or undefined (decrypt/gap/parse error)\n return (\n (httpStatus === 0 && navigator.onLine === false) ||\n (!!httpStatus && (httpStatus < 400 || httpStatus > 499))\n );\n}\n","type BinarySearchComparison<T> = (candidate: T) => -1 | 0 | 1;\n\nconst BinarySearch = {\n /**\n * Searches for an item in an array which matches a certain condition.\n * This requires the condition to only match one item in the array,\n * and for the array to be ordered.\n *\n * @param list The array to search.\n * @param comparisonFn\n * Called and provided a candidate item as the first argument.\n * Should return:\n * > -1 if the item should be located at a lower index than the provided item.\n * > 1 if the item should be located at a higher index than the provided item.\n * > 0 if the item is the item you're looking for.\n *\n * @returns the object if found, otherwise returns null\n */\n search: function <T>(\n list: T[],\n comparisonFn: BinarySearchComparison<T>\n ): T | null {\n let minIndex: number = 0;\n let maxIndex: number = list.length - 1;\n let currentIndex: number | null = null;\n let currentElement: T | null = null;\n\n while (minIndex <= maxIndex) {\n currentIndex = ((minIndex + maxIndex) / 2) | 0;\n currentElement = list[currentIndex];\n\n const comparisonResult = comparisonFn(currentElement);\n if (comparisonResult > 0) {\n minIndex = currentIndex + 1;\n } else if (comparisonResult < 0) {\n maxIndex = currentIndex - 1;\n } else {\n return currentElement;\n }\n }\n\n return null;\n },\n};\n\nexport default BinarySearch;\n","import BinarySearch from '../utils/binary-search';\nimport { Fragment } from '../loader/fragment';\n\n/**\n * Returns first fragment whose endPdt value exceeds the given PDT, or null.\n * @param fragments - The array of candidate fragments\n * @param PDTValue - The PDT value which must be exceeded\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n */\nexport function findFragmentByPDT(\n fragments: Array<Fragment>,\n PDTValue: number | null,\n maxFragLookUpTolerance: number\n): Fragment | null {\n if (\n PDTValue === null ||\n !Array.isArray(fragments) ||\n !fragments.length ||\n !Number.isFinite(PDTValue)\n ) {\n return null;\n }\n\n // if less than start\n const startPDT = fragments[0].programDateTime;\n if (PDTValue < (startPDT || 0)) {\n return null;\n }\n\n const endPDT = fragments[fragments.length - 1].endProgramDateTime;\n if (PDTValue >= (endPDT || 0)) {\n return null;\n }\n\n maxFragLookUpTolerance = maxFragLookUpTolerance || 0;\n for (let seg = 0; seg < fragments.length; ++seg) {\n const frag = fragments[seg];\n if (pdtWithinToleranceTest(PDTValue, maxFragLookUpTolerance, frag)) {\n return frag;\n }\n }\n\n return null;\n}\n\n/**\n * Finds a fragment based on the SN of the previous fragment; or based on the needs of the current buffer.\n * This method compensates for small buffer gaps by applying a tolerance to the start of any candidate fragment, thus\n * breaking any traps which would cause the same fragment to be continuously selected within a small range.\n * @param fragPrevious - The last frag successfully appended\n * @param fragments - The array of candidate fragments\n * @param bufferEnd - The end of the contiguous buffered range the playhead is currently within\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start/end can be within in order to be considered contiguous\n * @returns a matching fragment or null\n */\nexport function findFragmentByPTS(\n fragPrevious: Fragment | null,\n fragments: Array<Fragment>,\n bufferEnd: number = 0,\n maxFragLookUpTolerance: number = 0\n): Fragment | null {\n let fragNext: Fragment | null = null;\n if (fragPrevious) {\n fragNext =\n fragments[\n (fragPrevious.sn as number) - (fragments[0].sn as number) + 1\n ] || null;\n } else if (bufferEnd === 0 && fragments[0].start === 0) {\n fragNext = fragments[0];\n }\n // Prefer the next fragment if it's within tolerance\n if (\n fragNext &&\n fragmentWithinToleranceTest(bufferEnd, maxFragLookUpTolerance, fragNext) ===\n 0\n ) {\n return fragNext;\n }\n // We might be seeking past the tolerance so find the best match\n const foundFragment = BinarySearch.search(\n fragments,\n fragmentWithinToleranceTest.bind(null, bufferEnd, maxFragLookUpTolerance)\n );\n if (foundFragment && (foundFragment !== fragPrevious || !fragNext)) {\n return foundFragment;\n }\n // If no match was found return the next fragment after fragPrevious, or null\n return fragNext;\n}\n\n/**\n * The test function used by the findFragmentBySn's BinarySearch to look for the best match to the current buffer conditions.\n * @param candidate - The fragment to test\n * @param bufferEnd - The end of the current buffered range the playhead is currently within\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns 0 if it matches, 1 if too low, -1 if too high\n */\nexport function fragmentWithinToleranceTest(\n bufferEnd = 0,\n maxFragLookUpTolerance = 0,\n candidate: Fragment\n) {\n // eagerly accept an accurate match (no tolerance)\n if (\n candidate.start <= bufferEnd &&\n candidate.start + candidate.duration > bufferEnd\n ) {\n return 0;\n }\n // offset should be within fragment boundary - config.maxFragLookUpTolerance\n // this is to cope with situations like\n // bufferEnd = 9.991\n // frag[Ø] : [0,10]\n // frag[1] : [10,20]\n // bufferEnd is within frag[0] range ... although what we are expecting is to return frag[1] here\n // frag start frag start+duration\n // |-----------------------------|\n // <---> <--->\n // ...--------><-----------------------------><---------....\n // previous frag matching fragment next frag\n // return -1 return 0 return 1\n // logger.log(`level/sn/start/end/bufEnd:${level}/${candidate.sn}/${candidate.start}/${(candidate.start+candidate.duration)}/${bufferEnd}`);\n // Set the lookup tolerance to be small enough to detect the current segment - ensures we don't skip over very small segments\n const candidateLookupTolerance = Math.min(\n maxFragLookUpTolerance,\n candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)\n );\n if (\n candidate.start + candidate.duration - candidateLookupTolerance <=\n bufferEnd\n ) {\n return 1;\n } else if (\n candidate.start - candidateLookupTolerance > bufferEnd &&\n candidate.start\n ) {\n // if maxFragLookUpTolerance will have negative value then don't return -1 for first element\n return -1;\n }\n\n return 0;\n}\n\n/**\n * The test function used by the findFragmentByPdt's BinarySearch to look for the best match to the current buffer conditions.\n * This function tests the candidate's program date time values, as represented in Unix time\n * @param candidate - The fragment to test\n * @param pdtBufferEnd - The Unix time representing the end of the current buffered range\n * @param maxFragLookUpTolerance - The amount of time that a fragment's start can be within in order to be considered contiguous\n * @returns true if contiguous, false otherwise\n */\nexport function pdtWithinToleranceTest(\n pdtBufferEnd: number,\n maxFragLookUpTolerance: number,\n candidate: Fragment\n): boolean {\n const candidateLookupTolerance =\n Math.min(\n maxFragLookUpTolerance,\n candidate.duration + (candidate.deltaPTS ? candidate.deltaPTS : 0)\n ) * 1000;\n\n // endProgramDateTime can be null, default to zero\n const endProgramDateTime = candidate.endProgramDateTime || 0;\n return endProgramDateTime - candidateLookupTolerance > pdtBufferEnd;\n}\n\nexport function findFragWithCC(\n fragments: Fragment[],\n cc: number\n): Fragment | null {\n return BinarySearch.search(fragments, (candidate) => {\n if (candidate.cc < cc) {\n return 1;\n } else if (candidate.cc > cc) {\n return -1;\n } else {\n return 0;\n }\n });\n}\n","import { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport {\n getRetryConfig,\n isTimeoutError,\n shouldRetry,\n} from '../utils/error-helper';\nimport { findFragmentByPTS } from './fragment-finders';\nimport { HdcpLevel, HdcpLevels, type Level } from '../types/level';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { RetryConfig } from '../config';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { ErrorData } from '../types/events';\nimport type { Fragment } from '../loader/fragment';\nimport type { LevelDetails } from '../hls';\n\nconst RENDITION_PENALTY_DURATION_MS = 300000;\n\nexport const enum NetworkErrorAction {\n DoNothing = 0,\n SendEndCallback = 1, // Reserved for future use\n SendAlternateToPenaltyBox = 2,\n RemoveAlternatePermanently = 3, // Reserved for future use\n InsertDiscontinuity = 4, // Reserved for future use\n RetryRequest = 5,\n}\n\nexport const enum ErrorActionFlags {\n None = 0,\n MoveAllAlternatesMatchingHost = 1,\n MoveAllAlternatesMatchingHDCP = 1 << 1,\n SwitchToSDR = 1 << 2, // Reserved for future use\n}\n\nexport type IErrorAction = {\n action: NetworkErrorAction;\n flags: ErrorActionFlags;\n retryCount?: number;\n retryConfig?: RetryConfig;\n hdcpLevel?: HdcpLevel;\n nextAutoLevel?: number;\n resolved?: boolean;\n};\n\ntype PenalizedRendition = {\n lastErrorPerfMs: number;\n errors: ErrorData[];\n details?: LevelDetails;\n};\n\ntype PenalizedRenditions = { [key: number]: PenalizedRendition };\n\nexport default class ErrorController implements NetworkComponentAPI {\n private readonly hls: Hls;\n private playlistError: number = 0;\n private penalizedRenditions: PenalizedRenditions = {};\n private log: (msg: any) => void;\n private warn: (msg: any) => void;\n private error: (msg: any) => void;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.log = logger.log.bind(logger, `[info]:`);\n this.warn = logger.warn.bind(logger, `[warning]:`);\n this.error = logger.error.bind(logger, `[error]:`);\n this.registerListeners();\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.ERROR, this.onErrorOut, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n }\n\n destroy() {\n this.unregisterListeners();\n // @ts-ignore\n this.hls = null;\n this.penalizedRenditions = {};\n }\n\n startLoad(startPosition: number): void {\n this.playlistError = 0;\n }\n\n stopLoad(): void {}\n\n private getVariantLevelIndex(frag: Fragment | undefined): number {\n return frag?.type === PlaylistLevelType.MAIN\n ? frag.level\n : this.hls.loadLevel;\n }\n\n private onManifestLoading() {\n this.playlistError = 0;\n this.penalizedRenditions = {};\n }\n\n private onLevelUpdated() {\n this.playlistError = 0;\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n return;\n }\n const hls = this.hls;\n const context = data.context;\n\n switch (data.details) {\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n data.errorAction = this.getFragRetryOrSwitchAction(data);\n return;\n case ErrorDetails.FRAG_PARSING_ERROR:\n // ignore empty segment errors marked as gap\n if (data.frag?.gap) {\n data.errorAction = {\n action: NetworkErrorAction.DoNothing,\n flags: ErrorActionFlags.None,\n };\n return;\n }\n // falls through\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_DECRYPT_ERROR: {\n // Switch level if possible, otherwise allow retry count to reach max error retries\n data.errorAction = this.getFragRetryOrSwitchAction(data);\n data.errorAction.action = NetworkErrorAction.SendAlternateToPenaltyBox;\n return;\n }\n case ErrorDetails.LEVEL_EMPTY_ERROR:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n {\n // Only retry when empty and live\n const levelIndex =\n data.parent === PlaylistLevelType.MAIN\n ? (data.level as number)\n : hls.loadLevel;\n if (\n data.details === ErrorDetails.LEVEL_EMPTY_ERROR &&\n !!data.context?.levelDetails?.live\n ) {\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n levelIndex\n );\n } else {\n // Escalate to fatal if not retrying or switching\n data.levelRetry = false;\n data.errorAction = this.getLevelSwitchAction(data, levelIndex);\n }\n }\n return;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n if (typeof context?.level === 'number') {\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n context.level\n );\n }\n return;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.SUBTITLE_LOAD_ERROR:\n case ErrorDetails.SUBTITLE_TRACK_LOAD_TIMEOUT:\n if (context) {\n const level = hls.levels[hls.loadLevel];\n if (\n level &&\n ((context.type === PlaylistContextType.AUDIO_TRACK &&\n context.groupId === level.audioGroupId) ||\n (context.type === PlaylistContextType.SUBTITLE_TRACK &&\n context.groupId === level.textGroupId))\n ) {\n // Perform Pathway switch or Redundant failover if possible for fastest recovery\n // otherwise allow playlist retry count to reach max error retries\n data.errorAction = this.getPlaylistRetryOrSwitchAction(\n data,\n hls.loadLevel\n );\n data.errorAction.action =\n NetworkErrorAction.SendAlternateToPenaltyBox;\n data.errorAction.flags =\n ErrorActionFlags.MoveAllAlternatesMatchingHost;\n return;\n }\n }\n return;\n case ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:\n {\n const level = hls.levels[hls.loadLevel];\n const restrictedHdcpLevel = level?.attrs['HDCP-LEVEL'];\n if (restrictedHdcpLevel) {\n data.errorAction = {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.MoveAllAlternatesMatchingHDCP,\n hdcpLevel: restrictedHdcpLevel,\n };\n }\n }\n return;\n case ErrorDetails.BUFFER_ADD_CODEC_ERROR:\n case ErrorDetails.REMUX_ALLOC_ERROR:\n data.errorAction = this.getLevelSwitchAction(\n data,\n data.level ?? hls.loadLevel\n );\n return;\n case ErrorDetails.INTERNAL_EXCEPTION:\n case ErrorDetails.BUFFER_APPENDING_ERROR:\n case ErrorDetails.BUFFER_APPEND_ERROR:\n case ErrorDetails.BUFFER_FULL_ERROR:\n case ErrorDetails.LEVEL_SWITCH_ERROR:\n case ErrorDetails.BUFFER_STALLED_ERROR:\n case ErrorDetails.BUFFER_SEEK_OVER_HOLE:\n case ErrorDetails.BUFFER_NUDGE_ON_STALL:\n data.errorAction = {\n action: NetworkErrorAction.DoNothing,\n flags: ErrorActionFlags.None,\n };\n return;\n }\n\n if (data.type === ErrorTypes.KEY_SYSTEM_ERROR) {\n const levelIndex = this.getVariantLevelIndex(data.frag);\n // Do not retry level. Escalate to fatal if switching levels fails.\n data.levelRetry = false;\n data.errorAction = this.getLevelSwitchAction(data, levelIndex);\n return;\n }\n }\n\n private getPlaylistRetryOrSwitchAction(\n data: ErrorData,\n levelIndex: number | null | undefined\n ): IErrorAction {\n const hls = this.hls;\n const retryConfig = getRetryConfig(hls.config.playlistLoadPolicy, data);\n const retryCount = this.playlistError++;\n const httpStatus = data.response?.code;\n const retry = shouldRetry(\n retryConfig,\n retryCount,\n isTimeoutError(data),\n httpStatus\n );\n if (retry) {\n return {\n action: NetworkErrorAction.RetryRequest,\n flags: ErrorActionFlags.None,\n retryConfig,\n retryCount,\n };\n }\n const errorAction = this.getLevelSwitchAction(data, levelIndex);\n if (retryConfig) {\n errorAction.retryConfig = retryConfig;\n errorAction.retryCount = retryCount;\n }\n return errorAction;\n }\n\n private getFragRetryOrSwitchAction(data: ErrorData): IErrorAction {\n const hls = this.hls;\n // Share fragment error count accross media options (main, audio, subs)\n // This allows for level based rendition switching when media option assets fail\n const variantLevelIndex = this.getVariantLevelIndex(data.frag);\n const level = hls.levels[variantLevelIndex];\n const { fragLoadPolicy, keyLoadPolicy } = hls.config;\n const retryConfig = getRetryConfig(\n data.details.startsWith('key') ? keyLoadPolicy : fragLoadPolicy,\n data\n );\n const fragmentErrors = hls.levels.reduce(\n (acc, level) => acc + level.fragmentError,\n 0\n );\n // Switch levels when out of retried or level index out of bounds\n if (level) {\n if (data.details !== ErrorDetails.FRAG_GAP) {\n level.fragmentError++;\n }\n const httpStatus = data.response?.code;\n const retry = shouldRetry(\n retryConfig,\n fragmentErrors,\n isTimeoutError(data),\n httpStatus\n );\n if (retry) {\n return {\n action: NetworkErrorAction.RetryRequest,\n flags: ErrorActionFlags.None,\n retryConfig,\n retryCount: fragmentErrors,\n };\n }\n }\n // Reach max retry count, or Missing level reference\n // Switch to valid index\n const errorAction = this.getLevelSwitchAction(data, variantLevelIndex);\n // Add retry details to allow skipping of FRAG_PARSING_ERROR\n if (retryConfig) {\n errorAction.retryConfig = retryConfig;\n errorAction.retryCount = fragmentErrors;\n }\n return errorAction;\n }\n\n private getLevelSwitchAction(\n data: ErrorData,\n levelIndex: number | null | undefined\n ): IErrorAction {\n const hls = this.hls;\n if (levelIndex === null || levelIndex === undefined) {\n levelIndex = hls.loadLevel;\n }\n const level = this.hls.levels[levelIndex];\n if (level) {\n level.loadError++;\n if (hls.autoLevelEnabled) {\n // Search for next level to retry\n let nextLevel = -1;\n const { levels, loadLevel, minAutoLevel, maxAutoLevel } = hls;\n const fragErrorType = data.frag?.type;\n const { type: playlistErrorType, groupId: playlistErrorGroupId } =\n data.context ?? {};\n for (let i = levels.length; i--; ) {\n const candidate = (i + loadLevel) % levels.length;\n if (\n candidate !== loadLevel &&\n candidate >= minAutoLevel &&\n candidate <= maxAutoLevel &&\n levels[candidate].loadError === 0\n ) {\n const levelCandidate = levels[candidate];\n // Skip level switch if GAP tag is found in next level at same position\n if (data.details === ErrorDetails.FRAG_GAP && data.frag) {\n const levelDetails = levels[candidate].details;\n if (levelDetails) {\n const fragCandidate = findFragmentByPTS(\n data.frag,\n levelDetails.fragments,\n data.frag.start\n );\n if (fragCandidate?.gap) {\n continue;\n }\n }\n } else if (\n (playlistErrorType === PlaylistContextType.AUDIO_TRACK &&\n playlistErrorGroupId === levelCandidate.audioGroupId) ||\n (playlistErrorType === PlaylistContextType.SUBTITLE_TRACK &&\n playlistErrorGroupId === levelCandidate.textGroupId)\n ) {\n // For audio/subs playlist errors find another group ID or fallthrough to redundant fail-over\n continue;\n } else if (\n (fragErrorType === PlaylistLevelType.AUDIO &&\n level.audioGroupId === levelCandidate.audioGroupId) ||\n (fragErrorType === PlaylistLevelType.SUBTITLE &&\n level.textGroupId === levelCandidate.textGroupId)\n ) {\n // For audio/subs frag errors find another group ID or fallthrough to redundant fail-over\n continue;\n }\n nextLevel = candidate;\n break;\n }\n }\n if (nextLevel > -1 && hls.loadLevel !== nextLevel) {\n data.levelRetry = true;\n this.playlistError = 0;\n return {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.None,\n nextAutoLevel: nextLevel,\n };\n }\n }\n }\n // No levels to switch / Manual level selection / Level not found\n // Resolve with Pathway switch, Redundant fail-over, or stay on lowest Level\n return {\n action: NetworkErrorAction.SendAlternateToPenaltyBox,\n flags: ErrorActionFlags.MoveAllAlternatesMatchingHost,\n };\n }\n\n public onErrorOut(event: Events.ERROR, data: ErrorData) {\n switch (data.errorAction?.action) {\n case NetworkErrorAction.DoNothing:\n break;\n case NetworkErrorAction.SendAlternateToPenaltyBox:\n this.sendAlternateToPenaltyBox(data);\n if (\n !data.errorAction.resolved &&\n data.details !== ErrorDetails.FRAG_GAP\n ) {\n data.fatal = true;\n }\n break;\n case NetworkErrorAction.RetryRequest:\n // handled by stream and playlist/level controllers\n break;\n }\n\n if (data.fatal) {\n this.hls.stopLoad();\n return;\n }\n }\n\n private sendAlternateToPenaltyBox(data: ErrorData) {\n const hls = this.hls;\n const errorAction = data.errorAction;\n if (!errorAction) {\n return;\n }\n const { flags, hdcpLevel, nextAutoLevel } = errorAction;\n\n switch (flags) {\n case ErrorActionFlags.None:\n this.switchLevel(data, nextAutoLevel);\n break;\n case ErrorActionFlags.MoveAllAlternatesMatchingHost:\n {\n // Handle Redundant Levels here. Pathway switching is handled by content-steering-controller\n if (!errorAction.resolved) {\n errorAction.resolved = this.redundantFailover(data);\n }\n }\n break;\n case ErrorActionFlags.MoveAllAlternatesMatchingHDCP:\n if (hdcpLevel) {\n hls.maxHdcpLevel = HdcpLevels[HdcpLevels.indexOf(hdcpLevel) - 1];\n errorAction.resolved = true;\n }\n this.warn(\n `Restricting playback to HDCP-LEVEL of \"${hls.maxHdcpLevel}\" or lower`\n );\n break;\n }\n // If not resolved by previous actions try to switch to next level\n if (!errorAction.resolved) {\n this.switchLevel(data, nextAutoLevel);\n }\n }\n\n private switchLevel(data: ErrorData, levelIndex: number | undefined) {\n if (levelIndex !== undefined && data.errorAction) {\n this.warn(`switching to level ${levelIndex} after ${data.details}`);\n this.hls.nextAutoLevel = levelIndex;\n data.errorAction.resolved = true;\n // Stream controller is responsible for this but won't switch on false start\n this.hls.nextLoadLevel = this.hls.nextAutoLevel;\n }\n }\n\n private redundantFailover(data: ErrorData): boolean {\n const { hls, penalizedRenditions } = this;\n const levelIndex: number =\n data.parent === PlaylistLevelType.MAIN\n ? (data.level as number)\n : hls.loadLevel;\n const level = hls.levels[levelIndex];\n const redundantLevels = level.url.length;\n const errorUrlId = data.frag ? data.frag.urlId : level.urlId;\n if (level.urlId === errorUrlId && (!data.frag || level.details)) {\n this.penalizeRendition(level, data);\n }\n for (let i = 1; i < redundantLevels; i++) {\n const newUrlId = (errorUrlId + i) % redundantLevels;\n const penalizedRendition = penalizedRenditions[newUrlId];\n // Check if rendition is penalized and skip if it is a bad fit for failover\n if (\n !penalizedRendition ||\n checkExpired(penalizedRendition, data, penalizedRenditions[errorUrlId])\n ) {\n // delete penalizedRenditions[newUrlId];\n // Update the url id of all levels so that we stay on the same set of variants when level switching\n this.warn(\n `Switching to Redundant Stream ${newUrlId + 1}/${redundantLevels}: \"${\n level.url[newUrlId]\n }\" after ${data.details}`\n );\n this.playlistError = 0;\n hls.levels.forEach((lv) => {\n lv.urlId = newUrlId;\n });\n hls.nextLoadLevel = levelIndex;\n return true;\n }\n }\n return false;\n }\n\n private penalizeRendition(level: Level, data: ErrorData) {\n const { penalizedRenditions } = this;\n const penalizedRendition = penalizedRenditions[level.urlId] || {\n lastErrorPerfMs: 0,\n errors: [],\n details: undefined,\n };\n penalizedRendition.lastErrorPerfMs = performance.now();\n penalizedRendition.errors.push(data);\n penalizedRendition.details = level.details;\n penalizedRenditions[level.urlId] = penalizedRendition;\n }\n}\n\nfunction checkExpired(\n penalizedRendition: PenalizedRendition,\n data: ErrorData,\n currentPenaltyState: PenalizedRendition | undefined\n): boolean {\n // Expire penalty for switching back to rendition after RENDITION_PENALTY_DURATION_MS\n if (\n performance.now() - penalizedRendition.lastErrorPerfMs >\n RENDITION_PENALTY_DURATION_MS\n ) {\n return true;\n }\n // Expire penalty on GAP tag error if rendition has no GAP at position (does not cover media tracks)\n const lastErrorDetails = penalizedRendition.details;\n if (data.details === ErrorDetails.FRAG_GAP && lastErrorDetails && data.frag) {\n const position = data.frag.start;\n const candidateFrag = findFragmentByPTS(\n null,\n lastErrorDetails.fragments,\n position\n );\n if (candidateFrag && !candidateFrag.gap) {\n return true;\n }\n }\n // Expire penalty if there are more errors in currentLevel than in penalizedRendition\n if (\n currentPenaltyState &&\n penalizedRendition.errors.length < currentPenaltyState.errors.length\n ) {\n const lastCandidateError =\n penalizedRendition.errors[penalizedRendition.errors.length - 1];\n if (\n lastErrorDetails &&\n lastCandidateError.frag &&\n data.frag &&\n Math.abs(lastCandidateError.frag.start - data.frag.start) >\n lastErrorDetails.targetduration * 3\n ) {\n return true;\n }\n }\n return false;\n}\n","/*\n * Level Controller\n */\n\nimport {\n ManifestLoadedData,\n ManifestParsedData,\n LevelLoadedData,\n TrackSwitchedData,\n FragLoadedData,\n ErrorData,\n LevelSwitchingData,\n LevelsUpdatedData,\n ManifestLoadingData,\n} from '../types/events';\nimport { Level } from '../types/level';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { isCodecSupportedInMp4 } from '../utils/codecs';\nimport BasePlaylistController from './base-playlist-controller';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport type Hls from '../hls';\nimport type { HlsUrlParameters, LevelParsed } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport ContentSteeringController from './content-steering-controller';\n\nlet chromeOrFirefox: boolean;\n\nexport default class LevelController extends BasePlaylistController {\n private _levels: Level[] = [];\n private _firstLevel: number = -1;\n private _startLevel?: number;\n private currentLevel: Level | null = null;\n private currentLevelIndex: number = -1;\n private manualLevelIndex: number = -1;\n private steering: ContentSteeringController | null;\n\n public onParsedComplete!: Function;\n\n constructor(\n hls: Hls,\n contentSteeringController: ContentSteeringController | null\n ) {\n super(hls, '[level-controller]');\n this.steering = contentSteeringController;\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n public destroy() {\n this._unregisterListeners();\n this.steering = null;\n this.resetLevels();\n super.destroy();\n }\n\n public startLoad(): void {\n const levels = this._levels;\n\n // clean up live level details to force reload them, and reset load errors\n levels.forEach((level) => {\n level.loadError = 0;\n level.fragmentError = 0;\n });\n\n super.startLoad();\n }\n\n private resetLevels() {\n this._startLevel = undefined;\n this.manualLevelIndex = -1;\n this.currentLevelIndex = -1;\n this.currentLevel = null;\n this._levels = [];\n }\n\n private onManifestLoading(\n event: Events.MANIFEST_LOADING,\n data: ManifestLoadingData\n ) {\n this.resetLevels();\n }\n\n protected onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ) {\n const levels: Level[] = [];\n const levelSet: { [key: string]: Level } = {};\n let levelFromSet: Level;\n\n // regroup redundant levels together\n data.levels.forEach((levelParsed: LevelParsed) => {\n const attributes = levelParsed.attrs;\n\n // erase audio codec info if browser does not support mp4a.40.34.\n // demuxer will autodetect codec and fallback to mpeg/audio\n if (levelParsed.audioCodec?.indexOf('mp4a.40.34') !== -1) {\n chromeOrFirefox ||= /chrome|firefox/i.test(navigator.userAgent);\n if (chromeOrFirefox) {\n levelParsed.audioCodec = undefined;\n }\n }\n\n const {\n AUDIO,\n CODECS,\n 'FRAME-RATE': FRAMERATE,\n 'PATHWAY-ID': PATHWAY,\n RESOLUTION,\n SUBTITLES,\n } = attributes;\n const contentSteeringPrefix = __USE_CONTENT_STEERING__\n ? `${PATHWAY || '.'}-`\n : '';\n const levelKey = `${contentSteeringPrefix}${levelParsed.bitrate}-${RESOLUTION}-${FRAMERATE}-${CODECS}`;\n levelFromSet = levelSet[levelKey];\n\n if (!levelFromSet) {\n levelFromSet = new Level(levelParsed);\n levelSet[levelKey] = levelFromSet;\n levels.push(levelFromSet);\n } else {\n levelFromSet.addFallback(levelParsed);\n }\n\n addGroupId(levelFromSet, 'audio', AUDIO);\n addGroupId(levelFromSet, 'text', SUBTITLES);\n });\n\n this.filterAndSortMediaOptions(levels, data);\n }\n\n private filterAndSortMediaOptions(\n unfilteredLevels: Level[],\n data: ManifestLoadedData\n ) {\n let audioTracks: MediaPlaylist[] = [];\n let subtitleTracks: MediaPlaylist[] = [];\n\n let resolutionFound = false;\n let videoCodecFound = false;\n let audioCodecFound = false;\n\n // only keep levels with supported audio/video codecs\n let levels = unfilteredLevels.filter(\n ({ audioCodec, videoCodec, width, height, unknownCodecs }) => {\n resolutionFound ||= !!(width && height);\n videoCodecFound ||= !!videoCodec;\n audioCodecFound ||= !!audioCodec;\n return (\n !unknownCodecs?.length &&\n (!audioCodec || isCodecSupportedInMp4(audioCodec, 'audio')) &&\n (!videoCodec || isCodecSupportedInMp4(videoCodec, 'video'))\n );\n }\n );\n\n // remove audio-only level if we also have levels with video codecs or RESOLUTION signalled\n if ((resolutionFound || videoCodecFound) && audioCodecFound) {\n levels = levels.filter(\n ({ videoCodec, width, height }) => !!videoCodec || !!(width && height)\n );\n }\n\n if (levels.length === 0) {\n // Dispatch error after MANIFEST_LOADED is done propagating\n Promise.resolve().then(() => {\n if (this.hls) {\n const error = new Error(\n 'no level with compatible codecs found in manifest'\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.MANIFEST_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n url: data.url,\n error,\n reason: error.message,\n });\n }\n });\n return;\n }\n\n if (data.audioTracks) {\n audioTracks = data.audioTracks.filter(\n (track) =>\n !track.audioCodec || isCodecSupportedInMp4(track.audioCodec, 'audio')\n );\n // Assign ids after filtering as array indices by group-id\n assignTrackIdsByGroup(audioTracks);\n }\n\n if (data.subtitles) {\n subtitleTracks = data.subtitles;\n assignTrackIdsByGroup(subtitleTracks);\n }\n // start bitrate is the first bitrate of the manifest\n const unsortedLevels = levels.slice(0);\n // sort levels from lowest to highest\n levels.sort((a, b) => {\n if (a.attrs['HDCP-LEVEL'] !== b.attrs['HDCP-LEVEL']) {\n return (a.attrs['HDCP-LEVEL'] || '') > (b.attrs['HDCP-LEVEL'] || '')\n ? 1\n : -1;\n }\n if (a.bitrate !== b.bitrate) {\n return a.bitrate - b.bitrate;\n }\n if (a.attrs['FRAME-RATE'] !== b.attrs['FRAME-RATE']) {\n return (\n a.attrs.decimalFloatingPoint('FRAME-RATE') -\n b.attrs.decimalFloatingPoint('FRAME-RATE')\n );\n }\n if (a.attrs.SCORE !== b.attrs.SCORE) {\n return (\n a.attrs.decimalFloatingPoint('SCORE') -\n b.attrs.decimalFloatingPoint('SCORE')\n );\n }\n if (resolutionFound && a.height !== b.height) {\n return a.height - b.height;\n }\n return 0;\n });\n\n let firstLevelInPlaylist = unsortedLevels[0];\n if (this.steering) {\n levels = this.steering.filterParsedLevels(levels);\n if (levels.length !== unsortedLevels.length) {\n for (let i = 0; i < unsortedLevels.length; i++) {\n if (unsortedLevels[i].pathwayId === levels[0].pathwayId) {\n firstLevelInPlaylist = unsortedLevels[i];\n break;\n }\n }\n }\n }\n\n this._levels = levels;\n\n // find index of first level in sorted levels\n for (let i = 0; i < levels.length; i++) {\n if (levels[i] === firstLevelInPlaylist) {\n this._firstLevel = i;\n this.log(\n `manifest loaded, ${levels.length} level(s) found, first bitrate: ${firstLevelInPlaylist.bitrate}`\n );\n break;\n }\n }\n\n // Audio is only alternate if manifest include a URI along with the audio group tag,\n // and this is not an audio-only stream where levels contain audio-only\n const audioOnly = audioCodecFound && !videoCodecFound;\n const edata: ManifestParsedData = {\n levels,\n audioTracks,\n subtitleTracks,\n sessionData: data.sessionData,\n sessionKeys: data.sessionKeys,\n firstLevel: this._firstLevel,\n stats: data.stats,\n audio: audioCodecFound,\n video: videoCodecFound,\n altAudio: !audioOnly && audioTracks.some((t) => !!t.url),\n };\n this.hls.trigger(Events.MANIFEST_PARSED, edata);\n\n // Initiate loading after all controllers have received MANIFEST_PARSED\n if (this.hls.config.autoStartLoad || this.hls.forceStartLoad) {\n this.hls.startLoad(this.hls.config.startPosition);\n }\n }\n\n get levels(): Level[] | null {\n if (this._levels.length === 0) {\n return null;\n }\n return this._levels;\n }\n\n get level(): number {\n return this.currentLevelIndex;\n }\n\n set level(newLevel: number) {\n const levels = this._levels;\n if (levels.length === 0) {\n return;\n }\n // check if level idx is valid\n if (newLevel < 0 || newLevel >= levels.length) {\n // invalid level id given, trigger error\n const error = new Error('invalid level idx');\n const fatal = newLevel < 0;\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.LEVEL_SWITCH_ERROR,\n level: newLevel,\n fatal,\n error,\n reason: error.message,\n });\n if (fatal) {\n return;\n }\n newLevel = Math.min(newLevel, levels.length - 1);\n }\n\n const lastLevelIndex = this.currentLevelIndex;\n const lastLevel = this.currentLevel;\n const lastPathwayId = lastLevel ? lastLevel.attrs['PATHWAY-ID'] : undefined;\n const level = levels[newLevel];\n const pathwayId = level.attrs['PATHWAY-ID'];\n this.currentLevelIndex = newLevel;\n this.currentLevel = level;\n\n if (\n lastLevelIndex === newLevel &&\n level.details &&\n lastLevel &&\n lastPathwayId === pathwayId\n ) {\n return;\n }\n\n this.log(\n `Switching to level ${newLevel}${\n pathwayId ? ' with Pathway ' + pathwayId : ''\n } from level ${lastLevelIndex}${\n lastPathwayId ? ' with Pathway ' + lastPathwayId : ''\n }`\n );\n\n const levelSwitchingData: LevelSwitchingData = Object.assign({}, level, {\n level: newLevel,\n maxBitrate: level.maxBitrate,\n attrs: level.attrs,\n uri: level.uri,\n urlId: level.urlId,\n });\n // @ts-ignore\n delete levelSwitchingData._attrs;\n // @ts-ignore\n delete levelSwitchingData._urlId;\n this.hls.trigger(Events.LEVEL_SWITCHING, levelSwitchingData);\n // check if we need to load playlist for this level\n const levelDetails = level.details;\n if (!levelDetails || levelDetails.live) {\n // level not retrieved yet, or live playlist we need to (re)load it\n const hlsUrlParameters = this.switchParams(level.uri, lastLevel?.details);\n this.loadPlaylist(hlsUrlParameters);\n }\n }\n\n get manualLevel(): number {\n return this.manualLevelIndex;\n }\n\n set manualLevel(newLevel) {\n this.manualLevelIndex = newLevel;\n if (this._startLevel === undefined) {\n this._startLevel = newLevel;\n }\n\n if (newLevel !== -1) {\n this.level = newLevel;\n }\n }\n\n get firstLevel(): number {\n return this._firstLevel;\n }\n\n set firstLevel(newLevel) {\n this._firstLevel = newLevel;\n }\n\n get startLevel() {\n // hls.startLevel takes precedence over config.startLevel\n // if none of these values are defined, fallback on this._firstLevel (first quality level appearing in variant manifest)\n if (this._startLevel === undefined) {\n const configStartLevel = this.hls.config.startLevel;\n if (configStartLevel !== undefined) {\n return configStartLevel;\n } else {\n return this._firstLevel;\n }\n } else {\n return this._startLevel;\n }\n }\n\n set startLevel(newLevel) {\n this._startLevel = newLevel;\n }\n\n protected onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.LEVEL &&\n data.context.level === this.level\n ) {\n this.checkRetry(data);\n }\n }\n\n // reset errors on the successful load of a fragment\n protected onFragLoaded(event: Events.FRAG_LOADED, { frag }: FragLoadedData) {\n if (frag !== undefined && frag.type === PlaylistLevelType.MAIN) {\n const level = this._levels[frag.level];\n if (level !== undefined) {\n level.loadError = 0;\n }\n }\n }\n\n protected onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const { level, details } = data;\n const curLevel = this._levels[level];\n\n if (!curLevel) {\n this.warn(`Invalid level index ${level}`);\n if (data.deliveryDirectives?.skip) {\n details.deltaUpdateFailed = true;\n }\n return;\n }\n\n // only process level loaded events matching with expected level\n if (level === this.currentLevelIndex) {\n // reset level load error counter on successful level loaded only if there is no issues with fragments\n if (curLevel.fragmentError === 0) {\n curLevel.loadError = 0;\n }\n this.playlistLoaded(level, data, curLevel.details);\n } else if (data.deliveryDirectives?.skip) {\n // received a delta playlist update that cannot be merged\n details.deltaUpdateFailed = true;\n }\n }\n\n protected onAudioTrackSwitched(\n event: Events.AUDIO_TRACK_SWITCHED,\n data: TrackSwitchedData\n ) {\n const currentLevel = this.currentLevel;\n if (!currentLevel) {\n return;\n }\n\n const audioGroupId = this.hls.audioTracks[data.id].groupId;\n if (\n currentLevel.audioGroupIds &&\n currentLevel.audioGroupId !== audioGroupId\n ) {\n let urlId = -1;\n for (let i = 0; i < currentLevel.audioGroupIds.length; i++) {\n if (currentLevel.audioGroupIds[i] === audioGroupId) {\n urlId = i;\n break;\n }\n }\n\n if (urlId !== -1 && urlId !== currentLevel.urlId) {\n currentLevel.urlId = urlId;\n if (this.canLoad) {\n this.startLoad();\n }\n }\n }\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters) {\n super.loadPlaylist();\n const currentLevelIndex = this.currentLevelIndex;\n const currentLevel = this.currentLevel;\n\n if (currentLevel && this.shouldLoadPlaylist(currentLevel)) {\n const id = currentLevel.urlId;\n let url = currentLevel.uri;\n if (hlsUrlParameters) {\n try {\n url = hlsUrlParameters.addDirectives(url);\n } catch (error) {\n this.warn(\n `Could not construct new URL with HLS Delivery Directives: ${error}`\n );\n }\n }\n\n const pathwayId = currentLevel.attrs['PATHWAY-ID'];\n this.log(\n `Loading level index ${currentLevelIndex}${\n hlsUrlParameters?.msn !== undefined\n ? ' at sn ' +\n hlsUrlParameters.msn +\n ' part ' +\n hlsUrlParameters.part\n : ''\n } with${pathwayId ? ' Pathway ' + pathwayId : ''} URI ${id + 1}/${\n currentLevel.url.length\n } ${url}`\n );\n\n // console.log('Current audio track group ID:', this.hls.audioTracks[this.hls.audioTrack].groupId);\n // console.log('New video quality level audio group id:', levelObject.attrs.AUDIO, level);\n this.clearTimer();\n this.hls.trigger(Events.LEVEL_LOADING, {\n url,\n level: currentLevelIndex,\n id,\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n\n get nextLoadLevel() {\n if (this.manualLevelIndex !== -1) {\n return this.manualLevelIndex;\n } else {\n return this.hls.nextAutoLevel;\n }\n }\n\n set nextLoadLevel(nextLevel) {\n this.level = nextLevel;\n if (this.manualLevelIndex === -1) {\n this.hls.nextAutoLevel = nextLevel;\n }\n }\n\n removeLevel(levelIndex, urlId) {\n const filterLevelAndGroupByIdIndex = (url, id) => id !== urlId;\n const levels = this._levels.filter((level, index) => {\n if (index !== levelIndex) {\n return true;\n }\n\n if (level.url.length > 1 && urlId !== undefined) {\n level.url = level.url.filter(filterLevelAndGroupByIdIndex);\n if (level.audioGroupIds) {\n level.audioGroupIds = level.audioGroupIds.filter(\n filterLevelAndGroupByIdIndex\n );\n }\n if (level.textGroupIds) {\n level.textGroupIds = level.textGroupIds.filter(\n filterLevelAndGroupByIdIndex\n );\n }\n level.urlId = 0;\n return true;\n }\n if (this.steering) {\n this.steering.removeLevel(level);\n }\n return false;\n });\n\n this.hls.trigger(Events.LEVELS_UPDATED, { levels });\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n { levels }: LevelsUpdatedData\n ) {\n levels.forEach((level, index) => {\n const { details } = level;\n if (details?.fragments) {\n details.fragments.forEach((fragment) => {\n fragment.level = index;\n });\n }\n });\n this._levels = levels;\n }\n}\n\nexport function addGroupId(\n level: Level,\n type: string,\n id: string | undefined\n): void {\n if (!id) {\n return;\n }\n if (type === 'audio') {\n if (!level.audioGroupIds) {\n level.audioGroupIds = [];\n }\n level.audioGroupIds[level.url.length - 1] = id;\n } else if (type === 'text') {\n if (!level.textGroupIds) {\n level.textGroupIds = [];\n }\n level.textGroupIds[level.url.length - 1] = id;\n }\n}\n\nfunction assignTrackIdsByGroup(tracks: MediaPlaylist[]): void {\n const groups = {};\n tracks.forEach((track) => {\n const groupId = track.groupId || '';\n track.id = groups[groupId] = groups[groupId] || 0;\n groups[groupId]++;\n });\n}\n","import type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport { getSkipValue, HlsSkip, HlsUrlParameters, Level } from '../types/level';\nimport { computeReloadInterval, mergeDetails } from './level-helper';\nimport { ErrorData } from '../types/events';\nimport { getRetryDelay, isTimeoutError } from '../utils/error-helper';\nimport { NetworkErrorAction } from './error-controller';\nimport { logger } from '../utils/logger';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport type {\n AudioTrackLoadedData,\n LevelLoadedData,\n TrackLoadedData,\n} from '../types/events';\n\nexport default class BasePlaylistController implements NetworkComponentAPI {\n protected hls: Hls;\n protected timer: number = -1;\n protected requestScheduled: number = -1;\n protected canLoad: boolean = false;\n protected log: (msg: any) => void;\n protected warn: (msg: any) => void;\n\n constructor(hls: Hls, logPrefix: string) {\n this.log = logger.log.bind(logger, `${logPrefix}:`);\n this.warn = logger.warn.bind(logger, `${logPrefix}:`);\n this.hls = hls;\n }\n\n public destroy(): void {\n this.clearTimer();\n // @ts-ignore\n this.hls = this.log = this.warn = null;\n }\n\n protected clearTimer(): void {\n clearTimeout(this.timer);\n this.timer = -1;\n }\n\n public startLoad(): void {\n this.canLoad = true;\n this.requestScheduled = -1;\n this.loadPlaylist();\n }\n\n public stopLoad(): void {\n this.canLoad = false;\n this.clearTimer();\n }\n\n protected switchParams(\n playlistUri: string,\n previous: LevelDetails | undefined\n ): HlsUrlParameters | undefined {\n const renditionReports = previous?.renditionReports;\n if (renditionReports) {\n let foundIndex = -1;\n for (let i = 0; i < renditionReports.length; i++) {\n const attr = renditionReports[i];\n let uri: string;\n try {\n uri = new self.URL(attr.URI, previous.url).href;\n } catch (error) {\n logger.warn(\n `Could not construct new URL for Rendition Report: ${error}`\n );\n uri = attr.URI || '';\n }\n // Use exact match. Otherwise, the last partial match, if any, will be used\n // (Playlist URI includes a query string that the Rendition Report does not)\n if (uri === playlistUri) {\n foundIndex = i;\n break;\n } else if (uri === playlistUri.substring(0, uri.length)) {\n foundIndex = i;\n }\n }\n if (foundIndex !== -1) {\n const attr = renditionReports[foundIndex];\n const msn = parseInt(attr['LAST-MSN']) || previous?.lastPartSn;\n let part = parseInt(attr['LAST-PART']) || previous?.lastPartIndex;\n if (this.hls.config.lowLatencyMode) {\n const currentGoal = Math.min(\n previous.age - previous.partTarget,\n previous.targetduration\n );\n if (part >= 0 && currentGoal > previous.partTarget) {\n part += 1;\n }\n }\n return new HlsUrlParameters(\n msn,\n part >= 0 ? part : undefined,\n HlsSkip.No\n );\n }\n }\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n if (this.requestScheduled === -1) {\n this.requestScheduled = self.performance.now();\n }\n // Loading is handled by the subclasses\n }\n\n protected shouldLoadPlaylist(\n playlist: Level | MediaPlaylist | null | undefined\n ): boolean {\n return (\n this.canLoad &&\n !!playlist &&\n !!playlist.url &&\n (!playlist.details || playlist.details.live)\n );\n }\n\n protected shouldReloadPlaylist(\n playlist: Level | MediaPlaylist | null | undefined\n ): boolean {\n return (\n this.timer === -1 &&\n this.requestScheduled === -1 &&\n this.shouldLoadPlaylist(playlist)\n );\n }\n\n protected playlistLoaded(\n index: number,\n data: LevelLoadedData | AudioTrackLoadedData | TrackLoadedData,\n previousDetails?: LevelDetails\n ) {\n const { details, stats } = data;\n\n // Set last updated date-time\n const now = self.performance.now();\n const elapsed = stats.loading.first\n ? Math.max(0, now - stats.loading.first)\n : 0;\n details.advancedDateTime = Date.now() - elapsed;\n\n // if current playlist is a live playlist, arm a timer to reload it\n if (details.live || previousDetails?.live) {\n details.reloaded(previousDetails);\n if (previousDetails) {\n this.log(\n `live playlist ${index} ${\n details.advanced\n ? 'REFRESHED ' + details.lastPartSn + '-' + details.lastPartIndex\n : details.updated\n ? 'UPDATED'\n : 'MISSED'\n }`\n );\n }\n // Merge live playlists to adjust fragment starts and fill in delta playlist skipped segments\n if (previousDetails && details.fragments.length > 0) {\n mergeDetails(previousDetails, details);\n }\n if (!this.canLoad || !details.live) {\n return;\n }\n let deliveryDirectives: HlsUrlParameters | undefined;\n let msn: number | undefined = undefined;\n let part: number | undefined = undefined;\n if (details.canBlockReload && details.endSN && details.advanced) {\n // Load level with LL-HLS delivery directives\n const lowLatencyMode = this.hls.config.lowLatencyMode;\n const lastPartSn = details.lastPartSn;\n const endSn = details.endSN;\n const lastPartIndex = details.lastPartIndex;\n const hasParts = lastPartIndex !== -1;\n const lastPart = lastPartSn === endSn;\n // When low latency mode is disabled, we'll skip part requests once the last part index is found\n const nextSnStartIndex = lowLatencyMode ? 0 : lastPartIndex;\n if (hasParts) {\n msn = lastPart ? endSn + 1 : lastPartSn;\n part = lastPart ? nextSnStartIndex : lastPartIndex + 1;\n } else {\n msn = endSn + 1;\n }\n // Low-Latency CDN Tune-in: \"age\" header and time since load indicates we're behind by more than one part\n // Update directives to obtain the Playlist that has the estimated additional duration of media\n const lastAdvanced = details.age;\n const cdnAge = lastAdvanced + details.ageHeader;\n let currentGoal = Math.min(\n cdnAge - details.partTarget,\n details.targetduration * 1.5\n );\n if (currentGoal > 0) {\n if (previousDetails && currentGoal > previousDetails.tuneInGoal) {\n // If we attempted to get the next or latest playlist update, but currentGoal increased,\n // then we either can't catchup, or the \"age\" header cannot be trusted.\n this.warn(\n `CDN Tune-in goal increased from: ${previousDetails.tuneInGoal} to: ${currentGoal} with playlist age: ${details.age}`\n );\n currentGoal = 0;\n } else {\n const segments = Math.floor(currentGoal / details.targetduration);\n msn += segments;\n if (part !== undefined) {\n const parts = Math.round(\n (currentGoal % details.targetduration) / details.partTarget\n );\n part += parts;\n }\n this.log(\n `CDN Tune-in age: ${\n details.ageHeader\n }s last advanced ${lastAdvanced.toFixed(\n 2\n )}s goal: ${currentGoal} skip sn ${segments} to part ${part}`\n );\n }\n details.tuneInGoal = currentGoal;\n }\n deliveryDirectives = this.getDeliveryDirectives(\n details,\n data.deliveryDirectives,\n msn,\n part\n );\n if (lowLatencyMode || !lastPart) {\n this.loadPlaylist(deliveryDirectives);\n return;\n }\n } else if (details.canBlockReload || details.canSkipUntil) {\n deliveryDirectives = this.getDeliveryDirectives(\n details,\n data.deliveryDirectives,\n msn,\n part\n );\n }\n const bufferInfo = this.hls.mainForwardBufferInfo;\n const position = bufferInfo ? bufferInfo.end - bufferInfo.len : 0;\n const distanceToLiveEdgeMs = (details.edge - position) * 1000;\n const reloadInterval = computeReloadInterval(\n details,\n distanceToLiveEdgeMs\n );\n if (details.updated && now > this.requestScheduled + reloadInterval) {\n this.requestScheduled = stats.loading.start;\n }\n\n if (msn !== undefined && details.canBlockReload) {\n this.requestScheduled =\n stats.loading.first +\n reloadInterval -\n (details.partTarget * 1000 || 1000);\n } else if (\n this.requestScheduled === -1 ||\n this.requestScheduled + reloadInterval < now\n ) {\n this.requestScheduled = now;\n } else if (this.requestScheduled - now <= 0) {\n this.requestScheduled += reloadInterval;\n }\n let estimatedTimeUntilUpdate = this.requestScheduled - now;\n estimatedTimeUntilUpdate = Math.max(0, estimatedTimeUntilUpdate);\n this.log(\n `reload live playlist ${index} in ${Math.round(\n estimatedTimeUntilUpdate\n )} ms`\n );\n // this.log(\n // `live reload ${details.updated ? 'REFRESHED' : 'MISSED'}\n // reload in ${estimatedTimeUntilUpdate / 1000}\n // round trip ${(stats.loading.end - stats.loading.start) / 1000}\n // diff ${\n // (reloadInterval -\n // (estimatedTimeUntilUpdate +\n // stats.loading.end -\n // stats.loading.start)) /\n // 1000\n // }\n // reload interval ${reloadInterval / 1000}\n // target duration ${details.targetduration}\n // distance to edge ${distanceToLiveEdgeMs / 1000}`\n // );\n\n this.timer = self.setTimeout(\n () => this.loadPlaylist(deliveryDirectives),\n estimatedTimeUntilUpdate\n );\n } else {\n this.clearTimer();\n }\n }\n\n private getDeliveryDirectives(\n details: LevelDetails,\n previousDeliveryDirectives: HlsUrlParameters | null,\n msn?: number,\n part?: number\n ): HlsUrlParameters {\n let skip = getSkipValue(details, msn);\n if (previousDeliveryDirectives?.skip && details.deltaUpdateFailed) {\n msn = previousDeliveryDirectives.msn;\n part = previousDeliveryDirectives.part;\n skip = HlsSkip.No;\n }\n return new HlsUrlParameters(msn, part, skip);\n }\n\n protected checkRetry(errorEvent: ErrorData): boolean {\n const errorDetails = errorEvent.details;\n const isTimeout = isTimeoutError(errorEvent);\n const errorAction = errorEvent.errorAction;\n const { action, retryCount = 0, retryConfig } = errorAction || {};\n const retry =\n !!errorAction &&\n !!retryConfig &&\n (action === NetworkErrorAction.RetryRequest ||\n (!errorAction.resolved &&\n action === NetworkErrorAction.SendAlternateToPenaltyBox));\n if (retry) {\n this.requestScheduled = -1;\n if (retryCount >= retryConfig.maxNumRetry) {\n return false;\n }\n if (isTimeout && errorEvent.context?.deliveryDirectives) {\n // The LL-HLS request already timed out so retry immediately\n this.warn(\n `Retrying playlist loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } after \"${errorDetails}\" without delivery-directives`\n );\n this.loadPlaylist();\n } else {\n const delay = getRetryDelay(retryConfig, retryCount);\n // Schedule level/track reload\n this.timer = self.setTimeout(() => this.loadPlaylist(), delay);\n this.warn(\n `Retrying playlist loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } after \"${errorDetails}\" in ${delay}ms`\n );\n }\n // `levelRetry = true` used to inform other controllers that a retry is happening\n errorEvent.levelRetry = true;\n errorAction.resolved = true;\n }\n return retry;\n }\n}\n","import { Events } from '../events';\nimport { Fragment, Part } from '../loader/fragment';\nimport { PlaylistLevelType } from '../types/loader';\nimport type { SourceBufferName } from '../types/buffer';\nimport type {\n FragmentBufferedRange,\n FragmentEntity,\n FragmentTimeRange,\n} from '../types/fragment-tracker';\nimport type { ComponentAPI } from '../types/component-api';\nimport type {\n BufferAppendedData,\n FragBufferedData,\n FragLoadedData,\n} from '../types/events';\nimport type Hls from '../hls';\n\nexport const enum FragmentState {\n NOT_LOADED = 'NOT_LOADED',\n APPENDING = 'APPENDING',\n PARTIAL = 'PARTIAL',\n OK = 'OK',\n}\n\nexport class FragmentTracker implements ComponentAPI {\n private activePartLists: { [key in PlaylistLevelType]?: Part[] } =\n Object.create(null);\n private endListFragments: { [key in PlaylistLevelType]?: FragmentEntity } =\n Object.create(null);\n private fragments: Partial<Record<string, FragmentEntity>> =\n Object.create(null);\n private timeRanges:\n | {\n [key in SourceBufferName]?: TimeRanges;\n }\n | null = Object.create(null);\n\n private bufferPadding: number = 0.2;\n private hls: Hls;\n private hasGaps: boolean = false;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.BUFFER_APPENDED, this.onBufferAppended, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n }\n\n public destroy() {\n this._unregisterListeners();\n // @ts-ignore\n this.fragments =\n // @ts-ignore\n this.activePartLists =\n // @ts-ignore\n this.endListFragments =\n this.timeRanges =\n null;\n }\n\n /**\n * Return a Fragment or Part with an appended range that matches the position and levelType\n * Otherwise, return null\n */\n public getAppendedFrag(\n position: number,\n levelType: PlaylistLevelType\n ): Fragment | Part | null {\n const activeParts = this.activePartLists[levelType];\n if (activeParts) {\n for (let i = activeParts.length; i--; ) {\n const activePart = activeParts[i];\n if (!activePart) {\n break;\n }\n const appendedPTS = activePart.end;\n if (\n activePart.start <= position &&\n appendedPTS !== null &&\n position <= appendedPTS\n ) {\n return activePart;\n }\n }\n }\n return this.getBufferedFrag(position, levelType);\n }\n\n /**\n * Return a buffered Fragment that matches the position and levelType.\n * A buffered Fragment is one whose loading, parsing and appending is done (completed or \"partial\" meaning aborted).\n * If not found any Fragment, return null\n */\n public getBufferedFrag(\n position: number,\n levelType: PlaylistLevelType\n ): Fragment | null {\n const { fragments } = this;\n const keys = Object.keys(fragments);\n for (let i = keys.length; i--; ) {\n const fragmentEntity = fragments[keys[i]];\n if (fragmentEntity?.body.type === levelType && fragmentEntity.buffered) {\n const frag = fragmentEntity.body;\n if (frag.start <= position && position <= frag.end) {\n return frag;\n }\n }\n }\n return null;\n }\n\n /**\n * Partial fragments effected by coded frame eviction will be removed\n * The browser will unload parts of the buffer to free up memory for new buffer data\n * 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)\n */\n public detectEvictedFragments(\n elementaryStream: SourceBufferName,\n timeRange: TimeRanges,\n playlistType: PlaylistLevelType,\n appendedPart?: Part | null\n ) {\n if (this.timeRanges) {\n this.timeRanges[elementaryStream] = timeRange;\n }\n // Check if any flagged fragments have been unloaded\n // excluding anything newer than appendedPartSn\n const appendedPartSn = (appendedPart?.fragment.sn || -1) as number;\n Object.keys(this.fragments).forEach((key) => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (appendedPartSn >= (fragmentEntity.body.sn as number)) {\n return;\n }\n if (!fragmentEntity.buffered && !fragmentEntity.loaded) {\n if (fragmentEntity.body.type === playlistType) {\n this.removeFragment(fragmentEntity.body);\n }\n return;\n }\n const esData = fragmentEntity.range[elementaryStream];\n if (!esData) {\n return;\n }\n esData.time.some((time: FragmentTimeRange) => {\n const isNotBuffered = !this.isTimeBuffered(\n time.startPTS,\n time.endPTS,\n timeRange\n );\n if (isNotBuffered) {\n // Unregister partial fragment as it needs to load again to be reused\n this.removeFragment(fragmentEntity.body);\n }\n return isNotBuffered;\n });\n });\n }\n\n /**\n * Checks if the fragment passed in is loaded in the buffer properly\n * Partially loaded fragments will be registered as a partial fragment\n */\n public detectPartialFragments(data: FragBufferedData) {\n const timeRanges = this.timeRanges;\n const { frag, part } = data;\n if (!timeRanges || frag.sn === 'initSegment') {\n return;\n }\n\n const fragKey = getFragmentKey(frag);\n const fragmentEntity = this.fragments[fragKey];\n if (!fragmentEntity || (fragmentEntity.buffered && frag.gap)) {\n return;\n }\n const isFragHint = !frag.relurl;\n Object.keys(timeRanges).forEach((elementaryStream: SourceBufferName) => {\n const streamInfo = frag.elementaryStreams[elementaryStream];\n if (!streamInfo) {\n return;\n }\n const timeRange = timeRanges[elementaryStream] as TimeRanges;\n const partial = isFragHint || streamInfo.partial === true;\n fragmentEntity.range[elementaryStream] = this.getBufferedTimes(\n frag,\n part,\n partial,\n timeRange\n );\n });\n fragmentEntity.loaded = null;\n if (Object.keys(fragmentEntity.range).length) {\n fragmentEntity.buffered = true;\n const endList = (fragmentEntity.body.endList =\n frag.endList || fragmentEntity.body.endList);\n if (endList) {\n this.endListFragments[fragmentEntity.body.type] = fragmentEntity;\n }\n if (!isPartial(fragmentEntity)) {\n // Remove older fragment parts from lookup after frag is tracked as buffered\n this.removeParts((frag.sn as number) - 1, frag.type);\n }\n } else {\n // remove fragment if nothing was appended\n this.removeFragment(fragmentEntity.body);\n }\n }\n\n private removeParts(snToKeep: number, levelType: PlaylistLevelType) {\n const activeParts = this.activePartLists[levelType];\n if (!activeParts) {\n return;\n }\n this.activePartLists[levelType] = activeParts.filter(\n (part) => (part.fragment.sn as number) >= snToKeep\n );\n }\n\n public fragBuffered(frag: Fragment, force?: true) {\n const fragKey = getFragmentKey(frag);\n let fragmentEntity = this.fragments[fragKey];\n if (!fragmentEntity && force) {\n fragmentEntity = this.fragments[fragKey] = {\n body: frag,\n appendedPTS: null,\n loaded: null,\n buffered: false,\n range: Object.create(null),\n };\n if (frag.gap) {\n this.hasGaps = true;\n }\n }\n if (fragmentEntity) {\n fragmentEntity.loaded = null;\n fragmentEntity.buffered = true;\n }\n }\n\n private getBufferedTimes(\n fragment: Fragment,\n part: Part | null,\n partial: boolean,\n timeRange: TimeRanges\n ): FragmentBufferedRange {\n const buffered: FragmentBufferedRange = {\n time: [],\n partial,\n };\n const startPTS = fragment.start;\n const endPTS = fragment.end;\n const minEndPTS = fragment.minEndPTS || endPTS;\n const maxStartPTS = fragment.maxStartPTS || startPTS;\n for (let i = 0; i < timeRange.length; i++) {\n const startTime = timeRange.start(i) - this.bufferPadding;\n const endTime = timeRange.end(i) + this.bufferPadding;\n if (maxStartPTS >= startTime && minEndPTS <= endTime) {\n // Fragment is entirely contained in buffer\n // No need to check the other timeRange times since it's completely playable\n buffered.time.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i)),\n });\n break;\n } else if (startPTS < endTime && endPTS > startTime) {\n buffered.partial = true;\n // Check for intersection with buffer\n // Get playable sections of the fragment\n buffered.time.push({\n startPTS: Math.max(startPTS, timeRange.start(i)),\n endPTS: Math.min(endPTS, timeRange.end(i)),\n });\n } else if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n break;\n }\n }\n return buffered;\n }\n\n /**\n * Gets the partial fragment for a certain time\n */\n public getPartialFragment(time: number): Fragment | null {\n let bestFragment: Fragment | null = null;\n let timePadding: number;\n let startTime: number;\n let endTime: number;\n let bestOverlap: number = 0;\n const { bufferPadding, fragments } = this;\n Object.keys(fragments).forEach((key) => {\n const fragmentEntity = fragments[key];\n if (!fragmentEntity) {\n return;\n }\n if (isPartial(fragmentEntity)) {\n startTime = fragmentEntity.body.start - bufferPadding;\n endTime = fragmentEntity.body.end + bufferPadding;\n if (time >= startTime && time <= endTime) {\n // Use the fragment that has the most padding from start and end time\n timePadding = Math.min(time - startTime, endTime - time);\n if (bestOverlap <= timePadding) {\n bestFragment = fragmentEntity.body;\n bestOverlap = timePadding;\n }\n }\n }\n });\n return bestFragment;\n }\n\n public isEndListAppended(type: PlaylistLevelType): boolean {\n const lastFragmentEntity = this.endListFragments[type];\n return (\n lastFragmentEntity !== undefined &&\n (lastFragmentEntity.buffered || isPartial(lastFragmentEntity))\n );\n }\n\n public getState(fragment: Fragment): FragmentState {\n const fragKey = getFragmentKey(fragment);\n const fragmentEntity = this.fragments[fragKey];\n\n if (fragmentEntity) {\n if (!fragmentEntity.buffered) {\n return FragmentState.APPENDING;\n } else if (isPartial(fragmentEntity)) {\n return FragmentState.PARTIAL;\n } else {\n return FragmentState.OK;\n }\n }\n\n return FragmentState.NOT_LOADED;\n }\n\n private isTimeBuffered(\n startPTS: number,\n endPTS: number,\n timeRange: TimeRanges\n ): boolean {\n let startTime;\n let endTime;\n for (let i = 0; i < timeRange.length; i++) {\n startTime = timeRange.start(i) - this.bufferPadding;\n endTime = timeRange.end(i) + this.bufferPadding;\n if (startPTS >= startTime && endPTS <= endTime) {\n return true;\n }\n\n if (endPTS <= startTime) {\n // No need to check the rest of the timeRange as it is in order\n return false;\n }\n }\n\n return false;\n }\n\n private onFragLoaded(event: Events.FRAG_LOADED, data: FragLoadedData) {\n const { frag, part } = data;\n // don't track initsegment (for which sn is not a number)\n // don't track frags used for bitrateTest, they're irrelevant.\n if (frag.sn === 'initSegment' || frag.bitrateTest) {\n return;\n }\n\n // Fragment entity `loaded` FragLoadedData is null when loading parts\n const loaded = part ? null : data;\n\n const fragKey = getFragmentKey(frag);\n this.fragments[fragKey] = {\n body: frag,\n appendedPTS: null,\n loaded,\n buffered: false,\n range: Object.create(null),\n };\n }\n\n private onBufferAppended(\n event: Events.BUFFER_APPENDED,\n data: BufferAppendedData\n ) {\n const { frag, part, timeRanges } = data;\n if (frag.sn === 'initSegment') {\n return;\n }\n const playlistType = frag.type;\n if (part) {\n let activeParts = this.activePartLists[playlistType];\n if (!activeParts) {\n this.activePartLists[playlistType] = activeParts = [];\n }\n activeParts.push(part);\n }\n // Store the latest timeRanges loaded in the buffer\n this.timeRanges = timeRanges;\n Object.keys(timeRanges).forEach((elementaryStream: SourceBufferName) => {\n const timeRange = timeRanges[elementaryStream] as TimeRanges;\n this.detectEvictedFragments(\n elementaryStream,\n timeRange,\n playlistType,\n part\n );\n });\n }\n\n private onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n this.detectPartialFragments(data);\n }\n\n private hasFragment(fragment: Fragment): boolean {\n const fragKey = getFragmentKey(fragment);\n return !!this.fragments[fragKey];\n }\n\n public hasParts(type: PlaylistLevelType): boolean {\n return !!this.activePartLists[type]?.length;\n }\n\n public removeFragmentsInRange(\n start: number,\n end: number,\n playlistType: PlaylistLevelType,\n withGapOnly?: boolean,\n unbufferedOnly?: boolean\n ) {\n if (withGapOnly && !this.hasGaps) {\n return;\n }\n Object.keys(this.fragments).forEach((key) => {\n const fragmentEntity = this.fragments[key];\n if (!fragmentEntity) {\n return;\n }\n const frag = fragmentEntity.body;\n if (frag.type !== playlistType || (withGapOnly && !frag.gap)) {\n return;\n }\n if (\n frag.start < end &&\n frag.end > start &&\n (fragmentEntity.buffered || unbufferedOnly)\n ) {\n this.removeFragment(frag);\n }\n });\n }\n\n public removeFragment(fragment: Fragment) {\n const fragKey = getFragmentKey(fragment);\n fragment.stats.loaded = 0;\n fragment.clearElementaryStreamInfo();\n const activeParts = this.activePartLists[fragment.type];\n if (activeParts) {\n const snToRemove = fragment.sn;\n this.activePartLists[fragment.type] = activeParts.filter(\n (part) => part.fragment.sn !== snToRemove\n );\n }\n delete this.fragments[fragKey];\n if (fragment.endList) {\n delete this.endListFragments[fragment.type];\n }\n }\n\n public removeAllFragments() {\n this.fragments = Object.create(null);\n this.endListFragments = Object.create(null);\n this.activePartLists = Object.create(null);\n this.hasGaps = false;\n }\n}\n\nfunction isPartial(fragmentEntity: FragmentEntity): boolean {\n return (\n fragmentEntity.buffered &&\n (fragmentEntity.body.gap ||\n fragmentEntity.range.video?.partial ||\n fragmentEntity.range.audio?.partial ||\n fragmentEntity.range.audiovideo?.partial)\n );\n}\n\nfunction getFragmentKey(fragment: Fragment): string {\n return `${fragment.type}_${fragment.level}_${fragment.urlId}_${fragment.sn}`;\n}\n","import { ErrorTypes, ErrorDetails } from '../errors';\nimport { Fragment } from './fragment';\nimport {\n Loader,\n LoaderConfiguration,\n FragmentLoaderContext,\n} from '../types/loader';\nimport { getLoaderConfigWithoutReties } from '../utils/error-helper';\nimport type { HlsConfig } from '../config';\nimport type { BaseSegment, Part } from './fragment';\nimport type {\n ErrorData,\n FragLoadedData,\n PartsLoadedData,\n} from '../types/events';\n\nconst MIN_CHUNK_SIZE = Math.pow(2, 17); // 128kb\n\nexport default class FragmentLoader {\n private readonly config: HlsConfig;\n private loader: Loader<FragmentLoaderContext> | null = null;\n private partLoadTimeout: number = -1;\n\n constructor(config: HlsConfig) {\n this.config = config;\n }\n\n destroy() {\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n }\n\n abort() {\n if (this.loader) {\n // Abort the loader for current fragment. Only one may load at any given time\n this.loader.abort();\n }\n }\n\n load(\n frag: Fragment,\n onProgress?: FragmentLoadProgressCallback\n ): Promise<FragLoadedData> {\n const url = frag.url;\n if (!url) {\n return Promise.reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n error: new Error(\n `Fragment does not have a ${url ? 'part list' : 'url'}`\n ),\n networkDetails: null,\n })\n );\n }\n this.abort();\n\n const config = this.config;\n const FragmentILoader = config.fLoader;\n const DefaultILoader = config.loader;\n\n return new Promise((resolve, reject) => {\n if (this.loader) {\n this.loader.destroy();\n }\n if (frag.gap) {\n if (frag.tagList.some((tags) => tags[0] === 'GAP')) {\n reject(createGapLoadError(frag));\n return;\n } else {\n // Reset temporary treatment as GAP tag\n frag.gap = false;\n }\n }\n const loader =\n (this.loader =\n frag.loader =\n FragmentILoader\n ? new FragmentILoader(config)\n : (new DefaultILoader(config) as Loader<FragmentLoaderContext>));\n const loaderContext = createLoaderContext(frag);\n const loadPolicy = getLoaderConfigWithoutReties(\n config.fragLoadPolicy.default\n );\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n highWaterMark: frag.sn === 'initSegment' ? Infinity : MIN_CHUNK_SIZE,\n };\n // Assign frag stats to the loader's stats reference\n frag.stats = loader.stats;\n loader.load(loaderContext, loaderConfig, {\n onSuccess: (response, stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n let payload = response.data as ArrayBuffer;\n if (context.resetIV && frag.decryptdata) {\n frag.decryptdata.iv = new Uint8Array(payload.slice(0, 16));\n payload = payload.slice(16);\n }\n resolve({\n frag,\n part: null,\n payload,\n networkDetails,\n });\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n response: { url, data: undefined, ...response },\n error: new Error(`HTTP Error ${response.code} ${response.text}`),\n networkDetails,\n stats,\n })\n );\n },\n onAbort: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n error: new Error('Aborted'),\n networkDetails,\n stats,\n })\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_TIMEOUT,\n fatal: false,\n frag,\n error: new Error(`Timeout after ${loaderConfig.timeout}ms`),\n networkDetails,\n stats,\n })\n );\n },\n onProgress: (stats, context, data, networkDetails) => {\n if (onProgress) {\n onProgress({\n frag,\n part: null,\n payload: data as ArrayBuffer,\n networkDetails,\n });\n }\n },\n });\n });\n }\n\n public loadPart(\n frag: Fragment,\n part: Part,\n onProgress: FragmentLoadProgressCallback\n ): Promise<FragLoadedData> {\n this.abort();\n\n const config = this.config;\n const FragmentILoader = config.fLoader;\n const DefaultILoader = config.loader;\n\n return new Promise((resolve, reject) => {\n if (this.loader) {\n this.loader.destroy();\n }\n if (frag.gap || part.gap) {\n reject(createGapLoadError(frag, part));\n return;\n }\n const loader =\n (this.loader =\n frag.loader =\n FragmentILoader\n ? new FragmentILoader(config)\n : (new DefaultILoader(config) as Loader<FragmentLoaderContext>));\n const loaderContext = createLoaderContext(frag, part);\n // Should we define another load policy for parts?\n const loadPolicy = getLoaderConfigWithoutReties(\n config.fragLoadPolicy.default\n );\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n highWaterMark: MIN_CHUNK_SIZE,\n };\n // Assign part stats to the loader's stats reference\n part.stats = loader.stats;\n loader.load(loaderContext, loaderConfig, {\n onSuccess: (response, stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n this.updateStatsFromPart(frag, part);\n const partLoadedData: FragLoadedData = {\n frag,\n part,\n payload: response.data as ArrayBuffer,\n networkDetails,\n };\n onProgress(partLoadedData);\n resolve(partLoadedData);\n },\n onError: (response, context, networkDetails, stats) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_ERROR,\n fatal: false,\n frag,\n part,\n response: {\n url: loaderContext.url,\n data: undefined,\n ...response,\n },\n error: new Error(`HTTP Error ${response.code} ${response.text}`),\n networkDetails,\n stats,\n })\n );\n },\n onAbort: (stats, context, networkDetails) => {\n frag.stats.aborted = part.stats.aborted;\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.INTERNAL_ABORTED,\n fatal: false,\n frag,\n part,\n error: new Error('Aborted'),\n networkDetails,\n stats,\n })\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n this.resetLoader(frag, loader);\n reject(\n new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details: ErrorDetails.FRAG_LOAD_TIMEOUT,\n fatal: false,\n frag,\n part,\n error: new Error(`Timeout after ${loaderConfig.timeout}ms`),\n networkDetails,\n stats,\n })\n );\n },\n });\n });\n }\n\n private updateStatsFromPart(frag: Fragment, part: Part) {\n const fragStats = frag.stats;\n const partStats = part.stats;\n const partTotal = partStats.total;\n fragStats.loaded += partStats.loaded;\n if (partTotal) {\n const estTotalParts = Math.round(frag.duration / part.duration);\n const estLoadedParts = Math.min(\n Math.round(fragStats.loaded / partTotal),\n estTotalParts\n );\n const estRemainingParts = estTotalParts - estLoadedParts;\n const estRemainingBytes =\n estRemainingParts * Math.round(fragStats.loaded / estLoadedParts);\n fragStats.total = fragStats.loaded + estRemainingBytes;\n } else {\n fragStats.total = Math.max(fragStats.loaded, fragStats.total);\n }\n const fragLoading = fragStats.loading;\n const partLoading = partStats.loading;\n if (fragLoading.start) {\n // add to fragment loader latency\n fragLoading.first += partLoading.first - partLoading.start;\n } else {\n fragLoading.start = partLoading.start;\n fragLoading.first = partLoading.first;\n }\n fragLoading.end = partLoading.end;\n }\n\n private resetLoader(frag: Fragment, loader: Loader<FragmentLoaderContext>) {\n frag.loader = null;\n if (this.loader === loader) {\n self.clearTimeout(this.partLoadTimeout);\n this.loader = null;\n }\n loader.destroy();\n }\n}\n\nfunction createLoaderContext(\n frag: Fragment,\n part: Part | null = null\n): FragmentLoaderContext {\n const segment: BaseSegment = part || frag;\n const loaderContext: FragmentLoaderContext = {\n frag,\n part,\n responseType: 'arraybuffer',\n url: segment.url,\n headers: {},\n rangeStart: 0,\n rangeEnd: 0,\n };\n const start = segment.byteRangeStartOffset;\n const end = segment.byteRangeEndOffset;\n if (Number.isFinite(start) && Number.isFinite(end)) {\n let byteRangeStart = start;\n let byteRangeEnd = end;\n if (frag.sn === 'initSegment' && frag.decryptdata?.method === 'AES-128') {\n // MAP segment encrypted with method 'AES-128', when served with HTTP Range,\n // has the unencrypted size specified in the range.\n // Ref: https://tools.ietf.org/html/draft-pantos-hls-rfc8216bis-08#section-6.3.6\n const fragmentLen = end - start;\n if (fragmentLen % 16) {\n byteRangeEnd = end + (16 - (fragmentLen % 16));\n }\n if (start !== 0) {\n loaderContext.resetIV = true;\n byteRangeStart = start - 16;\n }\n }\n loaderContext.rangeStart = byteRangeStart;\n loaderContext.rangeEnd = byteRangeEnd;\n }\n return loaderContext;\n}\n\nfunction createGapLoadError(frag: Fragment, part?: Part): LoadError {\n const error = new Error(`GAP ${frag.gap ? 'tag' : 'attribute'} found`);\n const errorData: FragLoadFailResult = {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_GAP,\n fatal: false,\n frag,\n error,\n networkDetails: null,\n };\n if (part) {\n errorData.part = part;\n }\n (part ? part : frag).stats.aborted = true;\n return new LoadError(errorData);\n}\n\nexport class LoadError extends Error {\n public readonly data: FragLoadFailResult;\n constructor(data: FragLoadFailResult) {\n super(data.error.message);\n this.data = data;\n }\n}\n\nexport interface FragLoadFailResult extends ErrorData {\n frag: Fragment;\n part?: Part;\n response?: {\n data: any;\n // error status code\n code: number;\n // error description\n text: string;\n url: string;\n };\n networkDetails: any;\n}\n\nexport type FragmentLoadProgressCallback = (\n result: FragLoadedData | PartsLoadedData\n) => void;\n","import { ErrorTypes, ErrorDetails } from '../errors';\nimport {\n LoaderStats,\n LoaderResponse,\n LoaderConfiguration,\n LoaderCallbacks,\n Loader,\n KeyLoaderContext,\n PlaylistLevelType,\n} from '../types/loader';\nimport { LoadError } from './fragment-loader';\nimport type { HlsConfig } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { KeyLoadedData } from '../types/events';\nimport type { LevelKey } from './level-key';\nimport type EMEController from '../controller/eme-controller';\nimport type { MediaKeySessionContext } from '../controller/eme-controller';\nimport type { KeySystemFormats } from '../utils/mediakeys-helper';\n\nexport interface KeyLoaderInfo {\n decryptdata: LevelKey;\n keyLoadPromise: Promise<KeyLoadedData> | null;\n loader: Loader<KeyLoaderContext> | null;\n mediaKeySessionContext: MediaKeySessionContext | null;\n}\nexport default class KeyLoader implements ComponentAPI {\n private readonly config: HlsConfig;\n public keyUriToKeyInfo: { [keyuri: string]: KeyLoaderInfo } = {};\n public emeController: EMEController | null = null;\n\n constructor(config: HlsConfig) {\n this.config = config;\n }\n\n abort(type?: PlaylistLevelType) {\n for (const uri in this.keyUriToKeyInfo) {\n const loader = this.keyUriToKeyInfo[uri].loader;\n if (loader) {\n if (type && type !== loader.context.frag.type) {\n return;\n }\n loader.abort();\n }\n }\n }\n\n detach() {\n for (const uri in this.keyUriToKeyInfo) {\n const keyInfo = this.keyUriToKeyInfo[uri];\n // Remove cached EME keys on detach\n if (\n keyInfo.mediaKeySessionContext ||\n keyInfo.decryptdata.isCommonEncryption\n ) {\n delete this.keyUriToKeyInfo[uri];\n }\n }\n }\n\n destroy() {\n this.detach();\n for (const uri in this.keyUriToKeyInfo) {\n const loader = this.keyUriToKeyInfo[uri].loader;\n if (loader) {\n loader.destroy();\n }\n }\n this.keyUriToKeyInfo = {};\n }\n\n createKeyLoadError(\n frag: Fragment,\n details: ErrorDetails = ErrorDetails.KEY_LOAD_ERROR,\n error: Error,\n networkDetails?: any,\n response?: { url: string; data: undefined; code: number; text: string }\n ): LoadError {\n return new LoadError({\n type: ErrorTypes.NETWORK_ERROR,\n details,\n fatal: false,\n frag,\n response,\n error,\n networkDetails,\n });\n }\n\n loadClear(\n loadingFrag: Fragment,\n encryptedFragments: Fragment[]\n ): void | Promise<void> {\n if (this.emeController && this.config.emeEnabled) {\n // access key-system with nearest key on start (loaidng frag is unencrypted)\n const { sn, cc } = loadingFrag;\n for (let i = 0; i < encryptedFragments.length; i++) {\n const frag = encryptedFragments[i];\n if (\n cc <= frag.cc &&\n (sn === 'initSegment' || frag.sn === 'initSegment' || sn < frag.sn)\n ) {\n this.emeController\n .selectKeySystemFormat(frag)\n .then((keySystemFormat) => {\n frag.setKeyFormat(keySystemFormat);\n });\n break;\n }\n }\n }\n }\n\n load(frag: Fragment): Promise<KeyLoadedData> {\n if (!frag.decryptdata && frag.encrypted && this.emeController) {\n // Multiple keys, but none selected, resolve in eme-controller\n return this.emeController\n .selectKeySystemFormat(frag)\n .then((keySystemFormat) => {\n return this.loadInternal(frag, keySystemFormat);\n });\n }\n\n return this.loadInternal(frag);\n }\n\n loadInternal(\n frag: Fragment,\n keySystemFormat?: KeySystemFormats\n ): Promise<KeyLoadedData> {\n if (keySystemFormat) {\n frag.setKeyFormat(keySystemFormat);\n }\n const decryptdata = frag.decryptdata;\n if (!decryptdata) {\n const error = new Error(\n keySystemFormat\n ? `Expected frag.decryptdata to be defined after setting format ${keySystemFormat}`\n : 'Missing decryption data on fragment in onKeyLoading'\n );\n return Promise.reject(\n this.createKeyLoadError(frag, ErrorDetails.KEY_LOAD_ERROR, error)\n );\n }\n const uri = decryptdata.uri;\n if (!uri) {\n return Promise.reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_ERROR,\n new Error(`Invalid key URI: \"${uri}\"`)\n )\n );\n }\n let keyInfo = this.keyUriToKeyInfo[uri];\n\n if (keyInfo?.decryptdata.key) {\n decryptdata.key = keyInfo.decryptdata.key;\n return Promise.resolve({ frag, keyInfo });\n }\n // Return key load promise as long as it does not have a mediakey session with an unusable key status\n if (keyInfo?.keyLoadPromise) {\n switch (keyInfo.mediaKeySessionContext?.keyStatus) {\n case undefined:\n case 'status-pending':\n case 'usable':\n case 'usable-in-future':\n return keyInfo.keyLoadPromise.then((keyLoadedData) => {\n // Return the correct fragment with updated decryptdata key and loaded keyInfo\n decryptdata.key = keyLoadedData.keyInfo.decryptdata.key;\n return { frag, keyInfo };\n });\n }\n // If we have a key session and status and it is not pending or usable, continue\n // This will go back to the eme-controller for expired keys to get a new keyLoadPromise\n }\n\n // Load the key or return the loading promise\n keyInfo = this.keyUriToKeyInfo[uri] = {\n decryptdata,\n keyLoadPromise: null,\n loader: null,\n mediaKeySessionContext: null,\n };\n\n switch (decryptdata.method) {\n case 'ISO-23001-7':\n case 'SAMPLE-AES':\n case 'SAMPLE-AES-CENC':\n case 'SAMPLE-AES-CTR':\n if (decryptdata.keyFormat === 'identity') {\n // loadKeyHTTP handles http(s) and data URLs\n return this.loadKeyHTTP(keyInfo, frag);\n }\n return this.loadKeyEME(keyInfo, frag);\n case 'AES-128':\n return this.loadKeyHTTP(keyInfo, frag);\n default:\n return Promise.reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_ERROR,\n new Error(\n `Key supplied with unsupported METHOD: \"${decryptdata.method}\"`\n )\n )\n );\n }\n }\n\n loadKeyEME(keyInfo: KeyLoaderInfo, frag: Fragment): Promise<KeyLoadedData> {\n const keyLoadedData: KeyLoadedData = { frag, keyInfo };\n if (this.emeController && this.config.emeEnabled) {\n const keySessionContextPromise =\n this.emeController.loadKey(keyLoadedData);\n if (keySessionContextPromise) {\n return (keyInfo.keyLoadPromise = keySessionContextPromise.then(\n (keySessionContext) => {\n keyInfo.mediaKeySessionContext = keySessionContext;\n return keyLoadedData;\n }\n )).catch((error) => {\n // Remove promise for license renewal or retry\n keyInfo.keyLoadPromise = null;\n throw error;\n });\n }\n }\n return Promise.resolve(keyLoadedData);\n }\n\n loadKeyHTTP(keyInfo: KeyLoaderInfo, frag: Fragment): Promise<KeyLoadedData> {\n const config = this.config;\n const Loader = config.loader;\n const keyLoader = new Loader(config) as Loader<KeyLoaderContext>;\n frag.keyLoader = keyInfo.loader = keyLoader;\n\n return (keyInfo.keyLoadPromise = new Promise((resolve, reject) => {\n const loaderContext: KeyLoaderContext = {\n keyInfo,\n frag,\n responseType: 'arraybuffer',\n url: keyInfo.decryptdata.uri,\n };\n\n // maxRetry is 0 so that instead of retrying the same key on the same variant multiple times,\n // key-loader will trigger an error and rely on stream-controller to handle retry logic.\n // this will also align retry logic with fragment-loader\n const loadPolicy = config.keyLoadPolicy.default;\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n };\n\n const loaderCallbacks: LoaderCallbacks<KeyLoaderContext> = {\n onSuccess: (\n response: LoaderResponse,\n stats: LoaderStats,\n context: KeyLoaderContext,\n networkDetails: any\n ) => {\n const { frag, keyInfo, url: uri } = context;\n if (!frag.decryptdata || keyInfo !== this.keyUriToKeyInfo[uri]) {\n return reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_ERROR,\n new Error('after key load, decryptdata unset or changed'),\n networkDetails\n )\n );\n }\n\n keyInfo.decryptdata.key = frag.decryptdata.key = new Uint8Array(\n response.data as ArrayBuffer\n );\n\n // detach fragment key loader on load success\n frag.keyLoader = null;\n keyInfo.loader = null;\n resolve({ frag, keyInfo });\n },\n\n onError: (\n response: { code: number; text: string },\n context: KeyLoaderContext,\n networkDetails: any,\n stats: LoaderStats\n ) => {\n this.resetLoader(context);\n reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_ERROR,\n new Error(\n `HTTP Error ${response.code} loading key ${response.text}`\n ),\n networkDetails,\n { url: loaderContext.url, data: undefined, ...response }\n )\n );\n },\n\n onTimeout: (\n stats: LoaderStats,\n context: KeyLoaderContext,\n networkDetails: any\n ) => {\n this.resetLoader(context);\n reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.KEY_LOAD_TIMEOUT,\n new Error('key loading timed out'),\n networkDetails\n )\n );\n },\n\n onAbort: (\n stats: LoaderStats,\n context: KeyLoaderContext,\n networkDetails: any\n ) => {\n this.resetLoader(context);\n reject(\n this.createKeyLoadError(\n frag,\n ErrorDetails.INTERNAL_ABORTED,\n new Error('key loading aborted'),\n networkDetails\n )\n );\n },\n };\n\n keyLoader.load(loaderContext, loaderConfig, loaderCallbacks);\n }));\n }\n\n private resetLoader(context: KeyLoaderContext) {\n const { frag, keyInfo, url: uri } = context;\n const loader = keyInfo.loader;\n if (frag.keyLoader === loader) {\n frag.keyLoader = null;\n keyInfo.loader = null;\n }\n delete this.keyUriToKeyInfo[uri];\n if (loader) {\n loader.destroy();\n }\n }\n}\n","/**\n * @ignore\n * Sub-class specialization of EventHandler base class.\n *\n * TaskLoop allows to schedule a task function being called (optionnaly repeatedly) on the main loop,\n * scheduled asynchroneously, avoiding recursive calls in the same tick.\n *\n * The task itself is implemented in `doTick`. It can be requested and called for single execution\n * using the `tick` method.\n *\n * It will be assured that the task execution method (`tick`) only gets called once per main loop \"tick\",\n * no matter how often it gets requested for execution. Execution in further ticks will be scheduled accordingly.\n *\n * If further execution requests have already been scheduled on the next tick, it can be checked with `hasNextTick`,\n * and cancelled with `clearNextTick`.\n *\n * The task can be scheduled as an interval repeatedly with a period as parameter (see `setInterval`, `clearInterval`).\n *\n * Sub-classes need to implement the `doTick` method which will effectively have the task execution routine.\n *\n * Further explanations:\n *\n * The baseclass has a `tick` method that will schedule the doTick call. It may be called synchroneously\n * only for a stack-depth of one. On re-entrant calls, sub-sequent calls are scheduled for next main loop ticks.\n *\n * When the task execution (`tick` method) is called in re-entrant way this is detected and\n * we are limiting the task execution per call stack to exactly one, but scheduling/post-poning further\n * task processing on the next main loop iteration (also known as \"next tick\" in the Node/JS runtime lingo).\n */\nexport default class TaskLoop {\n private readonly _boundTick: () => void;\n private _tickTimer: number | null = null;\n private _tickInterval: number | null = null;\n private _tickCallCount = 0;\n\n constructor() {\n this._boundTick = this.tick.bind(this);\n }\n\n public destroy() {\n this.onHandlerDestroying();\n this.onHandlerDestroyed();\n }\n\n protected onHandlerDestroying() {\n // clear all timers before unregistering from event bus\n this.clearNextTick();\n this.clearInterval();\n }\n\n protected onHandlerDestroyed() {}\n\n public hasInterval(): boolean {\n return !!this._tickInterval;\n }\n\n public hasNextTick(): boolean {\n return !!this._tickTimer;\n }\n\n /**\n * @param millis - Interval time (ms)\n * @eturns True when interval has been scheduled, false when already scheduled (no effect)\n */\n public setInterval(millis: number): boolean {\n if (!this._tickInterval) {\n this._tickCallCount = 0;\n this._tickInterval = self.setInterval(this._boundTick, millis);\n return true;\n }\n return false;\n }\n\n /**\n * @returns True when interval was cleared, false when none was set (no effect)\n */\n public clearInterval(): boolean {\n if (this._tickInterval) {\n self.clearInterval(this._tickInterval);\n this._tickInterval = null;\n return true;\n }\n return false;\n }\n\n /**\n * @returns True when timeout was cleared, false when none was set (no effect)\n */\n public clearNextTick(): boolean {\n if (this._tickTimer) {\n self.clearTimeout(this._tickTimer);\n this._tickTimer = null;\n return true;\n }\n return false;\n }\n\n /**\n * Will call the subclass doTick implementation in this main loop tick\n * or in the next one (via setTimeout(,0)) in case it has already been called\n * in this tick (in case this is a re-entrant call).\n */\n public tick(): void {\n this._tickCallCount++;\n if (this._tickCallCount === 1) {\n this.doTick();\n // re-entrant call to tick from previous doTick call stack\n // -> schedule a call on the next main loop iteration to process this task processing request\n if (this._tickCallCount > 1) {\n // make sure only one timer exists at any time at max\n this.tickImmediate();\n }\n this._tickCallCount = 0;\n }\n }\n\n public tickImmediate(): void {\n this.clearNextTick();\n this._tickTimer = self.setTimeout(this._boundTick, 0);\n }\n\n /**\n * For subclass to implement task logic\n * @abstract\n */\n protected doTick(): void {}\n}\n","/**\n * Provides methods dealing with buffer length retrieval for example.\n *\n * In general, a helper around HTML5 MediaElement TimeRanges gathered from `buffered` property.\n *\n * Also @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/buffered\n */\n\nimport { logger } from './logger';\n\ntype BufferTimeRange = {\n start: number;\n end: number;\n};\n\nexport type Bufferable = {\n buffered: TimeRanges;\n};\n\nexport type BufferInfo = {\n len: number;\n start: number;\n end: number;\n nextStart?: number;\n};\n\nconst noopBuffered: TimeRanges = {\n length: 0,\n start: () => 0,\n end: () => 0,\n};\n\nexport class BufferHelper {\n /**\n * Return true if `media`'s buffered include `position`\n */\n static isBuffered(media: Bufferable, position: number): boolean {\n try {\n if (media) {\n const buffered = BufferHelper.getBuffered(media);\n for (let i = 0; i < buffered.length; i++) {\n if (position >= buffered.start(i) && position <= buffered.end(i)) {\n return true;\n }\n }\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return false;\n }\n\n static bufferInfo(\n media: Bufferable | null,\n pos: number,\n maxHoleDuration: number\n ): BufferInfo {\n try {\n if (media) {\n const vbuffered = BufferHelper.getBuffered(media);\n const buffered: BufferTimeRange[] = [];\n let i: number;\n for (i = 0; i < vbuffered.length; i++) {\n buffered.push({ start: vbuffered.start(i), end: vbuffered.end(i) });\n }\n\n return this.bufferedInfo(buffered, pos, maxHoleDuration);\n }\n } catch (error) {\n // this is to catch\n // InvalidStateError: Failed to read the 'buffered' property from 'SourceBuffer':\n // This SourceBuffer has been removed from the parent media source\n }\n return { len: 0, start: pos, end: pos, nextStart: undefined };\n }\n\n static bufferedInfo(\n buffered: BufferTimeRange[],\n pos: number,\n maxHoleDuration: number\n ): {\n len: number;\n start: number;\n end: number;\n nextStart?: number;\n } {\n pos = Math.max(0, pos);\n // sort on buffer.start/smaller end (IE does not always return sorted buffered range)\n buffered.sort(function (a, b) {\n const diff = a.start - b.start;\n if (diff) {\n return diff;\n } else {\n return b.end - a.end;\n }\n });\n\n let buffered2: BufferTimeRange[] = [];\n if (maxHoleDuration) {\n // there might be some small holes between buffer time range\n // consider that holes smaller than maxHoleDuration are irrelevant and build another\n // buffer time range representations that discards those holes\n for (let i = 0; i < buffered.length; i++) {\n const buf2len = buffered2.length;\n if (buf2len) {\n const buf2end = buffered2[buf2len - 1].end;\n // if small hole (value between 0 or maxHoleDuration ) or overlapping (negative)\n if (buffered[i].start - buf2end < maxHoleDuration) {\n // merge overlapping time ranges\n // update lastRange.end only if smaller than item.end\n // e.g. [ 1, 15] with [ 2,8] => [ 1,15] (no need to modify lastRange.end)\n // whereas [ 1, 8] with [ 2,15] => [ 1,15] ( lastRange should switch from [1,8] to [1,15])\n if (buffered[i].end > buf2end) {\n buffered2[buf2len - 1].end = buffered[i].end;\n }\n } else {\n // big hole\n buffered2.push(buffered[i]);\n }\n } else {\n // first value\n buffered2.push(buffered[i]);\n }\n }\n } else {\n buffered2 = buffered;\n }\n\n let bufferLen = 0;\n\n // bufferStartNext can possibly be undefined based on the conditional logic below\n let bufferStartNext: number | undefined;\n\n // bufferStart and bufferEnd are buffer boundaries around current video position\n let bufferStart: number = pos;\n let bufferEnd: number = pos;\n for (let i = 0; i < buffered2.length; i++) {\n const start = buffered2[i].start;\n const end = buffered2[i].end;\n // logger.log('buf start/end:' + buffered.start(i) + '/' + buffered.end(i));\n if (pos + maxHoleDuration >= start && pos < end) {\n // play position is inside this buffer TimeRange, retrieve end of buffer position and buffer length\n bufferStart = start;\n bufferEnd = end;\n bufferLen = bufferEnd - pos;\n } else if (pos + maxHoleDuration < start) {\n bufferStartNext = start;\n break;\n }\n }\n return {\n len: bufferLen,\n start: bufferStart || 0,\n end: bufferEnd || 0,\n nextStart: bufferStartNext,\n };\n }\n\n /**\n * Safe method to get buffered property.\n * SourceBuffer.buffered may throw if SourceBuffer is removed from it's MediaSource\n */\n static getBuffered(media: Bufferable): TimeRanges {\n try {\n return media.buffered;\n } catch (e) {\n logger.log('failed to get media.buffered', e);\n return noopBuffered;\n }\n }\n}\n","import type { RemuxerResult } from './remuxer';\nimport type { HlsChunkPerformanceTiming } from './loader';\nimport type { SourceBufferName } from './buffer';\n\nexport interface TransmuxerResult {\n remuxResult: RemuxerResult;\n chunkMeta: ChunkMetadata;\n}\n\nexport class ChunkMetadata {\n public readonly level: number;\n public readonly sn: number;\n public readonly part: number;\n public readonly id: number;\n public readonly size: number;\n public readonly partial: boolean;\n public readonly transmuxing: HlsChunkPerformanceTiming =\n getNewPerformanceTiming();\n public readonly buffering: {\n [key in SourceBufferName]: HlsChunkPerformanceTiming;\n } = {\n audio: getNewPerformanceTiming(),\n video: getNewPerformanceTiming(),\n audiovideo: getNewPerformanceTiming(),\n };\n\n constructor(\n level: number,\n sn: number,\n id: number,\n size = 0,\n part = -1,\n partial = false\n ) {\n this.level = level;\n this.sn = sn;\n this.id = id;\n this.size = size;\n this.part = part;\n this.partial = partial;\n }\n}\n\nfunction getNewPerformanceTiming(): HlsChunkPerformanceTiming {\n return { start: 0, executeStart: 0, executeEnd: 0, end: 0 };\n}\n","import { logger } from './logger';\nimport { adjustSliding } from '../controller/level-helper';\n\nimport type { Fragment } from '../loader/fragment';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { Level } from '../types/level';\nimport type { RequiredProperties } from '../types/general';\n\nexport function findFirstFragWithCC(fragments: Fragment[], cc: number) {\n let firstFrag: Fragment | null = null;\n\n for (let i = 0, len = fragments.length; i < len; i++) {\n const currentFrag = fragments[i];\n if (currentFrag && currentFrag.cc === cc) {\n firstFrag = currentFrag;\n break;\n }\n }\n\n return firstFrag;\n}\n\nexport function shouldAlignOnDiscontinuities(\n lastFrag: Fragment | null,\n lastLevel: Level,\n details: LevelDetails\n): lastLevel is RequiredProperties<Level, 'details'> {\n if (lastLevel.details) {\n if (\n details.endCC > details.startCC ||\n (lastFrag && lastFrag.cc < details.startCC)\n ) {\n return true;\n }\n }\n return false;\n}\n\n// Find the first frag in the previous level which matches the CC of the first frag of the new level\nexport function findDiscontinuousReferenceFrag(\n prevDetails: LevelDetails,\n curDetails: LevelDetails,\n referenceIndex: number = 0\n) {\n const prevFrags = prevDetails.fragments;\n const curFrags = curDetails.fragments;\n\n if (!curFrags.length || !prevFrags.length) {\n logger.log('No fragments to align');\n return;\n }\n\n const prevStartFrag = findFirstFragWithCC(prevFrags, curFrags[0].cc);\n\n if (!prevStartFrag || (prevStartFrag && !prevStartFrag.startPTS)) {\n logger.log('No frag in previous level to align on');\n return;\n }\n\n return prevStartFrag;\n}\n\nfunction adjustFragmentStart(frag: Fragment, sliding: number) {\n if (frag) {\n const start = frag.start + sliding;\n frag.start = frag.startPTS = start;\n frag.endPTS = start + frag.duration;\n }\n}\n\nexport function adjustSlidingStart(sliding: number, details: LevelDetails) {\n // Update segments\n const fragments = details.fragments;\n for (let i = 0, len = fragments.length; i < len; i++) {\n adjustFragmentStart(fragments[i], sliding);\n }\n // Update LL-HLS parts at the end of the playlist\n if (details.fragmentHint) {\n adjustFragmentStart(details.fragmentHint, sliding);\n }\n details.alignedSliding = true;\n}\n\n/**\n * Using the parameters of the last level, this function computes PTS' of the new fragments so that they form a\n * contiguous stream with the last fragments.\n * The PTS of a fragment lets Hls.js know where it fits into a stream - by knowing every PTS, we know which fragment to\n * download at any given time. PTS is normally computed when the fragment is demuxed, so taking this step saves us time\n * and an extra download.\n * @param lastFrag\n * @param lastLevel\n * @param details\n */\nexport function alignStream(\n lastFrag: Fragment | null,\n lastLevel: Level | null,\n details: LevelDetails\n) {\n if (!lastLevel) {\n return;\n }\n alignDiscontinuities(lastFrag, details, lastLevel);\n if (!details.alignedSliding && lastLevel.details) {\n // If the PTS wasn't figured out via discontinuity sequence that means there was no CC increase within the level.\n // Aligning via Program Date Time should therefore be reliable, since PDT should be the same within the same\n // discontinuity sequence.\n alignPDT(details, lastLevel.details);\n }\n if (\n !details.alignedSliding &&\n lastLevel.details &&\n !details.skippedSegments\n ) {\n // Try to align on sn so that we pick a better start fragment.\n // Do not perform this on playlists with delta updates as this is only to align levels on switch\n // and adjustSliding only adjusts fragments after skippedSegments.\n adjustSliding(lastLevel.details, details);\n }\n}\n\n/**\n * Computes the PTS if a new level's fragments using the PTS of a fragment in the last level which shares the same\n * discontinuity sequence.\n * @param lastFrag - The last Fragment which shares the same discontinuity sequence\n * @param lastLevel - The details of the last loaded level\n * @param details - The details of the new level\n */\nfunction alignDiscontinuities(\n lastFrag: Fragment | null,\n details: LevelDetails,\n lastLevel: Level\n) {\n if (shouldAlignOnDiscontinuities(lastFrag, lastLevel, details)) {\n const referenceFrag = findDiscontinuousReferenceFrag(\n lastLevel.details,\n details\n );\n if (referenceFrag && Number.isFinite(referenceFrag.start)) {\n logger.log(\n `Adjusting PTS using last level due to CC increase within current level ${details.url}`\n );\n adjustSlidingStart(referenceFrag.start, details);\n }\n }\n}\n\n/**\n * Computes the PTS of a new level's fragments using the difference in Program Date Time from the last level.\n * @param details - The details of the new level\n * @param lastDetails - The details of the last loaded level\n */\nexport function alignPDT(details: LevelDetails, lastDetails: LevelDetails) {\n // This check protects the unsafe \"!\" usage below for null program date time access.\n if (\n !lastDetails.fragments.length ||\n !details.hasProgramDateTime ||\n !lastDetails.hasProgramDateTime\n ) {\n return;\n }\n // if last level sliding is 1000 and its first frag PROGRAM-DATE-TIME is 2017-08-20 1:10:00 AM\n // and if new details first frag PROGRAM DATE-TIME is 2017-08-20 1:10:08 AM\n // then we can deduce that playlist B sliding is 1000+8 = 1008s\n const lastPDT = lastDetails.fragments[0].programDateTime!; // hasProgramDateTime check above makes this safe.\n const newPDT = details.fragments[0].programDateTime!;\n // date diff is in ms. frag.start is in seconds\n const sliding = (newPDT - lastPDT) / 1000 + lastDetails.fragments[0].start;\n if (sliding && Number.isFinite(sliding)) {\n logger.log(\n `Adjusting PTS using programDateTime delta ${\n newPDT - lastPDT\n }ms, sliding:${sliding.toFixed(3)} ${details.url} `\n );\n adjustSlidingStart(sliding, details);\n }\n}\n\n/**\n * Ensures appropriate time-alignment between renditions based on PDT. Unlike `alignPDT`, which adjusts\n * the timeline based on the delta between PDTs of the 0th fragment of two playlists/`LevelDetails`,\n * this function assumes the timelines represented in `refDetails` are accurate, including the PDTs,\n * and uses the \"wallclock\"/PDT timeline as a cross-reference to `details`, adjusting the presentation\n * times/timelines of `details` accordingly.\n * Given the asynchronous nature of fetches and initial loads of live `main` and audio/subtitle tracks,\n * the primary purpose of this function is to ensure the \"local timelines\" of audio/subtitle tracks\n * are aligned to the main/video timeline, using PDT as the cross-reference/\"anchor\" that should\n * be consistent across playlists, per the HLS spec.\n * @param details - The details of the rendition you'd like to time-align (e.g. an audio rendition).\n * @param refDetails - The details of the reference rendition with start and PDT times for alignment.\n */\nexport function alignMediaPlaylistByPDT(\n details: LevelDetails,\n refDetails: LevelDetails\n) {\n if (!details.hasProgramDateTime || !refDetails.hasProgramDateTime) {\n return;\n }\n\n const fragments = details.fragments;\n const refFragments = refDetails.fragments;\n if (!fragments.length || !refFragments.length) {\n return;\n }\n\n // Calculate a delta to apply to all fragments according to the delta in PDT times and start times\n // of a fragment in the reference details, and a fragment in the target details of the same discontinuity.\n // If a fragment of the same discontinuity was not found use the middle fragment of both.\n const middleFrag = Math.round(refFragments.length / 2) - 1;\n const refFrag = refFragments[middleFrag];\n const frag =\n findFirstFragWithCC(fragments, refFrag.cc) ||\n fragments[Math.round(fragments.length / 2) - 1];\n\n const refPDT = refFrag.programDateTime;\n const targetPDT = frag.programDateTime;\n if (refPDT === null || targetPDT === null) {\n return;\n }\n\n const delta = (targetPDT - refPDT) / 1000 - (frag.start - refFrag.start);\n adjustSlidingStart(delta, details);\n}\n","export default class AESCrypto {\n private subtle: SubtleCrypto;\n private aesIV: Uint8Array;\n\n constructor(subtle: SubtleCrypto, iv: Uint8Array) {\n this.subtle = subtle;\n this.aesIV = iv;\n }\n\n decrypt(data: ArrayBuffer, key: CryptoKey) {\n return this.subtle.decrypt({ name: 'AES-CBC', iv: this.aesIV }, key, data);\n }\n}\n","export default class FastAESKey {\n private subtle: any;\n private key: ArrayBuffer;\n\n constructor(subtle, key) {\n this.subtle = subtle;\n this.key = key;\n }\n\n expandKey() {\n return this.subtle.importKey('raw', this.key, { name: 'AES-CBC' }, false, [\n 'encrypt',\n 'decrypt',\n ]);\n }\n}\n","import { sliceUint8 } from '../utils/typed-array';\n\n// PKCS7\nexport function removePadding(array: Uint8Array): Uint8Array {\n const outputBytes = array.byteLength;\n const paddingBytes =\n outputBytes && new DataView(array.buffer).getUint8(outputBytes - 1);\n if (paddingBytes) {\n return sliceUint8(array, 0, outputBytes - paddingBytes);\n }\n return array;\n}\n\nexport default class AESDecryptor {\n private rcon: Array<number> = [\n 0x0, 0x1, 0x2, 0x4, 0x8, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36,\n ];\n private subMix: Array<Uint32Array> = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n private invSubMix: Array<Uint32Array> = [\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n new Uint32Array(256),\n ];\n private sBox: Uint32Array = new Uint32Array(256);\n private invSBox: Uint32Array = new Uint32Array(256);\n private key: Uint32Array = new Uint32Array(0);\n\n private ksRows: number = 0;\n private keySize: number = 0;\n private keySchedule!: Uint32Array;\n private invKeySchedule!: Uint32Array;\n\n constructor() {\n this.initTable();\n }\n\n // Using view.getUint32() also swaps the byte order.\n uint8ArrayToUint32Array_(arrayBuffer) {\n const view = new DataView(arrayBuffer);\n const newArray = new Uint32Array(4);\n for (let i = 0; i < 4; i++) {\n newArray[i] = view.getUint32(i * 4);\n }\n\n return newArray;\n }\n\n initTable() {\n const sBox = this.sBox;\n const invSBox = this.invSBox;\n const subMix = this.subMix;\n const subMix0 = subMix[0];\n const subMix1 = subMix[1];\n const subMix2 = subMix[2];\n const subMix3 = subMix[3];\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n const d = new Uint32Array(256);\n let x = 0;\n let xi = 0;\n let i = 0;\n for (i = 0; i < 256; i++) {\n if (i < 128) {\n d[i] = i << 1;\n } else {\n d[i] = (i << 1) ^ 0x11b;\n }\n }\n\n for (i = 0; i < 256; i++) {\n let sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);\n sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;\n sBox[x] = sx;\n invSBox[sx] = x;\n\n // Compute multiplication\n const x2 = d[x];\n const x4 = d[x2];\n const x8 = d[x4];\n\n // Compute sub/invSub bytes, mix columns tables\n let t = (d[sx] * 0x101) ^ (sx * 0x1010100);\n subMix0[x] = (t << 24) | (t >>> 8);\n subMix1[x] = (t << 16) | (t >>> 16);\n subMix2[x] = (t << 8) | (t >>> 24);\n subMix3[x] = t;\n\n // Compute inv sub bytes, inv mix columns tables\n t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);\n invSubMix0[sx] = (t << 24) | (t >>> 8);\n invSubMix1[sx] = (t << 16) | (t >>> 16);\n invSubMix2[sx] = (t << 8) | (t >>> 24);\n invSubMix3[sx] = t;\n\n // Compute next counter\n if (!x) {\n x = xi = 1;\n } else {\n x = x2 ^ d[d[d[x8 ^ x2]]];\n xi ^= d[d[xi]];\n }\n }\n }\n\n expandKey(keyBuffer: ArrayBuffer) {\n // convert keyBuffer to Uint32Array\n const key = this.uint8ArrayToUint32Array_(keyBuffer);\n let sameKey = true;\n let offset = 0;\n\n while (offset < key.length && sameKey) {\n sameKey = key[offset] === this.key[offset];\n offset++;\n }\n\n if (sameKey) {\n return;\n }\n\n this.key = key;\n const keySize = (this.keySize = key.length);\n\n if (keySize !== 4 && keySize !== 6 && keySize !== 8) {\n throw new Error('Invalid aes key size=' + keySize);\n }\n\n const ksRows = (this.ksRows = (keySize + 6 + 1) * 4);\n let ksRow;\n let invKsRow;\n\n const keySchedule = (this.keySchedule = new Uint32Array(ksRows));\n const invKeySchedule = (this.invKeySchedule = new Uint32Array(ksRows));\n const sbox = this.sBox;\n const rcon = this.rcon;\n\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n let prev;\n let t;\n\n for (ksRow = 0; ksRow < ksRows; ksRow++) {\n if (ksRow < keySize) {\n prev = keySchedule[ksRow] = key[ksRow];\n continue;\n }\n t = prev;\n\n if (ksRow % keySize === 0) {\n // Rot word\n t = (t << 8) | (t >>> 24);\n\n // Sub word\n t =\n (sbox[t >>> 24] << 24) |\n (sbox[(t >>> 16) & 0xff] << 16) |\n (sbox[(t >>> 8) & 0xff] << 8) |\n sbox[t & 0xff];\n\n // Mix Rcon\n t ^= rcon[(ksRow / keySize) | 0] << 24;\n } else if (keySize > 6 && ksRow % keySize === 4) {\n // Sub word\n t =\n (sbox[t >>> 24] << 24) |\n (sbox[(t >>> 16) & 0xff] << 16) |\n (sbox[(t >>> 8) & 0xff] << 8) |\n sbox[t & 0xff];\n }\n\n keySchedule[ksRow] = prev = (keySchedule[ksRow - keySize] ^ t) >>> 0;\n }\n\n for (invKsRow = 0; invKsRow < ksRows; invKsRow++) {\n ksRow = ksRows - invKsRow;\n if (invKsRow & 3) {\n t = keySchedule[ksRow];\n } else {\n t = keySchedule[ksRow - 4];\n }\n\n if (invKsRow < 4 || ksRow <= 4) {\n invKeySchedule[invKsRow] = t;\n } else {\n invKeySchedule[invKsRow] =\n invSubMix0[sbox[t >>> 24]] ^\n invSubMix1[sbox[(t >>> 16) & 0xff]] ^\n invSubMix2[sbox[(t >>> 8) & 0xff]] ^\n invSubMix3[sbox[t & 0xff]];\n }\n\n invKeySchedule[invKsRow] = invKeySchedule[invKsRow] >>> 0;\n }\n }\n\n // Adding this as a method greatly improves performance.\n networkToHostOrderSwap(word) {\n return (\n (word << 24) |\n ((word & 0xff00) << 8) |\n ((word & 0xff0000) >> 8) |\n (word >>> 24)\n );\n }\n\n decrypt(inputArrayBuffer: ArrayBuffer, offset: number, aesIV: ArrayBuffer) {\n const nRounds = this.keySize + 6;\n const invKeySchedule = this.invKeySchedule;\n const invSBOX = this.invSBox;\n\n const invSubMix = this.invSubMix;\n const invSubMix0 = invSubMix[0];\n const invSubMix1 = invSubMix[1];\n const invSubMix2 = invSubMix[2];\n const invSubMix3 = invSubMix[3];\n\n const initVector = this.uint8ArrayToUint32Array_(aesIV);\n let initVector0 = initVector[0];\n let initVector1 = initVector[1];\n let initVector2 = initVector[2];\n let initVector3 = initVector[3];\n\n const inputInt32 = new Int32Array(inputArrayBuffer);\n const outputInt32 = new Int32Array(inputInt32.length);\n\n let t0, t1, t2, t3;\n let s0, s1, s2, s3;\n let inputWords0, inputWords1, inputWords2, inputWords3;\n\n let ksRow, i;\n const swapWord = this.networkToHostOrderSwap;\n\n while (offset < inputInt32.length) {\n inputWords0 = swapWord(inputInt32[offset]);\n inputWords1 = swapWord(inputInt32[offset + 1]);\n inputWords2 = swapWord(inputInt32[offset + 2]);\n inputWords3 = swapWord(inputInt32[offset + 3]);\n\n s0 = inputWords0 ^ invKeySchedule[0];\n s1 = inputWords3 ^ invKeySchedule[1];\n s2 = inputWords2 ^ invKeySchedule[2];\n s3 = inputWords1 ^ invKeySchedule[3];\n\n ksRow = 4;\n\n // Iterate through the rounds of decryption\n for (i = 1; i < nRounds; i++) {\n t0 =\n invSubMix0[s0 >>> 24] ^\n invSubMix1[(s1 >> 16) & 0xff] ^\n invSubMix2[(s2 >> 8) & 0xff] ^\n invSubMix3[s3 & 0xff] ^\n invKeySchedule[ksRow];\n t1 =\n invSubMix0[s1 >>> 24] ^\n invSubMix1[(s2 >> 16) & 0xff] ^\n invSubMix2[(s3 >> 8) & 0xff] ^\n invSubMix3[s0 & 0xff] ^\n invKeySchedule[ksRow + 1];\n t2 =\n invSubMix0[s2 >>> 24] ^\n invSubMix1[(s3 >> 16) & 0xff] ^\n invSubMix2[(s0 >> 8) & 0xff] ^\n invSubMix3[s1 & 0xff] ^\n invKeySchedule[ksRow + 2];\n t3 =\n invSubMix0[s3 >>> 24] ^\n invSubMix1[(s0 >> 16) & 0xff] ^\n invSubMix2[(s1 >> 8) & 0xff] ^\n invSubMix3[s2 & 0xff] ^\n invKeySchedule[ksRow + 3];\n // Update state\n s0 = t0;\n s1 = t1;\n s2 = t2;\n s3 = t3;\n\n ksRow = ksRow + 4;\n }\n\n // Shift rows, sub bytes, add round key\n t0 =\n (invSBOX[s0 >>> 24] << 24) ^\n (invSBOX[(s1 >> 16) & 0xff] << 16) ^\n (invSBOX[(s2 >> 8) & 0xff] << 8) ^\n invSBOX[s3 & 0xff] ^\n invKeySchedule[ksRow];\n t1 =\n (invSBOX[s1 >>> 24] << 24) ^\n (invSBOX[(s2 >> 16) & 0xff] << 16) ^\n (invSBOX[(s3 >> 8) & 0xff] << 8) ^\n invSBOX[s0 & 0xff] ^\n invKeySchedule[ksRow + 1];\n t2 =\n (invSBOX[s2 >>> 24] << 24) ^\n (invSBOX[(s3 >> 16) & 0xff] << 16) ^\n (invSBOX[(s0 >> 8) & 0xff] << 8) ^\n invSBOX[s1 & 0xff] ^\n invKeySchedule[ksRow + 2];\n t3 =\n (invSBOX[s3 >>> 24] << 24) ^\n (invSBOX[(s0 >> 16) & 0xff] << 16) ^\n (invSBOX[(s1 >> 8) & 0xff] << 8) ^\n invSBOX[s2 & 0xff] ^\n invKeySchedule[ksRow + 3];\n\n // Write\n outputInt32[offset] = swapWord(t0 ^ initVector0);\n outputInt32[offset + 1] = swapWord(t3 ^ initVector1);\n outputInt32[offset + 2] = swapWord(t2 ^ initVector2);\n outputInt32[offset + 3] = swapWord(t1 ^ initVector3);\n\n // reset initVector to last 4 unsigned int\n initVector0 = inputWords0;\n initVector1 = inputWords1;\n initVector2 = inputWords2;\n initVector3 = inputWords3;\n\n offset = offset + 4;\n }\n\n return outputInt32.buffer;\n }\n}\n","import AESCrypto from './aes-crypto';\nimport FastAESKey from './fast-aes-key';\nimport AESDecryptor, { removePadding } from './aes-decryptor';\nimport { logger } from '../utils/logger';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { sliceUint8 } from '../utils/typed-array';\nimport type { HlsConfig } from '../config';\n\nconst CHUNK_SIZE = 16; // 16 bytes, 128 bits\n\nexport default class Decrypter {\n private logEnabled: boolean = true;\n private removePKCS7Padding: boolean;\n private subtle: SubtleCrypto | null = null;\n private softwareDecrypter: AESDecryptor | null = null;\n private key: ArrayBuffer | null = null;\n private fastAesKey: FastAESKey | null = null;\n private remainderData: Uint8Array | null = null;\n private currentIV: ArrayBuffer | null = null;\n private currentResult: ArrayBuffer | null = null;\n private useSoftware: boolean;\n\n constructor(config: HlsConfig, { removePKCS7Padding = true } = {}) {\n this.useSoftware = config.enableSoftwareAES;\n this.removePKCS7Padding = removePKCS7Padding;\n // built in decryptor expects PKCS7 padding\n if (removePKCS7Padding) {\n try {\n const browserCrypto = self.crypto;\n if (browserCrypto) {\n this.subtle =\n browserCrypto.subtle ||\n ((browserCrypto as any).webkitSubtle as SubtleCrypto);\n }\n } catch (e) {\n /* no-op */\n }\n }\n if (this.subtle === null) {\n this.useSoftware = true;\n }\n }\n\n destroy() {\n this.subtle = null;\n this.softwareDecrypter = null;\n this.key = null;\n this.fastAesKey = null;\n this.remainderData = null;\n this.currentIV = null;\n this.currentResult = null;\n }\n\n public isSync() {\n return this.useSoftware;\n }\n\n public flush(): Uint8Array | null {\n const { currentResult, remainderData } = this;\n if (!currentResult || remainderData) {\n this.reset();\n return null;\n }\n const data = new Uint8Array(currentResult);\n this.reset();\n if (this.removePKCS7Padding) {\n return removePadding(data);\n }\n return data;\n }\n\n public reset() {\n this.currentResult = null;\n this.currentIV = null;\n this.remainderData = null;\n if (this.softwareDecrypter) {\n this.softwareDecrypter = null;\n }\n }\n\n public decrypt(\n data: Uint8Array | ArrayBuffer,\n key: ArrayBuffer,\n iv: ArrayBuffer\n ): Promise<ArrayBuffer> {\n if (this.useSoftware) {\n return new Promise((resolve, reject) => {\n this.softwareDecrypt(new Uint8Array(data), key, iv);\n const decryptResult = this.flush();\n if (decryptResult) {\n resolve(decryptResult.buffer);\n } else {\n reject(new Error('[softwareDecrypt] Failed to decrypt data'));\n }\n });\n }\n return this.webCryptoDecrypt(new Uint8Array(data), key, iv);\n }\n\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n public softwareDecrypt(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer\n ): ArrayBuffer | null {\n const { currentIV, currentResult, remainderData } = this;\n this.logOnce('JS AES decrypt');\n // The output is staggered during progressive parsing - the current result is cached, and emitted on the next call\n // This is done in order to strip PKCS7 padding, which is found at the end of each segment. We only know we've reached\n // the end on flush(), but by that time we have already received all bytes for the segment.\n // Progressive decryption does not work with WebCrypto\n\n if (remainderData) {\n data = appendUint8Array(remainderData, data);\n this.remainderData = null;\n }\n\n // Byte length must be a multiple of 16 (AES-128 = 128 bit blocks = 16 bytes)\n const currentChunk = this.getValidChunk(data);\n if (!currentChunk.length) {\n return null;\n }\n\n if (currentIV) {\n iv = currentIV;\n }\n\n let softwareDecrypter = this.softwareDecrypter;\n if (!softwareDecrypter) {\n softwareDecrypter = this.softwareDecrypter = new AESDecryptor();\n }\n softwareDecrypter.expandKey(key);\n\n const result = currentResult;\n\n this.currentResult = softwareDecrypter.decrypt(currentChunk.buffer, 0, iv);\n this.currentIV = sliceUint8(currentChunk, -16).buffer;\n\n if (!result) {\n return null;\n }\n return result;\n }\n\n public webCryptoDecrypt(\n data: Uint8Array,\n key: ArrayBuffer,\n iv: ArrayBuffer\n ): Promise<ArrayBuffer> {\n const subtle = this.subtle;\n if (this.key !== key || !this.fastAesKey) {\n this.key = key;\n this.fastAesKey = new FastAESKey(subtle, key);\n }\n return this.fastAesKey\n .expandKey()\n .then((aesKey) => {\n // decrypt using web crypto\n if (!subtle) {\n return Promise.reject(new Error('web crypto not initialized'));\n }\n this.logOnce('WebCrypto AES decrypt');\n const crypto = new AESCrypto(subtle, new Uint8Array(iv));\n return crypto.decrypt(data.buffer, aesKey);\n })\n .catch((err) => {\n logger.warn(\n `[decrypter]: WebCrypto Error, disable WebCrypto API, ${err.name}: ${err.message}`\n );\n\n return this.onWebCryptoError(data, key, iv);\n });\n }\n\n private onWebCryptoError(data, key, iv): ArrayBuffer | never {\n this.useSoftware = true;\n this.logEnabled = true;\n this.softwareDecrypt(data, key, iv);\n const decryptResult = this.flush();\n if (decryptResult) {\n return decryptResult.buffer;\n }\n throw new Error('WebCrypto and softwareDecrypt: failed to decrypt data');\n }\n\n private getValidChunk(data: Uint8Array): Uint8Array {\n let currentChunk = data;\n const splitPoint = data.length - (data.length % CHUNK_SIZE);\n if (splitPoint !== data.length) {\n currentChunk = sliceUint8(data, 0, splitPoint);\n this.remainderData = sliceUint8(data, splitPoint);\n }\n return currentChunk;\n }\n\n private logOnce(msg: string) {\n if (!this.logEnabled) {\n return;\n }\n logger.log(`[decrypter]: ${msg}`);\n this.logEnabled = false;\n }\n}\n","/**\n * TimeRanges to string helper\n */\n\nconst TimeRanges = {\n toString: function (r: TimeRanges) {\n let log = '';\n const len = r.length;\n for (let i = 0; i < len; i++) {\n log += `[${r.start(i).toFixed(3)}-${r.end(i).toFixed(3)}]`;\n }\n\n return log;\n },\n};\n\nexport default TimeRanges;\n","import TaskLoop from '../task-loop';\nimport { FragmentState } from './fragment-tracker';\nimport { Bufferable, BufferHelper, BufferInfo } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\nimport { Events } from '../events';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { alignStream } from '../utils/discontinuities';\nimport {\n findFragmentByPDT,\n findFragmentByPTS,\n findFragWithCC,\n} from './fragment-finders';\nimport {\n findPart,\n getFragmentWithSN,\n getPartWith,\n updateFragPTSDTS,\n} from './level-helper';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { Fragment, Part } from '../loader/fragment';\nimport FragmentLoader, {\n FragmentLoadProgressCallback,\n LoadError,\n} from '../loader/fragment-loader';\nimport KeyLoader from '../loader/key-loader';\nimport { LevelDetails } from '../loader/level-details';\nimport Decrypter from '../crypt/decrypter';\nimport TimeRanges from '../utils/time-ranges';\nimport { PlaylistLevelType } from '../types/loader';\nimport { getRetryDelay } from '../utils/error-helper';\nimport { NetworkErrorAction } from './error-controller';\nimport type {\n BufferAppendingData,\n ErrorData,\n FragLoadedData,\n PartsLoadedData,\n KeyLoadedData,\n MediaAttachedData,\n BufferFlushingData,\n ManifestLoadedData,\n} from '../types/events';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type { Level } from '../types/level';\nimport type { RemuxedTrack } from '../types/remuxer';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type { SourceBufferName } from '../types/buffer';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\ntype ResolveFragLoaded = (FragLoadedEndData) => void;\ntype RejectFragLoaded = (LoadError) => void;\n\nexport const State = {\n STOPPED: 'STOPPED',\n IDLE: 'IDLE',\n KEY_LOADING: 'KEY_LOADING',\n FRAG_LOADING: 'FRAG_LOADING',\n FRAG_LOADING_WAITING_RETRY: 'FRAG_LOADING_WAITING_RETRY',\n WAITING_TRACK: 'WAITING_TRACK',\n PARSING: 'PARSING',\n PARSED: 'PARSED',\n ENDED: 'ENDED',\n ERROR: 'ERROR',\n WAITING_INIT_PTS: 'WAITING_INIT_PTS',\n WAITING_LEVEL: 'WAITING_LEVEL',\n};\n\nexport default class BaseStreamController\n extends TaskLoop\n implements NetworkComponentAPI\n{\n protected hls: Hls;\n\n protected fragPrevious: Fragment | null = null;\n protected fragCurrent: Fragment | null = null;\n protected fragmentTracker: FragmentTracker;\n protected transmuxer: TransmuxerInterface | null = null;\n protected _state: string = State.STOPPED;\n protected playlistType: PlaylistLevelType;\n protected media: HTMLMediaElement | null = null;\n protected mediaBuffer: Bufferable | null = null;\n protected config: HlsConfig;\n protected bitrateTest: boolean = false;\n protected lastCurrentTime: number = 0;\n protected nextLoadPosition: number = 0;\n protected startPosition: number = 0;\n protected startTimeOffset: number | null = null;\n protected loadedmetadata: boolean = false;\n protected retryDate: number = 0;\n protected levels: Array<Level> | null = null;\n protected fragmentLoader: FragmentLoader;\n protected keyLoader: KeyLoader;\n protected levelLastLoaded: number | null = null;\n protected startFragRequested: boolean = false;\n protected decrypter: Decrypter;\n protected initPTS: RationalTimestamp[] = [];\n protected onvseeking: EventListener | null = null;\n protected onvended: EventListener | null = null;\n\n private readonly logPrefix: string = '';\n protected log: (msg: any) => void;\n protected warn: (msg: any) => void;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader,\n logPrefix: string,\n playlistType: PlaylistLevelType\n ) {\n super();\n this.playlistType = playlistType;\n this.logPrefix = logPrefix;\n this.log = logger.log.bind(logger, `${logPrefix}:`);\n this.warn = logger.warn.bind(logger, `${logPrefix}:`);\n this.hls = hls;\n this.fragmentLoader = new FragmentLoader(hls.config);\n this.keyLoader = keyLoader;\n this.fragmentTracker = fragmentTracker;\n this.config = hls.config;\n this.decrypter = new Decrypter(hls.config);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n\n protected doTick() {\n this.onTickEnd();\n }\n\n protected onTickEnd() {}\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n public startLoad(startPosition: number): void {}\n\n public stopLoad() {\n this.fragmentLoader.abort();\n this.keyLoader.abort(this.playlistType);\n const frag = this.fragCurrent;\n if (frag?.loader) {\n frag.abortRequests();\n this.fragmentTracker.removeFragment(frag);\n }\n this.resetTransmuxer();\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.clearInterval();\n this.clearNextTick();\n this.state = State.STOPPED;\n }\n\n protected _streamEnded(\n bufferInfo: BufferInfo,\n levelDetails: LevelDetails\n ): boolean {\n // If playlist is live, there is another buffered range after the current range, nothing buffered, media is detached,\n // of nothing loading/loaded return false\n if (\n levelDetails.live ||\n bufferInfo.nextStart ||\n !bufferInfo.end ||\n !this.media\n ) {\n return false;\n }\n const partList = levelDetails.partList;\n // Since the last part isn't guaranteed to correspond to the last playlist segment for Low-Latency HLS,\n // check instead if the last part is buffered.\n if (partList?.length) {\n const lastPart = partList[partList.length - 1];\n\n // Checking the midpoint of the part for potential margin of error and related issues.\n // NOTE: Technically I believe parts could yield content that is < the computed duration (including potential a duration of 0)\n // and still be spec-compliant, so there may still be edge cases here. Likewise, there could be issues in end of stream\n // part mismatches for independent audio and video playlists/segments.\n const lastPartBuffered = BufferHelper.isBuffered(\n this.media,\n lastPart.start + lastPart.duration / 2\n );\n return lastPartBuffered;\n }\n\n const playlistType =\n levelDetails.fragments[levelDetails.fragments.length - 1].type;\n return this.fragmentTracker.isEndListAppended(playlistType);\n }\n\n protected getLevelDetails(): LevelDetails | undefined {\n if (this.levels && this.levelLastLoaded !== null) {\n return this.levels[this.levelLastLoaded]?.details;\n }\n }\n\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) {\n const media = (this.media = this.mediaBuffer = data.media);\n this.onvseeking = this.onMediaSeeking.bind(this) as EventListener;\n this.onvended = this.onMediaEnded.bind(this) as EventListener;\n media.addEventListener('seeking', this.onvseeking);\n media.addEventListener('ended', this.onvended);\n const config = this.config;\n if (this.levels && config.autoStartLoad && this.state === State.STOPPED) {\n this.startLoad(config.startPosition);\n }\n }\n\n protected onMediaDetaching() {\n const media = this.media;\n if (media?.ended) {\n this.log('MSE detaching and video ended, reset startPosition');\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n // remove video listeners\n if (media && this.onvseeking && this.onvended) {\n media.removeEventListener('seeking', this.onvseeking);\n media.removeEventListener('ended', this.onvended);\n this.onvseeking = this.onvended = null;\n }\n if (this.keyLoader) {\n this.keyLoader.detach();\n }\n this.media = this.mediaBuffer = null;\n this.loadedmetadata = false;\n this.fragmentTracker.removeAllFragments();\n this.stopLoad();\n }\n\n protected onMediaSeeking() {\n const { config, fragCurrent, media, mediaBuffer, state } = this;\n const currentTime: number = media ? media.currentTime : 0;\n const bufferInfo = BufferHelper.bufferInfo(\n mediaBuffer ? mediaBuffer : media,\n currentTime,\n config.maxBufferHole\n );\n\n this.log(\n `media seeking to ${\n Number.isFinite(currentTime) ? currentTime.toFixed(3) : currentTime\n }, state: ${state}`\n );\n\n if (this.state === State.ENDED) {\n this.resetLoadingState();\n } else if (fragCurrent) {\n // Seeking while frag load is in progress\n const tolerance = config.maxFragLookUpTolerance;\n const fragStartOffset = fragCurrent.start - tolerance;\n const fragEndOffset =\n fragCurrent.start + fragCurrent.duration + tolerance;\n // if seeking out of buffered range or into new one\n if (\n !bufferInfo.len ||\n fragEndOffset < bufferInfo.start ||\n fragStartOffset > bufferInfo.end\n ) {\n const pastFragment = currentTime > fragEndOffset;\n // if the seek position is outside the current fragment range\n if (currentTime < fragStartOffset || pastFragment) {\n if (pastFragment && fragCurrent.loader) {\n this.log(\n 'seeking outside of buffer while fragment load in progress, cancel fragment load'\n );\n fragCurrent.abortRequests();\n this.resetLoadingState();\n }\n this.fragPrevious = null;\n }\n }\n }\n\n if (media) {\n // Remove gap fragments\n this.fragmentTracker.removeFragmentsInRange(\n currentTime,\n Infinity,\n this.playlistType,\n true\n );\n\n this.lastCurrentTime = currentTime;\n }\n\n // in case seeking occurs although no media buffered, adjust startPosition and nextLoadPosition to seek target\n if (!this.loadedmetadata && !bufferInfo.len) {\n this.nextLoadPosition = this.startPosition = currentTime;\n }\n\n // Async tick to speed up processing\n this.tickImmediate();\n }\n\n protected onMediaEnded() {\n // reset startPosition and lastCurrentTime to restart playback @ stream beginning\n this.startPosition = this.lastCurrentTime = 0;\n }\n\n protected onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ): void {\n this.startTimeOffset = data.startTimeOffset;\n this.initPTS = [];\n }\n\n protected onHandlerDestroying() {\n this.stopLoad();\n super.onHandlerDestroying();\n }\n\n protected onHandlerDestroyed() {\n this.state = State.STOPPED;\n if (this.fragmentLoader) {\n this.fragmentLoader.destroy();\n }\n if (this.keyLoader) {\n this.keyLoader.destroy();\n }\n if (this.decrypter) {\n this.decrypter.destroy();\n }\n\n this.hls =\n this.log =\n this.warn =\n this.decrypter =\n this.keyLoader =\n this.fragmentLoader =\n this.fragmentTracker =\n null as any;\n super.onHandlerDestroyed();\n }\n\n protected loadFragment(\n frag: Fragment,\n level: Level,\n targetBufferTime: number\n ) {\n this._loadFragForPlayback(frag, level, targetBufferTime);\n }\n\n private _loadFragForPlayback(\n frag: Fragment,\n level: Level,\n targetBufferTime: number\n ) {\n const progressCallback: FragmentLoadProgressCallback = (\n data: FragLoadedData\n ) => {\n if (this.fragContextChanged(frag)) {\n this.warn(\n `Fragment ${frag.sn}${\n data.part ? ' p: ' + data.part.index : ''\n } of level ${frag.level} was dropped during download.`\n );\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n frag.stats.chunkCount++;\n this._handleFragmentLoadProgress(data);\n };\n\n this._doFragLoad(frag, level, targetBufferTime, progressCallback)\n .then((data) => {\n if (!data) {\n // if we're here we probably needed to backtrack or are waiting for more parts\n return;\n }\n const state = this.state;\n if (this.fragContextChanged(frag)) {\n if (\n state === State.FRAG_LOADING ||\n (!this.fragCurrent && state === State.PARSING)\n ) {\n this.fragmentTracker.removeFragment(frag);\n this.state = State.IDLE;\n }\n return;\n }\n\n if ('payload' in data) {\n this.log(`Loaded fragment ${frag.sn} of level ${frag.level}`);\n this.hls.trigger(Events.FRAG_LOADED, data);\n }\n\n // Pass through the whole payload; controllers not implementing progressive loading receive data from this callback\n this._handleFragmentLoadComplete(data);\n })\n .catch((reason) => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(reason);\n this.resetFragmentLoading(frag);\n });\n }\n\n protected clearTrackerIfNeeded(frag: Fragment) {\n const { fragmentTracker } = this;\n const fragState = fragmentTracker.getState(frag);\n if (fragState === FragmentState.APPENDING) {\n // Lower the buffer size and try again\n const playlistType = frag.type as PlaylistLevelType;\n const bufferedInfo = this.getFwdBufferInfo(\n this.mediaBuffer,\n playlistType\n );\n const minForwardBufferLength = Math.max(\n frag.duration,\n bufferedInfo ? bufferedInfo.len : this.config.maxBufferLength\n );\n if (this.reduceMaxBufferLength(minForwardBufferLength)) {\n fragmentTracker.removeFragment(frag);\n }\n } else if (this.mediaBuffer?.buffered.length === 0) {\n // Stop gap for bad tracker / buffer flush behavior\n fragmentTracker.removeAllFragments();\n } else if (fragmentTracker.hasParts(frag.type)) {\n // In low latency mode, remove fragments for which only some parts were buffered\n fragmentTracker.detectPartialFragments({\n frag,\n part: null,\n stats: frag.stats,\n id: frag.type,\n });\n if (fragmentTracker.getState(frag) === FragmentState.PARTIAL) {\n fragmentTracker.removeFragment(frag);\n }\n }\n }\n\n protected checkLiveUpdate(details: LevelDetails) {\n if (details.updated && !details.live) {\n // Live stream ended, update fragment tracker\n const lastFragment = details.fragments[details.fragments.length - 1];\n this.fragmentTracker.detectPartialFragments({\n frag: lastFragment,\n part: null,\n stats: lastFragment.stats,\n id: lastFragment.type,\n });\n }\n if (!details.fragments[0]) {\n details.deltaUpdateFailed = true;\n }\n }\n\n protected flushMainBuffer(\n startOffset: number,\n endOffset: number,\n type: SourceBufferName | null = null\n ) {\n if (!(startOffset - endOffset)) {\n return;\n }\n // When alternate audio is playing, the audio-stream-controller is responsible for the audio buffer. Otherwise,\n // passing a null type flushes both buffers\n const flushScope: BufferFlushingData = { startOffset, endOffset, type };\n this.hls.trigger(Events.BUFFER_FLUSHING, flushScope);\n }\n\n protected _loadInitSegment(frag: Fragment, level: Level) {\n this._doFragLoad(frag, level)\n .then((data) => {\n if (!data || this.fragContextChanged(frag) || !this.levels) {\n throw new Error('init load aborted');\n }\n\n return data;\n })\n .then((data: FragLoadedData) => {\n const { hls } = this;\n const { payload } = data;\n const decryptData = frag.decryptdata;\n\n // check to see if the payload needs to be decrypted\n if (\n payload &&\n payload.byteLength > 0 &&\n decryptData &&\n decryptData.key &&\n decryptData.iv &&\n decryptData.method === 'AES-128'\n ) {\n const startTime = self.performance.now();\n // decrypt init segment data\n return this.decrypter\n .decrypt(\n new Uint8Array(payload),\n decryptData.key.buffer,\n decryptData.iv.buffer\n )\n .catch((err) => {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_DECRYPT_ERROR,\n fatal: false,\n error: err,\n reason: err.message,\n frag,\n });\n throw err;\n })\n .then((decryptedData) => {\n const endTime = self.performance.now();\n hls.trigger(Events.FRAG_DECRYPTED, {\n frag,\n payload: decryptedData,\n stats: {\n tstart: startTime,\n tdecrypt: endTime,\n },\n });\n data.payload = decryptedData;\n\n return data;\n });\n }\n\n return data;\n })\n .then((data: FragLoadedData) => {\n const { fragCurrent, hls, levels } = this;\n if (!levels) {\n throw new Error('init load aborted, missing levels');\n }\n\n const stats = frag.stats;\n this.state = State.IDLE;\n level.fragmentError = 0;\n frag.data = new Uint8Array(data.payload);\n stats.parsing.start = stats.buffering.start = self.performance.now();\n stats.parsing.end = stats.buffering.end = self.performance.now();\n\n // Silence FRAG_BUFFERED event if fragCurrent is null\n if (data.frag === fragCurrent) {\n hls.trigger(Events.FRAG_BUFFERED, {\n stats,\n frag: fragCurrent,\n part: null,\n id: frag.type,\n });\n }\n this.tick();\n })\n .catch((reason) => {\n if (this.state === State.STOPPED || this.state === State.ERROR) {\n return;\n }\n this.warn(reason);\n this.resetFragmentLoading(frag);\n });\n }\n\n protected fragContextChanged(frag: Fragment | null) {\n const { fragCurrent } = this;\n return (\n !frag ||\n !fragCurrent ||\n frag.level !== fragCurrent.level ||\n frag.sn !== fragCurrent.sn ||\n frag.urlId !== fragCurrent.urlId\n );\n }\n\n protected fragBufferedComplete(frag: Fragment, part: Part | null) {\n const media = this.mediaBuffer ? this.mediaBuffer : this.media;\n this.log(\n `Buffered ${frag.type} sn: ${frag.sn}${\n part ? ' part: ' + part.index : ''\n } of ${\n this.playlistType === PlaylistLevelType.MAIN ? 'level' : 'track'\n } ${frag.level} (frag:[${(frag.startPTS ?? NaN).toFixed(3)}-${(\n frag.endPTS ?? NaN\n ).toFixed(3)}] > buffer:${\n media\n ? TimeRanges.toString(BufferHelper.getBuffered(media))\n : '(detached)'\n })`\n );\n this.state = State.IDLE;\n if (!media) {\n return;\n }\n if (\n !this.loadedmetadata &&\n frag.type == PlaylistLevelType.MAIN &&\n media.buffered.length &&\n this.fragCurrent?.sn === this.fragPrevious?.sn\n ) {\n this.loadedmetadata = true;\n this.seekToStartPos();\n }\n this.tick();\n }\n\n protected seekToStartPos() {}\n\n protected _handleFragmentLoadComplete(fragLoadedEndData: PartsLoadedData) {\n const { transmuxer } = this;\n if (!transmuxer) {\n return;\n }\n const { frag, part, partsLoaded } = fragLoadedEndData;\n // If we did not load parts, or loaded all parts, we have complete (not partial) fragment data\n const complete =\n !partsLoaded ||\n partsLoaded.length === 0 ||\n partsLoaded.some((fragLoaded) => !fragLoaded);\n const chunkMeta = new ChunkMetadata(\n frag.level,\n frag.sn as number,\n frag.stats.chunkCount + 1,\n 0,\n part ? part.index : -1,\n !complete\n );\n transmuxer.flush(chunkMeta);\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n protected _handleFragmentLoadProgress(\n frag: PartsLoadedData | FragLoadedData\n ) {}\n\n protected _doFragLoad(\n frag: Fragment,\n level: Level,\n targetBufferTime: number | null = null,\n progressCallback?: FragmentLoadProgressCallback\n ): Promise<PartsLoadedData | FragLoadedData | null> {\n const details = level?.details;\n if (!this.levels || !details) {\n throw new Error(\n `frag load aborted, missing level${details ? '' : ' detail'}s`\n );\n }\n\n let keyLoadingPromise: Promise<KeyLoadedData | void> | null = null;\n if (frag.encrypted && !frag.decryptdata?.key) {\n this.log(\n `Loading key for ${frag.sn} of [${details.startSN}-${details.endSN}], ${\n this.logPrefix === '[stream-controller]' ? 'level' : 'track'\n } ${frag.level}`\n );\n this.state = State.KEY_LOADING;\n this.fragCurrent = frag;\n keyLoadingPromise = this.keyLoader.load(frag).then((keyLoadedData) => {\n if (!this.fragContextChanged(keyLoadedData.frag)) {\n this.hls.trigger(Events.KEY_LOADED, keyLoadedData);\n if (this.state === State.KEY_LOADING) {\n this.state = State.IDLE;\n }\n return keyLoadedData;\n }\n });\n this.hls.trigger(Events.KEY_LOADING, { frag });\n if (this.fragCurrent === null) {\n keyLoadingPromise = Promise.reject(\n new Error(`frag load aborted, context changed in KEY_LOADING`)\n );\n }\n } else if (!frag.encrypted && details.encryptedFragments.length) {\n this.keyLoader.loadClear(frag, details.encryptedFragments);\n }\n\n targetBufferTime = Math.max(frag.start, targetBufferTime || 0);\n if (this.config.lowLatencyMode && frag.sn !== 'initSegment') {\n const partList = details.partList;\n if (partList && progressCallback) {\n if (targetBufferTime > frag.end && details.fragmentHint) {\n frag = details.fragmentHint;\n }\n const partIndex = this.getNextPart(partList, frag, targetBufferTime);\n if (partIndex > -1) {\n const part = partList[partIndex];\n this.log(\n `Loading part sn: ${frag.sn} p: ${part.index} cc: ${\n frag.cc\n } of playlist [${details.startSN}-${\n details.endSN\n }] parts [0-${partIndex}-${partList.length - 1}] ${\n this.logPrefix === '[stream-controller]' ? 'level' : 'track'\n }: ${frag.level}, target: ${parseFloat(\n targetBufferTime.toFixed(3)\n )}`\n );\n this.nextLoadPosition = part.start + part.duration;\n this.state = State.FRAG_LOADING;\n let result: Promise<PartsLoadedData | FragLoadedData | null>;\n if (keyLoadingPromise) {\n result = keyLoadingPromise\n .then((keyLoadedData) => {\n if (\n !keyLoadedData ||\n this.fragContextChanged(keyLoadedData.frag)\n ) {\n return null;\n }\n return this.doFragPartsLoad(\n frag,\n part,\n level,\n progressCallback\n );\n })\n .catch((error) => this.handleFragLoadError(error));\n } else {\n result = this.doFragPartsLoad(\n frag,\n part,\n level,\n progressCallback\n ).catch((error: LoadError) => this.handleFragLoadError(error));\n }\n this.hls.trigger(Events.FRAG_LOADING, {\n frag,\n part,\n targetBufferTime,\n });\n if (this.fragCurrent === null) {\n return Promise.reject(\n new Error(\n `frag load aborted, context changed in FRAG_LOADING parts`\n )\n );\n }\n return result;\n } else if (\n !frag.url ||\n this.loadedEndOfParts(partList, targetBufferTime)\n ) {\n // Fragment hint has no parts\n return Promise.resolve(null);\n }\n }\n }\n\n this.log(\n `Loading fragment ${frag.sn} cc: ${frag.cc} ${\n details ? 'of [' + details.startSN + '-' + details.endSN + '] ' : ''\n }${this.logPrefix === '[stream-controller]' ? 'level' : 'track'}: ${\n frag.level\n }, target: ${parseFloat(targetBufferTime.toFixed(3))}`\n );\n // Don't update nextLoadPosition for fragments which are not buffered\n if (Number.isFinite(frag.sn as number) && !this.bitrateTest) {\n this.nextLoadPosition = frag.start + frag.duration;\n }\n this.state = State.FRAG_LOADING;\n\n // Load key before streaming fragment data\n const dataOnProgress = this.config.progressive;\n let result: Promise<PartsLoadedData | FragLoadedData | null>;\n if (dataOnProgress && keyLoadingPromise) {\n result = keyLoadingPromise\n .then((keyLoadedData) => {\n if (!keyLoadedData || this.fragContextChanged(keyLoadedData?.frag)) {\n return null;\n }\n return this.fragmentLoader.load(frag, progressCallback);\n })\n .catch((error) => this.handleFragLoadError(error));\n } else {\n // load unencrypted fragment data with progress event,\n // or handle fragment result after key and fragment are finished loading\n result = Promise.all([\n this.fragmentLoader.load(\n frag,\n dataOnProgress ? progressCallback : undefined\n ),\n keyLoadingPromise,\n ])\n .then(([fragLoadedData]) => {\n if (!dataOnProgress && fragLoadedData && progressCallback) {\n progressCallback(fragLoadedData);\n }\n return fragLoadedData;\n })\n .catch((error) => this.handleFragLoadError(error));\n }\n this.hls.trigger(Events.FRAG_LOADING, { frag, targetBufferTime });\n if (this.fragCurrent === null) {\n return Promise.reject(\n new Error(`frag load aborted, context changed in FRAG_LOADING`)\n );\n }\n return result;\n }\n\n private doFragPartsLoad(\n frag: Fragment,\n fromPart: Part,\n level: Level,\n progressCallback: FragmentLoadProgressCallback\n ): Promise<PartsLoadedData | null> {\n return new Promise(\n (resolve: ResolveFragLoaded, reject: RejectFragLoaded) => {\n const partsLoaded: FragLoadedData[] = [];\n const initialPartList = level.details?.partList;\n const loadPart = (part: Part) => {\n this.fragmentLoader\n .loadPart(frag, part, progressCallback)\n .then((partLoadedData: FragLoadedData) => {\n partsLoaded[part.index] = partLoadedData;\n const loadedPart = partLoadedData.part as Part;\n this.hls.trigger(Events.FRAG_LOADED, partLoadedData);\n const nextPart =\n getPartWith(level, frag.sn as number, part.index + 1) ||\n findPart(initialPartList, frag.sn as number, part.index + 1);\n if (nextPart) {\n loadPart(nextPart);\n } else {\n return resolve({\n frag,\n part: loadedPart,\n partsLoaded,\n });\n }\n })\n .catch(reject);\n };\n loadPart(fromPart);\n }\n );\n }\n\n private handleFragLoadError(error: LoadError | Error) {\n if ('data' in error) {\n const data = error.data;\n if (error.data && data.details === ErrorDetails.INTERNAL_ABORTED) {\n this.handleFragLoadAborted(data.frag, data.part);\n } else {\n this.hls.trigger(Events.ERROR, data as ErrorData);\n }\n } else {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n err: error,\n error,\n fatal: true,\n });\n }\n return null;\n }\n\n protected _handleTransmuxerFlush(chunkMeta: ChunkMetadata) {\n const context = this.getCurrentContext(chunkMeta);\n if (!context || this.state !== State.PARSING) {\n if (\n !this.fragCurrent &&\n this.state !== State.STOPPED &&\n this.state !== State.ERROR\n ) {\n this.state = State.IDLE;\n }\n return;\n }\n const { frag, part, level } = context;\n const now = self.performance.now();\n frag.stats.parsing.end = now;\n if (part) {\n part.stats.parsing.end = now;\n }\n this.updateLevelTiming(frag, part, level, chunkMeta.partial);\n }\n\n protected getCurrentContext(\n chunkMeta: ChunkMetadata\n ): { frag: Fragment; part: Part | null; level: Level } | null {\n const { levels, fragCurrent } = this;\n const { level: levelIndex, sn, part: partIndex } = chunkMeta;\n if (!levels?.[levelIndex]) {\n this.warn(\n `Levels object was unset while buffering fragment ${sn} of level ${levelIndex}. The current chunk will not be buffered.`\n );\n return null;\n }\n const level = levels[levelIndex];\n const part = partIndex > -1 ? getPartWith(level, sn, partIndex) : null;\n const frag = part\n ? part.fragment\n : getFragmentWithSN(level, sn, fragCurrent);\n if (!frag) {\n return null;\n }\n if (fragCurrent && fragCurrent !== frag) {\n frag.stats = fragCurrent.stats;\n }\n return { frag, part, level };\n }\n\n protected bufferFragmentData(\n data: RemuxedTrack,\n frag: Fragment,\n part: Part | null,\n chunkMeta: ChunkMetadata,\n noBacktracking?: boolean\n ) {\n if (!data || this.state !== State.PARSING) {\n return;\n }\n\n const { data1, data2 } = data;\n let buffer = data1;\n if (data1 && data2) {\n // Combine the moof + mdat so that we buffer with a single append\n buffer = appendUint8Array(data1, data2);\n }\n\n if (!buffer?.length) {\n return;\n }\n\n const segment: BufferAppendingData = {\n type: data.type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n data: buffer,\n };\n this.hls.trigger(Events.BUFFER_APPENDING, segment);\n\n if (data.dropped && data.independent && !part) {\n if (noBacktracking) {\n return;\n }\n // Clear buffer so that we reload previous segments sequentially if required\n this.flushBufferGap(frag);\n }\n }\n\n protected flushBufferGap(frag: Fragment) {\n const media = this.media;\n if (!media) {\n return;\n }\n // If currentTime is not buffered, clear the back buffer so that we can backtrack as much as needed\n if (!BufferHelper.isBuffered(media, media.currentTime)) {\n this.flushMainBuffer(0, frag.start);\n return;\n }\n // Remove back-buffer without interrupting playback to allow back tracking\n const currentTime = media.currentTime;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const fragDuration = frag.duration;\n const segmentFraction = Math.min(\n this.config.maxFragLookUpTolerance * 2,\n fragDuration * 0.25\n );\n const start = Math.max(\n Math.min(frag.start - segmentFraction, bufferInfo.end - segmentFraction),\n currentTime + segmentFraction\n );\n if (frag.start - start > segmentFraction) {\n this.flushMainBuffer(start, frag.start);\n }\n }\n\n protected getFwdBufferInfo(\n bufferable: Bufferable | null,\n type: PlaylistLevelType\n ): BufferInfo | null {\n const pos = this.getLoadPosition();\n if (!Number.isFinite(pos)) {\n return null;\n }\n return this.getFwdBufferInfoAtPos(bufferable, pos, type);\n }\n\n protected getFwdBufferInfoAtPos(\n bufferable: Bufferable | null,\n pos: number,\n type: PlaylistLevelType\n ): BufferInfo | null {\n const {\n config: { maxBufferHole },\n } = this;\n const bufferInfo = BufferHelper.bufferInfo(bufferable, pos, maxBufferHole);\n // Workaround flaw in getting forward buffer when maxBufferHole is smaller than gap at current pos\n if (bufferInfo.len === 0 && bufferInfo.nextStart !== undefined) {\n const bufferedFragAtPos = this.fragmentTracker.getBufferedFrag(pos, type);\n if (bufferedFragAtPos && bufferInfo.nextStart < bufferedFragAtPos.end) {\n return BufferHelper.bufferInfo(\n bufferable,\n pos,\n Math.max(bufferInfo.nextStart, maxBufferHole)\n );\n }\n }\n return bufferInfo;\n }\n\n protected getMaxBufferLength(levelBitrate?: number): number {\n const { config } = this;\n let maxBufLen;\n if (levelBitrate) {\n maxBufLen = Math.max(\n (8 * config.maxBufferSize) / levelBitrate,\n config.maxBufferLength\n );\n } else {\n maxBufLen = config.maxBufferLength;\n }\n return Math.min(maxBufLen, config.maxMaxBufferLength);\n }\n\n protected reduceMaxBufferLength(threshold: number) {\n const config = this.config;\n const minLength = threshold || config.maxBufferLength;\n if (config.maxMaxBufferLength >= minLength) {\n // reduce max buffer length as it might be too high. we do this to avoid loop flushing ...\n config.maxMaxBufferLength /= 2;\n this.warn(`Reduce max buffer length to ${config.maxMaxBufferLength}s`);\n return true;\n }\n return false;\n }\n\n protected getAppendedFrag(\n position: number,\n playlistType: PlaylistLevelType = PlaylistLevelType.MAIN\n ): Fragment | null {\n const fragOrPart = this.fragmentTracker.getAppendedFrag(\n position,\n PlaylistLevelType.MAIN\n );\n if (fragOrPart && 'fragment' in fragOrPart) {\n return fragOrPart.fragment;\n }\n return fragOrPart;\n }\n\n protected getNextFragment(\n pos: number,\n levelDetails: LevelDetails\n ): Fragment | null {\n const fragments = levelDetails.fragments;\n const fragLen = fragments.length;\n\n if (!fragLen) {\n return null;\n }\n\n // find fragment index, contiguous with end of buffer position\n const { config } = this;\n const start = fragments[0].start;\n let frag;\n\n if (levelDetails.live) {\n const initialLiveManifestSize = config.initialLiveManifestSize;\n if (fragLen < initialLiveManifestSize) {\n this.warn(\n `Not enough fragments to start playback (have: ${fragLen}, need: ${initialLiveManifestSize})`\n );\n return null;\n }\n // The real fragment start times for a live stream are only known after the PTS range for that level is known.\n // In order to discover the range, we load the best matching fragment for that level and demux it.\n // Do not load using live logic if the starting frag is requested - we want to use getFragmentAtPosition() so that\n // we get the fragment matching that start time\n if (\n !levelDetails.PTSKnown &&\n !this.startFragRequested &&\n this.startPosition === -1\n ) {\n frag = this.getInitialLiveFragment(levelDetails, fragments);\n this.startPosition = frag\n ? this.hls.liveSyncPosition || frag.start\n : pos;\n }\n } else if (pos <= start) {\n // VoD playlist: if loadPosition before start of playlist, load first fragment\n frag = fragments[0];\n }\n\n // If we haven't run into any special cases already, just load the fragment most closely matching the requested position\n if (!frag) {\n const end = config.lowLatencyMode\n ? levelDetails.partEnd\n : levelDetails.fragmentEnd;\n frag = this.getFragmentAtPosition(pos, end, levelDetails);\n }\n\n return this.mapToInitFragWhenRequired(frag);\n }\n\n protected isLoopLoading(frag: Fragment, targetBufferTime: number): boolean {\n const trackerState = this.fragmentTracker.getState(frag);\n return (\n (trackerState === FragmentState.OK ||\n (trackerState === FragmentState.PARTIAL && !!frag.gap)) &&\n this.nextLoadPosition > targetBufferTime\n );\n }\n\n protected getNextFragmentLoopLoading(\n frag: Fragment,\n levelDetails: LevelDetails,\n bufferInfo: BufferInfo,\n playlistType: PlaylistLevelType,\n maxBufLen: number\n ): Fragment | null {\n const gapStart = frag.gap;\n const nextFragment = this.getNextFragment(\n this.nextLoadPosition,\n levelDetails\n );\n if (nextFragment === null) {\n return nextFragment;\n }\n frag = nextFragment;\n if (gapStart && frag && !frag.gap && bufferInfo.nextStart) {\n // Media buffered after GAP tags should not make the next buffer timerange exceed forward buffer length\n const nextbufferInfo = this.getFwdBufferInfoAtPos(\n this.mediaBuffer ? this.mediaBuffer : this.media,\n bufferInfo.nextStart,\n playlistType\n );\n if (\n nextbufferInfo !== null &&\n bufferInfo.len + nextbufferInfo.len >= maxBufLen\n ) {\n // Returning here might result in not finding an audio and video candiate to skip to\n this.log(\n `buffer full after gaps in \"${playlistType}\" playlist starting at sn: ${frag.sn}`\n );\n return null;\n }\n }\n return frag;\n }\n\n mapToInitFragWhenRequired(frag: Fragment | null): typeof frag {\n // If an initSegment is present, it must be buffered first\n if (frag?.initSegment && !frag?.initSegment.data && !this.bitrateTest) {\n return frag.initSegment;\n }\n\n return frag;\n }\n\n getNextPart(\n partList: Part[],\n frag: Fragment,\n targetBufferTime: number\n ): number {\n let nextPart = -1;\n let contiguous = false;\n let independentAttrOmitted = true;\n for (let i = 0, len = partList.length; i < len; i++) {\n const part = partList[i];\n independentAttrOmitted = independentAttrOmitted && !part.independent;\n if (nextPart > -1 && targetBufferTime < part.start) {\n break;\n }\n const loaded = part.loaded;\n if (loaded) {\n nextPart = -1;\n } else if (\n (contiguous || part.independent || independentAttrOmitted) &&\n part.fragment === frag\n ) {\n nextPart = i;\n }\n contiguous = loaded;\n }\n return nextPart;\n }\n\n private loadedEndOfParts(\n partList: Part[],\n targetBufferTime: number\n ): boolean {\n const lastPart = partList[partList.length - 1];\n return lastPart && targetBufferTime > lastPart.start && lastPart.loaded;\n }\n\n /*\n This method is used find the best matching first fragment for a live playlist. This fragment is used to calculate the\n \"sliding\" of the playlist, which is its offset from the start of playback. After sliding we can compute the real\n start and end times for each fragment in the playlist (after which this method will not need to be called).\n */\n protected getInitialLiveFragment(\n levelDetails: LevelDetails,\n fragments: Array<Fragment>\n ): Fragment | null {\n const fragPrevious = this.fragPrevious;\n let frag: Fragment | null = null;\n if (fragPrevious) {\n if (levelDetails.hasProgramDateTime) {\n // Prefer using PDT, because it can be accurate enough to choose the correct fragment without knowing the level sliding\n this.log(\n `Live playlist, switching playlist, load frag with same PDT: ${fragPrevious.programDateTime}`\n );\n frag = findFragmentByPDT(\n fragments,\n fragPrevious.endProgramDateTime,\n this.config.maxFragLookUpTolerance\n );\n }\n if (!frag) {\n // SN does not need to be accurate between renditions, but depending on the packaging it may be so.\n const targetSN = (fragPrevious.sn as number) + 1;\n if (\n targetSN >= levelDetails.startSN &&\n targetSN <= levelDetails.endSN\n ) {\n const fragNext = fragments[targetSN - levelDetails.startSN];\n // Ensure that we're staying within the continuity range, since PTS resets upon a new range\n if (fragPrevious.cc === fragNext.cc) {\n frag = fragNext;\n this.log(\n `Live playlist, switching playlist, load frag with next SN: ${\n frag!.sn\n }`\n );\n }\n }\n // It's important to stay within the continuity range if available; otherwise the fragments in the playlist\n // will have the wrong start times\n if (!frag) {\n frag = findFragWithCC(fragments, fragPrevious.cc);\n if (frag) {\n this.log(\n `Live playlist, switching playlist, load frag with same CC: ${frag.sn}`\n );\n }\n }\n }\n } else {\n // Find a new start fragment when fragPrevious is null\n const liveStart = this.hls.liveSyncPosition;\n if (liveStart !== null) {\n frag = this.getFragmentAtPosition(\n liveStart,\n this.bitrateTest ? levelDetails.fragmentEnd : levelDetails.edge,\n levelDetails\n );\n }\n }\n\n return frag;\n }\n\n /*\n This method finds the best matching fragment given the provided position.\n */\n protected getFragmentAtPosition(\n bufferEnd: number,\n end: number,\n levelDetails: LevelDetails\n ): Fragment | null {\n const { config } = this;\n let { fragPrevious } = this;\n let { fragments, endSN } = levelDetails;\n const { fragmentHint } = levelDetails;\n const tolerance = config.maxFragLookUpTolerance;\n const partList = levelDetails.partList;\n\n const loadingParts = !!(\n config.lowLatencyMode &&\n partList?.length &&\n fragmentHint\n );\n if (loadingParts && fragmentHint && !this.bitrateTest) {\n // Include incomplete fragment with parts at end\n fragments = fragments.concat(fragmentHint);\n endSN = fragmentHint.sn as number;\n }\n\n let frag;\n if (bufferEnd < end) {\n const lookupTolerance = bufferEnd > end - tolerance ? 0 : tolerance;\n // Remove the tolerance if it would put the bufferEnd past the actual end of stream\n // Uses buffer and sequence number to calculate switch segment (required if using EXT-X-DISCONTINUITY-SEQUENCE)\n frag = findFragmentByPTS(\n fragPrevious,\n fragments,\n bufferEnd,\n lookupTolerance\n );\n } else {\n // reach end of playlist\n frag = fragments[fragments.length - 1];\n }\n\n if (frag) {\n const curSNIdx = frag.sn - levelDetails.startSN;\n // Move fragPrevious forward to support forcing the next fragment to load\n // when the buffer catches up to a previously buffered range.\n const fragState = this.fragmentTracker.getState(frag);\n if (\n fragState === FragmentState.OK ||\n (fragState === FragmentState.PARTIAL && frag.gap)\n ) {\n fragPrevious = frag;\n }\n if (\n fragPrevious &&\n frag.sn === fragPrevious.sn &&\n (!loadingParts || partList[0].fragment.sn > frag.sn)\n ) {\n // Force the next fragment to load if the previous one was already selected. This can occasionally happen with\n // non-uniform fragment durations\n const sameLevel = fragPrevious && frag.level === fragPrevious.level;\n if (sameLevel) {\n const nextFrag = fragments[curSNIdx + 1];\n if (\n frag.sn < endSN &&\n this.fragmentTracker.getState(nextFrag) !== FragmentState.OK\n ) {\n frag = nextFrag;\n } else {\n frag = null;\n }\n }\n }\n }\n return frag;\n }\n\n protected synchronizeToLiveEdge(levelDetails: LevelDetails) {\n const { config, media } = this;\n if (!media) {\n return;\n }\n const liveSyncPosition = this.hls.liveSyncPosition;\n const currentTime = media.currentTime;\n const start = levelDetails.fragments[0].start;\n const end = levelDetails.edge;\n const withinSlidingWindow =\n currentTime >= start - config.maxFragLookUpTolerance &&\n currentTime <= end;\n // Continue if we can seek forward to sync position or if current time is outside of sliding window\n if (\n liveSyncPosition !== null &&\n media.duration > liveSyncPosition &&\n (currentTime < liveSyncPosition || !withinSlidingWindow)\n ) {\n // Continue if buffer is starving or if current time is behind max latency\n const maxLatency =\n config.liveMaxLatencyDuration !== undefined\n ? config.liveMaxLatencyDuration\n : config.liveMaxLatencyDurationCount * levelDetails.targetduration;\n if (\n (!withinSlidingWindow && media.readyState < 4) ||\n currentTime < end - maxLatency\n ) {\n if (!this.loadedmetadata) {\n this.nextLoadPosition = liveSyncPosition;\n }\n // Only seek if ready and there is not a significant forward buffer available for playback\n if (media.readyState) {\n this.warn(\n `Playback: ${currentTime.toFixed(\n 3\n )} is located too far from the end of live sliding playlist: ${end}, reset currentTime to : ${liveSyncPosition.toFixed(\n 3\n )}`\n );\n media.currentTime = liveSyncPosition;\n }\n }\n }\n }\n\n protected alignPlaylists(\n details: LevelDetails,\n previousDetails?: LevelDetails\n ): number {\n const { levels, levelLastLoaded, fragPrevious } = this;\n const lastLevel: Level | null =\n levelLastLoaded !== null ? levels![levelLastLoaded] : null;\n\n // FIXME: If not for `shouldAlignOnDiscontinuities` requiring fragPrevious.cc,\n // this could all go in level-helper mergeDetails()\n const length = details.fragments.length;\n if (!length) {\n this.warn(`No fragments in live playlist`);\n return 0;\n }\n const slidingStart = details.fragments[0].start;\n const firstLevelLoad = !previousDetails;\n const aligned = details.alignedSliding && Number.isFinite(slidingStart);\n if (firstLevelLoad || (!aligned && !slidingStart)) {\n alignStream(fragPrevious, lastLevel, details);\n const alignedSlidingStart = details.fragments[0].start;\n this.log(\n `Live playlist sliding: ${alignedSlidingStart.toFixed(2)} start-sn: ${\n previousDetails ? previousDetails.startSN : 'na'\n }->${details.startSN} prev-sn: ${\n fragPrevious ? fragPrevious.sn : 'na'\n } fragments: ${length}`\n );\n return alignedSlidingStart;\n }\n return slidingStart;\n }\n\n protected waitForCdnTuneIn(details: LevelDetails) {\n // Wait for Low-Latency CDN Tune-in to get an updated playlist\n const advancePartLimit = 3;\n return (\n details.live &&\n details.canBlockReload &&\n details.partTarget &&\n details.tuneInGoal >\n Math.max(details.partHoldBack, details.partTarget * advancePartLimit)\n );\n }\n\n protected setStartPosition(details: LevelDetails, sliding: number) {\n // compute start position if set to -1. use it straight away if value is defined\n let startPosition = this.startPosition;\n if (startPosition < sliding) {\n startPosition = -1;\n }\n if (startPosition === -1 || this.lastCurrentTime === -1) {\n // Use Playlist EXT-X-START:TIME-OFFSET when set\n // Prioritize Multivariant Playlist offset so that main, audio, and subtitle stream-controller start times match\n const offsetInMultivariantPlaylist = this.startTimeOffset !== null;\n const startTimeOffset = offsetInMultivariantPlaylist\n ? this.startTimeOffset\n : details.startTimeOffset;\n if (startTimeOffset !== null && Number.isFinite(startTimeOffset)) {\n startPosition = sliding + startTimeOffset;\n if (startTimeOffset < 0) {\n startPosition += details.totalduration;\n }\n startPosition = Math.min(\n Math.max(sliding, startPosition),\n sliding + details.totalduration\n );\n this.log(\n `Start time offset ${startTimeOffset} found in ${\n offsetInMultivariantPlaylist ? 'multivariant' : 'media'\n } playlist, adjust startPosition to ${startPosition}`\n );\n this.startPosition = startPosition;\n } else if (details.live) {\n // Leave this.startPosition at -1, so that we can use `getInitialLiveFragment` logic when startPosition has\n // not been specified via the config or an as an argument to startLoad (#3736).\n startPosition = this.hls.liveSyncPosition || sliding;\n } else {\n this.startPosition = startPosition = 0;\n }\n this.lastCurrentTime = startPosition;\n }\n this.nextLoadPosition = startPosition;\n }\n\n protected getLoadPosition(): number {\n const { media } = this;\n // if we have not yet loaded any fragment, start loading from start position\n let pos = 0;\n if (this.loadedmetadata && media) {\n pos = media.currentTime;\n } else if (this.nextLoadPosition) {\n pos = this.nextLoadPosition;\n }\n\n return pos;\n }\n\n private handleFragLoadAborted(frag: Fragment, part: Part | undefined) {\n if (this.transmuxer && frag.sn !== 'initSegment' && frag.stats.aborted) {\n this.warn(\n `Fragment ${frag.sn}${part ? ' part ' + part.index : ''} of level ${\n frag.level\n } was aborted`\n );\n this.resetFragmentLoading(frag);\n }\n }\n\n protected resetFragmentLoading(frag: Fragment) {\n if (\n !this.fragCurrent ||\n (!this.fragContextChanged(frag) &&\n this.state !== State.FRAG_LOADING_WAITING_RETRY)\n ) {\n this.state = State.IDLE;\n }\n }\n\n protected onFragmentOrKeyLoadError(\n filterType: PlaylistLevelType,\n data: ErrorData\n ) {\n if (data.chunkMeta && !data.frag) {\n const context = this.getCurrentContext(data.chunkMeta);\n if (context) {\n data.frag = context.frag;\n }\n }\n const frag = data.frag;\n // Handle frag error related to caller's filterType\n if (!frag || frag.type !== filterType || !this.levels) {\n return;\n }\n if (this.fragContextChanged(frag)) {\n this.warn(\n `Frag load error must match current frag to retry ${frag.url} > ${this.fragCurrent?.url}`\n );\n return;\n }\n const gapTagEncountered = data.details === ErrorDetails.FRAG_GAP;\n if (gapTagEncountered) {\n this.fragmentTracker.fragBuffered(frag, true);\n }\n // keep retrying until the limit will be reached\n const errorAction = data.errorAction;\n const { action, retryCount = 0, retryConfig } = errorAction || {};\n if (\n errorAction &&\n action === NetworkErrorAction.RetryRequest &&\n retryConfig\n ) {\n this.resetStartWhenNotLoaded(this.levelLastLoaded ?? frag.level);\n const delay = getRetryDelay(retryConfig, retryCount);\n this.warn(\n `Fragment ${frag.sn} of ${filterType} ${frag.level} errored with ${\n data.details\n }, retrying loading ${retryCount + 1}/${\n retryConfig.maxNumRetry\n } in ${delay}ms`\n );\n errorAction.resolved = true;\n this.retryDate = self.performance.now() + delay;\n this.state = State.FRAG_LOADING_WAITING_RETRY;\n } else if (retryConfig && errorAction) {\n this.resetFragmentErrors(filterType);\n if (retryCount < retryConfig.maxNumRetry) {\n // Network retry is skipped when level switch is preferred\n if (!gapTagEncountered) {\n errorAction.resolved = true;\n }\n } else {\n logger.warn(\n `${data.details} reached or exceeded max retry (${retryCount})`\n );\n }\n } else if (\n errorAction?.action === NetworkErrorAction.SendAlternateToPenaltyBox\n ) {\n this.state = State.WAITING_LEVEL;\n } else {\n this.state = State.ERROR;\n }\n // Perform next async tick sooner to speed up error action resolution\n this.tickImmediate();\n }\n\n protected reduceLengthAndFlushBuffer(data: ErrorData): boolean {\n // if in appending state\n if (this.state === State.PARSING || this.state === State.PARSED) {\n const playlistType = data.parent as PlaylistLevelType;\n const bufferedInfo = this.getFwdBufferInfo(\n this.mediaBuffer,\n playlistType\n );\n // 0.5 : tolerance needed as some browsers stalls playback before reaching buffered end\n // reduce max buf len if current position is buffered\n const buffered = bufferedInfo && bufferedInfo.len > 0.5;\n if (buffered) {\n this.reduceMaxBufferLength(bufferedInfo.len);\n }\n const flushBuffer = !buffered;\n if (flushBuffer) {\n // current position is not buffered, but browser is still complaining about buffer full error\n // this happens on IE/Edge, refer to https://github.com/video-dev/hls.js/pull/708\n // in that case flush the whole audio buffer to recover\n this.warn(\n `Buffer full error while media.currentTime is not buffered, flush ${playlistType} buffer`\n );\n }\n if (data.frag) {\n this.fragmentTracker.removeFragment(data.frag);\n this.nextLoadPosition = data.frag.start;\n }\n this.resetLoadingState();\n return flushBuffer;\n }\n return false;\n }\n\n protected resetFragmentErrors(filterType: PlaylistLevelType) {\n if (filterType === PlaylistLevelType.AUDIO) {\n // Reset current fragment since audio track audio is essential and may not have a fail-over track\n this.fragCurrent = null;\n }\n // Fragment errors that result in a level switch or redundant fail-over\n // should reset the stream controller state to idle\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n }\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n\n protected afterBufferFlushed(\n media: Bufferable,\n bufferType: SourceBufferName,\n playlistType: PlaylistLevelType\n ) {\n if (!media) {\n return;\n }\n // After successful buffer flushing, filter flushed fragments from bufferedFrags use mediaBuffered instead of media\n // (so that we will check against video.buffered ranges in case of alt audio track)\n const bufferedTimeRanges = BufferHelper.getBuffered(media);\n this.fragmentTracker.detectEvictedFragments(\n bufferType,\n bufferedTimeRanges,\n playlistType\n );\n if (this.state === State.ENDED) {\n this.resetLoadingState();\n }\n }\n\n protected resetLoadingState() {\n this.log('Reset loading state');\n this.fragCurrent = null;\n this.fragPrevious = null;\n this.state = State.IDLE;\n }\n\n protected resetStartWhenNotLoaded(level: number): void {\n // if loadedmetadata is not set, it means that first frag request failed\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n const details = this.levels ? this.levels[level].details : null;\n if (details?.live) {\n // Update the start position and return to IDLE to recover live start\n this.startPosition = -1;\n this.setStartPosition(details, 0);\n this.resetLoadingState();\n } else {\n this.nextLoadPosition = this.startPosition;\n }\n }\n }\n\n protected resetWhenMissingContext(chunkMeta: ChunkMetadata) {\n this.warn(\n `The loading context changed while buffering fragment ${chunkMeta.sn} of level ${chunkMeta.level}. This chunk will not be buffered.`\n );\n this.removeUnbufferedFrags();\n this.resetStartWhenNotLoaded(this.levelLastLoaded ?? chunkMeta.level);\n this.resetLoadingState();\n }\n\n protected removeUnbufferedFrags(start: number = 0) {\n this.fragmentTracker.removeFragmentsInRange(\n start,\n Infinity,\n this.playlistType,\n false,\n true\n );\n }\n\n private updateLevelTiming(\n frag: Fragment,\n part: Part | null,\n level: Level,\n partial: boolean\n ) {\n const details = level.details as LevelDetails;\n if (!details) {\n this.warn('level.details undefined');\n return;\n }\n const parsed = Object.keys(frag.elementaryStreams).reduce(\n (result, type) => {\n const info = frag.elementaryStreams[type];\n if (info) {\n const parsedDuration = info.endPTS - info.startPTS;\n if (parsedDuration <= 0) {\n // Destroy the transmuxer after it's next time offset failed to advance because duration was <= 0.\n // The new transmuxer will be configured with a time offset matching the next fragment start,\n // preventing the timeline from shifting.\n this.warn(\n `Could not parse fragment ${frag.sn} ${type} duration reliably (${parsedDuration})`\n );\n return result || false;\n }\n const drift = partial\n ? 0\n : updateFragPTSDTS(\n details,\n frag,\n info.startPTS,\n info.endPTS,\n info.startDTS,\n info.endDTS\n );\n this.hls.trigger(Events.LEVEL_PTS_UPDATED, {\n details,\n level,\n drift,\n type,\n frag,\n start: info.startPTS,\n end: info.endPTS,\n });\n return true;\n }\n return result;\n },\n false\n );\n if (parsed) {\n level.fragmentError = 0;\n } else if (this.transmuxer?.error === null) {\n const error = new Error(\n `Found no media in fragment ${frag.sn} of level ${frag.level} resetting transmuxer to fallback to playlist timing`\n );\n if (level.fragmentError === 0) {\n // Mark and track the odd empty segment as a gap to avoid reloading\n level.fragmentError++;\n frag.gap = true;\n this.fragmentTracker.removeFragment(frag);\n this.fragmentTracker.fragBuffered(frag, true);\n }\n this.warn(error.message);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n frag,\n reason: `Found no media in msn ${frag.sn} of level \"${level.url}\"`,\n });\n if (!this.hls) {\n return;\n }\n this.resetTransmuxer();\n // For this error fallthrough. Marking parsed will allow advancing to next fragment.\n }\n this.state = State.PARSED;\n this.hls.trigger(Events.FRAG_PARSED, { frag, part });\n }\n\n protected resetTransmuxer() {\n if (this.transmuxer) {\n this.transmuxer.destroy();\n this.transmuxer = null;\n }\n }\n\n protected recoverWorkerError(data: ErrorData) {\n if (data.event === 'demuxerWorker') {\n this.fragmentTracker.removeAllFragments();\n this.resetTransmuxer();\n this.resetStartWhenNotLoaded(\n this.levelLastLoaded ?? this.fragCurrent?.level ?? 0\n );\n this.resetLoadingState();\n }\n }\n\n set state(nextState) {\n const previousState = this._state;\n if (previousState !== nextState) {\n this._state = nextState;\n this.log(`${previousState}->${nextState}`);\n }\n }\n\n get state() {\n return this._state;\n }\n}\n","import { getMediaSource } from './utils/mediasource-helper';\nimport type { ExtendedSourceBuffer } from './types/buffer';\n\nfunction getSourceBuffer(): typeof self.SourceBuffer {\n return self.SourceBuffer || (self as any).WebKitSourceBuffer;\n}\n\n/**\n * @ignore\n */\nexport function isSupported(): boolean {\n const mediaSource = getMediaSource();\n if (!mediaSource) {\n return false;\n }\n const sourceBuffer = getSourceBuffer();\n const isTypeSupported =\n mediaSource &&\n typeof mediaSource.isTypeSupported === 'function' &&\n mediaSource.isTypeSupported('video/mp4; codecs=\"avc1.42E01E,mp4a.40.2\"');\n\n // if SourceBuffer is exposed ensure its API is valid\n // Older browsers do not expose SourceBuffer globally so checking SourceBuffer.prototype is impossible\n const sourceBufferValidAPI =\n !sourceBuffer ||\n (sourceBuffer.prototype &&\n typeof sourceBuffer.prototype.appendBuffer === 'function' &&\n typeof sourceBuffer.prototype.remove === 'function');\n return !!isTypeSupported && !!sourceBufferValidAPI;\n}\n\n/**\n * @ignore\n */\nexport function changeTypeSupported(): boolean {\n const sourceBuffer = getSourceBuffer();\n return (\n typeof (sourceBuffer?.prototype as ExtendedSourceBuffer)?.changeType ===\n 'function'\n );\n}\n","import type { DemuxedTrack } from '../types/demuxer';\n\nexport function dummyTrack(type = '', inputTimeScale = 90000): DemuxedTrack {\n return {\n type,\n id: -1,\n pid: -1,\n inputTimeScale,\n sequenceNumber: -1,\n samples: [],\n dropped: 0,\n };\n}\n","import * as ID3 from '../demux/id3';\nimport {\n DemuxerResult,\n Demuxer,\n DemuxedAudioTrack,\n AudioFrame,\n DemuxedMetadataTrack,\n DemuxedVideoTrack,\n DemuxedUserdataTrack,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport { dummyTrack } from './dummy-demuxed-track';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { sliceUint8 } from '../utils/typed-array';\nimport { RationalTimestamp } from '../utils/timescale-conversion';\n\nclass BaseAudioDemuxer implements Demuxer {\n protected _audioTrack!: DemuxedAudioTrack;\n protected _id3Track!: DemuxedMetadataTrack;\n protected frameIndex: number = 0;\n protected cachedData: Uint8Array | null = null;\n protected basePTS: number | null = null;\n protected initPTS: RationalTimestamp | null = null;\n protected lastPTS: number | null = null;\n\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number\n ) {\n this._id3Track = {\n type: 'id3',\n id: 3,\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0,\n };\n }\n\n resetTimeStamp(deaultTimestamp: RationalTimestamp | null) {\n this.initPTS = deaultTimestamp;\n this.resetContiguity();\n }\n\n resetContiguity(): void {\n this.basePTS = null;\n this.lastPTS = null;\n this.frameIndex = 0;\n }\n\n canParse(data: Uint8Array, offset: number): boolean {\n return false;\n }\n\n appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number\n ): AudioFrame | void {}\n\n // feed incoming data to the front of the parsing pipeline\n demux(data: Uint8Array, timeOffset: number): DemuxerResult {\n if (this.cachedData) {\n data = appendUint8Array(this.cachedData, data);\n this.cachedData = null;\n }\n\n let id3Data: Uint8Array | undefined = ID3.getID3Data(data, 0);\n let offset = id3Data ? id3Data.length : 0;\n let lastDataIndex;\n const track = this._audioTrack;\n const id3Track = this._id3Track;\n const timestamp = id3Data ? ID3.getTimeStamp(id3Data) : undefined;\n const length = data.length;\n\n if (\n this.basePTS === null ||\n (this.frameIndex === 0 && Number.isFinite(timestamp))\n ) {\n this.basePTS = initPTSFn(timestamp, timeOffset, this.initPTS);\n this.lastPTS = this.basePTS;\n }\n\n if (this.lastPTS === null) {\n this.lastPTS = this.basePTS;\n }\n\n // more expressive than alternative: id3Data?.length\n if (id3Data && id3Data.length > 0) {\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n }\n\n while (offset < length) {\n if (this.canParse(data, offset)) {\n const frame = this.appendFrame(track, data, offset);\n if (frame) {\n this.frameIndex++;\n this.lastPTS = frame.sample.pts;\n offset += frame.length;\n lastDataIndex = offset;\n } else {\n offset = length;\n }\n } else if (ID3.canParse(data, offset)) {\n // after a ID3.canParse, a call to ID3.getID3Data *should* always returns some data\n id3Data = ID3.getID3Data(data, offset)!;\n id3Track.samples.push({\n pts: this.lastPTS,\n dts: this.lastPTS,\n data: id3Data,\n type: MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n offset += id3Data.length;\n lastDataIndex = offset;\n } else {\n offset++;\n }\n if (offset === length && lastDataIndex !== length) {\n const partialData = sliceUint8(data, lastDataIndex);\n if (this.cachedData) {\n this.cachedData = appendUint8Array(this.cachedData, partialData);\n } else {\n this.cachedData = partialData;\n }\n }\n }\n\n return {\n audioTrack: track,\n videoTrack: dummyTrack() as DemuxedVideoTrack,\n id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number\n ): Promise<DemuxerResult> {\n return Promise.reject(\n new Error(`[${this}] This demuxer does not support Sample-AES decryption`)\n );\n }\n\n flush(timeOffset: number): DemuxerResult {\n // Parse cache in case of remaining frames.\n const cachedData = this.cachedData;\n if (cachedData) {\n this.cachedData = null;\n this.demux(cachedData, 0);\n }\n\n return {\n audioTrack: this._audioTrack,\n videoTrack: dummyTrack() as DemuxedVideoTrack,\n id3Track: this._id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n destroy() {}\n}\n\n/**\n * Initialize PTS\n * <p>\n * use timestamp unless it is undefined, NaN or Infinity\n * </p>\n */\nexport const initPTSFn = (\n timestamp: number | undefined,\n timeOffset: number,\n initPTS: RationalTimestamp | null\n): number => {\n if (Number.isFinite(timestamp as number)) {\n return timestamp! * 90;\n }\n const init90kHz = initPTS\n ? (initPTS.baseTime * 90000) / initPTS.timescale\n : 0;\n return timeOffset * 90000 + init90kHz;\n};\nexport default BaseAudioDemuxer;\n","/**\n * ADTS parser helper\n * @link https://wiki.multimedia.cx/index.php?title=ADTS\n */\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport type {\n DemuxedAudioTrack,\n AudioFrame,\n AudioSample,\n} from '../types/demuxer';\n\ntype AudioConfig = {\n config: number[];\n samplerate: number;\n channelCount: number;\n codec: string;\n manifestCodec: string;\n};\n\ntype FrameHeader = {\n headerLength: number;\n frameLength: number;\n};\n\nexport function getAudioConfig(\n observer,\n data: Uint8Array,\n offset: number,\n audioCodec: string\n): AudioConfig | void {\n let adtsObjectType: number;\n let adtsExtensionSamplingIndex: number;\n let adtsChannelConfig: number;\n let config: number[];\n const userAgent = navigator.userAgent.toLowerCase();\n const manifestCodec = audioCodec;\n const adtsSamplingRates = [\n 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025,\n 8000, 7350,\n ];\n // byte 2\n adtsObjectType = ((data[offset + 2] & 0xc0) >>> 6) + 1;\n const adtsSamplingIndex = (data[offset + 2] & 0x3c) >>> 2;\n if (adtsSamplingIndex > adtsSamplingRates.length - 1) {\n observer.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: true,\n reason: `invalid ADTS sampling index:${adtsSamplingIndex}`,\n });\n return;\n }\n adtsChannelConfig = (data[offset + 2] & 0x01) << 2;\n // byte 3\n adtsChannelConfig |= (data[offset + 3] & 0xc0) >>> 6;\n logger.log(\n `manifest codec:${audioCodec}, ADTS type:${adtsObjectType}, samplingIndex:${adtsSamplingIndex}`\n );\n // firefox: freq less than 24kHz = AAC SBR (HE-AAC)\n if (/firefox/i.test(userAgent)) {\n if (adtsSamplingIndex >= 6) {\n adtsObjectType = 5;\n config = new Array(4);\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n } else {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n }\n // Android : always use AAC\n } else if (userAgent.indexOf('android') !== -1) {\n adtsObjectType = 2;\n config = new Array(2);\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n } else {\n /* for other browsers (Chrome/Vivaldi/Opera ...)\n always force audio type to be HE-AAC SBR, as some browsers do not support audio codec switch properly (like Chrome ...)\n */\n adtsObjectType = 5;\n config = new Array(4);\n // if (manifest codec is HE-AAC or HE-AACv2) OR (manifest codec not specified AND frequency less than 24kHz)\n if (\n (audioCodec &&\n (audioCodec.indexOf('mp4a.40.29') !== -1 ||\n audioCodec.indexOf('mp4a.40.5') !== -1)) ||\n (!audioCodec && adtsSamplingIndex >= 6)\n ) {\n // HE-AAC uses SBR (Spectral Band Replication) , high frequencies are constructed from low frequencies\n // there is a factor 2 between frame sample rate and output sample rate\n // multiply frequency by 2 (see table below, equivalent to substract 3)\n adtsExtensionSamplingIndex = adtsSamplingIndex - 3;\n } else {\n // if (manifest codec is AAC) AND (frequency less than 24kHz AND nb channel is 1) OR (manifest codec not specified and mono audio)\n // Chrome fails to play back with low frequency AAC LC mono when initialized with HE-AAC. This is not a problem with stereo.\n if (\n (audioCodec &&\n audioCodec.indexOf('mp4a.40.2') !== -1 &&\n ((adtsSamplingIndex >= 6 && adtsChannelConfig === 1) ||\n /vivaldi/i.test(userAgent))) ||\n (!audioCodec && adtsChannelConfig === 1)\n ) {\n adtsObjectType = 2;\n config = new Array(2);\n }\n adtsExtensionSamplingIndex = adtsSamplingIndex;\n }\n }\n /* refer to http://wiki.multimedia.cx/index.php?title=MPEG-4_Audio#Audio_Specific_Config\n ISO 14496-3 (AAC).pdf - Table 1.13 — Syntax of AudioSpecificConfig()\n Audio Profile / Audio Object Type\n 0: Null\n 1: AAC Main\n 2: AAC LC (Low Complexity)\n 3: AAC SSR (Scalable Sample Rate)\n 4: AAC LTP (Long Term Prediction)\n 5: SBR (Spectral Band Replication)\n 6: AAC Scalable\n sampling freq\n 0: 96000 Hz\n 1: 88200 Hz\n 2: 64000 Hz\n 3: 48000 Hz\n 4: 44100 Hz\n 5: 32000 Hz\n 6: 24000 Hz\n 7: 22050 Hz\n 8: 16000 Hz\n 9: 12000 Hz\n 10: 11025 Hz\n 11: 8000 Hz\n 12: 7350 Hz\n 13: Reserved\n 14: Reserved\n 15: frequency is written explictly\n Channel Configurations\n These are the channel configurations:\n 0: Defined in AOT Specifc Config\n 1: 1 channel: front-center\n 2: 2 channels: front-left, front-right\n */\n // audioObjectType = profile => profile, the MPEG-4 Audio Object Type minus 1\n config[0] = adtsObjectType << 3;\n // samplingFrequencyIndex\n config[0] |= (adtsSamplingIndex & 0x0e) >> 1;\n config[1] |= (adtsSamplingIndex & 0x01) << 7;\n // channelConfiguration\n config[1] |= adtsChannelConfig << 3;\n if (adtsObjectType === 5) {\n // adtsExtensionSamplingIndex\n config[1] |= (adtsExtensionSamplingIndex & 0x0e) >> 1;\n config[2] = (adtsExtensionSamplingIndex & 0x01) << 7;\n // adtsObjectType (force to 2, chrome is checking that object type is less than 5 ???\n // https://chromium.googlesource.com/chromium/src.git/+/master/media/formats/mp4/aac.cc\n config[2] |= 2 << 2;\n config[3] = 0;\n }\n return {\n config,\n samplerate: adtsSamplingRates[adtsSamplingIndex],\n channelCount: adtsChannelConfig,\n codec: 'mp4a.40.' + adtsObjectType,\n manifestCodec,\n };\n}\n\nexport function isHeaderPattern(data: Uint8Array, offset: number): boolean {\n return data[offset] === 0xff && (data[offset + 1] & 0xf6) === 0xf0;\n}\n\nexport function getHeaderLength(data: Uint8Array, offset: number): number {\n return data[offset + 1] & 0x01 ? 7 : 9;\n}\n\nexport function getFullFrameLength(data: Uint8Array, offset: number): number {\n return (\n ((data[offset + 3] & 0x03) << 11) |\n (data[offset + 4] << 3) |\n ((data[offset + 5] & 0xe0) >>> 5)\n );\n}\n\nexport function canGetFrameLength(data: Uint8Array, offset: number): boolean {\n return offset + 5 < data.length;\n}\n\nexport function isHeader(data: Uint8Array, offset: number): boolean {\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\n\nexport function canParse(data: Uint8Array, offset: number): boolean {\n return (\n canGetFrameLength(data, offset) &&\n isHeaderPattern(data, offset) &&\n getFullFrameLength(data, offset) <= data.length - offset\n );\n}\n\nexport function probe(data: Uint8Array, offset: number): boolean {\n // same as isHeader but we also check that ADTS frame follows last ADTS frame\n // or end of data is reached\n if (isHeader(data, offset)) {\n // ADTS header Length\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength >= data.length) {\n return false;\n }\n // ADTS frame Length\n const frameLength = getFullFrameLength(data, offset);\n if (frameLength <= headerLength) {\n return false;\n }\n\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n\nexport function initTrackConfig(\n track: DemuxedAudioTrack,\n observer: HlsEventEmitter,\n data: Uint8Array,\n offset: number,\n audioCodec: string\n) {\n if (!track.samplerate) {\n const config = getAudioConfig(observer, data, offset, audioCodec);\n if (!config) {\n return;\n }\n track.config = config.config;\n track.samplerate = config.samplerate;\n track.channelCount = config.channelCount;\n track.codec = config.codec;\n track.manifestCodec = config.manifestCodec;\n logger.log(\n `parsed codec:${track.codec}, rate:${config.samplerate}, channels:${config.channelCount}`\n );\n }\n}\n\nexport function getFrameDuration(samplerate: number): number {\n return (1024 * 90000) / samplerate;\n}\n\nexport function parseFrameHeader(\n data: Uint8Array,\n offset: number\n): FrameHeader | void {\n // The protection skip bit tells us if we have 2 bytes of CRC data at the end of the ADTS header\n const headerLength = getHeaderLength(data, offset);\n if (offset + headerLength <= data.length) {\n // retrieve frame size\n const frameLength = getFullFrameLength(data, offset) - headerLength;\n if (frameLength > 0) {\n // logger.log(`AAC frame, offset/length/total/pts:${offset+headerLength}/${frameLength}/${data.byteLength}`);\n return { headerLength, frameLength };\n }\n }\n}\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n pts: number,\n frameIndex: number\n): AudioFrame {\n const frameDuration = getFrameDuration(track.samplerate as number);\n const stamp = pts + frameIndex * frameDuration;\n const header = parseFrameHeader(data, offset);\n let unit: Uint8Array;\n if (header) {\n const { frameLength, headerLength } = header;\n const length = headerLength + frameLength;\n const missing = Math.max(0, offset + length - data.length);\n // logger.log(`AAC frame ${frameIndex}, pts:${stamp} length@offset/total: ${frameLength}@${offset+headerLength}/${data.byteLength} missing: ${missing}`);\n if (missing) {\n unit = new Uint8Array(length - headerLength);\n unit.set(data.subarray(offset + headerLength, data.length), 0);\n } else {\n unit = data.subarray(offset + headerLength, offset + length);\n }\n\n const sample: AudioSample = {\n unit,\n pts: stamp,\n };\n if (!missing) {\n track.samples.push(sample as AudioSample);\n }\n\n return { sample, length, missing };\n }\n // overflow incomplete header\n const length = data.length - offset;\n unit = new Uint8Array(length);\n unit.set(data.subarray(offset, data.length), 0);\n const sample: AudioSample = {\n unit,\n pts: stamp,\n };\n return { sample, length, missing: -1 };\n}\n","/**\n * AAC demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport * as ADTS from './adts';\nimport { logger } from '../utils/logger';\nimport * as ID3 from '../demux/id3';\nimport type { HlsEventEmitter } from '../events';\nimport type { HlsConfig } from '../config';\n\nclass AACDemuxer extends BaseAudioDemuxer {\n private readonly observer: HlsEventEmitter;\n private readonly config: HlsConfig;\n\n constructor(observer, config) {\n super();\n this.observer = observer;\n this.config = config;\n }\n\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number\n ) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/adts',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'aac',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n // Source for probe info - https://wiki.multimedia.cx/index.php?title=ADTS\n static probe(data): boolean {\n if (!data) {\n return false;\n }\n\n // Check for the ADTS sync word\n // Look for ADTS header | 1111 1111 | 1111 X00X | where X can be either 0 or 1\n // Layer bits (position 14 and 15) in header should be always 0 for ADTS\n // More info https://wiki.multimedia.cx/index.php?title=ADTS\n const id3Data = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\n\n for (let length = data.length; offset < length; offset++) {\n if (ADTS.probe(data, offset)) {\n logger.log('ADTS sync word found !');\n return true;\n }\n }\n return false;\n }\n\n canParse(data, offset) {\n return ADTS.canParse(data, offset);\n }\n\n appendFrame(track, data, offset) {\n ADTS.initTrackConfig(\n track,\n this.observer,\n data,\n offset,\n track.manifestCodec\n );\n const frame = ADTS.appendFrame(\n track,\n data,\n offset,\n this.basePTS as number,\n this.frameIndex\n );\n if (frame && frame.missing === 0) {\n return frame;\n }\n }\n}\n\nexport default AACDemuxer;\n","/**\n * MP4 demuxer\n */\nimport {\n Demuxer,\n DemuxerResult,\n PassthroughTrack,\n DemuxedAudioTrack,\n DemuxedUserdataTrack,\n DemuxedMetadataTrack,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport {\n findBox,\n segmentValidRange,\n appendUint8Array,\n parseEmsg,\n parseSamples,\n parseInitSegment,\n RemuxerTrackIdConfig,\n} from '../utils/mp4-tools';\nimport { dummyTrack } from './dummy-demuxed-track';\nimport type { HlsEventEmitter } from '../events';\nimport type { HlsConfig } from '../config';\n\nconst emsgSchemePattern = /\\/emsg[-/]ID3/i;\n\nclass MP4Demuxer implements Demuxer {\n private remainderData: Uint8Array | null = null;\n private timeOffset: number = 0;\n private config: HlsConfig;\n private videoTrack?: PassthroughTrack;\n private audioTrack?: DemuxedAudioTrack;\n private id3Track?: DemuxedMetadataTrack;\n private txtTrack?: DemuxedUserdataTrack;\n\n constructor(observer: HlsEventEmitter, config: HlsConfig) {\n this.config = config;\n }\n\n public resetTimeStamp() {}\n\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number\n ) {\n const videoTrack = (this.videoTrack = dummyTrack(\n 'video',\n 1\n ) as PassthroughTrack);\n const audioTrack = (this.audioTrack = dummyTrack(\n 'audio',\n 1\n ) as DemuxedAudioTrack);\n const captionTrack = (this.txtTrack = dummyTrack(\n 'text',\n 1\n ) as DemuxedUserdataTrack);\n\n this.id3Track = dummyTrack('id3', 1) as DemuxedMetadataTrack;\n this.timeOffset = 0;\n\n if (!initSegment?.byteLength) {\n return;\n }\n const initData = parseInitSegment(initSegment);\n\n if (initData.video) {\n const { id, timescale, codec } = initData.video;\n videoTrack.id = id;\n videoTrack.timescale = captionTrack.timescale = timescale;\n videoTrack.codec = codec;\n }\n\n if (initData.audio) {\n const { id, timescale, codec } = initData.audio;\n audioTrack.id = id;\n audioTrack.timescale = timescale;\n audioTrack.codec = codec;\n }\n\n captionTrack.id = RemuxerTrackIdConfig.text;\n videoTrack.sampleDuration = 0;\n videoTrack.duration = audioTrack.duration = trackDuration;\n }\n\n public resetContiguity(): void {\n this.remainderData = null;\n }\n\n static probe(data: Uint8Array) {\n // ensure we find a moof box in the first 16 kB\n data = data.length > 16384 ? data.subarray(0, 16384) : data;\n return findBox(data, ['moof']).length > 0;\n }\n\n public demux(data: Uint8Array, timeOffset: number): DemuxerResult {\n this.timeOffset = timeOffset;\n // Load all data into the avc track. The CMAF remuxer will look for the data in the samples object; the rest of the fields do not matter\n let videoSamples = data;\n const videoTrack = this.videoTrack as PassthroughTrack;\n const textTrack = this.txtTrack as DemuxedUserdataTrack;\n if (this.config.progressive) {\n // Split the bytestream into two ranges: one encompassing all data up until the start of the last moof, and everything else.\n // This is done to guarantee that we're sending valid data to MSE - when demuxing progressively, we have no guarantee\n // that the fetch loader gives us flush moof+mdat pairs. If we push jagged data to MSE, it will throw an exception.\n if (this.remainderData) {\n videoSamples = appendUint8Array(this.remainderData, data);\n }\n const segmentedData = segmentValidRange(videoSamples);\n this.remainderData = segmentedData.remainder;\n videoTrack.samples = segmentedData.valid || new Uint8Array();\n } else {\n videoTrack.samples = videoSamples;\n }\n\n const id3Track = this.extractID3Track(videoTrack, timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n\n return {\n videoTrack,\n audioTrack: this.audioTrack as DemuxedAudioTrack,\n id3Track,\n textTrack: this.txtTrack as DemuxedUserdataTrack,\n };\n }\n\n public flush() {\n const timeOffset = this.timeOffset;\n const videoTrack = this.videoTrack as PassthroughTrack;\n const textTrack = this.txtTrack as DemuxedUserdataTrack;\n videoTrack.samples = this.remainderData || new Uint8Array();\n this.remainderData = null;\n\n const id3Track = this.extractID3Track(videoTrack, this.timeOffset);\n textTrack.samples = parseSamples(timeOffset, videoTrack);\n\n return {\n videoTrack,\n audioTrack: dummyTrack() as DemuxedAudioTrack,\n id3Track,\n textTrack: dummyTrack() as DemuxedUserdataTrack,\n };\n }\n\n private extractID3Track(\n videoTrack: PassthroughTrack,\n timeOffset: number\n ): DemuxedMetadataTrack {\n const id3Track = this.id3Track as DemuxedMetadataTrack;\n if (videoTrack.samples.length) {\n const emsgs = findBox(videoTrack.samples, ['emsg']);\n if (emsgs) {\n emsgs.forEach((data: Uint8Array) => {\n const emsgInfo = parseEmsg(data);\n if (emsgSchemePattern.test(emsgInfo.schemeIdUri)) {\n const pts = Number.isFinite(emsgInfo.presentationTime)\n ? emsgInfo.presentationTime! / emsgInfo.timeScale\n : timeOffset +\n emsgInfo.presentationTimeDelta! / emsgInfo.timeScale;\n let duration =\n emsgInfo.eventDuration === 0xffffffff\n ? Number.POSITIVE_INFINITY\n : emsgInfo.eventDuration / emsgInfo.timeScale;\n // Safari takes anything <= 0.001 seconds and maps it to Infinity\n if (duration <= 0.001) {\n duration = Number.POSITIVE_INFINITY;\n }\n const payload = emsgInfo.payload;\n id3Track.samples.push({\n data: payload,\n len: payload.byteLength,\n dts: pts,\n pts: pts,\n type: MetadataSchema.emsg,\n duration: duration,\n });\n }\n });\n }\n }\n return id3Track;\n }\n\n demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number\n ): Promise<DemuxerResult> {\n return Promise.reject(\n new Error('The MP4 demuxer does not support SAMPLE-AES decryption')\n );\n }\n\n destroy() {}\n}\n\nexport default MP4Demuxer;\n","/**\n * MPEG parser helper\n */\nimport { DemuxedAudioTrack } from '../types/demuxer';\n\nlet chromeVersion: number | null = null;\n\nconst BitratesMap = [\n 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 32, 48, 56,\n 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 32, 40, 48, 56, 64, 80,\n 96, 112, 128, 160, 192, 224, 256, 320, 32, 48, 56, 64, 80, 96, 112, 128, 144,\n 160, 176, 192, 224, 256, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144,\n 160,\n];\n\nconst SamplingRateMap = [\n 44100, 48000, 32000, 22050, 24000, 16000, 11025, 12000, 8000,\n];\n\nconst SamplesCoefficients = [\n // MPEG 2.5\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n // Reserved\n [\n 0, // Reserved\n 0, // Layer3\n 0, // Layer2\n 0, // Layer1\n ],\n // MPEG 2\n [\n 0, // Reserved\n 72, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n // MPEG 1\n [\n 0, // Reserved\n 144, // Layer3\n 144, // Layer2\n 12, // Layer1\n ],\n];\n\nconst BytesInSlot = [\n 0, // Reserved\n 1, // Layer3\n 1, // Layer2\n 4, // Layer1\n];\n\nexport function appendFrame(\n track: DemuxedAudioTrack,\n data: Uint8Array,\n offset: number,\n pts: number,\n frameIndex: number\n) {\n // Using http://www.datavoyage.com/mpgscript/mpeghdr.htm as a reference\n if (offset + 24 > data.length) {\n return;\n }\n\n const header = parseHeader(data, offset);\n if (header && offset + header.frameLength <= data.length) {\n const frameDuration = (header.samplesPerFrame * 90000) / header.sampleRate;\n const stamp = pts + frameIndex * frameDuration;\n const sample = {\n unit: data.subarray(offset, offset + header.frameLength),\n pts: stamp,\n dts: stamp,\n };\n\n track.config = [];\n track.channelCount = header.channelCount;\n track.samplerate = header.sampleRate;\n track.samples.push(sample);\n\n return { sample, length: header.frameLength, missing: 0 };\n }\n}\n\nexport function parseHeader(data: Uint8Array, offset: number) {\n const mpegVersion = (data[offset + 1] >> 3) & 3;\n const mpegLayer = (data[offset + 1] >> 1) & 3;\n const bitRateIndex = (data[offset + 2] >> 4) & 15;\n const sampleRateIndex = (data[offset + 2] >> 2) & 3;\n if (\n mpegVersion !== 1 &&\n bitRateIndex !== 0 &&\n bitRateIndex !== 15 &&\n sampleRateIndex !== 3\n ) {\n const paddingBit = (data[offset + 2] >> 1) & 1;\n const channelMode = data[offset + 3] >> 6;\n const columnInBitrates =\n mpegVersion === 3 ? 3 - mpegLayer : mpegLayer === 3 ? 3 : 4;\n const bitRate =\n BitratesMap[columnInBitrates * 14 + bitRateIndex - 1] * 1000;\n const columnInSampleRates =\n mpegVersion === 3 ? 0 : mpegVersion === 2 ? 1 : 2;\n const sampleRate =\n SamplingRateMap[columnInSampleRates * 3 + sampleRateIndex];\n const channelCount = channelMode === 3 ? 1 : 2; // If bits of channel mode are `11` then it is a single channel (Mono)\n const sampleCoefficient = SamplesCoefficients[mpegVersion][mpegLayer];\n const bytesInSlot = BytesInSlot[mpegLayer];\n const samplesPerFrame = sampleCoefficient * 8 * bytesInSlot;\n const frameLength =\n Math.floor((sampleCoefficient * bitRate) / sampleRate + paddingBit) *\n bytesInSlot;\n\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n const needChromeFix = !!chromeVersion && chromeVersion <= 87;\n\n if (\n needChromeFix &&\n mpegLayer === 2 &&\n bitRate >= 224000 &&\n channelMode === 0\n ) {\n // Work around bug in Chromium by setting channelMode to dual-channel (01) instead of stereo (00)\n data[offset + 3] = data[offset + 3] | 0x80;\n }\n\n return { sampleRate, channelCount, frameLength, samplesPerFrame };\n }\n}\n\nexport function isHeaderPattern(data: Uint8Array, offset: number): boolean {\n return (\n data[offset] === 0xff &&\n (data[offset + 1] & 0xe0) === 0xe0 &&\n (data[offset + 1] & 0x06) !== 0x00\n );\n}\n\nexport function isHeader(data: Uint8Array, offset: number): boolean {\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n return offset + 1 < data.length && isHeaderPattern(data, offset);\n}\n\nexport function canParse(data: Uint8Array, offset: number): boolean {\n const headerSize = 4;\n\n return isHeaderPattern(data, offset) && headerSize <= data.length - offset;\n}\n\nexport function probe(data: Uint8Array, offset: number): boolean {\n // same as isHeader but we also check that MPEG frame follows last MPEG frame\n // or end of data is reached\n if (offset + 1 < data.length && isHeaderPattern(data, offset)) {\n // MPEG header Length\n const headerLength = 4;\n // MPEG frame Length\n const header = parseHeader(data, offset);\n let frameLength = headerLength;\n if (header?.frameLength) {\n frameLength = header.frameLength;\n }\n\n const newOffset = offset + frameLength;\n return newOffset === data.length || isHeader(data, newOffset);\n }\n return false;\n}\n","/**\n * Parser for exponential Golomb codes, a variable-bitwidth number encoding scheme used by h264.\n */\n\nimport { logger } from '../utils/logger';\n\nclass ExpGolomb {\n private data: Uint8Array;\n public bytesAvailable: number;\n private word: number;\n private bitsAvailable: number;\n\n constructor(data: Uint8Array) {\n this.data = data;\n // the number of bytes left to examine in this.data\n this.bytesAvailable = data.byteLength;\n // the current word being examined\n this.word = 0; // :uint\n // the number of bits left to examine in the current word\n this.bitsAvailable = 0; // :uint\n }\n\n // ():void\n loadWord(): void {\n const data = this.data;\n const bytesAvailable = this.bytesAvailable;\n const position = data.byteLength - bytesAvailable;\n const workingBytes = new Uint8Array(4);\n const availableBytes = Math.min(4, bytesAvailable);\n if (availableBytes === 0) {\n throw new Error('no bytes available');\n }\n\n workingBytes.set(data.subarray(position, position + availableBytes));\n this.word = new DataView(workingBytes.buffer).getUint32(0);\n // track the amount of this.data that has been processed\n this.bitsAvailable = availableBytes * 8;\n this.bytesAvailable -= availableBytes;\n }\n\n // (count:int):void\n skipBits(count: number): void {\n let skipBytes; // :int\n count = Math.min(count, this.bytesAvailable * 8 + this.bitsAvailable);\n if (this.bitsAvailable > count) {\n this.word <<= count;\n this.bitsAvailable -= count;\n } else {\n count -= this.bitsAvailable;\n skipBytes = count >> 3;\n count -= skipBytes << 3;\n this.bytesAvailable -= skipBytes;\n this.loadWord();\n this.word <<= count;\n this.bitsAvailable -= count;\n }\n }\n\n // (size:int):uint\n readBits(size: number): number {\n let bits = Math.min(this.bitsAvailable, size); // :uint\n const valu = this.word >>> (32 - bits); // :uint\n if (size > 32) {\n logger.error('Cannot read more than 32 bits at a time');\n }\n\n this.bitsAvailable -= bits;\n if (this.bitsAvailable > 0) {\n this.word <<= bits;\n } else if (this.bytesAvailable > 0) {\n this.loadWord();\n } else {\n throw new Error('no bits available');\n }\n\n bits = size - bits;\n if (bits > 0 && this.bitsAvailable) {\n return (valu << bits) | this.readBits(bits);\n } else {\n return valu;\n }\n }\n\n // ():uint\n skipLZ(): number {\n let leadingZeroCount; // :uint\n for (\n leadingZeroCount = 0;\n leadingZeroCount < this.bitsAvailable;\n ++leadingZeroCount\n ) {\n if ((this.word & (0x80000000 >>> leadingZeroCount)) !== 0) {\n // the first bit of working word is 1\n this.word <<= leadingZeroCount;\n this.bitsAvailable -= leadingZeroCount;\n return leadingZeroCount;\n }\n }\n // we exhausted word and still have not found a 1\n this.loadWord();\n return leadingZeroCount + this.skipLZ();\n }\n\n // ():void\n skipUEG(): void {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():void\n skipEG(): void {\n this.skipBits(1 + this.skipLZ());\n }\n\n // ():uint\n readUEG(): number {\n const clz = this.skipLZ(); // :uint\n return this.readBits(clz + 1) - 1;\n }\n\n // ():int\n readEG(): number {\n const valu = this.readUEG(); // :int\n if (0x01 & valu) {\n // the number is odd if the low order bit is set\n return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2\n } else {\n return -1 * (valu >>> 1); // divide by two then make it negative\n }\n }\n\n // Some convenience functions\n // :Boolean\n readBoolean(): boolean {\n return this.readBits(1) === 1;\n }\n\n // ():int\n readUByte(): number {\n return this.readBits(8);\n }\n\n // ():int\n readUShort(): number {\n return this.readBits(16);\n }\n\n // ():int\n readUInt(): number {\n return this.readBits(32);\n }\n\n /**\n * Advance the ExpGolomb decoder past a scaling list. The scaling\n * list is optionally transmitted as part of a sequence parameter\n * set and is not relevant to transmuxing.\n * @param count the number of entries in this scaling list\n * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1\n */\n skipScalingList(count: number): void {\n let lastScale = 8;\n let nextScale = 8;\n let deltaScale;\n for (let j = 0; j < count; j++) {\n if (nextScale !== 0) {\n deltaScale = this.readEG();\n nextScale = (lastScale + deltaScale + 256) % 256;\n }\n lastScale = nextScale === 0 ? lastScale : nextScale;\n }\n }\n\n /**\n * Read a sequence parameter set and return some interesting video\n * properties. A sequence parameter set is the H264 metadata that\n * describes the properties of upcoming video frames.\n * @returns an object with configuration parsed from the\n * sequence parameter set, including the dimensions of the\n * associated video frames.\n */\n readSPS(): {\n width: number;\n height: number;\n pixelRatio: [number, number];\n } {\n let frameCropLeftOffset = 0;\n let frameCropRightOffset = 0;\n let frameCropTopOffset = 0;\n let frameCropBottomOffset = 0;\n let numRefFramesInPicOrderCntCycle;\n let scalingListCount;\n let i;\n const readUByte = this.readUByte.bind(this);\n const readBits = this.readBits.bind(this);\n const readUEG = this.readUEG.bind(this);\n const readBoolean = this.readBoolean.bind(this);\n const skipBits = this.skipBits.bind(this);\n const skipEG = this.skipEG.bind(this);\n const skipUEG = this.skipUEG.bind(this);\n const skipScalingList = this.skipScalingList.bind(this);\n\n readUByte();\n const profileIdc = readUByte(); // profile_idc\n readBits(5); // profileCompat constraint_set[0-4]_flag, u(5)\n skipBits(3); // reserved_zero_3bits u(3),\n readUByte(); // level_idc u(8)\n skipUEG(); // seq_parameter_set_id\n // some profiles have more optional data we don't need\n if (\n profileIdc === 100 ||\n profileIdc === 110 ||\n profileIdc === 122 ||\n profileIdc === 244 ||\n profileIdc === 44 ||\n profileIdc === 83 ||\n profileIdc === 86 ||\n profileIdc === 118 ||\n profileIdc === 128\n ) {\n const chromaFormatIdc = readUEG();\n if (chromaFormatIdc === 3) {\n skipBits(1);\n } // separate_colour_plane_flag\n\n skipUEG(); // bit_depth_luma_minus8\n skipUEG(); // bit_depth_chroma_minus8\n skipBits(1); // qpprime_y_zero_transform_bypass_flag\n if (readBoolean()) {\n // seq_scaling_matrix_present_flag\n scalingListCount = chromaFormatIdc !== 3 ? 8 : 12;\n for (i = 0; i < scalingListCount; i++) {\n if (readBoolean()) {\n // seq_scaling_list_present_flag[ i ]\n if (i < 6) {\n skipScalingList(16);\n } else {\n skipScalingList(64);\n }\n }\n }\n }\n }\n skipUEG(); // log2_max_frame_num_minus4\n const picOrderCntType = readUEG();\n if (picOrderCntType === 0) {\n readUEG(); // log2_max_pic_order_cnt_lsb_minus4\n } else if (picOrderCntType === 1) {\n skipBits(1); // delta_pic_order_always_zero_flag\n skipEG(); // offset_for_non_ref_pic\n skipEG(); // offset_for_top_to_bottom_field\n numRefFramesInPicOrderCntCycle = readUEG();\n for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {\n skipEG();\n } // offset_for_ref_frame[ i ]\n }\n skipUEG(); // max_num_ref_frames\n skipBits(1); // gaps_in_frame_num_value_allowed_flag\n const picWidthInMbsMinus1 = readUEG();\n const picHeightInMapUnitsMinus1 = readUEG();\n const frameMbsOnlyFlag = readBits(1);\n if (frameMbsOnlyFlag === 0) {\n skipBits(1);\n } // mb_adaptive_frame_field_flag\n\n skipBits(1); // direct_8x8_inference_flag\n if (readBoolean()) {\n // frame_cropping_flag\n frameCropLeftOffset = readUEG();\n frameCropRightOffset = readUEG();\n frameCropTopOffset = readUEG();\n frameCropBottomOffset = readUEG();\n }\n let pixelRatio: [number, number] = [1, 1];\n if (readBoolean()) {\n // vui_parameters_present_flag\n if (readBoolean()) {\n // aspect_ratio_info_present_flag\n const aspectRatioIdc = readUByte();\n switch (aspectRatioIdc) {\n case 1:\n pixelRatio = [1, 1];\n break;\n case 2:\n pixelRatio = [12, 11];\n break;\n case 3:\n pixelRatio = [10, 11];\n break;\n case 4:\n pixelRatio = [16, 11];\n break;\n case 5:\n pixelRatio = [40, 33];\n break;\n case 6:\n pixelRatio = [24, 11];\n break;\n case 7:\n pixelRatio = [20, 11];\n break;\n case 8:\n pixelRatio = [32, 11];\n break;\n case 9:\n pixelRatio = [80, 33];\n break;\n case 10:\n pixelRatio = [18, 11];\n break;\n case 11:\n pixelRatio = [15, 11];\n break;\n case 12:\n pixelRatio = [64, 33];\n break;\n case 13:\n pixelRatio = [160, 99];\n break;\n case 14:\n pixelRatio = [4, 3];\n break;\n case 15:\n pixelRatio = [3, 2];\n break;\n case 16:\n pixelRatio = [2, 1];\n break;\n case 255: {\n pixelRatio = [\n (readUByte() << 8) | readUByte(),\n (readUByte() << 8) | readUByte(),\n ];\n break;\n }\n }\n }\n }\n return {\n width: Math.ceil(\n (picWidthInMbsMinus1 + 1) * 16 -\n frameCropLeftOffset * 2 -\n frameCropRightOffset * 2\n ),\n height:\n (2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16 -\n (frameMbsOnlyFlag ? 2 : 4) *\n (frameCropTopOffset + frameCropBottomOffset),\n pixelRatio: pixelRatio,\n };\n }\n\n readSliceType() {\n // skip NALu type\n this.readUByte();\n // discard first_mb_in_slice\n this.readUEG();\n // return slice_type\n return this.readUEG();\n }\n}\n\nexport default ExpGolomb;\n","/**\n * SAMPLE-AES decrypter\n */\n\nimport { HlsConfig } from '../config';\nimport Decrypter from '../crypt/decrypter';\nimport { HlsEventEmitter } from '../events';\nimport type {\n AudioSample,\n AvcSample,\n AvcSampleUnit,\n DemuxedVideoTrack,\n KeyData,\n} from '../types/demuxer';\nimport { discardEPB } from '../utils/mp4-tools';\n\nclass SampleAesDecrypter {\n private keyData: KeyData;\n private decrypter: Decrypter;\n\n constructor(observer: HlsEventEmitter, config: HlsConfig, keyData: KeyData) {\n this.keyData = keyData;\n this.decrypter = new Decrypter(config, {\n removePKCS7Padding: false,\n });\n }\n\n decryptBuffer(encryptedData: Uint8Array | ArrayBuffer): Promise<ArrayBuffer> {\n return this.decrypter.decrypt(\n encryptedData,\n this.keyData.key.buffer,\n this.keyData.iv.buffer\n );\n }\n\n // AAC - encrypt all full 16 bytes blocks starting from offset 16\n private decryptAacSample(\n samples: AudioSample[],\n sampleIndex: number,\n callback: () => void\n ) {\n const curUnit = samples[sampleIndex].unit;\n if (curUnit.length <= 16) {\n // No encrypted portion in this sample (first 16 bytes is not\n // encrypted, see https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/HLS_Sample_Encryption/Encryption/Encryption.html),\n return;\n }\n const encryptedData = curUnit.subarray(\n 16,\n curUnit.length - (curUnit.length % 16)\n );\n const encryptedBuffer = encryptedData.buffer.slice(\n encryptedData.byteOffset,\n encryptedData.byteOffset + encryptedData.length\n );\n\n this.decryptBuffer(encryptedBuffer).then((decryptedBuffer: ArrayBuffer) => {\n const decryptedData = new Uint8Array(decryptedBuffer);\n curUnit.set(decryptedData, 16);\n\n if (!this.decrypter.isSync()) {\n this.decryptAacSamples(samples, sampleIndex + 1, callback);\n }\n });\n }\n\n decryptAacSamples(\n samples: AudioSample[],\n sampleIndex: number,\n callback: () => void\n ) {\n for (; ; sampleIndex++) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n if (samples[sampleIndex].unit.length < 32) {\n continue;\n }\n\n this.decryptAacSample(samples, sampleIndex, callback);\n\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n\n // AVC - encrypt one 16 bytes block out of ten, starting from offset 32\n getAvcEncryptedData(decodedData: Uint8Array) {\n const encryptedDataLen =\n Math.floor((decodedData.length - 48) / 160) * 16 + 16;\n const encryptedData = new Int8Array(encryptedDataLen);\n let outputPos = 0;\n for (\n let inputPos = 32;\n inputPos < decodedData.length - 16;\n inputPos += 160, outputPos += 16\n ) {\n encryptedData.set(\n decodedData.subarray(inputPos, inputPos + 16),\n outputPos\n );\n }\n\n return encryptedData;\n }\n\n getAvcDecryptedUnit(\n decodedData: Uint8Array,\n decryptedData: ArrayLike<number> | ArrayBuffer | SharedArrayBuffer\n ) {\n const uint8DecryptedData = new Uint8Array(decryptedData);\n let inputPos = 0;\n for (\n let outputPos = 32;\n outputPos < decodedData.length - 16;\n outputPos += 160, inputPos += 16\n ) {\n decodedData.set(\n uint8DecryptedData.subarray(inputPos, inputPos + 16),\n outputPos\n );\n }\n\n return decodedData;\n }\n\n decryptAvcSample(\n samples: AvcSample[],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void,\n curUnit: AvcSampleUnit\n ) {\n const decodedData = discardEPB(curUnit.data);\n const encryptedData = this.getAvcEncryptedData(decodedData);\n\n this.decryptBuffer(encryptedData.buffer).then(\n (decryptedBuffer: ArrayBuffer) => {\n curUnit.data = this.getAvcDecryptedUnit(decodedData, decryptedBuffer);\n\n if (!this.decrypter.isSync()) {\n this.decryptAvcSamples(samples, sampleIndex, unitIndex + 1, callback);\n }\n }\n );\n }\n\n decryptAvcSamples(\n samples: DemuxedVideoTrack['samples'],\n sampleIndex: number,\n unitIndex: number,\n callback: () => void\n ) {\n if (samples instanceof Uint8Array) {\n throw new Error('Cannot decrypt samples of type Uint8Array');\n }\n\n for (; ; sampleIndex++, unitIndex = 0) {\n if (sampleIndex >= samples.length) {\n callback();\n return;\n }\n\n const curUnits = samples[sampleIndex].units;\n for (; ; unitIndex++) {\n if (unitIndex >= curUnits.length) {\n break;\n }\n\n const curUnit = curUnits[unitIndex];\n if (\n curUnit.data.length <= 48 ||\n (curUnit.type !== 1 && curUnit.type !== 5)\n ) {\n continue;\n }\n\n this.decryptAvcSample(\n samples,\n sampleIndex,\n unitIndex,\n callback,\n curUnit\n );\n\n if (!this.decrypter.isSync()) {\n return;\n }\n }\n }\n }\n}\n\nexport default SampleAesDecrypter;\n","/**\n * highly optimized TS demuxer:\n * parse PAT, PMT\n * extract PES packet from audio and video PIDs\n * extract AVC/H264 NAL units and AAC/ADTS samples from PES packet\n * trigger the remuxer upon parsing completion\n * 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.\n * it also controls the remuxing process :\n * upon discontinuity or level switch detection, it will also notifies the remuxer so that it can reset its state.\n */\n\nimport * as ADTS from './adts';\nimport * as MpegAudio from './mpegaudio';\nimport ExpGolomb from './exp-golomb';\nimport SampleAesDecrypter from './sample-aes';\nimport { Events } from '../events';\nimport {\n appendUint8Array,\n parseSEIMessageFromNALu,\n RemuxerTrackIdConfig,\n} from '../utils/mp4-tools';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport type { HlsConfig } from '../config';\nimport type { HlsEventEmitter } from '../events';\nimport {\n DemuxedAvcTrack,\n DemuxedAudioTrack,\n DemuxedTrack,\n Demuxer,\n DemuxerResult,\n AvcSample,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n ElementaryStreamData,\n KeyData,\n MetadataSchema,\n} from '../types/demuxer';\nimport { AudioFrame } from '../types/demuxer';\n\ntype ParsedTimestamp = {\n pts?: number;\n dts?: number;\n};\n\ntype PES = ParsedTimestamp & {\n data: Uint8Array;\n len: number;\n};\n\ntype ParsedAvcSample = ParsedTimestamp & Omit<AvcSample, 'pts' | 'dts'>;\n\nexport interface TypeSupported {\n mpeg: boolean;\n mp3: boolean;\n mp4: boolean;\n}\n\nconst PACKET_LENGTH = 188;\n\nclass TSDemuxer implements Demuxer {\n private readonly observer: HlsEventEmitter;\n private readonly config: HlsConfig;\n private typeSupported: TypeSupported;\n\n private sampleAes: SampleAesDecrypter | null = null;\n private pmtParsed: boolean = false;\n private audioCodec?: string;\n private videoCodec?: string;\n private _duration: number = 0;\n private _pmtId: number = -1;\n\n private _avcTrack?: DemuxedAvcTrack;\n private _audioTrack?: DemuxedAudioTrack;\n private _id3Track?: DemuxedMetadataTrack;\n private _txtTrack?: DemuxedUserdataTrack;\n private aacOverFlow: AudioFrame | null = null;\n private avcSample: ParsedAvcSample | null = null;\n private remainderData: Uint8Array | null = null;\n\n constructor(\n observer: HlsEventEmitter,\n config: HlsConfig,\n typeSupported: TypeSupported\n ) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n }\n\n static probe(data: Uint8Array) {\n const syncOffset = TSDemuxer.syncOffset(data);\n if (syncOffset > 0) {\n logger.warn(\n `MPEG2-TS detected but first sync word found @ offset ${syncOffset}`\n );\n }\n return syncOffset !== -1;\n }\n\n static syncOffset(data: Uint8Array): number {\n const length = data.length;\n let scanwindow =\n Math.min(PACKET_LENGTH * 5, data.length - PACKET_LENGTH) + 1;\n let i = 0;\n while (i < scanwindow) {\n // a TS init segment should contain at least 2 TS packets: PAT and PMT, each starting with 0x47\n let foundPat = false;\n let packetStart = -1;\n let tsPackets = 0;\n for (let j = i; j < length; j += PACKET_LENGTH) {\n if (data[j] === 0x47) {\n tsPackets++;\n if (packetStart === -1) {\n packetStart = j;\n // First sync word found at offset, increase scan length (#5251)\n if (packetStart !== 0) {\n scanwindow =\n Math.min(\n packetStart + PACKET_LENGTH * 99,\n data.length - PACKET_LENGTH\n ) + 1;\n }\n }\n if (!foundPat) {\n foundPat = parsePID(data, j) === 0;\n }\n // Sync word found at 0 with 3 packets, or found at offset least 2 packets up to scanwindow (#5501)\n if (\n foundPat &&\n tsPackets > 1 &&\n ((packetStart === 0 && tsPackets > 2) ||\n j + PACKET_LENGTH > scanwindow)\n ) {\n return packetStart;\n }\n } else if (tsPackets) {\n // Exit if sync word found, but does not contain contiguous packets (#5501)\n return -1;\n } else {\n break;\n }\n }\n i++;\n }\n return -1;\n }\n\n /**\n * Creates a track model internal to demuxer used to drive remuxing input\n */\n static createTrack(\n type: 'audio' | 'video' | 'id3' | 'text',\n duration?: number\n ): DemuxedTrack {\n return {\n container:\n type === 'video' || type === 'audio' ? 'video/mp2t' : undefined,\n type,\n id: RemuxerTrackIdConfig[type],\n pid: -1,\n inputTimeScale: 90000,\n sequenceNumber: 0,\n samples: [],\n dropped: 0,\n duration: type === 'audio' ? duration : undefined,\n };\n }\n\n /**\n * Initializes a new init segment on the demuxer/remuxer interface. Needed for discontinuities/track-switches (or at stream start)\n * Resets all internal track instances of the demuxer.\n */\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string,\n videoCodec: string,\n trackDuration: number\n ) {\n this.pmtParsed = false;\n this._pmtId = -1;\n\n this._avcTrack = TSDemuxer.createTrack('video') as DemuxedAvcTrack;\n this._audioTrack = TSDemuxer.createTrack(\n 'audio',\n trackDuration\n ) as DemuxedAudioTrack;\n this._id3Track = TSDemuxer.createTrack('id3') as DemuxedMetadataTrack;\n this._txtTrack = TSDemuxer.createTrack('text') as DemuxedUserdataTrack;\n this._audioTrack.segmentCodec = 'aac';\n\n // flush any partial content\n this.aacOverFlow = null;\n this.avcSample = null;\n this.remainderData = null;\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this._duration = trackDuration;\n }\n\n public resetTimeStamp() {}\n\n public resetContiguity(): void {\n const { _audioTrack, _avcTrack, _id3Track } = this;\n if (_audioTrack) {\n _audioTrack.pesData = null;\n }\n if (_avcTrack) {\n _avcTrack.pesData = null;\n }\n if (_id3Track) {\n _id3Track.pesData = null;\n }\n this.aacOverFlow = null;\n this.avcSample = null;\n this.remainderData = null;\n }\n\n public demux(\n data: Uint8Array,\n timeOffset: number,\n isSampleAes = false,\n flush = false\n ): DemuxerResult {\n if (!isSampleAes) {\n this.sampleAes = null;\n }\n\n let pes: PES | null;\n\n const videoTrack = this._avcTrack as DemuxedAvcTrack;\n const audioTrack = this._audioTrack as DemuxedAudioTrack;\n const id3Track = this._id3Track as DemuxedMetadataTrack;\n const textTrack = this._txtTrack as DemuxedUserdataTrack;\n\n let avcId = videoTrack.pid;\n let avcData = videoTrack.pesData;\n let audioId = audioTrack.pid;\n let id3Id = id3Track.pid;\n let audioData = audioTrack.pesData;\n let id3Data = id3Track.pesData;\n let unknownPID: number | null = null;\n let pmtParsed = this.pmtParsed;\n let pmtId = this._pmtId;\n\n let len = data.length;\n if (this.remainderData) {\n data = appendUint8Array(this.remainderData, data);\n len = data.length;\n this.remainderData = null;\n }\n\n if (len < PACKET_LENGTH && !flush) {\n this.remainderData = data;\n return {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n };\n }\n\n const syncOffset = Math.max(0, TSDemuxer.syncOffset(data));\n len -= (len - syncOffset) % PACKET_LENGTH;\n if (len < data.byteLength && !flush) {\n this.remainderData = new Uint8Array(\n data.buffer,\n len,\n data.buffer.byteLength - len\n );\n }\n\n // loop through TS packets\n let tsPacketErrors = 0;\n for (let start = syncOffset; start < len; start += PACKET_LENGTH) {\n if (data[start] === 0x47) {\n const stt = !!(data[start + 1] & 0x40);\n const pid = parsePID(data, start);\n const atf = (data[start + 3] & 0x30) >> 4;\n\n // if an adaption field is present, its length is specified by the fifth byte of the TS packet header.\n let offset: number;\n if (atf > 1) {\n offset = start + 5 + data[start + 4];\n // continue if there is only adaptation field\n if (offset === start + PACKET_LENGTH) {\n continue;\n }\n } else {\n offset = start + 4;\n }\n switch (pid) {\n case avcId:\n if (stt) {\n if (avcData && (pes = parsePES(avcData))) {\n this.parseAVCPES(videoTrack, textTrack, pes, false);\n }\n\n avcData = { data: [], size: 0 };\n }\n if (avcData) {\n avcData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n avcData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case audioId:\n if (stt) {\n if (audioData && (pes = parsePES(audioData))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n }\n }\n audioData = { data: [], size: 0 };\n }\n if (audioData) {\n audioData.data.push(data.subarray(offset, start + PACKET_LENGTH));\n audioData.size += start + PACKET_LENGTH - offset;\n }\n break;\n case id3Id:\n if (stt) {\n if (id3Data && (pes = parsePES(id3Data))) {\n this.parseID3PES(id3Track, pes);\n }\n\n id3Data = { data: [], size: 0 };\n }\n if (id3Data) {\n id3Data.data.push(data.subarray(offset, start + PACKET_LENGTH));\n id3Data.size += start + PACKET_LENGTH - offset;\n }\n break;\n case 0:\n if (stt) {\n offset += data[offset] + 1;\n }\n\n pmtId = this._pmtId = parsePAT(data, offset);\n // logger.log('PMT PID:' + this._pmtId);\n break;\n case pmtId: {\n if (stt) {\n offset += data[offset] + 1;\n }\n\n const parsedPIDs = parsePMT(\n data,\n offset,\n this.typeSupported,\n isSampleAes\n );\n\n // only update track id if track PID found while parsing PMT\n // this is to avoid resetting the PID to -1 in case\n // track PID transiently disappears from the stream\n // this could happen in case of transient missing audio samples for example\n // NOTE this is only the PID of the track as found in TS,\n // but we are not using this for MP4 track IDs.\n avcId = parsedPIDs.avc;\n if (avcId > 0) {\n videoTrack.pid = avcId;\n }\n\n audioId = parsedPIDs.audio;\n if (audioId > 0) {\n audioTrack.pid = audioId;\n audioTrack.segmentCodec = parsedPIDs.segmentCodec;\n }\n id3Id = parsedPIDs.id3;\n if (id3Id > 0) {\n id3Track.pid = id3Id;\n }\n\n if (unknownPID !== null && !pmtParsed) {\n logger.warn(\n `MPEG-TS PMT found at ${start} after unknown PID '${unknownPID}'. Backtracking to sync byte @${syncOffset} to parse all TS packets.`\n );\n unknownPID = null;\n // we set it to -188, the += 188 in the for loop will reset start to 0\n start = syncOffset - 188;\n }\n pmtParsed = this.pmtParsed = true;\n break;\n }\n case 0x11:\n case 0x1fff:\n break;\n default:\n unknownPID = pid;\n break;\n }\n } else {\n tsPacketErrors++;\n }\n }\n\n if (tsPacketErrors > 0) {\n const error = new Error(\n `Found ${tsPacketErrors} TS packet/s that do not start with 0x47`\n );\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n reason: error.message,\n });\n }\n\n videoTrack.pesData = avcData;\n audioTrack.pesData = audioData;\n id3Track.pesData = id3Data;\n\n const demuxResult: DemuxerResult = {\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n };\n\n if (flush) {\n this.extractRemainingSamples(demuxResult);\n }\n\n return demuxResult;\n }\n\n public flush(): DemuxerResult | Promise<DemuxerResult> {\n const { remainderData } = this;\n this.remainderData = null;\n let result: DemuxerResult;\n if (remainderData) {\n result = this.demux(remainderData, -1, false, true);\n } else {\n result = {\n videoTrack: this._avcTrack as DemuxedAvcTrack,\n audioTrack: this._audioTrack as DemuxedAudioTrack,\n id3Track: this._id3Track as DemuxedMetadataTrack,\n textTrack: this._txtTrack as DemuxedUserdataTrack,\n };\n }\n this.extractRemainingSamples(result);\n if (this.sampleAes) {\n return this.decrypt(result, this.sampleAes);\n }\n return result;\n }\n\n private extractRemainingSamples(demuxResult: DemuxerResult) {\n const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult;\n const avcData = videoTrack.pesData;\n const audioData = audioTrack.pesData;\n const id3Data = id3Track.pesData;\n // try to parse last PES packets\n let pes: PES | null;\n if (avcData && (pes = parsePES(avcData))) {\n this.parseAVCPES(\n videoTrack as DemuxedAvcTrack,\n textTrack as DemuxedUserdataTrack,\n pes,\n true\n );\n videoTrack.pesData = null;\n } else {\n // either avcData null or PES truncated, keep it for next frag parsing\n videoTrack.pesData = avcData;\n }\n\n if (audioData && (pes = parsePES(audioData))) {\n switch (audioTrack.segmentCodec) {\n case 'aac':\n this.parseAACPES(audioTrack, pes);\n break;\n case 'mp3':\n this.parseMPEGPES(audioTrack, pes);\n break;\n }\n audioTrack.pesData = null;\n } else {\n if (audioData?.size) {\n logger.log(\n 'last AAC PES packet truncated,might overlap between fragments'\n );\n }\n\n // either audioData null or PES truncated, keep it for next frag parsing\n audioTrack.pesData = audioData;\n }\n\n if (id3Data && (pes = parsePES(id3Data))) {\n this.parseID3PES(id3Track, pes);\n id3Track.pesData = null;\n } else {\n // either id3Data null or PES truncated, keep it for next frag parsing\n id3Track.pesData = id3Data;\n }\n }\n\n public demuxSampleAes(\n data: Uint8Array,\n keyData: KeyData,\n timeOffset: number\n ): Promise<DemuxerResult> {\n const demuxResult = this.demux(\n data,\n timeOffset,\n true,\n !this.config.progressive\n );\n const sampleAes = (this.sampleAes = new SampleAesDecrypter(\n this.observer,\n this.config,\n keyData\n ));\n return this.decrypt(demuxResult, sampleAes);\n }\n\n private decrypt(\n demuxResult: DemuxerResult,\n sampleAes: SampleAesDecrypter\n ): Promise<DemuxerResult> {\n return new Promise((resolve) => {\n const { audioTrack, videoTrack } = demuxResult;\n if (audioTrack.samples && audioTrack.segmentCodec === 'aac') {\n sampleAes.decryptAacSamples(audioTrack.samples, 0, () => {\n if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n } else {\n resolve(demuxResult);\n }\n });\n } else if (videoTrack.samples) {\n sampleAes.decryptAvcSamples(videoTrack.samples, 0, 0, () => {\n resolve(demuxResult);\n });\n }\n });\n }\n\n public destroy() {\n this._duration = 0;\n }\n\n private parseAVCPES(\n track: DemuxedAvcTrack,\n textTrack: DemuxedUserdataTrack,\n pes: PES,\n last: boolean\n ) {\n const units = this.parseAVCNALu(track, pes.data);\n const debug = false;\n let avcSample = this.avcSample;\n let push: boolean;\n let spsfound = false;\n // free pes.data to save up some memory\n (pes as any).data = null;\n\n // if new NAL units found and last sample still there, let's push ...\n // this helps parsing streams with missing AUD (only do this if AUD never found)\n if (avcSample && units.length && !track.audFound) {\n pushAccessUnit(avcSample, track);\n avcSample = this.avcSample = createAVCSample(false, pes.pts, pes.dts, '');\n }\n\n units.forEach((unit) => {\n switch (unit.type) {\n // NDR\n case 1: {\n let iskey = false;\n push = true;\n const data = unit.data;\n // only check slice type to detect KF in case SPS found in same packet (any keyframe is preceded by SPS ...)\n if (spsfound && data.length > 4) {\n // retrieve slice type by parsing beginning of NAL unit (follow H264 spec, slice_header definition) to detect keyframe embedded in NDR\n const sliceType = new ExpGolomb(data).readSliceType();\n // 2 : I slice, 4 : SI slice, 7 : I slice, 9: SI slice\n // SI slice : A slice that is coded using intra prediction only and using quantisation of the prediction samples.\n // An SI slice can be coded such that its decoded samples can be constructed identically to an SP slice.\n // I slice: A slice that is not an SI slice that is decoded using intra prediction only.\n // if (sliceType === 2 || sliceType === 7) {\n if (\n sliceType === 2 ||\n sliceType === 4 ||\n sliceType === 7 ||\n sliceType === 9\n ) {\n iskey = true;\n }\n }\n if (iskey) {\n // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push\n if (avcSample?.frame && !avcSample.key) {\n pushAccessUnit(avcSample, track);\n avcSample = this.avcSample = null;\n }\n }\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(\n true,\n pes.pts,\n pes.dts,\n ''\n );\n }\n\n if (debug) {\n avcSample.debug += 'NDR ';\n }\n\n avcSample.frame = true;\n avcSample.key = iskey;\n break;\n // IDR\n }\n case 5:\n push = true;\n // handle PES not starting with AUD\n // if we have non-keyframe data already, that cannot belong to the same frame as a keyframe, so force a push\n if (avcSample?.frame && !avcSample.key) {\n pushAccessUnit(avcSample, track);\n avcSample = this.avcSample = null;\n }\n if (!avcSample) {\n avcSample = this.avcSample = createAVCSample(\n true,\n pes.pts,\n pes.dts,\n ''\n );\n }\n\n if (debug) {\n avcSample.debug += 'IDR ';\n }\n\n avcSample.key = true;\n avcSample.frame = true;\n break;\n // SEI\n case 6: {\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'SEI ';\n }\n parseSEIMessageFromNALu(\n unit.data,\n 1,\n pes.pts as number,\n textTrack.samples\n );\n break;\n // SPS\n }\n case 7:\n push = true;\n spsfound = true;\n if (debug && avcSample) {\n avcSample.debug += 'SPS ';\n }\n\n if (!track.sps) {\n const sps = unit.data;\n const expGolombDecoder = new ExpGolomb(sps);\n const config = expGolombDecoder.readSPS();\n track.width = config.width;\n track.height = config.height;\n track.pixelRatio = config.pixelRatio;\n track.sps = [sps];\n track.duration = this._duration;\n const codecarray = sps.subarray(1, 4);\n let codecstring = 'avc1.';\n for (let i = 0; i < 3; i++) {\n let h = codecarray[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n\n codecstring += h;\n }\n track.codec = codecstring;\n }\n break;\n // PPS\n case 8:\n push = true;\n if (debug && avcSample) {\n avcSample.debug += 'PPS ';\n }\n\n if (!track.pps) {\n track.pps = [unit.data];\n }\n\n break;\n // AUD\n case 9:\n push = false;\n track.audFound = true;\n if (avcSample) {\n pushAccessUnit(avcSample, track);\n }\n\n avcSample = this.avcSample = createAVCSample(\n false,\n pes.pts,\n pes.dts,\n debug ? 'AUD ' : ''\n );\n break;\n // Filler Data\n case 12:\n push = true;\n break;\n default:\n push = false;\n if (avcSample) {\n avcSample.debug += 'unknown NAL ' + unit.type + ' ';\n }\n\n break;\n }\n if (avcSample && push) {\n const units = avcSample.units;\n units.push(unit);\n }\n });\n // if last PES packet, push samples\n if (last && avcSample) {\n pushAccessUnit(avcSample, track);\n this.avcSample = null;\n }\n }\n\n private getLastNalUnit(samples: AvcSample[]) {\n let avcSample = this.avcSample;\n let lastUnit;\n // try to fallback to previous sample if current one is empty\n if (!avcSample || avcSample.units.length === 0) {\n avcSample = samples[samples.length - 1];\n }\n if (avcSample?.units) {\n const units = avcSample.units;\n lastUnit = units[units.length - 1];\n }\n return lastUnit;\n }\n\n private parseAVCNALu(\n track: DemuxedAvcTrack,\n array: Uint8Array\n ): Array<{\n data: Uint8Array;\n type: number;\n state?: number;\n }> {\n const len = array.byteLength;\n let state = track.naluState || 0;\n const lastState = state;\n const units = [] as Array<{\n data: Uint8Array;\n type: number;\n state?: number;\n }>;\n let i = 0;\n let value;\n let overflow;\n let unitType;\n let lastUnitStart = -1;\n let lastUnitType: number = 0;\n // logger.log('PES:' + Hex.hexDump(array));\n\n if (state === -1) {\n // special use case where we found 3 or 4-byte start codes exactly at the end of previous PES packet\n lastUnitStart = 0;\n // NALu type is value read from offset 0\n lastUnitType = array[0] & 0x1f;\n state = 0;\n i = 1;\n }\n\n while (i < len) {\n value = array[i++];\n // optimization. state 0 and 1 are the predominant case. let's handle them outside of the switch/case\n if (!state) {\n state = value ? 0 : 1;\n continue;\n }\n if (state === 1) {\n state = value ? 0 : 2;\n continue;\n }\n // here we have state either equal to 2 or 3\n if (!value) {\n state = 3;\n } else if (value === 1) {\n if (lastUnitStart >= 0) {\n const unit = {\n data: array.subarray(lastUnitStart, i - state - 1),\n type: lastUnitType,\n };\n // logger.log('pushing NALU, type/size:' + unit.type + '/' + unit.data.byteLength);\n units.push(unit);\n } else {\n // lastUnitStart is undefined => this is the first start code found in this PES packet\n // first check if start code delimiter is overlapping between 2 PES packets,\n // ie it started in last packet (lastState not zero)\n // and ended at the beginning of this PES packet (i <= 4 - lastState)\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n if (lastState && i <= 4 - lastState) {\n // start delimiter overlapping between PES packets\n // strip start delimiter bytes from the end of last NAL unit\n // check if lastUnit had a state different from zero\n if (lastUnit.state) {\n // strip last bytes\n lastUnit.data = lastUnit.data.subarray(\n 0,\n lastUnit.data.byteLength - lastState\n );\n }\n }\n // If NAL units are not starting right at the beginning of the PES packet, push preceding data into previous NAL unit.\n overflow = i - state - 1;\n if (overflow > 0) {\n // logger.log('first NALU found with overflow:' + overflow);\n const tmp = new Uint8Array(lastUnit.data.byteLength + overflow);\n tmp.set(lastUnit.data, 0);\n tmp.set(array.subarray(0, overflow), lastUnit.data.byteLength);\n lastUnit.data = tmp;\n lastUnit.state = 0;\n }\n }\n }\n // check if we can read unit type\n if (i < len) {\n unitType = array[i] & 0x1f;\n // logger.log('find NALU @ offset:' + i + ',type:' + unitType);\n lastUnitStart = i;\n lastUnitType = unitType;\n state = 0;\n } else {\n // not enough byte to read unit type. let's read it on next PES parsing\n state = -1;\n }\n } else {\n state = 0;\n }\n }\n if (lastUnitStart >= 0 && state >= 0) {\n const unit = {\n data: array.subarray(lastUnitStart, len),\n type: lastUnitType,\n state: state,\n };\n units.push(unit);\n // logger.log('pushing NALU, type/size/state:' + unit.type + '/' + unit.data.byteLength + '/' + state);\n }\n // no NALu found\n if (units.length === 0) {\n // append pes.data to previous NAL unit\n const lastUnit = this.getLastNalUnit(track.samples);\n if (lastUnit) {\n const tmp = new Uint8Array(lastUnit.data.byteLength + array.byteLength);\n tmp.set(lastUnit.data, 0);\n tmp.set(array, lastUnit.data.byteLength);\n lastUnit.data = tmp;\n }\n }\n track.naluState = state;\n return units;\n }\n\n private parseAACPES(track: DemuxedAudioTrack, pes: PES) {\n let startOffset = 0;\n const aacOverFlow = this.aacOverFlow;\n let data = pes.data;\n if (aacOverFlow) {\n this.aacOverFlow = null;\n const frameMissingBytes = aacOverFlow.missing;\n const sampleLength = aacOverFlow.sample.unit.byteLength;\n // logger.log(`AAC: append overflowing ${sampleLength} bytes to beginning of new PES`);\n if (frameMissingBytes === -1) {\n const tmp = new Uint8Array(sampleLength + data.byteLength);\n tmp.set(aacOverFlow.sample.unit, 0);\n tmp.set(data, sampleLength);\n data = tmp;\n } else {\n const frameOverflowBytes = sampleLength - frameMissingBytes;\n aacOverFlow.sample.unit.set(\n data.subarray(0, frameMissingBytes),\n frameOverflowBytes\n );\n track.samples.push(aacOverFlow.sample);\n startOffset = aacOverFlow.missing;\n }\n }\n // look for ADTS header (0xFFFx)\n let offset: number;\n let len: number;\n for (offset = startOffset, len = data.length; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n // if ADTS header does not start straight from the beginning of the PES payload, raise an error\n if (offset !== startOffset) {\n let reason: string;\n const recoverable = offset < len - 1;\n if (recoverable) {\n reason = `AAC PES did not start with ADTS header,offset:${offset}`;\n } else {\n reason = 'No ADTS header found in AAC PES';\n }\n const error = new Error(reason);\n logger.warn(`parsing error: ${reason}`);\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n levelRetry: recoverable,\n error,\n reason,\n });\n if (!recoverable) {\n return;\n }\n }\n\n ADTS.initTrackConfig(\n track,\n this.observer,\n data,\n offset,\n this.audioCodec as string\n );\n\n let pts: number;\n if (pes.pts !== undefined) {\n pts = pes.pts;\n } else if (aacOverFlow) {\n // if last AAC frame is overflowing, we should ensure timestamps are contiguous:\n // first sample PTS should be equal to last sample PTS + frameDuration\n const frameDuration = ADTS.getFrameDuration(track.samplerate as number);\n pts = aacOverFlow.sample.pts + frameDuration;\n } else {\n logger.warn('[tsdemuxer]: AAC PES unknown PTS');\n return;\n }\n\n // scan for aac samples\n let frameIndex = 0;\n let frame;\n while (offset < len) {\n frame = ADTS.appendFrame(track, data, offset, pts, frameIndex);\n offset += frame.length;\n if (!frame.missing) {\n frameIndex++;\n for (; offset < len - 1; offset++) {\n if (ADTS.isHeader(data, offset)) {\n break;\n }\n }\n } else {\n this.aacOverFlow = frame;\n break;\n }\n }\n }\n\n private parseMPEGPES(track: DemuxedAudioTrack, pes: PES) {\n const data = pes.data;\n const length = data.length;\n let frameIndex = 0;\n let offset = 0;\n const pts = pes.pts;\n if (pts === undefined) {\n logger.warn('[tsdemuxer]: MPEG PES unknown PTS');\n return;\n }\n\n while (offset < length) {\n if (MpegAudio.isHeader(data, offset)) {\n const frame = MpegAudio.appendFrame(\n track,\n data,\n offset,\n pts,\n frameIndex\n );\n if (frame) {\n offset += frame.length;\n frameIndex++;\n } else {\n // logger.log('Unable to parse Mpeg audio frame');\n break;\n }\n } else {\n // nothing found, keep looking\n offset++;\n }\n }\n }\n\n private parseID3PES(id3Track: DemuxedMetadataTrack, pes: PES) {\n if (pes.pts === undefined) {\n logger.warn('[tsdemuxer]: ID3 PES unknown PTS');\n return;\n }\n const id3Sample = Object.assign({}, pes as Required<PES>, {\n type: this._avcTrack ? MetadataSchema.emsg : MetadataSchema.audioId3,\n duration: Number.POSITIVE_INFINITY,\n });\n id3Track.samples.push(id3Sample);\n }\n}\n\nfunction createAVCSample(\n key: boolean,\n pts: number | undefined,\n dts: number | undefined,\n debug: string\n): ParsedAvcSample {\n return {\n key,\n frame: false,\n pts,\n dts,\n units: [],\n debug,\n length: 0,\n };\n}\n\nfunction parsePID(data: Uint8Array, offset: number): number {\n // pid is a 13-bit field starting at the last bit of TS[1]\n return ((data[offset + 1] & 0x1f) << 8) + data[offset + 2];\n}\n\nfunction parsePAT(data: Uint8Array, offset: number): number {\n // skip the PSI header and parse the first PMT entry\n return ((data[offset + 10] & 0x1f) << 8) | data[offset + 11];\n}\n\nfunction parsePMT(\n data: Uint8Array,\n offset: number,\n typeSupported: TypeSupported,\n isSampleAes: boolean\n) {\n const result = { audio: -1, avc: -1, id3: -1, segmentCodec: 'aac' };\n const sectionLength = ((data[offset + 1] & 0x0f) << 8) | data[offset + 2];\n const tableEnd = offset + 3 + sectionLength - 4;\n // to determine where the table is, we have to figure out how\n // long the program info descriptors are\n const programInfoLength =\n ((data[offset + 10] & 0x0f) << 8) | data[offset + 11];\n // advance the offset to the first entry in the mapping table\n offset += 12 + programInfoLength;\n while (offset < tableEnd) {\n const pid = parsePID(data, offset);\n switch (data[offset]) {\n case 0xcf: // SAMPLE-AES AAC\n if (!isSampleAes) {\n logger.log(\n 'ADTS AAC with AES-128-CBC frame encryption found in unencrypted stream'\n );\n break;\n }\n /* falls through */\n case 0x0f: // ISO/IEC 13818-7 ADTS AAC (MPEG-2 lower bit-rate audio)\n // logger.log('AAC PID:' + pid);\n if (result.audio === -1) {\n result.audio = pid;\n }\n\n break;\n\n // Packetized metadata (ID3)\n case 0x15:\n // logger.log('ID3 PID:' + pid);\n if (result.id3 === -1) {\n result.id3 = pid;\n }\n\n break;\n\n case 0xdb: // SAMPLE-AES AVC\n if (!isSampleAes) {\n logger.log(\n 'H.264 with AES-128-CBC slice encryption found in unencrypted stream'\n );\n break;\n }\n /* falls through */\n case 0x1b: // ITU-T Rec. H.264 and ISO/IEC 14496-10 (lower bit-rate video)\n // logger.log('AVC PID:' + pid);\n if (result.avc === -1) {\n result.avc = pid;\n }\n\n break;\n\n // ISO/IEC 11172-3 (MPEG-1 audio)\n // or ISO/IEC 13818-3 (MPEG-2 halved sample rate audio)\n case 0x03:\n case 0x04:\n // logger.log('MPEG PID:' + pid);\n if (typeSupported.mpeg !== true && typeSupported.mp3 !== true) {\n logger.log('MPEG audio found, not supported in this browser');\n } else if (result.audio === -1) {\n result.audio = pid;\n result.segmentCodec = 'mp3';\n }\n break;\n\n case 0x24:\n logger.warn('Unsupported HEVC stream type found');\n break;\n\n default:\n // logger.log('unknown stream type:' + data[offset]);\n break;\n }\n // move to the next table entry\n // skip past the elementary stream descriptors, if present\n offset += (((data[offset + 3] & 0x0f) << 8) | data[offset + 4]) + 5;\n }\n return result;\n}\n\nfunction parsePES(stream: ElementaryStreamData): PES | null {\n let i = 0;\n let frag: Uint8Array;\n let pesLen: number;\n let pesHdrLen: number;\n let pesPts: number | undefined;\n let pesDts: number | undefined;\n const data = stream.data;\n // safety check\n if (!stream || stream.size === 0) {\n return null;\n }\n\n // we might need up to 19 bytes to read PES header\n // if first chunk of data is less than 19 bytes, let's merge it with following ones until we get 19 bytes\n // usually only one merge is needed (and this is rare ...)\n while (data[0].length < 19 && data.length > 1) {\n const newData = new Uint8Array(data[0].length + data[1].length);\n newData.set(data[0]);\n newData.set(data[1], data[0].length);\n data[0] = newData;\n data.splice(1, 1);\n }\n // retrieve PTS/DTS from first fragment\n frag = data[0];\n const pesPrefix = (frag[0] << 16) + (frag[1] << 8) + frag[2];\n if (pesPrefix === 1) {\n pesLen = (frag[4] << 8) + frag[5];\n // if PES parsed length is not zero and greater than total received length, stop parsing. PES might be truncated\n // minus 6 : PES header size\n if (pesLen && pesLen > stream.size - 6) {\n return null;\n }\n\n const pesFlags = frag[7];\n if (pesFlags & 0xc0) {\n /* PES header described here : http://dvd.sourceforge.net/dvdinfo/pes-hdr.html\n as PTS / DTS is 33 bit we cannot use bitwise operator in JS,\n as Bitwise operators treat their operands as a sequence of 32 bits */\n pesPts =\n (frag[9] & 0x0e) * 536870912 + // 1 << 29\n (frag[10] & 0xff) * 4194304 + // 1 << 22\n (frag[11] & 0xfe) * 16384 + // 1 << 14\n (frag[12] & 0xff) * 128 + // 1 << 7\n (frag[13] & 0xfe) / 2;\n\n if (pesFlags & 0x40) {\n pesDts =\n (frag[14] & 0x0e) * 536870912 + // 1 << 29\n (frag[15] & 0xff) * 4194304 + // 1 << 22\n (frag[16] & 0xfe) * 16384 + // 1 << 14\n (frag[17] & 0xff) * 128 + // 1 << 7\n (frag[18] & 0xfe) / 2;\n\n if (pesPts - pesDts > 60 * 90000) {\n logger.warn(\n `${Math.round(\n (pesPts - pesDts) / 90000\n )}s delta between PTS and DTS, align them`\n );\n pesPts = pesDts;\n }\n } else {\n pesDts = pesPts;\n }\n }\n pesHdrLen = frag[8];\n // 9 bytes : 6 bytes for PES header + 3 bytes for PES extension\n let payloadStartOffset = pesHdrLen + 9;\n if (stream.size <= payloadStartOffset) {\n return null;\n }\n stream.size -= payloadStartOffset;\n // reassemble PES packet\n const pesData = new Uint8Array(stream.size);\n for (let j = 0, dataLen = data.length; j < dataLen; j++) {\n frag = data[j];\n let len = frag.byteLength;\n if (payloadStartOffset) {\n if (payloadStartOffset > len) {\n // trim full frag if PES header bigger than frag\n payloadStartOffset -= len;\n continue;\n } else {\n // trim partial frag if PES header smaller than frag\n frag = frag.subarray(payloadStartOffset);\n len -= payloadStartOffset;\n payloadStartOffset = 0;\n }\n }\n pesData.set(frag, i);\n i += len;\n }\n if (pesLen) {\n // payload size : remove PES header + PES extension\n pesLen -= pesHdrLen + 3;\n }\n return { data: pesData, pts: pesPts, dts: pesDts, len: pesLen };\n }\n return null;\n}\n\nfunction pushAccessUnit(avcSample: ParsedAvcSample, avcTrack: DemuxedAvcTrack) {\n if (avcSample.units.length && avcSample.frame) {\n // if sample does not have PTS/DTS, patch with last sample PTS/DTS\n if (avcSample.pts === undefined) {\n const samples = avcTrack.samples;\n const nbSamples = samples.length;\n if (nbSamples) {\n const lastSample = samples[nbSamples - 1];\n avcSample.pts = lastSample.pts;\n avcSample.dts = lastSample.dts;\n } else {\n // dropping samples, no timestamp found\n avcTrack.dropped++;\n return;\n }\n }\n avcTrack.samples.push(avcSample as AvcSample);\n }\n if (avcSample.debug.length) {\n logger.log(avcSample.pts + '/' + avcSample.dts + ':' + avcSample.debug);\n }\n}\n\nexport default TSDemuxer;\n","/**\n * MP3 demuxer\n */\nimport BaseAudioDemuxer from './base-audio-demuxer';\nimport * as ID3 from '../demux/id3';\nimport { logger } from '../utils/logger';\nimport * as MpegAudio from './mpegaudio';\n\nclass MP3Demuxer extends BaseAudioDemuxer {\n resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number\n ) {\n super.resetInitSegment(initSegment, audioCodec, videoCodec, trackDuration);\n this._audioTrack = {\n container: 'audio/mpeg',\n type: 'audio',\n id: 2,\n pid: -1,\n sequenceNumber: 0,\n segmentCodec: 'mp3',\n samples: [],\n manifestCodec: audioCodec,\n duration: trackDuration,\n inputTimeScale: 90000,\n dropped: 0,\n };\n }\n\n static probe(data): boolean {\n if (!data) {\n return false;\n }\n\n // check if data contains ID3 timestamp and MPEG sync word\n // Look for MPEG header | 1111 1111 | 111X XYZX | where X can be either 0 or 1 and Y or Z should be 1\n // Layer bits (position 14 and 15) in header should be always different from 0 (Layer I or Layer II or Layer III)\n // More info http://www.mp3-tech.org/programmer/frame_header.html\n const id3Data = ID3.getID3Data(data, 0) || [];\n let offset = id3Data.length;\n\n for (let length = data.length; offset < length; offset++) {\n if (MpegAudio.probe(data, offset)) {\n logger.log('MPEG Audio sync word found !');\n return true;\n }\n }\n return false;\n }\n\n canParse(data, offset) {\n return MpegAudio.canParse(data, offset);\n }\n\n appendFrame(track, data, offset) {\n if (this.basePTS === null) {\n return;\n }\n return MpegAudio.appendFrame(\n track,\n data,\n offset,\n this.basePTS,\n this.frameIndex\n );\n }\n}\n\nexport default MP3Demuxer;\n","/**\n * AAC helper\n */\n\nclass AAC {\n static getSilentFrame(\n codec?: string,\n channelCount?: number\n ): Uint8Array | undefined {\n switch (codec) {\n case 'mp4a.40.2':\n if (channelCount === 1) {\n return new Uint8Array([0x00, 0xc8, 0x00, 0x80, 0x23, 0x80]);\n } else if (channelCount === 2) {\n return new Uint8Array([\n 0x21, 0x00, 0x49, 0x90, 0x02, 0x19, 0x00, 0x23, 0x80,\n ]);\n } else if (channelCount === 3) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x8e,\n ]);\n } else if (channelCount === 4) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x80, 0x2c, 0x80, 0x08, 0x02, 0x38,\n ]);\n } else if (channelCount === 5) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x38,\n ]);\n } else if (channelCount === 6) {\n return new Uint8Array([\n 0x00, 0xc8, 0x00, 0x80, 0x20, 0x84, 0x01, 0x26, 0x40, 0x08, 0x64,\n 0x00, 0x82, 0x30, 0x04, 0x99, 0x00, 0x21, 0x90, 0x02, 0x00, 0xb2,\n 0x00, 0x20, 0x08, 0xe0,\n ]);\n }\n\n break;\n // handle HE-AAC below (mp4a.40.5 / mp4a.40.29)\n default:\n if (channelCount === 1) {\n // 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\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x4e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x1c, 0x6, 0xf1, 0xc1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n } else if (channelCount === 2) {\n // 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\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n } else if (channelCount === 3) {\n // 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\n return new Uint8Array([\n 0x1, 0x40, 0x22, 0x80, 0xa3, 0x5e, 0xe6, 0x80, 0xba, 0x8, 0x0, 0x0,\n 0x0, 0x0, 0x95, 0x0, 0x6, 0xf1, 0xa1, 0xa, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a, 0x5a,\n 0x5a, 0x5e,\n ]);\n }\n break;\n }\n return undefined;\n }\n}\n\nexport default AAC;\n","/**\n * Generate MP4 Box\n */\n\ntype HdlrTypes = {\n video: Uint8Array;\n audio: Uint8Array;\n};\n\nconst UINT32_MAX = Math.pow(2, 32) - 1;\n\nclass MP4 {\n public static types: Record<string, number[]>;\n private static HDLR_TYPES: HdlrTypes;\n private static STTS: Uint8Array;\n private static STSC: Uint8Array;\n private static STCO: Uint8Array;\n private static STSZ: Uint8Array;\n private static VMHD: Uint8Array;\n private static SMHD: Uint8Array;\n private static STSD: Uint8Array;\n private static FTYP: Uint8Array;\n private static DINF: Uint8Array;\n\n static init() {\n MP4.types = {\n avc1: [], // codingname\n avcC: [],\n btrt: [],\n dinf: [],\n dref: [],\n esds: [],\n ftyp: [],\n hdlr: [],\n mdat: [],\n mdhd: [],\n mdia: [],\n mfhd: [],\n minf: [],\n moof: [],\n moov: [],\n mp4a: [],\n '.mp3': [],\n mvex: [],\n mvhd: [],\n pasp: [],\n sdtp: [],\n stbl: [],\n stco: [],\n stsc: [],\n stsd: [],\n stsz: [],\n stts: [],\n tfdt: [],\n tfhd: [],\n traf: [],\n trak: [],\n trun: [],\n trex: [],\n tkhd: [],\n vmhd: [],\n smhd: [],\n };\n\n let i: string;\n for (i in MP4.types) {\n if (MP4.types.hasOwnProperty(i)) {\n MP4.types[i] = [\n i.charCodeAt(0),\n i.charCodeAt(1),\n i.charCodeAt(2),\n i.charCodeAt(3),\n ];\n }\n }\n\n const videoHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0x76,\n 0x69,\n 0x64,\n 0x65, // handler_type: 'vide'\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x56,\n 0x69,\n 0x64,\n 0x65,\n 0x6f,\n 0x48,\n 0x61,\n 0x6e,\n 0x64,\n 0x6c,\n 0x65,\n 0x72,\n 0x00, // name: 'VideoHandler'\n ]);\n\n const audioHdlr = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0x73,\n 0x6f,\n 0x75,\n 0x6e, // handler_type: 'soun'\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x53,\n 0x6f,\n 0x75,\n 0x6e,\n 0x64,\n 0x48,\n 0x61,\n 0x6e,\n 0x64,\n 0x6c,\n 0x65,\n 0x72,\n 0x00, // name: 'SoundHandler'\n ]);\n\n MP4.HDLR_TYPES = {\n video: videoHdlr,\n audio: audioHdlr,\n };\n\n const dref = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x01, // entry_count\n 0x00,\n 0x00,\n 0x00,\n 0x0c, // entry_size\n 0x75,\n 0x72,\n 0x6c,\n 0x20, // 'url' type\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x01, // entry_flags\n ]);\n\n const stco = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // entry_count\n ]);\n\n MP4.STTS = MP4.STSC = MP4.STCO = stco;\n\n MP4.STSZ = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00, // sample_size\n 0x00,\n 0x00,\n 0x00,\n 0x00, // sample_count\n ]);\n MP4.VMHD = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x01, // flags\n 0x00,\n 0x00, // graphicsmode\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // opcolor\n ]);\n MP4.SMHD = new Uint8Array([\n 0x00, // version\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00, // balance\n 0x00,\n 0x00, // reserved\n ]);\n\n MP4.STSD = new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n ]); // entry_count\n\n const majorBrand = new Uint8Array([105, 115, 111, 109]); // isom\n const avc1Brand = new Uint8Array([97, 118, 99, 49]); // avc1\n const minorVersion = new Uint8Array([0, 0, 0, 1]);\n\n MP4.FTYP = MP4.box(\n MP4.types.ftyp,\n majorBrand,\n minorVersion,\n majorBrand,\n avc1Brand\n );\n MP4.DINF = MP4.box(MP4.types.dinf, MP4.box(MP4.types.dref, dref));\n }\n\n static box(type, ...payload: Uint8Array[]) {\n let size = 8;\n let i = payload.length;\n const len = i;\n // calculate the total size we need to allocate\n while (i--) {\n size += payload[i].byteLength;\n }\n\n const result = new Uint8Array(size);\n result[0] = (size >> 24) & 0xff;\n result[1] = (size >> 16) & 0xff;\n result[2] = (size >> 8) & 0xff;\n result[3] = size & 0xff;\n result.set(type, 4);\n // copy the payload into the result\n for (i = 0, size = 8; i < len; i++) {\n // copy payload[i] array @ offset size\n result.set(payload[i], size);\n size += payload[i].byteLength;\n }\n return result;\n }\n\n static hdlr(type) {\n return MP4.box(MP4.types.hdlr, MP4.HDLR_TYPES[type]);\n }\n\n static mdat(data) {\n return MP4.box(MP4.types.mdat, data);\n }\n\n static mdhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(\n MP4.types.mdhd,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (timescale >> 24) & 0xff,\n (timescale >> 16) & 0xff,\n (timescale >> 8) & 0xff,\n timescale & 0xff, // timescale\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x55,\n 0xc4, // 'und' language (undetermined)\n 0x00,\n 0x00,\n ])\n );\n }\n\n static mdia(track) {\n return MP4.box(\n MP4.types.mdia,\n MP4.mdhd(track.timescale, track.duration),\n MP4.hdlr(track.type),\n MP4.minf(track)\n );\n }\n\n static mfhd(sequenceNumber) {\n return MP4.box(\n MP4.types.mfhd,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00,\n 0x00, // flags\n sequenceNumber >> 24,\n (sequenceNumber >> 16) & 0xff,\n (sequenceNumber >> 8) & 0xff,\n sequenceNumber & 0xff, // sequence_number\n ])\n );\n }\n\n static minf(track) {\n if (track.type === 'audio') {\n return MP4.box(\n MP4.types.minf,\n MP4.box(MP4.types.smhd, MP4.SMHD),\n MP4.DINF,\n MP4.stbl(track)\n );\n } else {\n return MP4.box(\n MP4.types.minf,\n MP4.box(MP4.types.vmhd, MP4.VMHD),\n MP4.DINF,\n MP4.stbl(track)\n );\n }\n }\n\n static moof(sn, baseMediaDecodeTime, track) {\n return MP4.box(\n MP4.types.moof,\n MP4.mfhd(sn),\n MP4.traf(track, baseMediaDecodeTime)\n );\n }\n\n static moov(tracks) {\n let i = tracks.length;\n const boxes: Uint8Array[] = [];\n\n while (i--) {\n boxes[i] = MP4.trak(tracks[i]);\n }\n\n return MP4.box.apply(\n null,\n [MP4.types.moov, MP4.mvhd(tracks[0].timescale, tracks[0].duration)]\n .concat(boxes)\n .concat(MP4.mvex(tracks))\n );\n }\n\n static mvex(tracks) {\n let i = tracks.length;\n const boxes: Uint8Array[] = [];\n\n while (i--) {\n boxes[i] = MP4.trex(tracks[i]);\n }\n\n return MP4.box.apply(null, [MP4.types.mvex, ...boxes]);\n }\n\n static mvhd(timescale, duration) {\n duration *= timescale;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n const bytes = new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (timescale >> 24) & 0xff,\n (timescale >> 16) & 0xff,\n (timescale >> 8) & 0xff,\n timescale & 0xff, // timescale\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x00,\n 0x01,\n 0x00,\n 0x00, // 1.0 rate\n 0x01,\n 0x00, // 1.0 volume\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x00,\n 0x00,\n 0x00, // transformation: unity matrix\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n 0xff,\n 0xff,\n 0xff,\n 0xff, // next_track_ID\n ]);\n return MP4.box(MP4.types.mvhd, bytes);\n }\n\n static sdtp(track) {\n const samples = track.samples || [];\n const bytes = new Uint8Array(4 + samples.length);\n let i;\n let flags;\n // leave the full box header (4 bytes) all zero\n // write the sample table\n for (i = 0; i < samples.length; i++) {\n flags = samples[i].flags;\n bytes[i + 4] =\n (flags.dependsOn << 4) |\n (flags.isDependedOn << 2) |\n flags.hasRedundancy;\n }\n\n return MP4.box(MP4.types.sdtp, bytes);\n }\n\n static stbl(track) {\n return MP4.box(\n MP4.types.stbl,\n MP4.stsd(track),\n MP4.box(MP4.types.stts, MP4.STTS),\n MP4.box(MP4.types.stsc, MP4.STSC),\n MP4.box(MP4.types.stsz, MP4.STSZ),\n MP4.box(MP4.types.stco, MP4.STCO)\n );\n }\n\n static avc1(track) {\n let sps: number[] = [];\n let pps: number[] = [];\n let i;\n let data;\n let len;\n // assemble the SPSs\n\n for (i = 0; i < track.sps.length; i++) {\n data = track.sps[i];\n len = data.byteLength;\n sps.push((len >>> 8) & 0xff);\n sps.push(len & 0xff);\n\n // SPS\n sps = sps.concat(Array.prototype.slice.call(data));\n }\n\n // assemble the PPSs\n for (i = 0; i < track.pps.length; i++) {\n data = track.pps[i];\n len = data.byteLength;\n pps.push((len >>> 8) & 0xff);\n pps.push(len & 0xff);\n\n pps = pps.concat(Array.prototype.slice.call(data));\n }\n\n const avcc = MP4.box(\n MP4.types.avcC,\n new Uint8Array(\n [\n 0x01, // version\n sps[3], // profile\n sps[4], // profile compat\n sps[5], // level\n 0xfc | 3, // lengthSizeMinusOne, hard-coded to 4 bytes\n 0xe0 | track.sps.length, // 3bit reserved (111) + numOfSequenceParameterSets\n ]\n .concat(sps)\n .concat([\n track.pps.length, // numOfPictureParameterSets\n ])\n .concat(pps)\n )\n ); // \"PPS\"\n const width = track.width;\n const height = track.height;\n const hSpacing = track.pixelRatio[0];\n const vSpacing = track.pixelRatio[1];\n\n return MP4.box(\n MP4.types.avc1,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00, // pre_defined\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // pre_defined\n (width >> 8) & 0xff,\n width & 0xff, // width\n (height >> 8) & 0xff,\n height & 0xff, // height\n 0x00,\n 0x48,\n 0x00,\n 0x00, // horizresolution\n 0x00,\n 0x48,\n 0x00,\n 0x00, // vertresolution\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // frame_count\n 0x12,\n 0x64,\n 0x61,\n 0x69,\n 0x6c, // dailymotion/hls.js\n 0x79,\n 0x6d,\n 0x6f,\n 0x74,\n 0x69,\n 0x6f,\n 0x6e,\n 0x2f,\n 0x68,\n 0x6c,\n 0x73,\n 0x2e,\n 0x6a,\n 0x73,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // compressorname\n 0x00,\n 0x18, // depth = 24\n 0x11,\n 0x11,\n ]), // pre_defined = -1\n avcc,\n MP4.box(\n MP4.types.btrt,\n new Uint8Array([\n 0x00,\n 0x1c,\n 0x9c,\n 0x80, // bufferSizeDB\n 0x00,\n 0x2d,\n 0xc6,\n 0xc0, // maxBitrate\n 0x00,\n 0x2d,\n 0xc6,\n 0xc0,\n ])\n ), // avgBitrate\n MP4.box(\n MP4.types.pasp,\n new Uint8Array([\n hSpacing >> 24, // hSpacing\n (hSpacing >> 16) & 0xff,\n (hSpacing >> 8) & 0xff,\n hSpacing & 0xff,\n vSpacing >> 24, // vSpacing\n (vSpacing >> 16) & 0xff,\n (vSpacing >> 8) & 0xff,\n vSpacing & 0xff,\n ])\n )\n );\n }\n\n static esds(track) {\n const configlen = track.config.length;\n return new Uint8Array(\n [\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n\n 0x03, // descriptor_type\n 0x17 + configlen, // length\n 0x00,\n 0x01, // es_id\n 0x00, // stream_priority\n\n 0x04, // descriptor_type\n 0x0f + configlen, // length\n 0x40, // codec : mpeg4_audio\n 0x15, // stream_type\n 0x00,\n 0x00,\n 0x00, // buffer_size\n 0x00,\n 0x00,\n 0x00,\n 0x00, // maxBitrate\n 0x00,\n 0x00,\n 0x00,\n 0x00, // avgBitrate\n\n 0x05, // descriptor_type\n ]\n .concat([configlen])\n .concat(track.config)\n .concat([0x06, 0x01, 0x02])\n ); // GASpecificConfig)); // length + audio config descriptor\n }\n\n static mp4a(track) {\n const samplerate = track.samplerate;\n return MP4.box(\n MP4.types.mp4a,\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n track.channelCount, // channelcount\n 0x00,\n 0x10, // sampleSize:16bits\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved2\n (samplerate >> 8) & 0xff,\n samplerate & 0xff, //\n 0x00,\n 0x00,\n ]),\n MP4.box(MP4.types.esds, MP4.esds(track))\n );\n }\n\n static mp3(track) {\n const samplerate = track.samplerate;\n return MP4.box(\n MP4.types['.mp3'],\n new Uint8Array([\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01, // data_reference_index\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n track.channelCount, // channelcount\n 0x00,\n 0x10, // sampleSize:16bits\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved2\n (samplerate >> 8) & 0xff,\n samplerate & 0xff, //\n 0x00,\n 0x00,\n ])\n );\n }\n\n static stsd(track) {\n if (track.type === 'audio') {\n if (track.segmentCodec === 'mp3' && track.codec === 'mp3') {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp3(track));\n }\n\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.mp4a(track));\n } else {\n return MP4.box(MP4.types.stsd, MP4.STSD, MP4.avc1(track));\n }\n }\n\n static tkhd(track) {\n const id = track.id;\n const duration = track.duration * track.timescale;\n const width = track.width;\n const height = track.height;\n const upperWordDuration = Math.floor(duration / (UINT32_MAX + 1));\n const lowerWordDuration = Math.floor(duration % (UINT32_MAX + 1));\n return MP4.box(\n MP4.types.tkhd,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x07, // flags\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x02, // creation_time\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x03, // modification_time\n (id >> 24) & 0xff,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n upperWordDuration >> 24,\n (upperWordDuration >> 16) & 0xff,\n (upperWordDuration >> 8) & 0xff,\n upperWordDuration & 0xff,\n lowerWordDuration >> 24,\n (lowerWordDuration >> 16) & 0xff,\n (lowerWordDuration >> 8) & 0xff,\n lowerWordDuration & 0xff,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x00, // layer\n 0x00,\n 0x00, // alternate_group\n 0x00,\n 0x00, // non-audio track volume\n 0x00,\n 0x00, // reserved\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x01,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x00,\n 0x40,\n 0x00,\n 0x00,\n 0x00, // transformation: unity matrix\n (width >> 8) & 0xff,\n width & 0xff,\n 0x00,\n 0x00, // width\n (height >> 8) & 0xff,\n height & 0xff,\n 0x00,\n 0x00, // height\n ])\n );\n }\n\n static traf(track, baseMediaDecodeTime) {\n const sampleDependencyTable = MP4.sdtp(track);\n const id = track.id;\n const upperWordBaseMediaDecodeTime = Math.floor(\n baseMediaDecodeTime / (UINT32_MAX + 1)\n );\n const lowerWordBaseMediaDecodeTime = Math.floor(\n baseMediaDecodeTime % (UINT32_MAX + 1)\n );\n return MP4.box(\n MP4.types.traf,\n MP4.box(\n MP4.types.tfhd,\n new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n id >> 24,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n ])\n ),\n MP4.box(\n MP4.types.tfdt,\n new Uint8Array([\n 0x01, // version 1\n 0x00,\n 0x00,\n 0x00, // flags\n upperWordBaseMediaDecodeTime >> 24,\n (upperWordBaseMediaDecodeTime >> 16) & 0xff,\n (upperWordBaseMediaDecodeTime >> 8) & 0xff,\n upperWordBaseMediaDecodeTime & 0xff,\n lowerWordBaseMediaDecodeTime >> 24,\n (lowerWordBaseMediaDecodeTime >> 16) & 0xff,\n (lowerWordBaseMediaDecodeTime >> 8) & 0xff,\n lowerWordBaseMediaDecodeTime & 0xff,\n ])\n ),\n MP4.trun(\n track,\n sampleDependencyTable.length +\n 16 + // tfhd\n 20 + // tfdt\n 8 + // traf header\n 16 + // mfhd\n 8 + // moof header\n 8\n ), // mdat header\n sampleDependencyTable\n );\n }\n\n /**\n * Generate a track box.\n * @param track a track definition\n */\n static trak(track) {\n track.duration = track.duration || 0xffffffff;\n return MP4.box(MP4.types.trak, MP4.tkhd(track), MP4.mdia(track));\n }\n\n static trex(track) {\n const id = track.id;\n return MP4.box(\n MP4.types.trex,\n new Uint8Array([\n 0x00, // version 0\n 0x00,\n 0x00,\n 0x00, // flags\n id >> 24,\n (id >> 16) & 0xff,\n (id >> 8) & 0xff,\n id & 0xff, // track_ID\n 0x00,\n 0x00,\n 0x00,\n 0x01, // default_sample_description_index\n 0x00,\n 0x00,\n 0x00,\n 0x00, // default_sample_duration\n 0x00,\n 0x00,\n 0x00,\n 0x00, // default_sample_size\n 0x00,\n 0x01,\n 0x00,\n 0x01, // default_sample_flags\n ])\n );\n }\n\n static trun(track, offset) {\n const samples = track.samples || [];\n const len = samples.length;\n const arraylen = 12 + 16 * len;\n const array = new Uint8Array(arraylen);\n let i;\n let sample;\n let duration;\n let size;\n let flags;\n let cts;\n offset += 8 + arraylen;\n array.set(\n [\n track.type === 'video' ? 0x01 : 0x00, // version 1 for video with signed-int sample_composition_time_offset\n 0x00,\n 0x0f,\n 0x01, // flags\n (len >>> 24) & 0xff,\n (len >>> 16) & 0xff,\n (len >>> 8) & 0xff,\n len & 0xff, // sample_count\n (offset >>> 24) & 0xff,\n (offset >>> 16) & 0xff,\n (offset >>> 8) & 0xff,\n offset & 0xff, // data_offset\n ],\n 0\n );\n for (i = 0; i < len; i++) {\n sample = samples[i];\n duration = sample.duration;\n size = sample.size;\n flags = sample.flags;\n cts = sample.cts;\n array.set(\n [\n (duration >>> 24) & 0xff,\n (duration >>> 16) & 0xff,\n (duration >>> 8) & 0xff,\n duration & 0xff, // sample_duration\n (size >>> 24) & 0xff,\n (size >>> 16) & 0xff,\n (size >>> 8) & 0xff,\n size & 0xff, // sample_size\n (flags.isLeading << 2) | flags.dependsOn,\n (flags.isDependedOn << 6) |\n (flags.hasRedundancy << 4) |\n (flags.paddingValue << 1) |\n flags.isNonSync,\n flags.degradPrio & (0xf0 << 8),\n flags.degradPrio & 0x0f, // sample_flags\n (cts >>> 24) & 0xff,\n (cts >>> 16) & 0xff,\n (cts >>> 8) & 0xff,\n cts & 0xff, // sample_composition_time_offset\n ],\n 12 + 16 * i\n );\n }\n return MP4.box(MP4.types.trun, array);\n }\n\n static initSegment(tracks) {\n if (!MP4.types) {\n MP4.init();\n }\n\n const movie = MP4.moov(tracks);\n const result = new Uint8Array(MP4.FTYP.byteLength + movie.byteLength);\n result.set(MP4.FTYP);\n result.set(movie, MP4.FTYP.byteLength);\n return result;\n }\n}\n\nexport default MP4;\n","const MPEG_TS_CLOCK_FREQ_HZ = 90000;\n\nexport type RationalTimestamp = {\n baseTime: number; // ticks\n timescale: number; // ticks per second\n};\n\nexport function toTimescaleFromBase(\n baseTime: number,\n destScale: number,\n srcBase: number = 1,\n round: boolean = false\n): number {\n const result = baseTime * destScale * srcBase; // equivalent to `(value * scale) / (1 / base)`\n return round ? Math.round(result) : result;\n}\n\nexport function toTimescaleFromScale(\n baseTime: number,\n destScale: number,\n srcScale: number = 1,\n round: boolean = false\n): number {\n return toTimescaleFromBase(baseTime, destScale, 1 / srcScale, round);\n}\n\nexport function toMsFromMpegTsClock(\n baseTime: number,\n round: boolean = false\n): number {\n return toTimescaleFromBase(baseTime, 1000, 1 / MPEG_TS_CLOCK_FREQ_HZ, round);\n}\n\nexport function toMpegTsClockFromTimescale(\n baseTime: number,\n srcScale: number = 1\n): number {\n return toTimescaleFromBase(baseTime, MPEG_TS_CLOCK_FREQ_HZ, 1 / srcScale);\n}\n","import AAC from './aac-helper';\nimport MP4 from './mp4-generator';\nimport type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport {\n InitSegmentData,\n Remuxer,\n RemuxerResult,\n RemuxedMetadata,\n RemuxedTrack,\n RemuxedUserdata,\n} from '../types/remuxer';\nimport { PlaylistLevelType } from '../types/loader';\nimport {\n RationalTimestamp,\n toMsFromMpegTsClock,\n} from '../utils/timescale-conversion';\nimport type {\n AudioSample,\n AvcSample,\n DemuxedAudioTrack,\n DemuxedAvcTrack,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n} from '../types/demuxer';\nimport type { TrackSet } from '../types/track';\nimport type { SourceBufferName } from '../types/buffer';\nimport type { Fragment } from '../loader/fragment';\nimport type { HlsConfig } from '../config';\n\nconst MAX_SILENT_FRAME_DURATION = 10 * 1000; // 10 seconds\nconst AAC_SAMPLES_PER_FRAME = 1024;\nconst MPEG_AUDIO_SAMPLE_PER_FRAME = 1152;\n\nlet chromeVersion: number | null = null;\nlet safariWebkitVersion: number | null = null;\n\nexport default class MP4Remuxer implements Remuxer {\n private observer: HlsEventEmitter;\n private config: HlsConfig;\n private typeSupported: any;\n private ISGenerated: boolean = false;\n private _initPTS: RationalTimestamp | null = null;\n private _initDTS: RationalTimestamp | null = null;\n private nextAvcDts: number | null = null;\n private nextAudioPts: number | null = null;\n private videoSampleDuration: number | null = null;\n private isAudioContiguous: boolean = false;\n private isVideoContiguous: boolean = false;\n\n constructor(\n observer: HlsEventEmitter,\n config: HlsConfig,\n typeSupported,\n vendor = ''\n ) {\n this.observer = observer;\n this.config = config;\n this.typeSupported = typeSupported;\n this.ISGenerated = false;\n\n if (chromeVersion === null) {\n const userAgent = navigator.userAgent || '';\n const result = userAgent.match(/Chrome\\/(\\d+)/i);\n chromeVersion = result ? parseInt(result[1]) : 0;\n }\n if (safariWebkitVersion === null) {\n const result = navigator.userAgent.match(/Safari\\/(\\d+)/i);\n safariWebkitVersion = result ? parseInt(result[1]) : 0;\n }\n }\n\n destroy() {}\n\n resetTimeStamp(defaultTimeStamp: RationalTimestamp | null) {\n logger.log('[mp4-remuxer]: initPTS & initDTS reset');\n this._initPTS = this._initDTS = defaultTimeStamp;\n }\n\n resetNextTimestamp() {\n logger.log('[mp4-remuxer]: reset next timestamp');\n this.isVideoContiguous = false;\n this.isAudioContiguous = false;\n }\n\n resetInitSegment() {\n logger.log('[mp4-remuxer]: ISGenerated flag reset');\n this.ISGenerated = false;\n }\n\n getVideoStartPts(videoSamples) {\n let rolloverDetected = false;\n const startPTS = videoSamples.reduce((minPTS, sample) => {\n const delta = sample.pts - minPTS;\n if (delta < -4294967296) {\n // 2^32, see PTSNormalize for reasoning, but we're hitting a rollover here, and we don't want that to impact the timeOffset calculation\n rolloverDetected = true;\n return normalizePts(minPTS, sample.pts);\n } else if (delta > 0) {\n return minPTS;\n } else {\n return sample.pts;\n }\n }, videoSamples[0].pts);\n if (rolloverDetected) {\n logger.debug('PTS rollover detected');\n }\n return startPTS;\n }\n\n remux(\n audioTrack: DemuxedAudioTrack,\n videoTrack: DemuxedAvcTrack,\n id3Track: DemuxedMetadataTrack,\n textTrack: DemuxedUserdataTrack,\n timeOffset: number,\n accurateTimeOffset: boolean,\n flush: boolean,\n playlistType: PlaylistLevelType\n ): RemuxerResult {\n let video: RemuxedTrack | undefined;\n let audio: RemuxedTrack | undefined;\n let initSegment: InitSegmentData | undefined;\n let text: RemuxedUserdata | undefined;\n let id3: RemuxedMetadata | undefined;\n let independent: boolean | undefined;\n let audioTimeOffset = timeOffset;\n let videoTimeOffset = timeOffset;\n\n // If we're remuxing audio and video progressively, wait until we've received enough samples for each track before proceeding.\n // This is done to synchronize the audio and video streams. We know if the current segment will have samples if the \"pid\"\n // parameter is greater than -1. The pid is set when the PMT is parsed, which contains the tracks list.\n // However, if the initSegment has already been generated, or we've reached the end of a segment (flush),\n // then we can remux one track without waiting for the other.\n const hasAudio = audioTrack.pid > -1;\n const hasVideo = videoTrack.pid > -1;\n const length = videoTrack.samples.length;\n const enoughAudioSamples = audioTrack.samples.length > 0;\n const enoughVideoSamples = (flush && length > 0) || length > 1;\n const canRemuxAvc =\n ((!hasAudio || enoughAudioSamples) &&\n (!hasVideo || enoughVideoSamples)) ||\n this.ISGenerated ||\n flush;\n\n if (canRemuxAvc) {\n if (!this.ISGenerated) {\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset\n );\n }\n\n const isVideoContiguous = this.isVideoContiguous;\n let firstKeyFrameIndex = -1;\n let firstKeyFramePTS;\n\n if (enoughVideoSamples) {\n firstKeyFrameIndex = findKeyframeIndex(videoTrack.samples);\n if (!isVideoContiguous && this.config.forceKeyFrameOnDiscontinuity) {\n independent = true;\n if (firstKeyFrameIndex > 0) {\n logger.warn(\n `[mp4-remuxer]: Dropped ${firstKeyFrameIndex} out of ${length} video samples due to a missing keyframe`\n );\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n videoTrack.samples = videoTrack.samples.slice(firstKeyFrameIndex);\n videoTrack.dropped += firstKeyFrameIndex;\n videoTimeOffset +=\n (videoTrack.samples[0].pts - startPTS) /\n videoTrack.inputTimeScale;\n firstKeyFramePTS = videoTimeOffset;\n } else if (firstKeyFrameIndex === -1) {\n logger.warn(\n `[mp4-remuxer]: No keyframe found out of ${length} video samples`\n );\n independent = false;\n }\n }\n }\n\n if (this.ISGenerated) {\n if (enoughAudioSamples && enoughVideoSamples) {\n // timeOffset is expected to be the offset of the first timestamp of this fragment (first DTS)\n // if first audio DTS is not aligned with first video DTS then we need to take that into account\n // when providing timeOffset to remuxAudio / remuxVideo. if we don't do that, there might be a permanent / small\n // drift between audio and video streams\n const startPTS = this.getVideoStartPts(videoTrack.samples);\n const tsDelta =\n normalizePts(audioTrack.samples[0].pts, startPTS) - startPTS;\n const audiovideoTimestampDelta = tsDelta / videoTrack.inputTimeScale;\n audioTimeOffset += Math.max(0, audiovideoTimestampDelta);\n videoTimeOffset += Math.max(0, -audiovideoTimestampDelta);\n }\n\n // Purposefully remuxing audio before video, so that remuxVideo can use nextAudioPts, which is calculated in remuxAudio.\n if (enoughAudioSamples) {\n // if initSegment was generated without audio samples, regenerate it again\n if (!audioTrack.samplerate) {\n logger.warn(\n '[mp4-remuxer]: regenerate InitSegment as audio detected'\n );\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset\n );\n }\n audio = this.remuxAudio(\n audioTrack,\n audioTimeOffset,\n this.isAudioContiguous,\n accurateTimeOffset,\n hasVideo ||\n enoughVideoSamples ||\n playlistType === PlaylistLevelType.AUDIO\n ? videoTimeOffset\n : undefined\n );\n if (enoughVideoSamples) {\n const audioTrackLength = audio ? audio.endPTS - audio.startPTS : 0;\n // if initSegment was generated without video samples, regenerate it again\n if (!videoTrack.inputTimeScale) {\n logger.warn(\n '[mp4-remuxer]: regenerate InitSegment as video detected'\n );\n initSegment = this.generateIS(\n audioTrack,\n videoTrack,\n timeOffset,\n accurateTimeOffset\n );\n }\n video = this.remuxVideo(\n videoTrack,\n videoTimeOffset,\n isVideoContiguous,\n audioTrackLength\n );\n }\n } else if (enoughVideoSamples) {\n video = this.remuxVideo(\n videoTrack,\n videoTimeOffset,\n isVideoContiguous,\n 0\n );\n }\n if (video) {\n video.firstKeyFrame = firstKeyFrameIndex;\n video.independent = firstKeyFrameIndex !== -1;\n video.firstKeyFramePTS = firstKeyFramePTS;\n }\n }\n }\n\n // Allow ID3 and text to remux, even if more audio/video samples are required\n if (this.ISGenerated && this._initPTS && this._initDTS) {\n if (id3Track.samples.length) {\n id3 = flushTextTrackMetadataCueSamples(\n id3Track,\n timeOffset,\n this._initPTS,\n this._initDTS\n );\n }\n\n if (textTrack.samples.length) {\n text = flushTextTrackUserdataCueSamples(\n textTrack,\n timeOffset,\n this._initPTS\n );\n }\n }\n\n return {\n audio,\n video,\n initSegment,\n independent,\n text,\n id3,\n };\n }\n\n generateIS(\n audioTrack: DemuxedAudioTrack,\n videoTrack: DemuxedAvcTrack,\n timeOffset: number,\n accurateTimeOffset: boolean\n ): InitSegmentData | undefined {\n const audioSamples = audioTrack.samples;\n const videoSamples = videoTrack.samples;\n const typeSupported = this.typeSupported;\n const tracks: TrackSet = {};\n const _initPTS = this._initPTS;\n let computePTSDTS = !_initPTS || accurateTimeOffset;\n let container = 'audio/mp4';\n let initPTS: number | undefined;\n let initDTS: number | undefined;\n let timescale: number | undefined;\n\n if (computePTSDTS) {\n initPTS = initDTS = Infinity;\n }\n\n if (audioTrack.config && audioSamples.length) {\n // let's use audio sampling rate as MP4 time scale.\n // rationale is that there is a integer nb of audio frames per audio sample (1024 for AAC)\n // using audio sampling rate here helps having an integer MP4 frame duration\n // this avoids potential rounding issue and AV sync issue\n audioTrack.timescale = audioTrack.samplerate;\n switch (audioTrack.segmentCodec) {\n case 'mp3':\n if (typeSupported.mpeg) {\n // Chrome and Safari\n container = 'audio/mpeg';\n audioTrack.codec = '';\n } else if (typeSupported.mp3) {\n // Firefox\n audioTrack.codec = 'mp3';\n }\n break;\n }\n tracks.audio = {\n id: 'audio',\n container: container,\n codec: audioTrack.codec,\n initSegment:\n audioTrack.segmentCodec === 'mp3' && typeSupported.mpeg\n ? new Uint8Array(0)\n : MP4.initSegment([audioTrack]),\n metadata: {\n channelCount: audioTrack.channelCount,\n },\n };\n if (computePTSDTS) {\n timescale = audioTrack.inputTimeScale;\n if (!_initPTS || timescale !== _initPTS.timescale) {\n // remember first PTS of this demuxing context. for audio, PTS = DTS\n initPTS = initDTS =\n audioSamples[0].pts - Math.round(timescale * timeOffset);\n } else {\n computePTSDTS = false;\n }\n }\n }\n\n if (videoTrack.sps && videoTrack.pps && videoSamples.length) {\n // let's use input time scale as MP4 video timescale\n // we use input time scale straight away to avoid rounding issues on frame duration / cts computation\n videoTrack.timescale = videoTrack.inputTimeScale;\n tracks.video = {\n id: 'main',\n container: 'video/mp4',\n codec: videoTrack.codec,\n initSegment: MP4.initSegment([videoTrack]),\n metadata: {\n width: videoTrack.width,\n height: videoTrack.height,\n },\n };\n if (computePTSDTS) {\n timescale = videoTrack.inputTimeScale;\n if (!_initPTS || timescale !== _initPTS.timescale) {\n const startPTS = this.getVideoStartPts(videoSamples);\n const startOffset = Math.round(timescale * timeOffset);\n initDTS = Math.min(\n initDTS as number,\n normalizePts(videoSamples[0].dts, startPTS) - startOffset\n );\n initPTS = Math.min(initPTS as number, startPTS - startOffset);\n } else {\n computePTSDTS = false;\n }\n }\n }\n\n if (Object.keys(tracks).length) {\n this.ISGenerated = true;\n if (computePTSDTS) {\n this._initPTS = {\n baseTime: initPTS as number,\n timescale: timescale as number,\n };\n this._initDTS = {\n baseTime: initDTS as number,\n timescale: timescale as number,\n };\n } else {\n initPTS = timescale = undefined;\n }\n\n return {\n tracks,\n initPTS,\n timescale,\n };\n }\n }\n\n remuxVideo(\n track: DemuxedAvcTrack,\n timeOffset: number,\n contiguous: boolean,\n audioTrackLength: number\n ): RemuxedTrack | undefined {\n const timeScale: number = track.inputTimeScale;\n const inputSamples: Array<AvcSample> = track.samples;\n const outputSamples: Array<Mp4Sample> = [];\n const nbSamples = inputSamples.length;\n const initPTS = this._initPTS as RationalTimestamp;\n let nextAvcDts = this.nextAvcDts;\n let offset = 8;\n let mp4SampleDuration = this.videoSampleDuration;\n let firstDTS;\n let lastDTS;\n let minPTS: number = Number.POSITIVE_INFINITY;\n let maxPTS: number = Number.NEGATIVE_INFINITY;\n let sortSamples = false;\n\n // if parsed fragment is contiguous with last one, let's use last DTS value as reference\n if (!contiguous || nextAvcDts === null) {\n const pts = timeOffset * timeScale;\n const cts =\n inputSamples[0].pts -\n normalizePts(inputSamples[0].dts, inputSamples[0].pts);\n // if not contiguous, let's use target timeOffset\n nextAvcDts = pts - cts;\n }\n\n // PTS is coded on 33bits, and can loop from -2^32 to 2^32\n // PTSNormalize will make PTS/DTS value monotonic, we use last known DTS value as reference value\n const initTime = (initPTS.baseTime * timeScale) / initPTS.timescale;\n for (let i = 0; i < nbSamples; i++) {\n const sample = inputSamples[i];\n sample.pts = normalizePts(sample.pts - initTime, nextAvcDts);\n sample.dts = normalizePts(sample.dts - initTime, nextAvcDts);\n if (sample.dts < inputSamples[i > 0 ? i - 1 : i].dts) {\n sortSamples = true;\n }\n }\n\n // sort video samples by DTS then PTS then demux id order\n if (sortSamples) {\n inputSamples.sort(function (a, b) {\n const deltadts = a.dts - b.dts;\n const deltapts = a.pts - b.pts;\n return deltadts || deltapts;\n });\n }\n\n // Get first/last DTS\n firstDTS = inputSamples[0].dts;\n lastDTS = inputSamples[inputSamples.length - 1].dts;\n\n // Sample duration (as expected by trun MP4 boxes), should be the delta between sample DTS\n // set this constant duration as being the avg delta between consecutive DTS.\n const inputDuration = lastDTS - firstDTS;\n const averageSampleDuration = inputDuration\n ? Math.round(inputDuration / (nbSamples - 1))\n : mp4SampleDuration || track.inputTimeScale / 30;\n\n // if fragment are contiguous, detect hole/overlapping between fragments\n if (contiguous) {\n // check timestamp continuity across consecutive fragments (this is to remove inter-fragment gap/hole)\n const delta = firstDTS - nextAvcDts;\n const foundHole = delta > averageSampleDuration;\n const foundOverlap = delta < -1;\n if (foundHole || foundOverlap) {\n if (foundHole) {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n delta,\n true\n )} ms (${delta}dts) hole between fragments detected, filling it`\n );\n } else {\n logger.warn(\n `AVC: ${toMsFromMpegTsClock(\n -delta,\n true\n )} ms (${delta}dts) overlapping between fragments detected`\n );\n }\n if (!foundOverlap || nextAvcDts >= inputSamples[0].pts) {\n firstDTS = nextAvcDts;\n const firstPTS = inputSamples[0].pts - delta;\n inputSamples[0].dts = firstDTS;\n inputSamples[0].pts = firstPTS;\n logger.log(\n `Video: First PTS/DTS adjusted: ${toMsFromMpegTsClock(\n firstPTS,\n true\n )}/${toMsFromMpegTsClock(\n firstDTS,\n true\n )}, delta: ${toMsFromMpegTsClock(delta, true)} ms`\n );\n }\n }\n }\n\n firstDTS = Math.max(0, firstDTS);\n\n let nbNalu = 0;\n let naluLen = 0;\n for (let i = 0; i < nbSamples; i++) {\n // compute total/avc sample length and nb of NAL units\n const sample = inputSamples[i];\n const units = sample.units;\n const nbUnits = units.length;\n let sampleLen = 0;\n for (let j = 0; j < nbUnits; j++) {\n sampleLen += units[j].data.length;\n }\n\n naluLen += sampleLen;\n nbNalu += nbUnits;\n sample.length = sampleLen;\n\n // ensure sample monotonic DTS\n sample.dts = Math.max(sample.dts, firstDTS);\n\n minPTS = Math.min(sample.pts, minPTS);\n maxPTS = Math.max(sample.pts, maxPTS);\n }\n lastDTS = inputSamples[nbSamples - 1].dts;\n\n /* concatenate the video data and construct the mdat in place\n (need 8 more bytes to fill length and mpdat type) */\n const mdatSize = naluLen + 4 * nbNalu + 8;\n let mdat;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n error: err,\n bytes: mdatSize,\n reason: `fail allocating video mdat ${mdatSize}`,\n });\n return;\n }\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n\n let stretchedLastFrame = false;\n let minDtsDelta = Number.POSITIVE_INFINITY;\n let minPtsDelta = Number.POSITIVE_INFINITY;\n let maxDtsDelta = Number.NEGATIVE_INFINITY;\n let maxPtsDelta = Number.NEGATIVE_INFINITY;\n for (let i = 0; i < nbSamples; i++) {\n const avcSample = inputSamples[i];\n const avcSampleUnits = avcSample.units;\n let mp4SampleLength = 0;\n // convert NALU bitstream to MP4 format (prepend NALU with size field)\n for (let j = 0, nbUnits = avcSampleUnits.length; j < nbUnits; j++) {\n const unit = avcSampleUnits[j];\n const unitData = unit.data;\n const unitDataLen = unit.data.byteLength;\n view.setUint32(offset, unitDataLen);\n offset += 4;\n mdat.set(unitData, offset);\n offset += unitDataLen;\n mp4SampleLength += 4 + unitDataLen;\n }\n\n // expected sample duration is the Decoding Timestamp diff of consecutive samples\n let ptsDelta;\n if (i < nbSamples - 1) {\n mp4SampleDuration = inputSamples[i + 1].dts - avcSample.dts;\n ptsDelta = inputSamples[i + 1].pts - avcSample.pts;\n } else {\n const config = this.config;\n const lastFrameDuration =\n i > 0\n ? avcSample.dts - inputSamples[i - 1].dts\n : averageSampleDuration;\n ptsDelta =\n i > 0\n ? avcSample.pts - inputSamples[i - 1].pts\n : averageSampleDuration;\n if (config.stretchShortVideoTrack && this.nextAudioPts !== null) {\n // In some cases, a segment's audio track duration may exceed the video track duration.\n // Since we've already remuxed audio, and we know how long the audio track is, we look to\n // see if the delta to the next segment is longer than maxBufferHole.\n // If so, playback would potentially get stuck, so we artificially inflate\n // the duration of the last frame to minimize any potential gap between segments.\n const gapTolerance = Math.floor(config.maxBufferHole * timeScale);\n const deltaToFrameEnd =\n (audioTrackLength\n ? minPTS + audioTrackLength * timeScale\n : this.nextAudioPts) - avcSample.pts;\n if (deltaToFrameEnd > gapTolerance) {\n // We subtract lastFrameDuration from deltaToFrameEnd to try to prevent any video\n // frame overlap. maxBufferHole should be >> lastFrameDuration anyway.\n mp4SampleDuration = deltaToFrameEnd - lastFrameDuration;\n if (mp4SampleDuration < 0) {\n mp4SampleDuration = lastFrameDuration;\n } else {\n stretchedLastFrame = true;\n }\n logger.log(\n `[mp4-remuxer]: It is approximately ${\n deltaToFrameEnd / 90\n } ms to the next segment; using duration ${\n mp4SampleDuration / 90\n } ms for the last video frame.`\n );\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n } else {\n mp4SampleDuration = lastFrameDuration;\n }\n }\n const compositionTimeOffset = Math.round(avcSample.pts - avcSample.dts);\n minDtsDelta = Math.min(minDtsDelta, mp4SampleDuration);\n maxDtsDelta = Math.max(maxDtsDelta, mp4SampleDuration);\n minPtsDelta = Math.min(minPtsDelta, ptsDelta);\n maxPtsDelta = Math.max(maxPtsDelta, ptsDelta);\n\n outputSamples.push(\n new Mp4Sample(\n avcSample.key,\n mp4SampleDuration,\n mp4SampleLength,\n compositionTimeOffset\n )\n );\n }\n\n if (outputSamples.length) {\n if (chromeVersion) {\n if (chromeVersion < 70) {\n // Chrome workaround, mark first sample as being a Random Access Point (keyframe) to avoid sourcebuffer append issue\n // https://code.google.com/p/chromium/issues/detail?id=229412\n const flags = outputSamples[0].flags;\n flags.dependsOn = 2;\n flags.isNonSync = 0;\n }\n } else if (safariWebkitVersion) {\n // Fix for \"CNN special report, with CC\" in test-streams (Safari browser only)\n // Ignore DTS when frame durations are irregular. Safari MSE does not handle this leading to gaps.\n if (\n maxPtsDelta - minPtsDelta < maxDtsDelta - minDtsDelta &&\n averageSampleDuration / maxDtsDelta < 0.025 &&\n outputSamples[0].cts === 0\n ) {\n logger.warn(\n 'Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.'\n );\n let dts = firstDTS;\n for (let i = 0, len = outputSamples.length; i < len; i++) {\n const nextDts = dts + outputSamples[i].duration;\n const pts = dts + outputSamples[i].cts;\n if (i < len - 1) {\n const nextPts = nextDts + outputSamples[i + 1].cts;\n outputSamples[i].duration = nextPts - pts;\n } else {\n outputSamples[i].duration = i\n ? outputSamples[i - 1].duration\n : averageSampleDuration;\n }\n outputSamples[i].cts = 0;\n dts = nextDts;\n }\n }\n }\n }\n // next AVC sample DTS should be equal to last sample DTS + last sample duration (in PES timescale)\n mp4SampleDuration =\n stretchedLastFrame || !mp4SampleDuration\n ? averageSampleDuration\n : mp4SampleDuration;\n this.nextAvcDts = nextAvcDts = lastDTS + mp4SampleDuration;\n this.videoSampleDuration = mp4SampleDuration;\n this.isVideoContiguous = true;\n const moof = MP4.moof(\n track.sequenceNumber++,\n firstDTS,\n Object.assign({}, track, {\n samples: outputSamples,\n })\n );\n const type: SourceBufferName = 'video';\n const data = {\n data1: moof,\n data2: mdat,\n startPTS: minPTS / timeScale,\n endPTS: (maxPTS + mp4SampleDuration) / timeScale,\n startDTS: firstDTS / timeScale,\n endDTS: (nextAvcDts as number) / timeScale,\n type,\n hasAudio: false,\n hasVideo: true,\n nb: outputSamples.length,\n dropped: track.dropped,\n };\n track.samples = [];\n track.dropped = 0;\n return data;\n }\n\n remuxAudio(\n track: DemuxedAudioTrack,\n timeOffset: number,\n contiguous: boolean,\n accurateTimeOffset: boolean,\n videoTimeOffset?: number\n ): RemuxedTrack | undefined {\n const inputTimeScale: number = track.inputTimeScale;\n const mp4timeScale: number = track.samplerate\n ? track.samplerate\n : inputTimeScale;\n const scaleFactor: number = inputTimeScale / mp4timeScale;\n const mp4SampleDuration: number =\n track.segmentCodec === 'aac'\n ? AAC_SAMPLES_PER_FRAME\n : MPEG_AUDIO_SAMPLE_PER_FRAME;\n const inputSampleDuration: number = mp4SampleDuration * scaleFactor;\n const initPTS = this._initPTS as RationalTimestamp;\n const rawMPEG: boolean =\n track.segmentCodec === 'mp3' && this.typeSupported.mpeg;\n const outputSamples: Array<Mp4Sample> = [];\n const alignedWithVideo = videoTimeOffset !== undefined;\n\n let inputSamples: Array<AudioSample> = track.samples;\n let offset: number = rawMPEG ? 0 : 8;\n let nextAudioPts: number = this.nextAudioPts || -1;\n\n // window.audioSamples ? window.audioSamples.push(inputSamples.map(s => s.pts)) : (window.audioSamples = [inputSamples.map(s => s.pts)]);\n\n // for audio samples, also consider consecutive fragments as being contiguous (even if a level switch occurs),\n // for sake of clarity:\n // consecutive fragments are frags with\n // - less than 100ms gaps between new time offset (if accurate) and next expected PTS OR\n // - less than 20 audio frames distance\n // contiguous fragments are consecutive fragments from same quality level (same level, new SN = old SN + 1)\n // this helps ensuring audio continuity\n // and this also avoids audio glitches/cut when switching quality, or reporting wrong duration on first audio frame\n const timeOffsetMpegTS = timeOffset * inputTimeScale;\n const initTime = (initPTS.baseTime * inputTimeScale) / initPTS.timescale;\n this.isAudioContiguous = contiguous =\n contiguous ||\n ((inputSamples.length &&\n nextAudioPts > 0 &&\n ((accurateTimeOffset &&\n Math.abs(timeOffsetMpegTS - nextAudioPts) < 9000) ||\n Math.abs(\n normalizePts(inputSamples[0].pts - initTime, timeOffsetMpegTS) -\n nextAudioPts\n ) <\n 20 * inputSampleDuration)) as boolean);\n\n // compute normalized PTS\n inputSamples.forEach(function (sample) {\n sample.pts = normalizePts(sample.pts - initTime, timeOffsetMpegTS);\n });\n\n if (!contiguous || nextAudioPts < 0) {\n // filter out sample with negative PTS that are not playable anyway\n // if we don't remove these negative samples, they will shift all audio samples forward.\n // leading to audio overlap between current / next fragment\n inputSamples = inputSamples.filter((sample) => sample.pts >= 0);\n\n // in case all samples have negative PTS, and have been filtered out, return now\n if (!inputSamples.length) {\n return;\n }\n\n if (videoTimeOffset === 0) {\n // Set the start to 0 to match video so that start gaps larger than inputSampleDuration are filled with silence\n nextAudioPts = 0;\n } else if (accurateTimeOffset && !alignedWithVideo) {\n // When not seeking, not live, and LevelDetails.PTSKnown, use fragment start as predicted next audio PTS\n nextAudioPts = Math.max(0, timeOffsetMpegTS);\n } else {\n // if frags are not contiguous and if we cant trust time offset, let's use first sample PTS as next audio PTS\n nextAudioPts = inputSamples[0].pts;\n }\n }\n\n // If the audio track is missing samples, the frames seem to get \"left-shifted\" within the\n // resulting mp4 segment, causing sync issues and leaving gaps at the end of the audio segment.\n // In an effort to prevent this from happening, we inject frames here where there are gaps.\n // When possible, we inject a silent frame; when that's not possible, we duplicate the last\n // frame.\n\n if (track.segmentCodec === 'aac') {\n const maxAudioFramesDrift = this.config.maxAudioFramesDrift;\n for (let i = 0, nextPts = nextAudioPts; i < inputSamples.length; i++) {\n // First, let's see how far off this frame is from where we expect it to be\n const sample = inputSamples[i];\n const pts = sample.pts;\n const delta = pts - nextPts;\n const duration = Math.abs((1000 * delta) / inputTimeScale);\n\n // When remuxing with video, if we're overlapping by more than a duration, drop this sample to stay in sync\n if (\n delta <= -maxAudioFramesDrift * inputSampleDuration &&\n alignedWithVideo\n ) {\n if (i === 0) {\n logger.warn(\n `Audio frame @ ${(pts / inputTimeScale).toFixed(\n 3\n )}s overlaps nextAudioPts by ${Math.round(\n (1000 * delta) / inputTimeScale\n )} ms.`\n );\n this.nextAudioPts = nextAudioPts = nextPts = pts;\n }\n } // eslint-disable-line brace-style\n\n // Insert missing frames if:\n // 1: We're more than maxAudioFramesDrift frame away\n // 2: Not more than MAX_SILENT_FRAME_DURATION away\n // 3: currentTime (aka nextPtsNorm) is not 0\n // 4: remuxing with video (videoTimeOffset !== undefined)\n else if (\n delta >= maxAudioFramesDrift * inputSampleDuration &&\n duration < MAX_SILENT_FRAME_DURATION &&\n alignedWithVideo\n ) {\n let missing = Math.round(delta / inputSampleDuration);\n // Adjust nextPts so that silent samples are aligned with media pts. This will prevent media samples from\n // later being shifted if nextPts is based on timeOffset and delta is not a multiple of inputSampleDuration.\n nextPts = pts - missing * inputSampleDuration;\n if (nextPts < 0) {\n missing--;\n nextPts += inputSampleDuration;\n }\n if (i === 0) {\n this.nextAudioPts = nextAudioPts = nextPts;\n }\n logger.warn(\n `[mp4-remuxer]: Injecting ${missing} audio frame @ ${(\n nextPts / inputTimeScale\n ).toFixed(3)}s due to ${Math.round(\n (1000 * delta) / inputTimeScale\n )} ms gap.`\n );\n for (let j = 0; j < missing; j++) {\n const newStamp = Math.max(nextPts as number, 0);\n let fillFrame = AAC.getSilentFrame(\n track.manifestCodec || track.codec,\n track.channelCount\n );\n if (!fillFrame) {\n logger.log(\n '[mp4-remuxer]: Unable to get silent frame for given audio codec; duplicating last frame instead.'\n );\n fillFrame = sample.unit.subarray();\n }\n inputSamples.splice(i, 0, {\n unit: fillFrame,\n pts: newStamp,\n });\n nextPts += inputSampleDuration;\n i++;\n }\n }\n sample.pts = nextPts;\n nextPts += inputSampleDuration;\n }\n }\n let firstPTS: number | null = null;\n let lastPTS: number | null = null;\n let mdat: any;\n let mdatSize: number = 0;\n let sampleLength: number = inputSamples.length;\n while (sampleLength--) {\n mdatSize += inputSamples[sampleLength].unit.byteLength;\n }\n for (let j = 0, nbSamples = inputSamples.length; j < nbSamples; j++) {\n const audioSample = inputSamples[j];\n const unit = audioSample.unit;\n let pts = audioSample.pts;\n if (lastPTS !== null) {\n // If we have more than one sample, set the duration of the sample to the \"real\" duration; the PTS diff with\n // the previous sample\n const prevSample = outputSamples[j - 1];\n prevSample.duration = Math.round((pts - lastPTS) / scaleFactor);\n } else {\n if (contiguous && track.segmentCodec === 'aac') {\n // set PTS/DTS to expected PTS/DTS\n pts = nextAudioPts;\n }\n // remember first PTS of our audioSamples\n firstPTS = pts;\n if (mdatSize > 0) {\n /* concatenate the audio data and construct the mdat in place\n (need 8 more bytes to fill length and mdat type) */\n mdatSize += offset;\n try {\n mdat = new Uint8Array(mdatSize);\n } catch (err) {\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MUX_ERROR,\n details: ErrorDetails.REMUX_ALLOC_ERROR,\n fatal: false,\n error: err,\n bytes: mdatSize,\n reason: `fail allocating audio mdat ${mdatSize}`,\n });\n return;\n }\n if (!rawMPEG) {\n const view = new DataView(mdat.buffer);\n view.setUint32(0, mdatSize);\n mdat.set(MP4.types.mdat, 4);\n }\n } else {\n // no audio samples\n return;\n }\n }\n mdat.set(unit, offset);\n const unitLen = unit.byteLength;\n offset += unitLen;\n // Default the sample's duration to the computed mp4SampleDuration, which will either be 1024 for AAC or 1152 for MPEG\n // In the case that we have 1 sample, this will be the duration. If we have more than one sample, the duration\n // becomes the PTS diff with the previous sample\n outputSamples.push(new Mp4Sample(true, mp4SampleDuration, unitLen, 0));\n lastPTS = pts;\n }\n\n // We could end up with no audio samples if all input samples were overlapping with the previously remuxed ones\n const nbSamples = outputSamples.length;\n if (!nbSamples) {\n return;\n }\n\n // The next audio sample PTS should be equal to last sample PTS + duration\n const lastSample = outputSamples[outputSamples.length - 1];\n this.nextAudioPts = nextAudioPts =\n lastPTS! + scaleFactor * lastSample.duration;\n\n // Set the track samples from inputSamples to outputSamples before remuxing\n const moof = rawMPEG\n ? new Uint8Array(0)\n : MP4.moof(\n track.sequenceNumber++,\n firstPTS! / scaleFactor,\n Object.assign({}, track, { samples: outputSamples })\n );\n\n // Clear the track samples. This also clears the samples array in the demuxer, since the reference is shared\n track.samples = [];\n const start = firstPTS! / inputTimeScale;\n const end = nextAudioPts / inputTimeScale;\n const type: SourceBufferName = 'audio';\n const audioData = {\n data1: moof,\n data2: mdat,\n startPTS: start,\n endPTS: end,\n startDTS: start,\n endDTS: end,\n type,\n hasAudio: true,\n hasVideo: false,\n nb: nbSamples,\n };\n\n this.isAudioContiguous = true;\n return audioData;\n }\n\n remuxEmptyAudio(\n track: DemuxedAudioTrack,\n timeOffset: number,\n contiguous: boolean,\n videoData: Fragment\n ): RemuxedTrack | undefined {\n const inputTimeScale: number = track.inputTimeScale;\n const mp4timeScale: number = track.samplerate\n ? track.samplerate\n : inputTimeScale;\n const scaleFactor: number = inputTimeScale / mp4timeScale;\n const nextAudioPts: number | null = this.nextAudioPts;\n // sync with video's timestamp\n const initDTS = this._initDTS as RationalTimestamp;\n const init90kHz = (initDTS.baseTime * 90000) / initDTS.timescale;\n const startDTS: number =\n (nextAudioPts !== null\n ? nextAudioPts\n : videoData.startDTS * inputTimeScale) + init90kHz;\n const endDTS: number = videoData.endDTS * inputTimeScale + init90kHz;\n // one sample's duration value\n const frameDuration: number = scaleFactor * AAC_SAMPLES_PER_FRAME;\n // samples count of this segment's duration\n const nbSamples: number = Math.ceil((endDTS - startDTS) / frameDuration);\n // silent frame\n const silentFrame: Uint8Array | undefined = AAC.getSilentFrame(\n track.manifestCodec || track.codec,\n track.channelCount\n );\n\n logger.warn('[mp4-remuxer]: remux empty Audio');\n // Can't remux if we can't generate a silent frame...\n if (!silentFrame) {\n logger.trace(\n '[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec'\n );\n return;\n }\n\n const samples: Array<any> = [];\n for (let i = 0; i < nbSamples; i++) {\n const stamp = startDTS + i * frameDuration;\n samples.push({ unit: silentFrame, pts: stamp, dts: stamp });\n }\n track.samples = samples;\n\n return this.remuxAudio(track, timeOffset, contiguous, false);\n }\n}\n\nexport function normalizePts(value: number, reference: number | null): number {\n let offset;\n if (reference === null) {\n return value;\n }\n\n if (reference < value) {\n // - 2^33\n offset = -8589934592;\n } else {\n // + 2^33\n offset = 8589934592;\n }\n /* PTS is 33bit (from 0 to 2^33 -1)\n if diff between value and reference is bigger than half of the amplitude (2^32) then it means that\n PTS looping occured. fill the gap */\n while (Math.abs(value - reference) > 4294967296) {\n value += offset;\n }\n\n return value;\n}\n\nfunction findKeyframeIndex(samples: Array<AvcSample>): number {\n for (let i = 0; i < samples.length; i++) {\n if (samples[i].key) {\n return i;\n }\n }\n return -1;\n}\n\nexport function flushTextTrackMetadataCueSamples(\n track: DemuxedMetadataTrack,\n timeOffset: number,\n initPTS: RationalTimestamp,\n initDTS: RationalTimestamp\n): RemuxedMetadata | undefined {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n const inputTimeScale = track.inputTimeScale;\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting id3 pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts =\n normalizePts(\n sample.pts - (initPTS.baseTime * inputTimeScale) / initPTS.timescale,\n timeOffset * inputTimeScale\n ) / inputTimeScale;\n sample.dts =\n normalizePts(\n sample.dts - (initDTS.baseTime * inputTimeScale) / initDTS.timescale,\n timeOffset * inputTimeScale\n ) / inputTimeScale;\n }\n const samples = track.samples;\n track.samples = [];\n return {\n samples,\n };\n}\n\nexport function flushTextTrackUserdataCueSamples(\n track: DemuxedUserdataTrack,\n timeOffset: number,\n initPTS: RationalTimestamp\n): RemuxedUserdata | undefined {\n const length = track.samples.length;\n if (!length) {\n return;\n }\n\n const inputTimeScale = track.inputTimeScale;\n for (let index = 0; index < length; index++) {\n const sample = track.samples[index];\n // setting text pts, dts to relative time\n // using this._initPTS and this._initDTS to calculate relative time\n sample.pts =\n normalizePts(\n sample.pts - (initPTS.baseTime * inputTimeScale) / initPTS.timescale,\n timeOffset * inputTimeScale\n ) / inputTimeScale;\n }\n track.samples.sort((a, b) => a.pts - b.pts);\n const samples = track.samples;\n track.samples = [];\n return {\n samples,\n };\n}\n\nclass Mp4Sample {\n public size: number;\n public duration: number;\n public cts: number;\n public flags: Mp4SampleFlags;\n\n constructor(\n isKeyframe: boolean,\n duration: number,\n size: number,\n cts: number\n ) {\n this.duration = duration;\n this.size = size;\n this.cts = cts;\n this.flags = new Mp4SampleFlags(isKeyframe);\n }\n}\n\nclass Mp4SampleFlags {\n public isLeading: 0 = 0;\n public isDependedOn: 0 = 0;\n public hasRedundancy: 0 = 0;\n public degradPrio: 0 = 0;\n public dependsOn: 1 | 2 = 1;\n public isNonSync: 0 | 1 = 1;\n\n constructor(isKeyframe) {\n this.dependsOn = isKeyframe ? 2 : 1;\n this.isNonSync = isKeyframe ? 0 : 1;\n }\n}\n","import type { HlsEventEmitter } from '../events';\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport Decrypter from '../crypt/decrypter';\nimport AACDemuxer from '../demux/aacdemuxer';\nimport MP4Demuxer from '../demux/mp4demuxer';\nimport TSDemuxer, { TypeSupported } from '../demux/tsdemuxer';\nimport MP3Demuxer from '../demux/mp3demuxer';\nimport MP4Remuxer from '../remux/mp4-remuxer';\nimport PassThroughRemuxer from '../remux/passthrough-remuxer';\nimport { logger } from '../utils/logger';\nimport type { Demuxer, DemuxerResult, KeyData } from '../types/demuxer';\nimport type { Remuxer } from '../types/remuxer';\nimport type { TransmuxerResult, ChunkMetadata } from '../types/transmuxer';\nimport type { HlsConfig } from '../config';\nimport type { DecryptData } from '../loader/level-key';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\nlet now;\n// performance.now() not available on WebWorker, at least on Safari Desktop\ntry {\n now = self.performance.now.bind(self.performance);\n} catch (err) {\n logger.debug('Unable to use Performance API on this environment');\n now = typeof self !== 'undefined' && self.Date.now;\n}\n\ntype MuxConfig =\n | { demux: typeof MP4Demuxer; remux: typeof PassThroughRemuxer }\n | { demux: typeof TSDemuxer; remux: typeof MP4Remuxer }\n | { demux: typeof AACDemuxer; remux: typeof MP4Remuxer }\n | { demux: typeof MP3Demuxer; remux: typeof MP4Remuxer };\n\nconst muxConfig: MuxConfig[] = [\n { demux: MP4Demuxer, remux: PassThroughRemuxer },\n { demux: TSDemuxer, remux: MP4Remuxer },\n { demux: AACDemuxer, remux: MP4Remuxer },\n { demux: MP3Demuxer, remux: MP4Remuxer },\n];\n\nexport default class Transmuxer {\n public async: boolean = false;\n private observer: HlsEventEmitter;\n private typeSupported: TypeSupported;\n private config: HlsConfig;\n private vendor: string;\n private id: PlaylistLevelType;\n private demuxer?: Demuxer;\n private remuxer?: Remuxer;\n private decrypter?: Decrypter;\n private probe!: Function;\n private decryptionPromise: Promise<TransmuxerResult> | null = null;\n private transmuxConfig!: TransmuxConfig;\n private currentTransmuxState!: TransmuxState;\n\n constructor(\n observer: HlsEventEmitter,\n typeSupported: TypeSupported,\n config: HlsConfig,\n vendor: string,\n id: PlaylistLevelType\n ) {\n this.observer = observer;\n this.typeSupported = typeSupported;\n this.config = config;\n this.vendor = vendor;\n this.id = id;\n }\n\n configure(transmuxConfig: TransmuxConfig) {\n this.transmuxConfig = transmuxConfig;\n if (this.decrypter) {\n this.decrypter.reset();\n }\n }\n\n push(\n data: ArrayBuffer,\n decryptdata: DecryptData | null,\n chunkMeta: ChunkMetadata,\n state?: TransmuxState\n ): TransmuxerResult | Promise<TransmuxerResult> {\n const stats = chunkMeta.transmuxing;\n stats.executeStart = now();\n\n let uintData: Uint8Array = new Uint8Array(data);\n const { currentTransmuxState, transmuxConfig } = this;\n if (state) {\n this.currentTransmuxState = state;\n }\n\n const {\n contiguous,\n discontinuity,\n trackSwitch,\n accurateTimeOffset,\n timeOffset,\n initSegmentChange,\n } = state || currentTransmuxState;\n const {\n audioCodec,\n videoCodec,\n defaultInitPts,\n duration,\n initSegmentData,\n } = transmuxConfig;\n\n const keyData = getEncryptionType(uintData, decryptdata);\n if (keyData && keyData.method === 'AES-128') {\n const decrypter = this.getDecrypter();\n // Software decryption is synchronous; webCrypto is not\n if (decrypter.isSync()) {\n // Software decryption is progressive. Progressive decryption may not return a result on each call. Any cached\n // data is handled in the flush() call\n let decryptedData = decrypter.softwareDecrypt(\n uintData,\n keyData.key.buffer,\n keyData.iv.buffer\n );\n // For Low-Latency HLS Parts, decrypt in place, since part parsing is expected on push progress\n const loadingParts = chunkMeta.part > -1;\n if (loadingParts) {\n decryptedData = decrypter.flush();\n }\n if (!decryptedData) {\n stats.executeEnd = now();\n return emptyResult(chunkMeta);\n }\n uintData = new Uint8Array(decryptedData);\n } else {\n this.decryptionPromise = decrypter\n .webCryptoDecrypt(uintData, keyData.key.buffer, keyData.iv.buffer)\n .then((decryptedData): TransmuxerResult => {\n // Calling push here is important; if flush() is called while this is still resolving, this ensures that\n // the decrypted data has been transmuxed\n const result = this.push(\n decryptedData,\n null,\n chunkMeta\n ) as TransmuxerResult;\n this.decryptionPromise = null;\n return result;\n });\n return this.decryptionPromise!;\n }\n }\n\n const resetMuxers = this.needsProbing(discontinuity, trackSwitch);\n if (resetMuxers) {\n const error = this.configureTransmuxer(uintData);\n if (error) {\n logger.warn(`[transmuxer] ${error.message}`);\n this.observer.emit(Events.ERROR, Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n fatal: false,\n error,\n reason: error.message,\n });\n stats.executeEnd = now();\n return emptyResult(chunkMeta);\n }\n }\n\n if (discontinuity || trackSwitch || initSegmentChange || resetMuxers) {\n this.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n duration,\n decryptdata\n );\n }\n\n if (discontinuity || initSegmentChange || resetMuxers) {\n this.resetInitialTimestamp(defaultInitPts);\n }\n\n if (!contiguous) {\n this.resetContiguity();\n }\n\n const result = this.transmux(\n uintData,\n keyData,\n timeOffset,\n accurateTimeOffset,\n chunkMeta\n );\n const currentState = this.currentTransmuxState;\n\n currentState.contiguous = true;\n currentState.discontinuity = false;\n currentState.trackSwitch = false;\n\n stats.executeEnd = now();\n return result;\n }\n\n // Due to data caching, flush calls can produce more than one TransmuxerResult (hence the Array type)\n flush(\n chunkMeta: ChunkMetadata\n ): TransmuxerResult[] | Promise<TransmuxerResult[]> {\n const stats = chunkMeta.transmuxing;\n stats.executeStart = now();\n\n const { decrypter, currentTransmuxState, decryptionPromise } = this;\n\n if (decryptionPromise) {\n // Upon resolution, the decryption promise calls push() and returns its TransmuxerResult up the stack. Therefore\n // only flushing is required for async decryption\n return decryptionPromise.then(() => {\n return this.flush(chunkMeta);\n });\n }\n\n const transmuxResults: TransmuxerResult[] = [];\n const { timeOffset } = currentTransmuxState;\n if (decrypter) {\n // The decrypter may have data cached, which needs to be demuxed. In this case we'll have two TransmuxResults\n // This happens in the case that we receive only 1 push call for a segment (either for non-progressive downloads,\n // or for progressive downloads with small segments)\n const decryptedData = decrypter.flush();\n if (decryptedData) {\n // Push always returns a TransmuxerResult if decryptdata is null\n transmuxResults.push(\n this.push(decryptedData, null, chunkMeta) as TransmuxerResult\n );\n }\n }\n\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n // If probing failed, then Hls.js has been given content its not able to handle\n stats.executeEnd = now();\n return [emptyResult(chunkMeta)];\n }\n\n const demuxResultOrPromise = demuxer.flush(timeOffset);\n if (isPromise(demuxResultOrPromise)) {\n // Decrypt final SAMPLE-AES samples\n return demuxResultOrPromise.then((demuxResult) => {\n this.flushRemux(transmuxResults, demuxResult, chunkMeta);\n return transmuxResults;\n });\n }\n\n this.flushRemux(transmuxResults, demuxResultOrPromise, chunkMeta);\n return transmuxResults;\n }\n\n private flushRemux(\n transmuxResults: TransmuxerResult[],\n demuxResult: DemuxerResult,\n chunkMeta: ChunkMetadata\n ) {\n const { audioTrack, videoTrack, id3Track, textTrack } = demuxResult;\n const { accurateTimeOffset, timeOffset } = this.currentTransmuxState;\n logger.log(\n `[transmuxer.ts]: Flushed fragment ${chunkMeta.sn}${\n chunkMeta.part > -1 ? ' p: ' + chunkMeta.part : ''\n } of level ${chunkMeta.level}`\n );\n const remuxResult = this.remuxer!.remux(\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n timeOffset,\n accurateTimeOffset,\n true,\n this.id\n );\n transmuxResults.push({\n remuxResult,\n chunkMeta,\n });\n\n chunkMeta.transmuxing.executeEnd = now();\n }\n\n resetInitialTimestamp(defaultInitPts: RationalTimestamp | null) {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetTimeStamp(defaultInitPts);\n remuxer.resetTimeStamp(defaultInitPts);\n }\n\n resetContiguity() {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetContiguity();\n remuxer.resetNextTimestamp();\n }\n\n resetInitSegment(\n initSegmentData: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n trackDuration: number,\n decryptdata: DecryptData | null\n ) {\n const { demuxer, remuxer } = this;\n if (!demuxer || !remuxer) {\n return;\n }\n demuxer.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n trackDuration\n );\n remuxer.resetInitSegment(\n initSegmentData,\n audioCodec,\n videoCodec,\n decryptdata\n );\n }\n\n destroy(): void {\n if (this.demuxer) {\n this.demuxer.destroy();\n this.demuxer = undefined;\n }\n if (this.remuxer) {\n this.remuxer.destroy();\n this.remuxer = undefined;\n }\n }\n\n private transmux(\n data: Uint8Array,\n keyData: KeyData | null,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata\n ): TransmuxerResult | Promise<TransmuxerResult> {\n let result: TransmuxerResult | Promise<TransmuxerResult>;\n if (keyData && keyData.method === 'SAMPLE-AES') {\n result = this.transmuxSampleAes(\n data,\n keyData,\n timeOffset,\n accurateTimeOffset,\n chunkMeta\n );\n } else {\n result = this.transmuxUnencrypted(\n data,\n timeOffset,\n accurateTimeOffset,\n chunkMeta\n );\n }\n return result;\n }\n\n private transmuxUnencrypted(\n data: Uint8Array,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata\n ): TransmuxerResult {\n const { audioTrack, videoTrack, id3Track, textTrack } = (\n this.demuxer as Demuxer\n ).demux(data, timeOffset, false, !this.config.progressive);\n const remuxResult = this.remuxer!.remux(\n audioTrack,\n videoTrack,\n id3Track,\n textTrack,\n timeOffset,\n accurateTimeOffset,\n false,\n this.id\n );\n return {\n remuxResult,\n chunkMeta,\n };\n }\n\n private transmuxSampleAes(\n data: Uint8Array,\n decryptData: KeyData,\n timeOffset: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata\n ): Promise<TransmuxerResult> {\n return (this.demuxer as Demuxer)\n .demuxSampleAes(data, decryptData, timeOffset)\n .then((demuxResult) => {\n const remuxResult = this.remuxer!.remux(\n demuxResult.audioTrack,\n demuxResult.videoTrack,\n demuxResult.id3Track,\n demuxResult.textTrack,\n timeOffset,\n accurateTimeOffset,\n false,\n this.id\n );\n return {\n remuxResult,\n chunkMeta,\n };\n });\n }\n\n private configureTransmuxer(data: Uint8Array): void | Error {\n const { config, observer, typeSupported, vendor } = this;\n // probe for content type\n let mux;\n for (let i = 0, len = muxConfig.length; i < len; i++) {\n if (muxConfig[i].demux.probe(data)) {\n mux = muxConfig[i];\n break;\n }\n }\n if (!mux) {\n return new Error('Failed to find demuxer by probing fragment data');\n }\n // so let's check that current remuxer and demuxer are still valid\n const demuxer = this.demuxer;\n const remuxer = this.remuxer;\n const Remuxer: MuxConfig['remux'] = mux.remux;\n const Demuxer: MuxConfig['demux'] = mux.demux;\n if (!remuxer || !(remuxer instanceof Remuxer)) {\n this.remuxer = new Remuxer(observer, config, typeSupported, vendor);\n }\n if (!demuxer || !(demuxer instanceof Demuxer)) {\n this.demuxer = new Demuxer(observer, config, typeSupported);\n this.probe = Demuxer.probe;\n }\n }\n\n private needsProbing(discontinuity: boolean, trackSwitch: boolean): boolean {\n // in case of continuity change, or track switch\n // we might switch from content type (AAC container to TS container, or TS to fmp4 for example)\n return !this.demuxer || !this.remuxer || discontinuity || trackSwitch;\n }\n\n private getDecrypter(): Decrypter {\n let decrypter = this.decrypter;\n if (!decrypter) {\n decrypter = this.decrypter = new Decrypter(this.config);\n }\n return decrypter;\n }\n}\n\nfunction getEncryptionType(\n data: Uint8Array,\n decryptData: DecryptData | null\n): KeyData | null {\n let encryptionType: KeyData | null = null;\n if (\n data.byteLength > 0 &&\n decryptData != null &&\n decryptData.key != null &&\n decryptData.iv !== null &&\n decryptData.method != null\n ) {\n encryptionType = decryptData as KeyData;\n }\n return encryptionType;\n}\n\nconst emptyResult = (chunkMeta): TransmuxerResult => ({\n remuxResult: {},\n chunkMeta,\n});\n\nexport function isPromise<T>(p: Promise<T> | any): p is Promise<T> {\n return 'then' in p && p.then instanceof Function;\n}\n\nexport class TransmuxConfig {\n public audioCodec?: string;\n public videoCodec?: string;\n public initSegmentData?: Uint8Array;\n public duration: number;\n public defaultInitPts: RationalTimestamp | null;\n\n constructor(\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n initSegmentData: Uint8Array | undefined,\n duration: number,\n defaultInitPts?: RationalTimestamp\n ) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.initSegmentData = initSegmentData;\n this.duration = duration;\n this.defaultInitPts = defaultInitPts || null;\n }\n}\n\nexport class TransmuxState {\n public discontinuity: boolean;\n public contiguous: boolean;\n public accurateTimeOffset: boolean;\n public trackSwitch: boolean;\n public timeOffset: number;\n public initSegmentChange: boolean;\n\n constructor(\n discontinuity: boolean,\n contiguous: boolean,\n accurateTimeOffset: boolean,\n trackSwitch: boolean,\n timeOffset: number,\n initSegmentChange: boolean\n ) {\n this.discontinuity = discontinuity;\n this.contiguous = contiguous;\n this.accurateTimeOffset = accurateTimeOffset;\n this.trackSwitch = trackSwitch;\n this.timeOffset = timeOffset;\n this.initSegmentChange = initSegmentChange;\n }\n}\n","import {\n flushTextTrackMetadataCueSamples,\n flushTextTrackUserdataCueSamples,\n} from './mp4-remuxer';\nimport {\n InitData,\n InitDataTrack,\n patchEncyptionData,\n} from '../utils/mp4-tools';\nimport {\n getDuration,\n getStartDTS,\n offsetStartDTS,\n parseInitSegment,\n} from '../utils/mp4-tools';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport { logger } from '../utils/logger';\nimport type { TrackSet } from '../types/track';\nimport type {\n InitSegmentData,\n RemuxedTrack,\n Remuxer,\n RemuxerResult,\n} from '../types/remuxer';\nimport type {\n DemuxedAudioTrack,\n DemuxedMetadataTrack,\n DemuxedUserdataTrack,\n PassthroughTrack,\n} from '../types/demuxer';\nimport type { DecryptData } from '../loader/level-key';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\nclass PassThroughRemuxer implements Remuxer {\n private emitInitSegment: boolean = false;\n private audioCodec?: string;\n private videoCodec?: string;\n private initData?: InitData;\n private initPTS: RationalTimestamp | null = null;\n private initTracks?: TrackSet;\n private lastEndTime: number | null = null;\n\n public destroy() {}\n\n public resetTimeStamp(defaultInitPTS: RationalTimestamp | null) {\n this.initPTS = defaultInitPTS;\n this.lastEndTime = null;\n }\n\n public resetNextTimestamp() {\n this.lastEndTime = null;\n }\n\n public resetInitSegment(\n initSegment: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n decryptdata: DecryptData | null\n ) {\n this.audioCodec = audioCodec;\n this.videoCodec = videoCodec;\n this.generateInitSegment(patchEncyptionData(initSegment, decryptdata));\n this.emitInitSegment = true;\n }\n\n private generateInitSegment(initSegment: Uint8Array | undefined): void {\n let { audioCodec, videoCodec } = this;\n if (!initSegment?.byteLength) {\n this.initTracks = undefined;\n this.initData = undefined;\n return;\n }\n const initData = (this.initData = parseInitSegment(initSegment));\n\n // Get codec from initSegment or fallback to default\n if (!audioCodec) {\n audioCodec = getParsedTrackCodec(\n initData.audio,\n ElementaryStreamTypes.AUDIO\n );\n }\n\n if (!videoCodec) {\n videoCodec = getParsedTrackCodec(\n initData.video,\n ElementaryStreamTypes.VIDEO\n );\n }\n\n const tracks: TrackSet = {};\n if (initData.audio && initData.video) {\n tracks.audiovideo = {\n container: 'video/mp4',\n codec: audioCodec + ',' + videoCodec,\n initSegment,\n id: 'main',\n };\n } else if (initData.audio) {\n tracks.audio = {\n container: 'audio/mp4',\n codec: audioCodec,\n initSegment,\n id: 'audio',\n };\n } else if (initData.video) {\n tracks.video = {\n container: 'video/mp4',\n codec: videoCodec,\n initSegment,\n id: 'main',\n };\n } else {\n logger.warn(\n '[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes.'\n );\n }\n this.initTracks = tracks;\n }\n\n public remux(\n audioTrack: DemuxedAudioTrack,\n videoTrack: PassthroughTrack,\n id3Track: DemuxedMetadataTrack,\n textTrack: DemuxedUserdataTrack,\n timeOffset: number,\n accurateTimeOffset: boolean\n ): RemuxerResult {\n let { initPTS, lastEndTime } = this;\n const result: RemuxerResult = {\n audio: undefined,\n video: undefined,\n text: textTrack,\n id3: id3Track,\n initSegment: undefined,\n };\n\n // If we haven't yet set a lastEndDTS, or it was reset, set it to the provided timeOffset. We want to use the\n // lastEndDTS over timeOffset whenever possible; during progressive playback, the media source will not update\n // the media duration (which is what timeOffset is provided as) before we need to process the next chunk.\n if (!Number.isFinite(lastEndTime!)) {\n lastEndTime = this.lastEndTime = timeOffset || 0;\n }\n\n // The binary segment data is added to the videoTrack in the mp4demuxer. We don't check to see if the data is only\n // audio or video (or both); adding it to video was an arbitrary choice.\n const data = videoTrack.samples;\n if (!data?.length) {\n return result;\n }\n\n const initSegment: InitSegmentData = {\n initPTS: undefined,\n timescale: 1,\n };\n let initData = this.initData;\n if (!initData?.length) {\n this.generateInitSegment(data);\n initData = this.initData;\n }\n if (!initData?.length) {\n // We can't remux if the initSegment could not be generated\n logger.warn('[passthrough-remuxer.ts]: Failed to generate initSegment.');\n return result;\n }\n if (this.emitInitSegment) {\n initSegment.tracks = this.initTracks as TrackSet;\n this.emitInitSegment = false;\n }\n\n const duration = getDuration(data, initData);\n const startDTS = getStartDTS(initData, data);\n const decodeTime = startDTS === null ? timeOffset : startDTS;\n if (\n isInvalidInitPts(initPTS, decodeTime, timeOffset, duration) ||\n (initSegment.timescale !== initPTS.timescale && accurateTimeOffset)\n ) {\n initSegment.initPTS = decodeTime - timeOffset;\n if (initPTS && initPTS.timescale === 1) {\n logger.warn(\n `Adjusting initPTS by ${initSegment.initPTS - initPTS.baseTime}`\n );\n }\n this.initPTS = initPTS = {\n baseTime: initSegment.initPTS,\n timescale: 1,\n };\n }\n\n const startTime = audioTrack\n ? decodeTime - initPTS.baseTime / initPTS.timescale\n : (lastEndTime as number);\n const endTime = startTime + duration;\n offsetStartDTS(initData, data, initPTS.baseTime / initPTS.timescale);\n\n if (duration > 0) {\n this.lastEndTime = endTime;\n } else {\n logger.warn('Duration parsed from mp4 should be greater than zero');\n this.resetNextTimestamp();\n }\n\n const hasAudio = !!initData.audio;\n const hasVideo = !!initData.video;\n\n let type: any = '';\n if (hasAudio) {\n type += 'audio';\n }\n\n if (hasVideo) {\n type += 'video';\n }\n\n const track: RemuxedTrack = {\n data1: data,\n startPTS: startTime,\n startDTS: startTime,\n endPTS: endTime,\n endDTS: endTime,\n type,\n hasAudio,\n hasVideo,\n nb: 1,\n dropped: 0,\n };\n\n result.audio = track.type === 'audio' ? track : undefined;\n result.video = track.type !== 'audio' ? track : undefined;\n result.initSegment = initSegment;\n result.id3 = flushTextTrackMetadataCueSamples(\n id3Track,\n timeOffset,\n initPTS,\n initPTS\n );\n\n if (textTrack.samples.length) {\n result.text = flushTextTrackUserdataCueSamples(\n textTrack,\n timeOffset,\n initPTS\n );\n }\n\n return result;\n }\n}\n\nfunction isInvalidInitPts(\n initPTS: RationalTimestamp | null,\n startDTS: number,\n timeOffset: number,\n duration: number\n): initPTS is null {\n if (initPTS === null) {\n return true;\n }\n // InitPTS is invalid when distance from program would be more than segment duration or a minimum of one second\n const minDuration = Math.max(duration, 1);\n const startTime = startDTS - initPTS.baseTime / initPTS.timescale;\n return Math.abs(startTime - timeOffset) > minDuration;\n}\n\nfunction getParsedTrackCodec(\n track: InitDataTrack | undefined,\n type: ElementaryStreamTypes.AUDIO | ElementaryStreamTypes.VIDEO\n): string {\n const parsedCodec = track?.codec;\n if (parsedCodec && parsedCodec.length > 4) {\n return parsedCodec;\n }\n // Since mp4-tools cannot parse full codec string (see 'TODO: Parse codec details'... in mp4-tools)\n // Provide defaults based on codec type\n // This allows for some playback of some fmp4 playlists without CODECS defined in manifest\n if (parsedCodec === 'hvc1' || parsedCodec === 'hev1') {\n return 'hvc1.1.6.L120.90';\n }\n if (parsedCodec === 'av01') {\n return 'av01.0.04M.08';\n }\n if (parsedCodec === 'avc1' || type === ElementaryStreamTypes.VIDEO) {\n return 'avc1.42e01e';\n }\n return 'mp4a.40.5';\n}\nexport default PassThroughRemuxer;\n","'use strict';\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n * Constructor to create a storage for our `EE` objects.\n * An `Events` instance is a plain object whose properties are event names.\n *\n * @constructor\n * @private\n */\nfunction Events() {}\n\n//\n// We try to not inherit from `Object.prototype`. In some engines creating an\n// instance in this way is faster than calling `Object.create(null)` directly.\n// If `Object.create(null)` is not supported we prefix the event names with a\n// character to make sure that the built-in object properties are not\n// overridden or used as an attack vector.\n//\nif (Object.create) {\n Events.prototype = Object.create(null);\n\n //\n // This hack is needed because the `__proto__` property is still inherited in\n // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.\n //\n if (!new Events().__proto__) prefix = false;\n}\n\n/**\n * Representation of a single event listener.\n *\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} [once=false] Specify if the listener is a one-time listener.\n * @constructor\n * @private\n */\nfunction EE(fn, context, once) {\n this.fn = fn;\n this.context = context;\n this.once = once || false;\n}\n\n/**\n * Add a listener for a given event.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} context The context to invoke the listener with.\n * @param {Boolean} once Specify if the listener is a one-time listener.\n * @returns {EventEmitter}\n * @private\n */\nfunction addListener(emitter, event, fn, context, once) {\n if (typeof fn !== 'function') {\n throw new TypeError('The listener must be a function');\n }\n\n var listener = new EE(fn, context || emitter, once)\n , evt = prefix ? prefix + event : event;\n\n if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++;\n else if (!emitter._events[evt].fn) emitter._events[evt].push(listener);\n else emitter._events[evt] = [emitter._events[evt], listener];\n\n return emitter;\n}\n\n/**\n * Clear event by name.\n *\n * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.\n * @param {(String|Symbol)} evt The Event name.\n * @private\n */\nfunction clearEvent(emitter, evt) {\n if (--emitter._eventsCount === 0) emitter._events = new Events();\n else delete emitter._events[evt];\n}\n\n/**\n * Minimal `EventEmitter` interface that is molded against the Node.js\n * `EventEmitter` interface.\n *\n * @constructor\n * @public\n */\nfunction EventEmitter() {\n this._events = new Events();\n this._eventsCount = 0;\n}\n\n/**\n * Return an array listing the events for which the emitter has registered\n * listeners.\n *\n * @returns {Array}\n * @public\n */\nEventEmitter.prototype.eventNames = function eventNames() {\n var names = []\n , events\n , name;\n\n if (this._eventsCount === 0) return names;\n\n for (name in (events = this._events)) {\n if (has.call(events, name)) names.push(prefix ? name.slice(1) : name);\n }\n\n if (Object.getOwnPropertySymbols) {\n return names.concat(Object.getOwnPropertySymbols(events));\n }\n\n return names;\n};\n\n/**\n * Return the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Array} The registered listeners.\n * @public\n */\nEventEmitter.prototype.listeners = function listeners(event) {\n var evt = prefix ? prefix + event : event\n , handlers = this._events[evt];\n\n if (!handlers) return [];\n if (handlers.fn) return [handlers.fn];\n\n for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {\n ee[i] = handlers[i].fn;\n }\n\n return ee;\n};\n\n/**\n * Return the number of listeners listening to a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Number} The number of listeners.\n * @public\n */\nEventEmitter.prototype.listenerCount = function listenerCount(event) {\n var evt = prefix ? prefix + event : event\n , listeners = this._events[evt];\n\n if (!listeners) return 0;\n if (listeners.fn) return 1;\n return listeners.length;\n};\n\n/**\n * Calls each of the listeners registered for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @returns {Boolean} `true` if the event had listeners, else `false`.\n * @public\n */\nEventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return false;\n\n var listeners = this._events[evt]\n , len = arguments.length\n , args\n , i;\n\n if (listeners.fn) {\n if (listeners.once) this.removeListener(event, listeners.fn, undefined, true);\n\n switch (len) {\n case 1: return listeners.fn.call(listeners.context), true;\n case 2: return listeners.fn.call(listeners.context, a1), true;\n case 3: return listeners.fn.call(listeners.context, a1, a2), true;\n case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;\n case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;\n case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;\n }\n\n for (i = 1, args = new Array(len -1); i < len; i++) {\n args[i - 1] = arguments[i];\n }\n\n listeners.fn.apply(listeners.context, args);\n } else {\n var length = listeners.length\n , j;\n\n for (i = 0; i < length; i++) {\n if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true);\n\n switch (len) {\n case 1: listeners[i].fn.call(listeners[i].context); break;\n case 2: listeners[i].fn.call(listeners[i].context, a1); break;\n case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;\n case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;\n default:\n if (!args) for (j = 1, args = new Array(len -1); j < len; j++) {\n args[j - 1] = arguments[j];\n }\n\n listeners[i].fn.apply(listeners[i].context, args);\n }\n }\n }\n\n return true;\n};\n\n/**\n * Add a listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.on = function on(event, fn, context) {\n return addListener(this, event, fn, context, false);\n};\n\n/**\n * Add a one-time listener for a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn The listener function.\n * @param {*} [context=this] The context to invoke the listener with.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.once = function once(event, fn, context) {\n return addListener(this, event, fn, context, true);\n};\n\n/**\n * Remove the listeners of a given event.\n *\n * @param {(String|Symbol)} event The event name.\n * @param {Function} fn Only remove the listeners that match this function.\n * @param {*} context Only remove the listeners that have this context.\n * @param {Boolean} once Only remove one-time listeners.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {\n var evt = prefix ? prefix + event : event;\n\n if (!this._events[evt]) return this;\n if (!fn) {\n clearEvent(this, evt);\n return this;\n }\n\n var listeners = this._events[evt];\n\n if (listeners.fn) {\n if (\n listeners.fn === fn &&\n (!once || listeners.once) &&\n (!context || listeners.context === context)\n ) {\n clearEvent(this, evt);\n }\n } else {\n for (var i = 0, events = [], length = listeners.length; i < length; i++) {\n if (\n listeners[i].fn !== fn ||\n (once && !listeners[i].once) ||\n (context && listeners[i].context !== context)\n ) {\n events.push(listeners[i]);\n }\n }\n\n //\n // Reset the array, or remove it completely if we have no more listeners.\n //\n if (events.length) this._events[evt] = events.length === 1 ? events[0] : events;\n else clearEvent(this, evt);\n }\n\n return this;\n};\n\n/**\n * Remove all listeners, or those of the specified event.\n *\n * @param {(String|Symbol)} [event] The event name.\n * @returns {EventEmitter} `this`.\n * @public\n */\nEventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {\n var evt;\n\n if (event) {\n evt = prefix ? prefix + event : event;\n if (this._events[evt]) clearEvent(this, evt);\n } else {\n this._events = new Events();\n this._eventsCount = 0;\n }\n\n return this;\n};\n\n//\n// Alias methods names because people roll like that.\n//\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\nEventEmitter.prototype.addListener = EventEmitter.prototype.on;\n\n//\n// Expose the prefix.\n//\nEventEmitter.prefixed = prefix;\n\n//\n// Allow `EventEmitter` to be imported as module namespace.\n//\nEventEmitter.EventEmitter = EventEmitter;\n\n//\n// Expose the module.\n//\nif ('undefined' !== typeof module) {\n module.exports = EventEmitter;\n}\n","import Transmuxer, { isPromise } from '../demux/transmuxer';\nimport { Events } from '../events';\nimport { ILogFunction, enableLogs, logger } from '../utils/logger';\nimport { EventEmitter } from 'eventemitter3';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport type { RemuxedTrack, RemuxerResult } from '../types/remuxer';\nimport type { TransmuxerResult, ChunkMetadata } from '../types/transmuxer';\n\nif (typeof __IN_WORKER__ !== 'undefined' && __IN_WORKER__) {\n startWorker(self);\n}\n\nfunction startWorker(self) {\n const observer = new EventEmitter();\n const forwardMessage = (ev, data) => {\n self.postMessage({ event: ev, data: data });\n };\n\n // forward events to main thread\n observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n observer.on(Events.ERROR, forwardMessage);\n\n // forward logger events to main thread\n const forwardWorkerLogs = () => {\n for (const logFn in logger) {\n const func: ILogFunction = (message?) => {\n forwardMessage('workerLog', {\n logType: logFn,\n message,\n });\n };\n\n logger[logFn] = func;\n }\n };\n\n self.addEventListener('message', (ev) => {\n const data = ev.data;\n switch (data.cmd) {\n case 'init': {\n const config = JSON.parse(data.config);\n self.transmuxer = new Transmuxer(\n observer,\n data.typeSupported,\n config,\n data.vendor,\n data.id\n );\n enableLogs(config.debug, data.id);\n forwardWorkerLogs();\n forwardMessage('init', null);\n break;\n }\n case 'configure': {\n self.transmuxer.configure(data.config);\n break;\n }\n case 'demux': {\n const transmuxResult: TransmuxerResult | Promise<TransmuxerResult> =\n self.transmuxer.push(\n data.data,\n data.decryptdata,\n data.chunkMeta,\n data.state\n );\n if (isPromise(transmuxResult)) {\n self.transmuxer.async = true;\n transmuxResult\n .then((data) => {\n emitTransmuxComplete(self, data);\n })\n .catch((error) => {\n forwardMessage(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta: data.chunkMeta,\n fatal: false,\n error,\n err: error,\n reason: `transmuxer-worker push error`,\n });\n });\n } else {\n self.transmuxer.async = false;\n emitTransmuxComplete(self, transmuxResult);\n }\n break;\n }\n case 'flush': {\n const id = data.chunkMeta;\n let transmuxResult = self.transmuxer.flush(id);\n const asyncFlush = isPromise(transmuxResult);\n if (asyncFlush || self.transmuxer.async) {\n if (!isPromise(transmuxResult)) {\n transmuxResult = Promise.resolve(transmuxResult);\n }\n transmuxResult\n .then((results: Array<TransmuxerResult>) => {\n handleFlushResult(self, results as Array<TransmuxerResult>, id);\n })\n .catch((error) => {\n forwardMessage(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta: data.chunkMeta,\n fatal: false,\n error,\n err: error,\n reason: `transmuxer-worker flush error`,\n });\n });\n } else {\n handleFlushResult(\n self,\n transmuxResult as Array<TransmuxerResult>,\n id\n );\n }\n break;\n }\n default:\n break;\n }\n });\n}\n\nfunction emitTransmuxComplete(\n self: any,\n transmuxResult: TransmuxerResult\n): boolean {\n if (isEmptyResult(transmuxResult.remuxResult)) {\n return false;\n }\n const transferable: Array<ArrayBuffer> = [];\n const { audio, video } = transmuxResult.remuxResult;\n if (audio) {\n addToTransferable(transferable, audio);\n }\n if (video) {\n addToTransferable(transferable, video);\n }\n self.postMessage(\n { event: 'transmuxComplete', data: transmuxResult },\n transferable\n );\n return true;\n}\n\n// Converts data to a transferable object https://developers.google.com/web/updates/2011/12/Transferable-Objects-Lightning-Fast)\n// in order to minimize message passing overhead\nfunction addToTransferable(\n transferable: Array<ArrayBuffer>,\n track: RemuxedTrack\n) {\n if (track.data1) {\n transferable.push(track.data1.buffer);\n }\n if (track.data2) {\n transferable.push(track.data2.buffer);\n }\n}\n\nfunction handleFlushResult(\n self: any,\n results: Array<TransmuxerResult>,\n chunkMeta: ChunkMetadata\n) {\n const parsed = results.reduce(\n (parsed, result) => emitTransmuxComplete(self, result) || parsed,\n false\n );\n if (!parsed) {\n // Emit at least one \"transmuxComplete\" message even if media is not found to update stream-controller state to PARSING\n self.postMessage({ event: 'transmuxComplete', data: results[0] });\n }\n self.postMessage({ event: 'flush', data: chunkMeta });\n}\n\nfunction isEmptyResult(remuxResult: RemuxerResult) {\n return (\n !remuxResult.audio &&\n !remuxResult.video &&\n !remuxResult.text &&\n !remuxResult.id3 &&\n !remuxResult.initSegment\n );\n}\n","import {\n WorkerContext,\n hasUMDWorker,\n injectWorker,\n loadWorker,\n} from './inject-worker';\nimport { Events } from '../events';\nimport Transmuxer, {\n TransmuxConfig,\n TransmuxState,\n isPromise,\n} from '../demux/transmuxer';\nimport { logger } from '../utils/logger';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { EventEmitter } from 'eventemitter3';\nimport { Fragment, Part } from '../loader/fragment';\nimport type { ChunkMetadata, TransmuxerResult } from '../types/transmuxer';\nimport type Hls from '../hls';\nimport type { HlsEventEmitter } from '../events';\nimport type { PlaylistLevelType } from '../types/loader';\nimport type { TypeSupported } from './tsdemuxer';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\nconst MediaSource = getMediaSource() || { isTypeSupported: () => false };\n\nexport default class TransmuxerInterface {\n public error: Error | null = null;\n private hls: Hls;\n private id: PlaylistLevelType;\n private observer: HlsEventEmitter;\n private frag: Fragment | null = null;\n private part: Part | null = null;\n private useWorker: boolean;\n private workerContext: WorkerContext | null = null;\n private onwmsg?: Function;\n private transmuxer: Transmuxer | null = null;\n private onTransmuxComplete: (transmuxResult: TransmuxerResult) => void;\n private onFlush: (chunkMeta: ChunkMetadata) => void;\n\n constructor(\n hls: Hls,\n id: PlaylistLevelType,\n onTransmuxComplete: (transmuxResult: TransmuxerResult) => void,\n onFlush: (chunkMeta: ChunkMetadata) => void\n ) {\n const config = hls.config;\n this.hls = hls;\n this.id = id;\n this.useWorker = !!config.enableWorker;\n this.onTransmuxComplete = onTransmuxComplete;\n this.onFlush = onFlush;\n\n const forwardMessage = (ev, data) => {\n data = data || {};\n data.frag = this.frag;\n data.id = this.id;\n if (ev === Events.ERROR) {\n this.error = data.error;\n }\n this.hls.trigger(ev, data);\n };\n\n // forward events to main thread\n this.observer = new EventEmitter() as HlsEventEmitter;\n this.observer.on(Events.FRAG_DECRYPTED, forwardMessage);\n this.observer.on(Events.ERROR, forwardMessage);\n\n const typeSupported: TypeSupported = {\n mp4: MediaSource.isTypeSupported('video/mp4'),\n mpeg: MediaSource.isTypeSupported('audio/mpeg'),\n mp3: MediaSource.isTypeSupported('audio/mp4; codecs=\"mp3\"'),\n };\n // navigator.vendor is not always available in Web Worker\n // refer to https://developer.mozilla.org/en-US/docs/Web/API/WorkerGlobalScope/navigator\n const vendor = navigator.vendor;\n if (this.useWorker && typeof Worker !== 'undefined') {\n const canCreateWorker = config.workerPath || hasUMDWorker();\n if (canCreateWorker) {\n try {\n if (config.workerPath) {\n logger.log(`loading Web Worker ${config.workerPath} for \"${id}\"`);\n this.workerContext = loadWorker(config.workerPath);\n } else {\n logger.log(`injecting Web Worker for \"${id}\"`);\n this.workerContext = injectWorker();\n }\n this.onwmsg = (ev: any) => this.onWorkerMessage(ev);\n const { worker } = this.workerContext;\n worker.addEventListener('message', this.onwmsg as any);\n worker.onerror = (event) => {\n const error = new Error(\n `${event.message} (${event.filename}:${event.lineno})`\n );\n config.enableWorker = false;\n logger.warn(`Error in \"${id}\" Web Worker, fallback to inline`);\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal: false,\n event: 'demuxerWorker',\n error,\n });\n };\n worker.postMessage({\n cmd: 'init',\n typeSupported: typeSupported,\n vendor: vendor,\n id: id,\n config: JSON.stringify(config),\n });\n } catch (err) {\n logger.warn(\n `Error setting up \"${id}\" Web Worker, fallback to inline`,\n err\n );\n this.resetWorker();\n this.error = null;\n this.transmuxer = new Transmuxer(\n this.observer,\n typeSupported,\n config,\n vendor,\n id\n );\n }\n return;\n }\n }\n\n this.transmuxer = new Transmuxer(\n this.observer,\n typeSupported,\n config,\n vendor,\n id\n );\n }\n\n resetWorker(): void {\n if (this.workerContext) {\n const { worker, objectURL } = this.workerContext;\n if (objectURL) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(objectURL);\n }\n worker.removeEventListener('message', this.onwmsg as any);\n worker.onerror = null;\n worker.terminate();\n this.workerContext = null;\n }\n }\n\n destroy(): void {\n if (this.workerContext) {\n this.resetWorker();\n this.onwmsg = undefined;\n } else {\n const transmuxer = this.transmuxer;\n if (transmuxer) {\n transmuxer.destroy();\n this.transmuxer = null;\n }\n }\n const observer = this.observer;\n if (observer) {\n observer.removeAllListeners();\n }\n this.frag = null;\n // @ts-ignore\n this.observer = null;\n // @ts-ignore\n this.hls = null;\n }\n\n push(\n data: ArrayBuffer,\n initSegmentData: Uint8Array | undefined,\n audioCodec: string | undefined,\n videoCodec: string | undefined,\n frag: Fragment,\n part: Part | null,\n duration: number,\n accurateTimeOffset: boolean,\n chunkMeta: ChunkMetadata,\n defaultInitPTS?: RationalTimestamp\n ): void {\n chunkMeta.transmuxing.start = self.performance.now();\n const { transmuxer } = this;\n const timeOffset = part ? part.start : frag.start;\n // TODO: push \"clear-lead\" decrypt data for unencrypted fragments in streams with encrypted ones\n const decryptdata = frag.decryptdata;\n const lastFrag = this.frag;\n\n const discontinuity = !(lastFrag && frag.cc === lastFrag.cc);\n const trackSwitch = !(lastFrag && chunkMeta.level === lastFrag.level);\n const snDiff = lastFrag ? chunkMeta.sn - (lastFrag.sn as number) : -1;\n const partDiff = this.part ? chunkMeta.part - this.part.index : -1;\n const progressive =\n snDiff === 0 &&\n chunkMeta.id > 1 &&\n chunkMeta.id === lastFrag?.stats.chunkCount;\n const contiguous =\n !trackSwitch &&\n (snDiff === 1 ||\n (snDiff === 0 && (partDiff === 1 || (progressive && partDiff <= 0))));\n const now = self.performance.now();\n\n if (trackSwitch || snDiff || frag.stats.parsing.start === 0) {\n frag.stats.parsing.start = now;\n }\n if (part && (partDiff || !contiguous)) {\n part.stats.parsing.start = now;\n }\n const initSegmentChange = !(\n lastFrag && frag.initSegment?.url === lastFrag.initSegment?.url\n );\n const state = new TransmuxState(\n discontinuity,\n contiguous,\n accurateTimeOffset,\n trackSwitch,\n timeOffset,\n initSegmentChange\n );\n if (!contiguous || discontinuity || initSegmentChange) {\n logger.log(`[transmuxer-interface, ${frag.type}]: Starting new transmux session for sn: ${chunkMeta.sn} p: ${chunkMeta.part} level: ${chunkMeta.level} id: ${chunkMeta.id}\n discontinuity: ${discontinuity}\n trackSwitch: ${trackSwitch}\n contiguous: ${contiguous}\n accurateTimeOffset: ${accurateTimeOffset}\n timeOffset: ${timeOffset}\n initSegmentChange: ${initSegmentChange}`);\n const config = new TransmuxConfig(\n audioCodec,\n videoCodec,\n initSegmentData,\n duration,\n defaultInitPTS\n );\n this.configureTransmuxer(config);\n }\n\n this.frag = frag;\n this.part = part;\n\n // Frags with sn of 'initSegment' are not transmuxed\n if (this.workerContext) {\n // post fragment payload as transferable objects for ArrayBuffer (no copy)\n this.workerContext.worker.postMessage(\n {\n cmd: 'demux',\n data,\n decryptdata,\n chunkMeta,\n state,\n },\n data instanceof ArrayBuffer ? [data] : []\n );\n } else if (transmuxer) {\n const transmuxResult = transmuxer.push(\n data,\n decryptdata,\n chunkMeta,\n state\n );\n if (isPromise(transmuxResult)) {\n transmuxer.async = true;\n transmuxResult\n .then((data) => {\n this.handleTransmuxComplete(data);\n })\n .catch((error) => {\n this.transmuxerError(\n error,\n chunkMeta,\n 'transmuxer-interface push error'\n );\n });\n } else {\n transmuxer.async = false;\n this.handleTransmuxComplete(transmuxResult as TransmuxerResult);\n }\n }\n }\n\n flush(chunkMeta: ChunkMetadata) {\n chunkMeta.transmuxing.start = self.performance.now();\n const { transmuxer } = this;\n if (this.workerContext) {\n 1;\n this.workerContext.worker.postMessage({\n cmd: 'flush',\n chunkMeta,\n });\n } else if (transmuxer) {\n let transmuxResult = transmuxer.flush(chunkMeta);\n const asyncFlush = isPromise(transmuxResult);\n if (asyncFlush || transmuxer.async) {\n if (!isPromise(transmuxResult)) {\n transmuxResult = Promise.resolve(transmuxResult);\n }\n transmuxResult\n .then((data) => {\n this.handleFlushResult(data, chunkMeta);\n })\n .catch((error) => {\n this.transmuxerError(\n error,\n chunkMeta,\n 'transmuxer-interface flush error'\n );\n });\n } else {\n this.handleFlushResult(\n transmuxResult as Array<TransmuxerResult>,\n chunkMeta\n );\n }\n }\n }\n\n private transmuxerError(\n error: Error,\n chunkMeta: ChunkMetadata,\n reason: string\n ) {\n if (!this.hls) {\n return;\n }\n this.error = error;\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_PARSING_ERROR,\n chunkMeta,\n fatal: false,\n error,\n err: error,\n reason,\n });\n }\n\n private handleFlushResult(\n results: Array<TransmuxerResult>,\n chunkMeta: ChunkMetadata\n ) {\n results.forEach((result) => {\n this.handleTransmuxComplete(result);\n });\n this.onFlush(chunkMeta);\n }\n\n private onWorkerMessage(ev: any): void {\n const data = ev.data;\n const hls = this.hls;\n switch (data.event) {\n case 'init': {\n const objectURL = this.workerContext?.objectURL;\n if (objectURL) {\n // revoke the Object URL that was used to create transmuxer worker, so as not to leak it\n self.URL.revokeObjectURL(objectURL);\n }\n break;\n }\n\n case 'transmuxComplete': {\n this.handleTransmuxComplete(data.data);\n break;\n }\n\n case 'flush': {\n this.onFlush(data.data);\n break;\n }\n\n // pass logs from the worker thread to the main logger\n case 'workerLog':\n if (logger[data.data.logType]) {\n logger[data.data.logType](data.data.message);\n }\n break;\n\n default: {\n data.data = data.data || {};\n data.data.frag = this.frag;\n data.data.id = this.id;\n hls.trigger(data.event, data.data);\n break;\n }\n }\n }\n\n private configureTransmuxer(config: TransmuxConfig) {\n const { transmuxer } = this;\n if (this.workerContext) {\n this.workerContext.worker.postMessage({\n cmd: 'configure',\n config,\n });\n } else if (transmuxer) {\n transmuxer.configure(config);\n }\n }\n\n private handleTransmuxComplete(result: TransmuxerResult) {\n result.chunkMeta.transmuxing.end = self.performance.now();\n this.onTransmuxComplete(result);\n }\n}\n","// ensure the worker ends up in the bundle\n// If the worker should not be included this gets aliased to empty.js\nimport './transmuxer-worker';\n\nexport function hasUMDWorker(): boolean {\n return typeof __HLS_WORKER_BUNDLE__ === 'function';\n}\n\nexport type WorkerContext = {\n worker: Worker;\n objectURL?: string;\n scriptURL?: string;\n};\n\nexport function injectWorker(): WorkerContext {\n const blob = new self.Blob(\n [\n `var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`,\n ],\n {\n type: 'text/javascript',\n }\n );\n const objectURL = self.URL.createObjectURL(blob);\n const worker = new self.Worker(objectURL);\n\n return {\n worker,\n objectURL,\n };\n}\n\nexport function loadWorker(path: string): WorkerContext {\n const scriptURL = new self.URL(path, self.location.href).href;\n const worker = new self.Worker(scriptURL);\n\n return {\n worker,\n scriptURL,\n };\n}\n","import type { BufferInfo } from '../utils/buffer-helper';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { HlsConfig } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type { FragmentTracker } from './fragment-tracker';\n\nexport const STALL_MINIMUM_DURATION_MS = 250;\nexport const MAX_START_GAP_JUMP = 2.0;\nexport const SKIP_BUFFER_HOLE_STEP_SECONDS = 0.1;\nexport const SKIP_BUFFER_RANGE_START = 0.05;\n\nexport default class GapController {\n private config: HlsConfig;\n private media: HTMLMediaElement | null = null;\n private fragmentTracker: FragmentTracker;\n private hls: Hls;\n private nudgeRetry: number = 0;\n private stallReported: boolean = false;\n private stalled: number | null = null;\n private moved: boolean = false;\n private seeking: boolean = false;\n\n constructor(config, media, fragmentTracker, hls) {\n this.config = config;\n this.media = media;\n this.fragmentTracker = fragmentTracker;\n this.hls = hls;\n }\n\n public destroy() {\n this.media = null;\n // @ts-ignore\n this.hls = this.fragmentTracker = null;\n }\n\n /**\n * Checks if the playhead is stuck within a gap, and if so, attempts to free it.\n * A gap is an unbuffered range between two buffered ranges (or the start and the first buffered range).\n *\n * @param lastCurrentTime - Previously read playhead position\n */\n public poll(lastCurrentTime: number, activeFrag: Fragment | null) {\n const { config, media, stalled } = this;\n if (media === null) {\n return;\n }\n const { currentTime, seeking } = media;\n const seeked = this.seeking && !seeking;\n const beginSeek = !this.seeking && seeking;\n\n this.seeking = seeking;\n\n // The playhead is moving, no-op\n if (currentTime !== lastCurrentTime) {\n this.moved = true;\n if (stalled !== null) {\n // The playhead is now moving, but was previously stalled\n if (this.stallReported) {\n const stalledDuration = self.performance.now() - stalled;\n logger.warn(\n `playback not stuck anymore @${currentTime}, after ${Math.round(\n stalledDuration\n )}ms`\n );\n this.stallReported = false;\n }\n this.stalled = null;\n this.nudgeRetry = 0;\n }\n return;\n }\n\n // Clear stalled state when beginning or finishing seeking so that we don't report stalls coming out of a seek\n if (beginSeek || seeked) {\n this.stalled = null;\n return;\n }\n\n // The playhead should not be moving\n if (\n (media.paused && !seeking) ||\n media.ended ||\n media.playbackRate === 0 ||\n !BufferHelper.getBuffered(media).length\n ) {\n return;\n }\n\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const isBuffered = bufferInfo.len > 0;\n const nextStart = bufferInfo.nextStart || 0;\n\n // There is no playable buffer (seeked, waiting for buffer)\n if (!isBuffered && !nextStart) {\n return;\n }\n\n if (seeking) {\n // Waiting for seeking in a buffered range to complete\n const hasEnoughBuffer = bufferInfo.len > MAX_START_GAP_JUMP;\n // Next buffered range is too far ahead to jump to while still seeking\n const noBufferGap =\n !nextStart ||\n (activeFrag && activeFrag.start <= currentTime) ||\n (nextStart - currentTime > MAX_START_GAP_JUMP &&\n !this.fragmentTracker.getPartialFragment(currentTime));\n if (hasEnoughBuffer || noBufferGap) {\n return;\n }\n // Reset moved state when seeking to a point in or before a gap\n this.moved = false;\n }\n\n // Skip start gaps if we haven't played, but the last poll detected the start of a stall\n // The addition poll gives the browser a chance to jump the gap for us\n if (!this.moved && this.stalled !== null) {\n // Jump start gaps within jump threshold\n const startJump =\n Math.max(nextStart, bufferInfo.start || 0) - currentTime;\n\n // When joining a live stream with audio tracks, account for live playlist window sliding by allowing\n // a larger jump over start gaps caused by the audio-stream-controller buffering a start fragment\n // that begins over 1 target duration after the video start position.\n const level = this.hls.levels\n ? this.hls.levels[this.hls.currentLevel]\n : null;\n const isLive = level?.details?.live;\n const maxStartGapJump = isLive\n ? level!.details!.targetduration * 2\n : MAX_START_GAP_JUMP;\n const partialOrGap = this.fragmentTracker.getPartialFragment(currentTime);\n if (startJump > 0 && (startJump <= maxStartGapJump || partialOrGap)) {\n this._trySkipBufferHole(partialOrGap);\n return;\n }\n }\n\n // Start tracking stall time\n const tnow = self.performance.now();\n if (stalled === null) {\n this.stalled = tnow;\n return;\n }\n\n const stalledDuration = tnow - stalled;\n if (!seeking && stalledDuration >= STALL_MINIMUM_DURATION_MS) {\n // Report stalling after trying to fix\n this._reportStall(bufferInfo);\n if (!this.media) {\n return;\n }\n }\n\n const bufferedWithHoles = BufferHelper.bufferInfo(\n media,\n currentTime,\n config.maxBufferHole\n );\n this._tryFixBufferStall(bufferedWithHoles, stalledDuration);\n }\n\n /**\n * Detects and attempts to fix known buffer stalling issues.\n * @param bufferInfo - The properties of the current buffer.\n * @param stalledDurationMs - The amount of time Hls.js has been stalling for.\n * @private\n */\n private _tryFixBufferStall(\n bufferInfo: BufferInfo,\n stalledDurationMs: number\n ) {\n const { config, fragmentTracker, media } = this;\n if (media === null) {\n return;\n }\n const currentTime = media.currentTime;\n\n const partial = fragmentTracker.getPartialFragment(currentTime);\n if (partial) {\n // Try to skip over the buffer hole caused by a partial fragment\n // This method isn't limited by the size of the gap between buffered ranges\n const targetTime = this._trySkipBufferHole(partial);\n // we return here in this case, meaning\n // the branch below only executes when we haven't seeked to a new position\n if (targetTime || !this.media) {\n return;\n }\n }\n\n // if we haven't had to skip over a buffer hole of a partial fragment\n // we may just have to \"nudge\" the playlist as the browser decoding/rendering engine\n // needs to cross some sort of threshold covering all source-buffers content\n // to start playing properly.\n if (\n (bufferInfo.len > config.maxBufferHole ||\n (bufferInfo.nextStart &&\n bufferInfo.nextStart - currentTime < config.maxBufferHole)) &&\n stalledDurationMs > config.highBufferWatchdogPeriod * 1000\n ) {\n logger.warn('Trying to nudge playhead over buffer-hole');\n // Try to nudge currentTime over a buffer hole if we've been stalling for the configured amount of seconds\n // We only try to jump the hole if it's under the configured size\n // Reset stalled so to rearm watchdog timer\n this.stalled = null;\n this._tryNudgeBuffer();\n }\n }\n\n /**\n * Triggers a BUFFER_STALLED_ERROR event, but only once per stall period.\n * @param bufferLen - The playhead distance from the end of the current buffer segment.\n * @private\n */\n private _reportStall(bufferInfo: BufferInfo) {\n const { hls, media, stallReported } = this;\n if (!stallReported && media) {\n // Report stalled error once\n this.stallReported = true;\n const error = new Error(\n `Playback stalling at @${\n media.currentTime\n } due to low buffer (${JSON.stringify(bufferInfo)})`\n );\n logger.warn(error.message);\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n fatal: false,\n error,\n buffer: bufferInfo.len,\n });\n }\n }\n\n /**\n * Attempts to fix buffer stalls by jumping over known gaps caused by partial fragments\n * @param partial - The partial fragment found at the current time (where playback is stalling).\n * @private\n */\n private _trySkipBufferHole(partial: Fragment | null): number {\n const { config, hls, media } = this;\n if (media === null) {\n return 0;\n }\n\n // Check if currentTime is between unbuffered regions of partial fragments\n const currentTime = media.currentTime;\n const bufferInfo = BufferHelper.bufferInfo(media, currentTime, 0);\n const startTime =\n currentTime < bufferInfo.start ? bufferInfo.start : bufferInfo.nextStart;\n if (startTime) {\n const bufferStarved = bufferInfo.len <= config.maxBufferHole;\n const waiting =\n bufferInfo.len > 0 && bufferInfo.len < 1 && media.readyState < 3;\n const gapLength = startTime - currentTime;\n if (gapLength > 0 && (bufferStarved || waiting)) {\n // Only allow large gaps to be skipped if it is a start gap, or all fragments in skip range are partial\n if (gapLength > config.maxBufferHole) {\n const { fragmentTracker } = this;\n let startGap = false;\n if (currentTime === 0) {\n const startFrag = fragmentTracker.getAppendedFrag(\n 0,\n PlaylistLevelType.MAIN\n );\n if (startFrag && startTime < startFrag.end) {\n startGap = true;\n }\n }\n if (!startGap) {\n const startProvisioned =\n partial ||\n fragmentTracker.getAppendedFrag(\n currentTime,\n PlaylistLevelType.MAIN\n );\n if (startProvisioned) {\n let moreToLoad = false;\n let pos = startProvisioned.end;\n while (pos < startTime) {\n const provisioned = fragmentTracker.getPartialFragment(pos);\n if (provisioned) {\n pos += provisioned.duration;\n } else {\n moreToLoad = true;\n break;\n }\n }\n if (moreToLoad) {\n return 0;\n }\n }\n }\n }\n const targetTime = Math.max(\n startTime + SKIP_BUFFER_RANGE_START,\n currentTime + SKIP_BUFFER_HOLE_STEP_SECONDS\n );\n logger.warn(\n `skipping hole, adjusting currentTime from ${currentTime} to ${targetTime}`\n );\n this.moved = true;\n this.stalled = null;\n media.currentTime = targetTime;\n if (partial && !partial.gap) {\n const error = new Error(\n `fragment loaded with buffer holes, seeking from ${currentTime} to ${targetTime}`\n );\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_SEEK_OVER_HOLE,\n fatal: false,\n error,\n reason: error.message,\n frag: partial,\n });\n }\n return targetTime;\n }\n }\n return 0;\n }\n\n /**\n * Attempts to fix buffer stalls by advancing the mediaElement's current time by a small amount.\n * @private\n */\n private _tryNudgeBuffer() {\n const { config, hls, media, nudgeRetry } = this;\n if (media === null) {\n return;\n }\n const currentTime = media.currentTime;\n this.nudgeRetry++;\n\n if (nudgeRetry < config.nudgeMaxRetry) {\n const targetTime = currentTime + (nudgeRetry + 1) * config.nudgeOffset;\n // playback stalled in buffered area ... let's nudge currentTime to try to overcome this\n const error = new Error(\n `Nudging 'currentTime' from ${currentTime} to ${targetTime}`\n );\n logger.warn(error.message);\n media.currentTime = targetTime;\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_NUDGE_ON_STALL,\n error,\n fatal: false,\n });\n } else {\n const error = new Error(\n `Playhead still not moving while enough data buffered @${currentTime} after ${config.nudgeMaxRetry} nudges`\n );\n logger.error(error.message);\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_STALLED_ERROR,\n error,\n fatal: true,\n });\n }\n }\n}\n","import BaseStreamController, { State } from './base-stream-controller';\nimport { changeTypeSupported } from '../is-supported';\nimport { Events } from '../events';\nimport { BufferHelper, BufferInfo } from '../utils/buffer-helper';\nimport { FragmentState } from './fragment-tracker';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport { ElementaryStreamTypes, Fragment } from '../loader/fragment';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport GapController from './gap-controller';\nimport { ErrorDetails } from '../errors';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { Level } from '../types/level';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type KeyLoader from '../loader/key-loader';\nimport type { TransmuxerResult } from '../types/transmuxer';\nimport type { TrackSet } from '../types/track';\nimport type { SourceBufferName } from '../types/buffer';\nimport type {\n AudioTrackSwitchedData,\n AudioTrackSwitchingData,\n BufferCreatedData,\n BufferEOSData,\n BufferFlushedData,\n ErrorData,\n FragBufferedData,\n FragLoadedData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n LevelLoadedData,\n LevelLoadingData,\n LevelsUpdatedData,\n ManifestParsedData,\n MediaAttachedData,\n} from '../types/events';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\nexport default class StreamController\n extends BaseStreamController\n implements NetworkComponentAPI\n{\n private audioCodecSwap: boolean = false;\n private gapController: GapController | null = null;\n private level: number = -1;\n private _forceStartLoad: boolean = false;\n private altAudio: boolean = false;\n private audioOnly: boolean = false;\n private fragPlaying: Fragment | null = null;\n private onvplaying: EventListener | null = null;\n private onvseeked: EventListener | null = null;\n private fragLastKbps: number = 0;\n private couldBacktrack: boolean = false;\n private backtrackFragment: Fragment | null = null;\n private audioCodecSwitch: boolean = false;\n private videoBuffer: any | null = null;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader\n ) {\n super(\n hls,\n fragmentTracker,\n keyLoader,\n '[stream-controller]',\n PlaylistLevelType.MAIN\n );\n this._registerListeners();\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(\n Events.FRAG_LOAD_EMERGENCY_ABORTED,\n this.onFragLoadEmergencyAborted,\n this\n );\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n protected _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(\n Events.FRAG_LOAD_EMERGENCY_ABORTED,\n this.onFragLoadEmergencyAborted,\n this\n );\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_SWITCHED, this.onAudioTrackSwitched, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.LEVELS_UPDATED, this.onLevelsUpdated, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n this.onMediaDetaching();\n }\n\n public startLoad(startPosition: number): void {\n if (this.levels) {\n const { lastCurrentTime, hls } = this;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n this.level = -1;\n if (!this.startFragRequested) {\n // determine load level\n let startLevel = hls.startLevel;\n if (startLevel === -1) {\n if (hls.config.testBandwidth && this.levels.length > 1) {\n // -1 : guess start Level by doing a bitrate test by loading first fragment of lowest quality level\n startLevel = 0;\n this.bitrateTest = true;\n } else {\n startLevel = hls.nextAutoLevel;\n }\n }\n // set new level to playlist loader : this will trigger start level load\n // hls.nextLoadLevel remains until it is set to a new value or until a new frag is successfully loaded\n this.level = hls.nextLoadLevel = startLevel;\n this.loadedmetadata = false;\n }\n // if startPosition undefined but lastCurrentTime set, set startPosition to last currentTime\n if (lastCurrentTime > 0 && startPosition === -1) {\n this.log(\n `Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(\n 3\n )}`\n );\n startPosition = lastCurrentTime;\n }\n this.state = State.IDLE;\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n this.tick();\n } else {\n this._forceStartLoad = true;\n this.state = State.STOPPED;\n }\n }\n\n public stopLoad() {\n this._forceStartLoad = false;\n super.stopLoad();\n }\n\n protected doTick() {\n switch (this.state) {\n case State.WAITING_LEVEL: {\n const { levels, level } = this;\n const details = levels?.[level]?.details;\n if (details && (!details.live || this.levelLastLoaded === this.level)) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.IDLE;\n break;\n } else if (this.hls.nextLoadLevel !== this.level) {\n this.state = State.IDLE;\n break;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY:\n {\n const now = self.performance.now();\n const retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || now >= retryDate || this.media?.seeking) {\n this.resetStartWhenNotLoaded(this.level);\n this.state = State.IDLE;\n }\n }\n break;\n default:\n break;\n }\n if (this.state === State.IDLE) {\n this.doTickIdle();\n }\n this.onTickEnd();\n }\n\n protected onTickEnd() {\n super.onTickEnd();\n this.checkBuffer();\n this.checkFragmentChanged();\n }\n\n private doTickIdle() {\n const { hls, levelLastLoaded, levels, media } = this;\n const { config, nextLoadLevel: level } = hls;\n\n // if start level not parsed yet OR\n // if video not attached AND start fragment already requested OR start frag prefetch not enabled\n // exit loop, as we either need more info (level not parsed) or we need media to be attached to load new fragment\n if (\n levelLastLoaded === null ||\n (!media && (this.startFragRequested || !config.startFragPrefetch))\n ) {\n return;\n }\n\n // If the \"main\" level is audio-only but we are loading an alternate track in the same group, do not load anything\n if (this.altAudio && this.audioOnly) {\n return;\n }\n\n if (!levels?.[level]) {\n return;\n }\n\n const levelInfo = levels[level];\n\n // if buffer length is less than maxBufLen try to load a new fragment\n\n const bufferInfo = this.getMainFwdBufferInfo();\n if (bufferInfo === null) {\n return;\n }\n\n const lastDetails = this.getLevelDetails();\n if (lastDetails && this._streamEnded(bufferInfo, lastDetails)) {\n const data: BufferEOSData = {};\n if (this.altAudio) {\n data.type = 'video';\n }\n\n this.hls.trigger(Events.BUFFER_EOS, data);\n this.state = State.ENDED;\n return;\n }\n\n // set next load level : this will trigger a playlist load if needed\n if (hls.loadLevel !== level && hls.manualLevel === -1) {\n this.log(`Adapting to level ${level} from level ${this.level}`);\n }\n this.level = hls.nextLoadLevel = level;\n\n const levelDetails = levelInfo.details;\n // if level info not retrieved yet, switch state and wait for level retrieval\n // if live playlist, ensure that new playlist has been refreshed to avoid loading/try to load\n // a useless and outdated fragment (that might even introduce load error if it is already out of the live playlist)\n if (\n !levelDetails ||\n this.state === State.WAITING_LEVEL ||\n (levelDetails.live && this.levelLastLoaded !== level)\n ) {\n this.level = level;\n this.state = State.WAITING_LEVEL;\n return;\n }\n\n const bufferLen = bufferInfo.len;\n\n // 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\n const maxBufLen = this.getMaxBufferLength(levelInfo.maxBitrate);\n\n // Stay idle if we are still with buffer margins\n if (bufferLen >= maxBufLen) {\n return;\n }\n\n if (\n this.backtrackFragment &&\n this.backtrackFragment.start > bufferInfo.end\n ) {\n this.backtrackFragment = null;\n }\n const targetBufferTime = this.backtrackFragment\n ? this.backtrackFragment.start\n : bufferInfo.end;\n let frag = this.getNextFragment(targetBufferTime, levelDetails);\n // Avoid backtracking by loading an earlier segment in streams with segments that do not start with a key frame (flagged by `couldBacktrack`)\n if (\n this.couldBacktrack &&\n !this.fragPrevious &&\n frag &&\n frag.sn !== 'initSegment' &&\n this.fragmentTracker.getState(frag) !== FragmentState.OK\n ) {\n const backtrackSn = (this.backtrackFragment ?? frag).sn as number;\n const fragIdx = backtrackSn - levelDetails.startSN;\n const backtrackFrag = levelDetails.fragments[fragIdx - 1];\n if (backtrackFrag && frag.cc === backtrackFrag.cc) {\n frag = backtrackFrag;\n this.fragmentTracker.removeFragment(backtrackFrag);\n }\n } else if (this.backtrackFragment && bufferInfo.len) {\n this.backtrackFragment = null;\n }\n // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags\n if (frag && this.isLoopLoading(frag, targetBufferTime)) {\n const gapStart = frag.gap;\n if (!gapStart) {\n // Cleanup the fragment tracker before trying to find the next unbuffered fragment\n const type =\n this.audioOnly && !this.altAudio\n ? ElementaryStreamTypes.AUDIO\n : ElementaryStreamTypes.VIDEO;\n const mediaBuffer =\n (type === ElementaryStreamTypes.VIDEO\n ? this.videoBuffer\n : this.mediaBuffer) || this.media;\n if (mediaBuffer) {\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);\n }\n }\n frag = this.getNextFragmentLoopLoading(\n frag,\n levelDetails,\n bufferInfo,\n PlaylistLevelType.MAIN,\n maxBufLen\n );\n }\n if (!frag) {\n return;\n }\n if (frag.initSegment && !frag.initSegment.data && !this.bitrateTest) {\n frag = frag.initSegment;\n }\n\n this.loadFragment(frag, levelInfo, targetBufferTime);\n }\n\n protected loadFragment(\n frag: Fragment,\n level: Level,\n targetBufferTime: number\n ) {\n // Check if fragment is not loaded\n const fragState = this.fragmentTracker.getState(frag);\n this.fragCurrent = frag;\n if (\n fragState === FragmentState.NOT_LOADED ||\n fragState === FragmentState.PARTIAL\n ) {\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, level);\n } else if (this.bitrateTest) {\n this.log(\n `Fragment ${frag.sn} of level ${frag.level} is being downloaded to test bitrate and will not be buffered`\n );\n this._loadBitrateTestFrag(frag, level);\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, level, targetBufferTime);\n }\n } else {\n this.clearTrackerIfNeeded(frag);\n }\n }\n\n private getBufferedFrag(position) {\n return this.fragmentTracker.getBufferedFrag(\n position,\n PlaylistLevelType.MAIN\n );\n }\n\n private followingBufferedFrag(frag: Fragment | null) {\n if (frag) {\n // try to get range of next fragment (500ms after this range)\n return this.getBufferedFrag(frag.end + 0.5);\n }\n return null;\n }\n\n /*\n on immediate level switch :\n - pause playback if playing\n - cancel any pending load request\n - and trigger a buffer flush\n */\n public immediateLevelSwitch() {\n this.abortCurrentFrag();\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n\n /**\n * try to switch ASAP without breaking video playback:\n * in order to ensure smooth but quick level switching,\n * we need to find the next flushable buffer range\n * we should take into account new segment fetch time\n */\n public nextLevelSwitch() {\n const { levels, media } = this;\n // ensure that media is defined and that metadata are available (to retrieve currentTime)\n if (media?.readyState) {\n let fetchdelay;\n const fragPlayingCurrent = this.getAppendedFrag(media.currentTime);\n if (fragPlayingCurrent && fragPlayingCurrent.start > 1) {\n // flush buffer preceding current fragment (flush until current fragment start offset)\n // minus 1s to avoid video freezing, that could happen if we flush keyframe of current video ...\n this.flushMainBuffer(0, fragPlayingCurrent.start - 1);\n }\n const levelDetails = this.getLevelDetails();\n if (levelDetails?.live) {\n const bufferInfo = this.getMainFwdBufferInfo();\n // Do not flush in live stream with low buffer\n if (!bufferInfo || bufferInfo.len < levelDetails.targetduration * 2) {\n return;\n }\n }\n if (!media.paused && levels) {\n // add a safety delay of 1s\n const nextLevelId = this.hls.nextLoadLevel;\n const nextLevel = levels[nextLevelId];\n const fragLastKbps = this.fragLastKbps;\n if (fragLastKbps && this.fragCurrent) {\n fetchdelay =\n (this.fragCurrent.duration * nextLevel.maxBitrate) /\n (1000 * fragLastKbps) +\n 1;\n } else {\n fetchdelay = 0;\n }\n } else {\n fetchdelay = 0;\n }\n // this.log('fetchdelay:'+fetchdelay);\n // find buffer range that will be reached once new fragment will be fetched\n const bufferedFrag = this.getBufferedFrag(media.currentTime + fetchdelay);\n if (bufferedFrag) {\n // we can flush buffer range following this one without stalling playback\n const nextBufferedFrag = this.followingBufferedFrag(bufferedFrag);\n if (nextBufferedFrag) {\n // if we are here, we can also cancel any loading/demuxing in progress, as they are useless\n this.abortCurrentFrag();\n // start flush position is in next buffered frag. Leave some padding for non-independent segments and smoother playback.\n const maxStart = nextBufferedFrag.maxStartPTS\n ? nextBufferedFrag.maxStartPTS\n : nextBufferedFrag.start;\n const fragDuration = nextBufferedFrag.duration;\n const startPts = Math.max(\n bufferedFrag.end,\n maxStart +\n Math.min(\n Math.max(\n fragDuration - this.config.maxFragLookUpTolerance,\n fragDuration * 0.5\n ),\n fragDuration * 0.75\n )\n );\n this.flushMainBuffer(startPts, Number.POSITIVE_INFINITY);\n }\n }\n }\n }\n\n private abortCurrentFrag() {\n const fragCurrent = this.fragCurrent;\n this.fragCurrent = null;\n this.backtrackFragment = null;\n if (fragCurrent) {\n fragCurrent.abortRequests();\n this.fragmentTracker.removeFragment(fragCurrent);\n }\n switch (this.state) {\n case State.KEY_LOADING:\n case State.FRAG_LOADING:\n case State.FRAG_LOADING_WAITING_RETRY:\n case State.PARSING:\n case State.PARSED:\n this.state = State.IDLE;\n break;\n }\n this.nextLoadPosition = this.getLoadPosition();\n }\n\n protected flushMainBuffer(startOffset: number, endOffset: number) {\n super.flushMainBuffer(\n startOffset,\n endOffset,\n this.altAudio ? 'video' : null\n );\n }\n\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) {\n super.onMediaAttached(event, data);\n const media = data.media;\n this.onvplaying = this.onMediaPlaying.bind(this);\n this.onvseeked = this.onMediaSeeked.bind(this);\n media.addEventListener('playing', this.onvplaying as EventListener);\n media.addEventListener('seeked', this.onvseeked as EventListener);\n this.gapController = new GapController(\n this.config,\n media,\n this.fragmentTracker,\n this.hls\n );\n }\n\n protected onMediaDetaching() {\n const { media } = this;\n if (media && this.onvplaying && this.onvseeked) {\n media.removeEventListener('playing', this.onvplaying);\n media.removeEventListener('seeked', this.onvseeked);\n this.onvplaying = this.onvseeked = null;\n this.videoBuffer = null;\n }\n this.fragPlaying = null;\n if (this.gapController) {\n this.gapController.destroy();\n this.gapController = null;\n }\n super.onMediaDetaching();\n }\n\n private onMediaPlaying() {\n // tick to speed up FRAG_CHANGED triggering\n this.tick();\n }\n\n private onMediaSeeked() {\n const media = this.media;\n const currentTime = media ? media.currentTime : null;\n if (Number.isFinite(currentTime)) {\n this.log(`Media seeked to ${(currentTime as number).toFixed(3)}`);\n }\n\n // If seeked was issued before buffer was appended do not tick immediately\n const bufferInfo = this.getMainFwdBufferInfo();\n if (bufferInfo === null || bufferInfo.len === 0) {\n this.warn(\n `Main forward buffer length on \"seeked\" event ${\n bufferInfo ? bufferInfo.len : 'empty'\n })`\n );\n return;\n }\n\n // tick to speed up FRAG_CHANGED triggering\n this.tick();\n }\n\n private onManifestLoading() {\n // reset buffer on manifest loading\n this.log('Trigger BUFFER_RESET');\n this.hls.trigger(Events.BUFFER_RESET, undefined);\n this.fragmentTracker.removeAllFragments();\n this.couldBacktrack = false;\n this.startPosition = this.lastCurrentTime = 0;\n this.levels = this.fragPlaying = this.backtrackFragment = null;\n this.altAudio = this.audioOnly = false;\n }\n\n private onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) {\n let aac = false;\n let heaac = false;\n let codec;\n data.levels.forEach((level) => {\n // detect if we have different kind of audio codecs used amongst playlists\n codec = level.audioCodec;\n if (codec) {\n if (codec.indexOf('mp4a.40.2') !== -1) {\n aac = true;\n }\n\n if (codec.indexOf('mp4a.40.5') !== -1) {\n heaac = true;\n }\n }\n });\n this.audioCodecSwitch = aac && heaac && !changeTypeSupported();\n if (this.audioCodecSwitch) {\n this.log(\n 'Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC'\n );\n }\n\n this.levels = data.levels;\n this.startFragRequested = false;\n }\n\n private onLevelLoading(event: Events.LEVEL_LOADING, data: LevelLoadingData) {\n const { levels } = this;\n if (!levels || this.state !== State.IDLE) {\n return;\n }\n const level = levels[data.level];\n if (\n !level.details ||\n (level.details.live && this.levelLastLoaded !== data.level) ||\n this.waitForCdnTuneIn(level.details)\n ) {\n this.state = State.WAITING_LEVEL;\n }\n }\n\n private onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const { levels } = this;\n const newLevelId = data.level;\n const newDetails = data.details;\n const duration = newDetails.totalduration;\n\n if (!levels) {\n this.warn(`Levels were reset while loading level ${newLevelId}`);\n return;\n }\n this.log(\n `Level ${newLevelId} loaded [${newDetails.startSN},${newDetails.endSN}]${\n newDetails.lastPartSn\n ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]`\n : ''\n }, cc [${newDetails.startCC}, ${newDetails.endCC}] duration:${duration}`\n );\n\n const curLevel = levels[newLevelId];\n const fragCurrent = this.fragCurrent;\n if (\n fragCurrent &&\n (this.state === State.FRAG_LOADING ||\n this.state === State.FRAG_LOADING_WAITING_RETRY)\n ) {\n if (\n (fragCurrent.level !== data.level ||\n fragCurrent.urlId !== curLevel.urlId) &&\n fragCurrent.loader\n ) {\n this.abortCurrentFrag();\n }\n }\n\n let sliding = 0;\n if (newDetails.live || curLevel.details?.live) {\n this.checkLiveUpdate(newDetails);\n if (newDetails.deltaUpdateFailed) {\n return;\n }\n sliding = this.alignPlaylists(newDetails, curLevel.details);\n }\n // override level info\n curLevel.details = newDetails;\n this.levelLastLoaded = newLevelId;\n\n this.hls.trigger(Events.LEVEL_UPDATED, {\n details: newDetails,\n level: newLevelId,\n });\n\n // only switch back to IDLE state if we were waiting for level to start downloading a new fragment\n if (this.state === State.WAITING_LEVEL) {\n if (this.waitForCdnTuneIn(newDetails)) {\n // Wait for Low-Latency CDN Tune-in\n return;\n }\n this.state = State.IDLE;\n }\n\n if (!this.startFragRequested) {\n this.setStartPosition(newDetails, sliding);\n } else if (newDetails.live) {\n this.synchronizeToLiveEdge(newDetails);\n }\n\n // trigger handler right now\n this.tick();\n }\n\n protected _handleFragmentLoadProgress(data: FragLoadedData) {\n const { frag, part, payload } = data;\n const { levels } = this;\n if (!levels) {\n this.warn(\n `Levels were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`\n );\n return;\n }\n const currentLevel = levels[frag.level];\n const details = currentLevel.details as LevelDetails;\n if (!details) {\n this.warn(\n `Dropping fragment ${frag.sn} of level ${frag.level} after level details were reset`\n );\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n const videoCodec = currentLevel.videoCodec;\n\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n const accurateTimeOffset = details.PTSKnown || !details.live;\n const initSegmentData = frag.initSegment?.data;\n const audioCodec = this._getAudioCodec(currentLevel);\n\n // transmux the MPEG-TS data to ISO-BMFF segments\n // this.log(`Transmuxing ${frag.sn} of [${details.startSN} ,${details.endSN}],level ${frag.level}, cc ${frag.cc}`);\n const transmuxer = (this.transmuxer =\n this.transmuxer ||\n new TransmuxerInterface(\n this.hls,\n PlaylistLevelType.MAIN,\n this._handleTransmuxComplete.bind(this),\n this._handleTransmuxerFlush.bind(this)\n ));\n const partIndex = part ? part.index : -1;\n const partial = partIndex !== -1;\n const chunkMeta = new ChunkMetadata(\n frag.level,\n frag.sn as number,\n frag.stats.chunkCount,\n payload.byteLength,\n partIndex,\n partial\n );\n const initPTS = this.initPTS[frag.cc];\n\n transmuxer.push(\n payload,\n initSegmentData,\n audioCodec,\n videoCodec,\n frag,\n part,\n details.totalduration,\n accurateTimeOffset,\n chunkMeta,\n initPTS\n );\n }\n\n private onAudioTrackSwitching(\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData\n ) {\n // if any URL found on new audio track, it is an alternate audio track\n const fromAltAudio = this.altAudio;\n const altAudio = !!data.url;\n // if we switch on main audio, ensure that main fragment scheduling is synced with media.buffered\n // don't do anything if we switch to alt audio: audio stream controller is handling it.\n // we will just have to change buffer scheduling on audioTrackSwitched\n if (!altAudio) {\n if (this.mediaBuffer !== this.media) {\n this.log(\n 'Switching on main audio, use media.buffered to schedule main fragment loading'\n );\n this.mediaBuffer = this.media;\n const fragCurrent = this.fragCurrent;\n // we need to refill audio buffer from main: cancel any frag loading to speed up audio switch\n if (fragCurrent) {\n this.log('Switching to main audio track, cancel main fragment load');\n fragCurrent.abortRequests();\n this.fragmentTracker.removeFragment(fragCurrent);\n }\n // destroy transmuxer to force init segment generation (following audio switch)\n this.resetTransmuxer();\n // switch to IDLE state to load new fragment\n this.resetLoadingState();\n } else if (this.audioOnly) {\n // Reset audio transmuxer so when switching back to main audio we're not still appending where we left off\n this.resetTransmuxer();\n }\n const hls = this.hls;\n // If switching from alt to main audio, flush all audio and trigger track switched\n if (fromAltAudio) {\n hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: Number.POSITIVE_INFINITY,\n type: null,\n });\n this.fragmentTracker.removeAllFragments();\n }\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, data);\n }\n }\n\n private onAudioTrackSwitched(\n event: Events.AUDIO_TRACK_SWITCHED,\n data: AudioTrackSwitchedData\n ) {\n const trackId = data.id;\n const altAudio = !!this.hls.audioTracks[trackId].url;\n if (altAudio) {\n const videoBuffer = this.videoBuffer;\n // if we switched on alternate audio, ensure that main fragment scheduling is synced with video sourcebuffer buffered\n if (videoBuffer && this.mediaBuffer !== videoBuffer) {\n this.log(\n 'Switching on alternate audio, use video.buffered to schedule main fragment loading'\n );\n this.mediaBuffer = videoBuffer;\n }\n }\n this.altAudio = altAudio;\n this.tick();\n }\n\n private onBufferCreated(\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData\n ) {\n const tracks = data.tracks;\n let mediaTrack;\n let name;\n let alternate = false;\n for (const type in tracks) {\n const track = tracks[type];\n if (track.id === 'main') {\n name = type;\n mediaTrack = track;\n // keep video source buffer reference\n if (type === 'video') {\n const videoTrack = tracks[type];\n if (videoTrack) {\n this.videoBuffer = videoTrack.buffer;\n }\n }\n } else {\n alternate = true;\n }\n }\n if (alternate && mediaTrack) {\n this.log(\n `Alternate track found, use ${name}.buffered to schedule main fragment loading`\n );\n this.mediaBuffer = mediaTrack.buffer;\n } else {\n this.mediaBuffer = this.media;\n }\n }\n\n private onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n const { frag, part } = data;\n if (frag && frag.type !== PlaylistLevelType.MAIN) {\n return;\n }\n if (this.fragContextChanged(frag)) {\n // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion\n // Avoid setting state back to IDLE, since that will interfere with a level switch\n this.warn(\n `Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${\n frag.level\n } finished buffering, but was aborted. state: ${this.state}`\n );\n if (this.state === State.PARSED) {\n this.state = State.IDLE;\n }\n return;\n }\n const stats = part ? part.stats : frag.stats;\n this.fragLastKbps = Math.round(\n (8 * stats.total) / (stats.buffering.end - stats.loading.first)\n );\n if (frag.sn !== 'initSegment') {\n this.fragPrevious = frag;\n }\n this.fragBufferedComplete(frag, part);\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n this.state = State.ERROR;\n return;\n }\n switch (data.details) {\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_PARSING_ERROR:\n case ErrorDetails.FRAG_DECRYPT_ERROR:\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n this.onFragmentOrKeyLoadError(PlaylistLevelType.MAIN, data);\n break;\n case ErrorDetails.LEVEL_LOAD_ERROR:\n case ErrorDetails.LEVEL_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n // in case of non fatal error while loading level, if level controller is not retrying to load level, switch back to IDLE\n if (\n !data.levelRetry &&\n this.state === State.WAITING_LEVEL &&\n data.context?.type === PlaylistContextType.LEVEL\n ) {\n this.state = State.IDLE;\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n if (!data.parent || data.parent !== 'main') {\n return;\n }\n if (this.reduceLengthAndFlushBuffer(data)) {\n this.flushMainBuffer(0, Number.POSITIVE_INFINITY);\n }\n break;\n case ErrorDetails.INTERNAL_EXCEPTION:\n this.recoverWorkerError(data);\n break;\n default:\n break;\n }\n }\n\n // Checks the health of the buffer and attempts to resolve playback stalls.\n private checkBuffer() {\n const { media, gapController } = this;\n if (!media || !gapController || !media.readyState) {\n // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)\n return;\n }\n\n if (this.loadedmetadata || !BufferHelper.getBuffered(media).length) {\n // Resolve gaps using the main buffer, whose ranges are the intersections of the A/V sourcebuffers\n const activeFrag = this.state !== State.IDLE ? this.fragCurrent : null;\n gapController.poll(this.lastCurrentTime, activeFrag);\n }\n\n this.lastCurrentTime = media.currentTime;\n }\n\n private onFragLoadEmergencyAborted() {\n this.state = State.IDLE;\n // if loadedmetadata is not set, it means that we are emergency switch down on first frag\n // in that case, reset startFragRequested flag\n if (!this.loadedmetadata) {\n this.startFragRequested = false;\n this.nextLoadPosition = this.startPosition;\n }\n this.tickImmediate();\n }\n\n private onBufferFlushed(\n event: Events.BUFFER_FLUSHED,\n { type }: BufferFlushedData\n ) {\n if (\n type !== ElementaryStreamTypes.AUDIO ||\n (this.audioOnly && !this.altAudio)\n ) {\n const mediaBuffer =\n (type === ElementaryStreamTypes.VIDEO\n ? this.videoBuffer\n : this.mediaBuffer) || this.media;\n this.afterBufferFlushed(mediaBuffer, type, PlaylistLevelType.MAIN);\n }\n }\n\n private onLevelsUpdated(\n event: Events.LEVELS_UPDATED,\n data: LevelsUpdatedData\n ) {\n this.levels = data.levels;\n }\n\n public swapAudioCodec() {\n this.audioCodecSwap = !this.audioCodecSwap;\n }\n\n /**\n * Seeks to the set startPosition if not equal to the mediaElement's current time.\n */\n protected seekToStartPos() {\n const { media } = this;\n if (!media) {\n return;\n }\n const currentTime = media.currentTime;\n let startPosition = this.startPosition;\n // only adjust currentTime if different from startPosition or if startPosition not buffered\n // at that stage, there should be only one buffered range, as we reach that code after first fragment has been buffered\n if (startPosition >= 0 && currentTime < startPosition) {\n if (media.seeking) {\n this.log(\n `could not seek to ${startPosition}, already seeking at ${currentTime}`\n );\n return;\n }\n const buffered = BufferHelper.getBuffered(media);\n const bufferStart = buffered.length ? buffered.start(0) : 0;\n const delta = bufferStart - startPosition;\n if (\n delta > 0 &&\n (delta < this.config.maxBufferHole ||\n delta < this.config.maxFragLookUpTolerance)\n ) {\n this.log(`adjusting start position by ${delta} to match buffer start`);\n startPosition += delta;\n this.startPosition = startPosition;\n }\n this.log(\n `seek to target start position ${startPosition} from current time ${currentTime}`\n );\n media.currentTime = startPosition;\n }\n }\n\n private _getAudioCodec(currentLevel) {\n let audioCodec = this.config.defaultAudioCodec || currentLevel.audioCodec;\n if (this.audioCodecSwap && audioCodec) {\n this.log('Swapping audio codec');\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n\n return audioCodec;\n }\n\n private _loadBitrateTestFrag(frag: Fragment, level: Level) {\n frag.bitrateTest = true;\n this._doFragLoad(frag, level).then((data) => {\n const { hls } = this;\n if (!data || this.fragContextChanged(frag)) {\n return;\n }\n level.fragmentError = 0;\n this.state = State.IDLE;\n this.startFragRequested = false;\n this.bitrateTest = false;\n const stats = frag.stats;\n // Bitrate tests fragments are neither parsed nor buffered\n stats.parsing.start =\n stats.parsing.end =\n stats.buffering.start =\n stats.buffering.end =\n self.performance.now();\n hls.trigger(Events.FRAG_LOADED, data as FragLoadedData);\n frag.bitrateTest = false;\n });\n }\n\n private _handleTransmuxComplete(transmuxResult: TransmuxerResult) {\n const id = 'main';\n const { hls } = this;\n const { remuxResult, chunkMeta } = transmuxResult;\n\n const context = this.getCurrentContext(chunkMeta);\n if (!context) {\n this.resetWhenMissingContext(chunkMeta);\n return;\n }\n const { frag, part, level } = context;\n const { video, text, id3, initSegment } = remuxResult;\n const { details } = level;\n // The audio-stream-controller handles audio buffering if Hls.js is playing an alternate audio track\n const audio = this.altAudio ? undefined : remuxResult.audio;\n\n // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.\n // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.\n if (this.fragContextChanged(frag)) {\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n\n this.state = State.PARSING;\n\n if (initSegment) {\n if (initSegment?.tracks) {\n const mapFragment = frag.initSegment || frag;\n this._bufferInitSegment(\n level,\n initSegment.tracks,\n mapFragment,\n chunkMeta\n );\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag: mapFragment,\n id,\n tracks: initSegment.tracks,\n });\n }\n\n // This would be nice if Number.isFinite acted as a typeguard, but it doesn't. See: https://github.com/Microsoft/TypeScript/issues/10038\n const initPTS = initSegment.initPTS as number;\n const timescale = initSegment.timescale as number;\n if (Number.isFinite(initPTS)) {\n this.initPTS[frag.cc] = { baseTime: initPTS, timescale };\n hls.trigger(Events.INIT_PTS_FOUND, { frag, id, initPTS, timescale });\n }\n }\n\n // Avoid buffering if backtracking this fragment\n if (video && details && frag.sn !== 'initSegment') {\n const prevFrag = details.fragments[frag.sn - 1 - details.startSN];\n const isFirstFragment = frag.sn === details.startSN;\n const isFirstInDiscontinuity = !prevFrag || frag.cc > prevFrag.cc;\n if (remuxResult.independent !== false) {\n const { startPTS, endPTS, startDTS, endDTS } = video;\n if (part) {\n part.elementaryStreams[video.type] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n } else {\n if (\n video.firstKeyFrame &&\n video.independent &&\n chunkMeta.id === 1 &&\n !isFirstInDiscontinuity\n ) {\n this.couldBacktrack = true;\n }\n if (video.dropped && video.independent) {\n // Backtrack if dropped frames create a gap after currentTime\n\n const bufferInfo = this.getMainFwdBufferInfo();\n const targetBufferTime =\n (bufferInfo ? bufferInfo.end : this.getLoadPosition()) +\n this.config.maxBufferHole;\n const startTime = video.firstKeyFramePTS\n ? video.firstKeyFramePTS\n : startPTS;\n if (\n !isFirstFragment &&\n targetBufferTime < startTime - this.config.maxBufferHole &&\n !isFirstInDiscontinuity\n ) {\n this.backtrack(frag);\n return;\n } else if (isFirstInDiscontinuity) {\n // Mark segment with a gap to avoid loop loading\n frag.gap = true;\n }\n // Set video stream start to fragment start so that truncated samples do not distort the timeline, and mark it partial\n frag.setElementaryStreamInfo(\n video.type as ElementaryStreamTypes,\n frag.start,\n endPTS,\n frag.start,\n endDTS,\n true\n );\n }\n }\n frag.setElementaryStreamInfo(\n video.type as ElementaryStreamTypes,\n startPTS,\n endPTS,\n startDTS,\n endDTS\n );\n if (this.backtrackFragment) {\n this.backtrackFragment = frag;\n }\n this.bufferFragmentData(\n video,\n frag,\n part,\n chunkMeta,\n isFirstFragment || isFirstInDiscontinuity\n );\n } else if (isFirstFragment || isFirstInDiscontinuity) {\n // Mark segment with a gap to avoid loop loading\n frag.gap = true;\n } else {\n this.backtrack(frag);\n return;\n }\n }\n\n if (audio) {\n const { startPTS, endPTS, startDTS, endDTS } = audio;\n if (part) {\n part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n }\n frag.setElementaryStreamInfo(\n ElementaryStreamTypes.AUDIO,\n startPTS,\n endPTS,\n startDTS,\n endDTS\n );\n this.bufferFragmentData(audio, frag, part, chunkMeta);\n }\n\n if (details && id3?.samples?.length) {\n const emittedID3: FragParsingMetadataData = {\n id,\n frag,\n details,\n samples: id3.samples,\n };\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (details && text) {\n const emittedText: FragParsingUserdataData = {\n id,\n frag,\n details,\n samples: text.samples,\n };\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n\n private _bufferInitSegment(\n currentLevel: Level,\n tracks: TrackSet,\n frag: Fragment,\n chunkMeta: ChunkMetadata\n ) {\n if (this.state !== State.PARSING) {\n return;\n }\n\n this.audioOnly = !!tracks.audio && !tracks.video;\n\n // if audio track is expected to come from audio stream controller, discard any coming from main\n if (this.altAudio && !this.audioOnly) {\n delete tracks.audio;\n }\n // include levelCodec in audio and video tracks\n const { audio, video, audiovideo } = tracks;\n if (audio) {\n let audioCodec = currentLevel.audioCodec;\n const ua = navigator.userAgent.toLowerCase();\n if (this.audioCodecSwitch) {\n if (audioCodec) {\n if (audioCodec.indexOf('mp4a.40.5') !== -1) {\n audioCodec = 'mp4a.40.2';\n } else {\n audioCodec = 'mp4a.40.5';\n }\n }\n // In the case that AAC and HE-AAC audio codecs are signalled in manifest,\n // force HE-AAC, as it seems that most browsers prefers it.\n // don't force HE-AAC if mono stream, or in Firefox\n if (audio.metadata.channelCount !== 1 && ua.indexOf('firefox') === -1) {\n audioCodec = 'mp4a.40.5';\n }\n }\n // HE-AAC is broken on Android, always signal audio codec as AAC even if variant manifest states otherwise\n if (ua.indexOf('android') !== -1 && audio.container !== 'audio/mpeg') {\n // Exclude mpeg audio\n audioCodec = 'mp4a.40.2';\n this.log(`Android: force audio codec to ${audioCodec}`);\n }\n if (currentLevel.audioCodec && currentLevel.audioCodec !== audioCodec) {\n this.log(\n `Swapping manifest audio codec \"${currentLevel.audioCodec}\" for \"${audioCodec}\"`\n );\n }\n audio.levelCodec = audioCodec;\n audio.id = 'main';\n this.log(\n `Init audio buffer, container:${\n audio.container\n }, codecs[selected/level/parsed]=[${audioCodec || ''}/${\n currentLevel.audioCodec || ''\n }/${audio.codec}]`\n );\n }\n if (video) {\n video.levelCodec = currentLevel.videoCodec;\n video.id = 'main';\n this.log(\n `Init video buffer, container:${\n video.container\n }, codecs[level/parsed]=[${currentLevel.videoCodec || ''}/${\n video.codec\n }]`\n );\n }\n if (audiovideo) {\n this.log(\n `Init audiovideo buffer, container:${\n audiovideo.container\n }, codecs[level/parsed]=[${currentLevel.attrs.CODECS || ''}/${\n audiovideo.codec\n }]`\n );\n }\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n // loop through tracks that are going to be provided to bufferController\n Object.keys(tracks).forEach((trackName) => {\n const track = tracks[trackName];\n const initSegment = track.initSegment;\n if (initSegment?.byteLength) {\n this.hls.trigger(Events.BUFFER_APPENDING, {\n type: trackName as SourceBufferName,\n data: initSegment,\n frag,\n part: null,\n chunkMeta,\n parent: frag.type,\n });\n }\n });\n // trigger handler right now\n this.tick();\n }\n\n public getMainFwdBufferInfo(): BufferInfo | null {\n return this.getFwdBufferInfo(\n this.mediaBuffer ? this.mediaBuffer : this.media,\n PlaylistLevelType.MAIN\n );\n }\n\n private backtrack(frag: Fragment) {\n this.couldBacktrack = true;\n // Causes findFragments to backtrack through fragments to find the keyframe\n this.backtrackFragment = frag;\n this.resetTransmuxer();\n this.flushBufferGap(frag);\n this.fragmentTracker.removeFragment(frag);\n this.fragPrevious = null;\n this.nextLoadPosition = frag.start;\n this.state = State.IDLE;\n }\n\n private checkFragmentChanged() {\n const video = this.media;\n let fragPlayingCurrent: Fragment | null = null;\n if (video && video.readyState > 1 && video.seeking === false) {\n const currentTime = video.currentTime;\n /* if video element is in seeked state, currentTime can only increase.\n (assuming that playback rate is positive ...)\n As sometimes currentTime jumps back to zero after a\n media decode error, check this, to avoid seeking back to\n wrong position after a media decode error\n */\n\n if (BufferHelper.isBuffered(video, currentTime)) {\n fragPlayingCurrent = this.getAppendedFrag(currentTime);\n } else if (BufferHelper.isBuffered(video, currentTime + 0.1)) {\n /* ensure that FRAG_CHANGED event is triggered at startup,\n when first video frame is displayed and playback is paused.\n add a tolerance of 100ms, in case current position is not buffered,\n check if current pos+100ms is buffered and use that buffer range\n for FRAG_CHANGED event reporting */\n fragPlayingCurrent = this.getAppendedFrag(currentTime + 0.1);\n }\n if (fragPlayingCurrent) {\n this.backtrackFragment = null;\n const fragPlaying = this.fragPlaying;\n const fragCurrentLevel = fragPlayingCurrent.level;\n if (\n !fragPlaying ||\n fragPlayingCurrent.sn !== fragPlaying.sn ||\n fragPlaying.level !== fragCurrentLevel ||\n fragPlayingCurrent.urlId !== fragPlaying.urlId\n ) {\n this.fragPlaying = fragPlayingCurrent;\n this.hls.trigger(Events.FRAG_CHANGED, { frag: fragPlayingCurrent });\n if (!fragPlaying || fragPlaying.level !== fragCurrentLevel) {\n this.hls.trigger(Events.LEVEL_SWITCHED, {\n level: fragCurrentLevel,\n });\n }\n }\n }\n }\n }\n\n get nextLevel(): number {\n const frag = this.nextBufferedFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n\n get currentFrag(): Fragment | null {\n const media = this.media;\n if (media) {\n return this.fragPlaying || this.getAppendedFrag(media.currentTime);\n }\n return null;\n }\n\n get currentProgramDateTime(): Date | null {\n const media = this.media;\n if (media) {\n const currentTime = media.currentTime;\n const frag = this.currentFrag;\n if (\n frag &&\n Number.isFinite(currentTime) &&\n Number.isFinite(frag.programDateTime)\n ) {\n const epocMs =\n (frag.programDateTime as number) + (currentTime - frag.start) * 1000;\n return new Date(epocMs);\n }\n }\n return null;\n }\n\n get currentLevel(): number {\n const frag = this.currentFrag;\n if (frag) {\n return frag.level;\n }\n return -1;\n }\n\n get nextBufferedFrag() {\n const frag = this.currentFrag;\n if (frag) {\n return this.followingBufferedFrag(frag);\n }\n return null;\n }\n\n get forceStartLoad() {\n return this._forceStartLoad;\n }\n}\n","/*\n * compute an Exponential Weighted moving average\n * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average\n * - heavily inspired from shaka-player\n */\n\nclass EWMA {\n public readonly halfLife: number;\n private alpha_: number;\n private estimate_: number;\n private totalWeight_: number;\n\n // About half of the estimated value will be from the last |halfLife| samples by weight.\n constructor(halfLife: number, estimate: number = 0, weight: number = 0) {\n this.halfLife = halfLife;\n // Larger values of alpha expire historical data more slowly.\n this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;\n this.estimate_ = estimate;\n this.totalWeight_ = weight;\n }\n\n sample(weight: number, value: number) {\n const adjAlpha = Math.pow(this.alpha_, weight);\n this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;\n this.totalWeight_ += weight;\n }\n\n getTotalWeight(): number {\n return this.totalWeight_;\n }\n\n getEstimate(): number {\n if (this.alpha_) {\n const zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);\n if (zeroFactor) {\n return this.estimate_ / zeroFactor;\n }\n }\n return this.estimate_;\n }\n}\n\nexport default EWMA;\n","/*\n * EWMA Bandwidth Estimator\n * - heavily inspired from shaka-player\n * Tracks bandwidth samples and estimates available bandwidth.\n * Based on the minimum of two exponentially-weighted moving averages with\n * different half-lives.\n */\n\nimport EWMA from '../utils/ewma';\n\nclass EwmaBandWidthEstimator {\n private defaultEstimate_: number;\n private minWeight_: number;\n private minDelayMs_: number;\n private slow_: EWMA;\n private fast_: EWMA;\n private defaultTTFB_: number;\n private ttfb_: EWMA;\n\n constructor(\n slow: number,\n fast: number,\n defaultEstimate: number,\n defaultTTFB: number = 100\n ) {\n this.defaultEstimate_ = defaultEstimate;\n this.minWeight_ = 0.001;\n this.minDelayMs_ = 50;\n this.slow_ = new EWMA(slow);\n this.fast_ = new EWMA(fast);\n this.defaultTTFB_ = defaultTTFB;\n this.ttfb_ = new EWMA(slow);\n }\n\n update(slow: number, fast: number) {\n const { slow_, fast_, ttfb_ } = this;\n if (slow_.halfLife !== slow) {\n this.slow_ = new EWMA(slow, slow_.getEstimate(), slow_.getTotalWeight());\n }\n if (fast_.halfLife !== fast) {\n this.fast_ = new EWMA(fast, fast_.getEstimate(), fast_.getTotalWeight());\n }\n if (ttfb_.halfLife !== slow) {\n this.ttfb_ = new EWMA(slow, ttfb_.getEstimate(), ttfb_.getTotalWeight());\n }\n }\n\n sample(durationMs: number, numBytes: number) {\n durationMs = Math.max(durationMs, this.minDelayMs_);\n const numBits = 8 * numBytes;\n // weight is duration in seconds\n const durationS = durationMs / 1000;\n // value is bandwidth in bits/s\n const bandwidthInBps = numBits / durationS;\n this.fast_.sample(durationS, bandwidthInBps);\n this.slow_.sample(durationS, bandwidthInBps);\n }\n\n sampleTTFB(ttfb: number) {\n // weight is frequency curve applied to TTFB in seconds\n // (longer times have less weight with expected input under 1 second)\n const seconds = ttfb / 1000;\n const weight = Math.sqrt(2) * Math.exp(-Math.pow(seconds, 2) / 2);\n this.ttfb_.sample(weight, Math.max(ttfb, 5));\n }\n\n canEstimate(): boolean {\n return this.fast_.getTotalWeight() >= this.minWeight_;\n }\n\n getEstimate(): number {\n if (this.canEstimate()) {\n // console.log('slow estimate:'+ Math.round(this.slow_.getEstimate()));\n // console.log('fast estimate:'+ Math.round(this.fast_.getEstimate()));\n // Take the minimum of these two estimates. This should have the effect of\n // adapting down quickly, but up more slowly.\n return Math.min(this.fast_.getEstimate(), this.slow_.getEstimate());\n } else {\n return this.defaultEstimate_;\n }\n }\n\n getEstimateTTFB(): number {\n if (this.ttfb_.getTotalWeight() >= this.minWeight_) {\n return this.ttfb_.getEstimate();\n } else {\n return this.defaultTTFB_;\n }\n }\n\n destroy() {}\n}\nexport default EwmaBandWidthEstimator;\n","import EwmaBandWidthEstimator from '../utils/ewma-bandwidth-estimator';\nimport { Events } from '../events';\nimport { PlaylistLevelType } from '../types/loader';\nimport { logger } from '../utils/logger';\nimport type { Fragment } from '../loader/fragment';\nimport type { Part } from '../loader/fragment';\nimport type { LoaderStats } from '../types/loader';\nimport type Hls from '../hls';\nimport type {\n FragLoadingData,\n FragLoadedData,\n FragBufferedData,\n LevelLoadedData,\n LevelSwitchingData,\n} from '../types/events';\nimport type { AbrComponentAPI } from '../types/component-api';\n\nclass AbrController implements AbrComponentAPI {\n protected hls: Hls;\n private lastLevelLoadSec: number = 0;\n private lastLoadedFragLevel: number = 0;\n private _nextAutoLevel: number = -1;\n private timer: number = -1;\n private onCheck: Function = this._abandonRulesCheck.bind(this);\n private fragCurrent: Fragment | null = null;\n private partCurrent: Part | null = null;\n private bitrateTestDelay: number = 0;\n\n public readonly bwEstimator: EwmaBandWidthEstimator;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n const config = hls.config;\n this.bwEstimator = new EwmaBandWidthEstimator(\n config.abrEwmaSlowVoD,\n config.abrEwmaFastVoD,\n config.abrEwmaDefaultEstimate\n );\n\n this.registerListeners();\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n }\n\n protected unregisterListeners() {\n const { hls } = this;\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n }\n\n public destroy() {\n this.unregisterListeners();\n this.clearTimer();\n // @ts-ignore\n this.hls = this.onCheck = null;\n this.fragCurrent = this.partCurrent = null;\n }\n\n protected onFragLoading(event: Events.FRAG_LOADING, data: FragLoadingData) {\n const frag = data.frag;\n if (this.ignoreFragment(frag)) {\n return;\n }\n this.fragCurrent = frag;\n this.partCurrent = data.part ?? null;\n this.clearTimer();\n this.timer = self.setInterval(this.onCheck, 100);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.clearTimer();\n }\n\n private getTimeToLoadFrag(\n timeToFirstByteSec: number,\n bandwidth: number,\n fragSizeBits: number,\n isSwitch: boolean\n ) {\n const fragLoadSec = timeToFirstByteSec + fragSizeBits / bandwidth;\n const playlistLoadSec = isSwitch ? this.lastLevelLoadSec : 0;\n return fragLoadSec + playlistLoadSec;\n }\n\n protected onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n const config = this.hls.config;\n const { total, bwEstimate } = data.stats;\n // Total is the bytelength and bwEstimate in bits/sec\n if (Number.isFinite(total) && Number.isFinite(bwEstimate)) {\n this.lastLevelLoadSec = (8 * total) / bwEstimate;\n }\n if (data.details.live) {\n this.bwEstimator.update(config.abrEwmaSlowLive, config.abrEwmaFastLive);\n } else {\n this.bwEstimator.update(config.abrEwmaSlowVoD, config.abrEwmaFastVoD);\n }\n }\n\n /*\n This method monitors the download rate of the current fragment, and will downswitch if that fragment will not load\n quickly enough to prevent underbuffering\n */\n private _abandonRulesCheck() {\n const { fragCurrent: frag, partCurrent: part, hls } = this;\n const { autoLevelEnabled, media } = hls;\n if (!frag || !media) {\n return;\n }\n\n const now = performance.now();\n const stats: LoaderStats = part ? part.stats : frag.stats;\n const duration = part ? part.duration : frag.duration;\n const timeLoading = now - stats.loading.start;\n // If frag loading is aborted, complete, or from lowest level, stop timer and return\n if (\n stats.aborted ||\n (stats.loaded && stats.loaded === stats.total) ||\n frag.level === 0\n ) {\n this.clearTimer();\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n return;\n }\n\n // This check only runs if we're in ABR mode and actually playing\n if (\n !autoLevelEnabled ||\n media.paused ||\n !media.playbackRate ||\n !media.readyState\n ) {\n return;\n }\n\n const bufferInfo = hls.mainForwardBufferInfo;\n if (bufferInfo === null) {\n return;\n }\n\n const ttfbEstimate = this.bwEstimator.getEstimateTTFB();\n const playbackRate = Math.abs(media.playbackRate);\n // To maintain stable adaptive playback, only begin monitoring frag loading after half or more of its playback duration has passed\n if (\n timeLoading <=\n Math.max(ttfbEstimate, 1000 * (duration / (playbackRate * 2)))\n ) {\n return;\n }\n\n // bufferStarvationDelay is an estimate of the amount time (in seconds) it will take to exhaust the buffer\n const bufferStarvationDelay = bufferInfo.len / playbackRate;\n // Only downswitch if less than 2 fragment lengths are buffered\n if (bufferStarvationDelay >= (2 * duration) / playbackRate) {\n return;\n }\n\n const ttfb = stats.loading.first\n ? stats.loading.first - stats.loading.start\n : -1;\n const loadedFirstByte = stats.loaded && ttfb > -1;\n const bwEstimate: number = this.bwEstimator.getEstimate();\n const { levels, minAutoLevel } = hls;\n const level = levels[frag.level];\n const expectedLen =\n stats.total ||\n Math.max(stats.loaded, Math.round((duration * level.maxBitrate) / 8));\n let timeStreaming = timeLoading - ttfb;\n if (timeStreaming < 1 && loadedFirstByte) {\n timeStreaming = Math.min(timeLoading, (stats.loaded * 8) / bwEstimate);\n }\n const loadRate = loadedFirstByte\n ? (stats.loaded * 1000) / timeStreaming\n : 0;\n // fragLoadDelay is an estimate of the time (in seconds) it will take to buffer the remainder of the fragment\n const fragLoadedDelay = loadRate\n ? (expectedLen - stats.loaded) / loadRate\n : (expectedLen * 8) / bwEstimate + ttfbEstimate / 1000;\n // Only downswitch if the time to finish loading the current fragment is greater than the amount of buffer left\n if (fragLoadedDelay <= bufferStarvationDelay) {\n return;\n }\n\n const bwe = loadRate ? loadRate * 8 : bwEstimate;\n let fragLevelNextLoadedDelay: number = Number.POSITIVE_INFINITY;\n let nextLoadLevel: number;\n // Iterate through lower level and try to find the largest one that avoids rebuffering\n for (\n nextLoadLevel = frag.level - 1;\n nextLoadLevel > minAutoLevel;\n nextLoadLevel--\n ) {\n // compute time to load next fragment at lower level\n // 8 = bits per byte (bps/Bps)\n const levelNextBitrate = levels[nextLoadLevel].maxBitrate;\n fragLevelNextLoadedDelay = this.getTimeToLoadFrag(\n ttfbEstimate / 1000,\n bwe,\n duration * levelNextBitrate,\n !levels[nextLoadLevel].details\n );\n if (fragLevelNextLoadedDelay < bufferStarvationDelay) {\n break;\n }\n }\n // Only emergency switch down if it takes less time to load a new fragment at lowest level instead of continuing\n // to load the current one\n if (fragLevelNextLoadedDelay >= fragLoadedDelay) {\n return;\n }\n\n // if estimated load time of new segment is completely unreasonable, ignore and do not emergency switch down\n if (fragLevelNextLoadedDelay > duration * 10) {\n return;\n }\n hls.nextLoadLevel = nextLoadLevel;\n if (loadedFirstByte) {\n // If there has been loading progress, sample bandwidth using loading time offset by minimum TTFB time\n this.bwEstimator.sample(\n timeLoading - Math.min(ttfbEstimate, ttfb),\n stats.loaded\n );\n } else {\n // If there has been no loading progress, sample TTFB\n this.bwEstimator.sampleTTFB(timeLoading);\n }\n\n this.clearTimer();\n logger.warn(`[abr] Fragment ${frag.sn}${\n part ? ' part ' + part.index : ''\n } of level ${frag.level} is loading too slowly;\n Time to underbuffer: ${bufferStarvationDelay.toFixed(3)} s\n Estimated load time for current fragment: ${fragLoadedDelay.toFixed(3)} s\n Estimated load time for down switch fragment: ${fragLevelNextLoadedDelay.toFixed(\n 3\n )} s\n TTFB estimate: ${ttfb}\n Current BW estimate: ${\n Number.isFinite(bwEstimate) ? (bwEstimate / 1024).toFixed(3) : 'Unknown'\n } Kb/s\n New BW estimate: ${(this.bwEstimator.getEstimate() / 1024).toFixed(\n 3\n )} Kb/s\n Aborting and switching to level ${nextLoadLevel}`);\n if (frag.loader) {\n this.fragCurrent = this.partCurrent = null;\n frag.abortRequests();\n }\n hls.trigger(Events.FRAG_LOAD_EMERGENCY_ABORTED, { frag, part, stats });\n }\n\n protected onFragLoaded(\n event: Events.FRAG_LOADED,\n { frag, part }: FragLoadedData\n ) {\n const stats = part ? part.stats : frag.stats;\n if (frag.type === PlaylistLevelType.MAIN) {\n this.bwEstimator.sampleTTFB(stats.loading.first - stats.loading.start);\n }\n if (this.ignoreFragment(frag)) {\n return;\n }\n // stop monitoring bw once frag loaded\n this.clearTimer();\n // store level id after successful fragment load\n this.lastLoadedFragLevel = frag.level;\n // reset forced auto level value so that next level will be selected\n this._nextAutoLevel = -1;\n\n // compute level average bitrate\n if (this.hls.config.abrMaxWithRealBitrate) {\n const duration = part ? part.duration : frag.duration;\n const level = this.hls.levels[frag.level];\n const loadedBytes =\n (level.loaded ? level.loaded.bytes : 0) + stats.loaded;\n const loadedDuration =\n (level.loaded ? level.loaded.duration : 0) + duration;\n level.loaded = { bytes: loadedBytes, duration: loadedDuration };\n level.realBitrate = Math.round((8 * loadedBytes) / loadedDuration);\n }\n if (frag.bitrateTest) {\n const fragBufferedData: FragBufferedData = {\n stats,\n frag,\n part,\n id: frag.type,\n };\n this.onFragBuffered(Events.FRAG_BUFFERED, fragBufferedData);\n frag.bitrateTest = false;\n }\n }\n\n protected onFragBuffered(\n event: Events.FRAG_BUFFERED,\n data: FragBufferedData\n ) {\n const { frag, part } = data;\n const stats = part?.stats.loaded ? part.stats : frag.stats;\n\n if (stats.aborted) {\n return;\n }\n if (this.ignoreFragment(frag)) {\n return;\n }\n // Use the difference between parsing and request instead of buffering and request to compute fragLoadingProcessing;\n // rationale is that buffer appending only happens once media is attached. This can happen when config.startFragPrefetch\n // is used. If we used buffering in that case, our BW estimate sample will be very large.\n const processingMs =\n stats.parsing.end -\n stats.loading.start -\n Math.min(\n stats.loading.first - stats.loading.start,\n this.bwEstimator.getEstimateTTFB()\n );\n this.bwEstimator.sample(processingMs, stats.loaded);\n stats.bwEstimate = this.bwEstimator.getEstimate();\n if (frag.bitrateTest) {\n this.bitrateTestDelay = processingMs / 1000;\n } else {\n this.bitrateTestDelay = 0;\n }\n }\n\n private ignoreFragment(frag: Fragment): boolean {\n // Only count non-alt-audio frags which were actually buffered in our BW calculations\n return frag.type !== PlaylistLevelType.MAIN || frag.sn === 'initSegment';\n }\n\n public clearTimer() {\n self.clearInterval(this.timer);\n }\n\n // return next auto level\n get nextAutoLevel() {\n const forcedAutoLevel = this._nextAutoLevel;\n const bwEstimator = this.bwEstimator;\n // in case next auto level has been forced, and bw not available or not reliable, return forced value\n if (forcedAutoLevel !== -1 && !bwEstimator.canEstimate()) {\n return forcedAutoLevel;\n }\n\n // compute next level using ABR logic\n let nextABRAutoLevel = this.getNextABRAutoLevel();\n // use forced auto level when ABR selected level has errored\n if (forcedAutoLevel !== -1) {\n const levels = this.hls.levels;\n if (\n levels.length > Math.max(forcedAutoLevel, nextABRAutoLevel) &&\n levels[forcedAutoLevel].loadError <= levels[nextABRAutoLevel].loadError\n ) {\n return forcedAutoLevel;\n }\n }\n // if forced auto level has been defined, use it to cap ABR computed quality level\n if (forcedAutoLevel !== -1) {\n nextABRAutoLevel = Math.min(forcedAutoLevel, nextABRAutoLevel);\n }\n\n return nextABRAutoLevel;\n }\n\n private getNextABRAutoLevel(): number {\n const { fragCurrent, partCurrent, hls } = this;\n const { maxAutoLevel, config, minAutoLevel, media } = hls;\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n\n // playbackRate is the absolute value of the playback rate; if media.playbackRate is 0, we use 1 to load as\n // if we're playing back at the normal rate.\n const playbackRate =\n media && media.playbackRate !== 0 ? Math.abs(media.playbackRate) : 1.0;\n const avgbw = this.bwEstimator\n ? this.bwEstimator.getEstimate()\n : config.abrEwmaDefaultEstimate;\n // bufferStarvationDelay is the wall-clock time left until the playback buffer is exhausted.\n const bufferInfo = hls.mainForwardBufferInfo;\n const bufferStarvationDelay =\n (bufferInfo ? bufferInfo.len : 0) / playbackRate;\n\n // First, look to see if we can find a level matching with our avg bandwidth AND that could also guarantee no rebuffering at all\n let bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay,\n config.abrBandWidthFactor,\n config.abrBandWidthUpFactor\n );\n if (bestLevel >= 0) {\n return bestLevel;\n }\n logger.trace(\n `[abr] ${\n bufferStarvationDelay ? 'rebuffering expected' : 'buffer is empty'\n }, finding optimal quality level`\n );\n // not possible to get rid of rebuffering ... let's try to find level that will guarantee less than maxStarvationDelay of rebuffering\n // if no matching level found, logic will return 0\n let maxStarvationDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxStarvationDelay)\n : config.maxStarvationDelay;\n let bwFactor = config.abrBandWidthFactor;\n let bwUpFactor = config.abrBandWidthUpFactor;\n\n if (!bufferStarvationDelay) {\n // in case buffer is empty, let's check if previous fragment was loaded to perform a bitrate test\n const bitrateTestDelay = this.bitrateTestDelay;\n if (bitrateTestDelay) {\n // if it is the case, then we need to adjust our max starvation delay using maxLoadingDelay config value\n // max video loading delay used in automatic start level selection :\n // in that mode ABR controller will ensure that video loading time (ie the time to fetch the first fragment at lowest quality level +\n // the time to fetch the fragment at the appropriate quality level is less than ```maxLoadingDelay``` )\n // cap maxLoadingDelay and ensure it is not bigger 'than bitrate test' frag duration\n const maxLoadingDelay = currentFragDuration\n ? Math.min(currentFragDuration, config.maxLoadingDelay)\n : config.maxLoadingDelay;\n maxStarvationDelay = maxLoadingDelay - bitrateTestDelay;\n logger.trace(\n `[abr] bitrate test took ${Math.round(\n 1000 * bitrateTestDelay\n )}ms, set first fragment max fetchDuration to ${Math.round(\n 1000 * maxStarvationDelay\n )} ms`\n );\n // don't use conservative factor on bitrate test\n bwFactor = bwUpFactor = 1;\n }\n }\n bestLevel = this.findBestLevel(\n avgbw,\n minAutoLevel,\n maxAutoLevel,\n bufferStarvationDelay + maxStarvationDelay,\n bwFactor,\n bwUpFactor\n );\n return Math.max(bestLevel, 0);\n }\n\n private findBestLevel(\n currentBw: number,\n minAutoLevel: number,\n maxAutoLevel: number,\n maxFetchDuration: number,\n bwFactor: number,\n bwUpFactor: number\n ): number {\n const {\n fragCurrent,\n partCurrent,\n lastLoadedFragLevel: currentLevel,\n } = this;\n const { levels } = this.hls;\n const level = levels[currentLevel];\n const live = !!level?.details?.live;\n const currentCodecSet = level?.codecSet;\n\n const currentFragDuration = partCurrent\n ? partCurrent.duration\n : fragCurrent\n ? fragCurrent.duration\n : 0;\n\n const ttfbEstimateSec = this.bwEstimator.getEstimateTTFB() / 1000;\n let levelSkippedMin = minAutoLevel;\n let levelSkippedMax = -1;\n for (let i = maxAutoLevel; i >= minAutoLevel; i--) {\n const levelInfo = levels[i];\n\n if (\n !levelInfo ||\n (currentCodecSet && levelInfo.codecSet !== currentCodecSet)\n ) {\n if (levelInfo) {\n levelSkippedMin = Math.min(i, levelSkippedMin);\n levelSkippedMax = Math.max(i, levelSkippedMax);\n }\n continue;\n }\n if (levelSkippedMax !== -1) {\n logger.trace(\n `[abr] Skipped level(s) ${levelSkippedMin}-${levelSkippedMax} with CODECS:\"${levels[levelSkippedMax].attrs.CODECS}\"; not compatible with \"${level.attrs.CODECS}\"`\n );\n }\n\n const levelDetails = levelInfo.details;\n const avgDuration =\n (partCurrent\n ? levelDetails?.partTarget\n : levelDetails?.averagetargetduration) || currentFragDuration;\n\n let adjustedbw: number;\n // follow algorithm captured from stagefright :\n // https://android.googlesource.com/platform/frameworks/av/+/master/media/libstagefright/httplive/LiveSession.cpp\n // Pick the highest bandwidth stream below or equal to estimated bandwidth.\n // consider only 80% of the available bandwidth, but if we are switching up,\n // be even more conservative (70%) to avoid overestimating and immediately\n // switching back.\n if (i <= currentLevel) {\n adjustedbw = bwFactor * currentBw;\n } else {\n adjustedbw = bwUpFactor * currentBw;\n }\n\n const bitrate: number = levels[i].maxBitrate;\n const fetchDuration: number = this.getTimeToLoadFrag(\n ttfbEstimateSec,\n adjustedbw,\n bitrate * avgDuration,\n levelDetails === undefined\n );\n\n logger.trace(\n `[abr] level:${i} adjustedbw-bitrate:${Math.round(\n adjustedbw - bitrate\n )} avgDuration:${avgDuration.toFixed(\n 1\n )} maxFetchDuration:${maxFetchDuration.toFixed(\n 1\n )} fetchDuration:${fetchDuration.toFixed(1)}`\n );\n // if adjusted bw is greater than level bitrate AND\n if (\n adjustedbw > bitrate &&\n // fragment fetchDuration unknown OR live stream OR fragment fetchDuration less than max allowed fetch duration, then this level matches\n // 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 ...\n // special case to support startLevel = -1 (bitrateTest) on live streams : in that case we should not exit loop so that findBestLevel will return -1\n (fetchDuration === 0 ||\n !Number.isFinite(fetchDuration) ||\n (live && !this.bitrateTestDelay) ||\n fetchDuration < maxFetchDuration)\n ) {\n // as we are looping from highest to lowest, this will return the best achievable quality level\n return i;\n }\n }\n // not enough time budget even with quality level 0 ... rebuffering might happen\n return -1;\n }\n\n set nextAutoLevel(nextLevel) {\n this._nextAutoLevel = nextLevel;\n }\n}\n\nexport default AbrController;\n","export default class ChunkCache {\n private chunks: Array<Uint8Array> = [];\n public dataLength: number = 0;\n\n push(chunk: Uint8Array) {\n this.chunks.push(chunk);\n this.dataLength += chunk.length;\n }\n\n flush(): Uint8Array {\n const { chunks, dataLength } = this;\n let result;\n if (!chunks.length) {\n return new Uint8Array(0);\n } else if (chunks.length === 1) {\n result = chunks[0];\n } else {\n result = concatUint8Arrays(chunks, dataLength);\n }\n this.reset();\n return result;\n }\n\n reset() {\n this.chunks.length = 0;\n this.dataLength = 0;\n }\n}\n\nfunction concatUint8Arrays(\n chunks: Array<Uint8Array>,\n dataLength: number\n): Uint8Array {\n const result = new Uint8Array(dataLength);\n let offset = 0;\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n result.set(chunk, offset);\n offset += chunk.length;\n }\n return result;\n}\n","import BaseStreamController, { State } from './base-stream-controller';\nimport { Events } from '../events';\nimport { Bufferable, BufferHelper } from '../utils/buffer-helper';\nimport { FragmentState } from './fragment-tracker';\nimport { Level } from '../types/level';\nimport { PlaylistContextType, PlaylistLevelType } from '../types/loader';\nimport { Fragment, ElementaryStreamTypes, Part } from '../loader/fragment';\nimport ChunkCache from '../demux/chunk-cache';\nimport TransmuxerInterface from '../demux/transmuxer-interface';\nimport { ChunkMetadata } from '../types/transmuxer';\nimport { fragmentWithinToleranceTest } from './fragment-finders';\nimport { alignMediaPlaylistByPDT } from '../utils/discontinuities';\nimport { ErrorDetails } from '../errors';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type KeyLoader from '../loader/key-loader';\nimport type { TransmuxerResult } from '../types/transmuxer';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { TrackSet } from '../types/track';\nimport type {\n BufferCreatedData,\n AudioTracksUpdatedData,\n AudioTrackSwitchingData,\n LevelLoadedData,\n TrackLoadedData,\n BufferAppendingData,\n BufferFlushedData,\n InitPTSFoundData,\n FragLoadedData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n FragBufferedData,\n ErrorData,\n} from '../types/events';\nimport type { MediaPlaylist } from '../types/media-playlist';\n\nconst TICK_INTERVAL = 100; // how often to tick in ms\n\ntype WaitingForPTSData = {\n frag: Fragment;\n part: Part | null;\n cache: ChunkCache;\n complete: boolean;\n};\n\nclass AudioStreamController\n extends BaseStreamController\n implements NetworkComponentAPI\n{\n private videoBuffer: Bufferable | null = null;\n private videoTrackCC: number = -1;\n private waitingVideoCC: number = -1;\n private bufferedTrack: MediaPlaylist | null = null;\n private switchingTrack: MediaPlaylist | null = null;\n private trackId: number = -1;\n private waitingData: WaitingForPTSData | null = null;\n private mainDetails: LevelDetails | null = null;\n private bufferFlushed: boolean = false;\n private cachedTrackLoadedData: TrackLoadedData | null = null;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader\n ) {\n super(\n hls,\n fragmentTracker,\n keyLoader,\n '[audio-stream-controller]',\n PlaylistLevelType.AUDIO\n );\n this._registerListeners();\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n this.mainDetails = null;\n this.bufferedTrack = null;\n this.switchingTrack = null;\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n hls.on(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.on(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.AUDIO_TRACKS_UPDATED, this.onAudioTracksUpdated, this);\n hls.off(Events.AUDIO_TRACK_SWITCHING, this.onAudioTrackSwitching, this);\n hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n hls.off(Events.BUFFER_FLUSHED, this.onBufferFlushed, this);\n hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n // INIT_PTS_FOUND is triggered when the video track parsed in the stream-controller has a new PTS value\n onInitPtsFound(\n event: Events.INIT_PTS_FOUND,\n { frag, id, initPTS, timescale }: InitPTSFoundData\n ) {\n // Always update the new INIT PTS\n // Can change due level switch\n if (id === 'main') {\n const cc = frag.cc;\n this.initPTS[frag.cc] = { baseTime: initPTS, timescale };\n this.log(`InitPTS for cc: ${cc} found from main: ${initPTS}`);\n this.videoTrackCC = cc;\n // If we are waiting, tick immediately to unblock audio fragment transmuxing\n if (this.state === State.WAITING_INIT_PTS) {\n this.tick();\n }\n }\n }\n\n startLoad(startPosition: number) {\n if (!this.levels) {\n this.startPosition = startPosition;\n this.state = State.STOPPED;\n return;\n }\n const lastCurrentTime = this.lastCurrentTime;\n this.stopLoad();\n this.setInterval(TICK_INTERVAL);\n if (lastCurrentTime > 0 && startPosition === -1) {\n this.log(\n `Override startPosition with lastCurrentTime @${lastCurrentTime.toFixed(\n 3\n )}`\n );\n startPosition = lastCurrentTime;\n this.state = State.IDLE;\n } else {\n this.loadedmetadata = false;\n this.state = State.WAITING_TRACK;\n }\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n\n this.tick();\n }\n\n doTick() {\n switch (this.state) {\n case State.IDLE:\n this.doTickIdle();\n break;\n case State.WAITING_TRACK: {\n const { levels, trackId } = this;\n const details = levels?.[trackId]?.details;\n if (details) {\n if (this.waitForCdnTuneIn(details)) {\n break;\n }\n this.state = State.WAITING_INIT_PTS;\n }\n break;\n }\n case State.FRAG_LOADING_WAITING_RETRY: {\n const now = performance.now();\n const retryDate = this.retryDate;\n // if current time is gt than retryDate, or if media seeking let's switch to IDLE state to retry loading\n if (!retryDate || now >= retryDate || this.media?.seeking) {\n this.log('RetryDate reached, switch back to IDLE state');\n this.resetStartWhenNotLoaded(this.trackId);\n this.state = State.IDLE;\n }\n break;\n }\n case State.WAITING_INIT_PTS: {\n // Ensure we don't get stuck in the WAITING_INIT_PTS state if the waiting frag CC doesn't match any initPTS\n const waitingData = this.waitingData;\n if (waitingData) {\n const { frag, part, cache, complete } = waitingData;\n if (this.initPTS[frag.cc] !== undefined) {\n this.waitingData = null;\n this.waitingVideoCC = -1;\n this.state = State.FRAG_LOADING;\n const payload = cache.flush();\n const data: FragLoadedData = {\n frag,\n part,\n payload,\n networkDetails: null,\n };\n this._handleFragmentLoadProgress(data);\n if (complete) {\n super._handleFragmentLoadComplete(data);\n }\n } else if (this.videoTrackCC !== this.waitingVideoCC) {\n // Drop waiting fragment if videoTrackCC has changed since waitingFragment was set and initPTS was not found\n this.log(\n `Waiting fragment cc (${frag.cc}) cancelled because video is at cc ${this.videoTrackCC}`\n );\n this.clearWaitingFragment();\n } else {\n // Drop waiting fragment if an earlier fragment is needed\n const pos = this.getLoadPosition();\n const bufferInfo = BufferHelper.bufferInfo(\n this.mediaBuffer,\n pos,\n this.config.maxBufferHole\n );\n const waitingFragmentAtPosition = fragmentWithinToleranceTest(\n bufferInfo.end,\n this.config.maxFragLookUpTolerance,\n frag\n );\n if (waitingFragmentAtPosition < 0) {\n this.log(\n `Waiting fragment cc (${frag.cc}) @ ${frag.start} cancelled because another fragment at ${bufferInfo.end} is needed`\n );\n this.clearWaitingFragment();\n }\n }\n } else {\n this.state = State.IDLE;\n }\n }\n }\n\n this.onTickEnd();\n }\n\n clearWaitingFragment() {\n const waitingData = this.waitingData;\n if (waitingData) {\n this.fragmentTracker.removeFragment(waitingData.frag);\n this.waitingData = null;\n this.waitingVideoCC = -1;\n this.state = State.IDLE;\n }\n }\n\n protected resetLoadingState() {\n this.clearWaitingFragment();\n super.resetLoadingState();\n }\n\n protected onTickEnd() {\n const { media } = this;\n if (!media?.readyState) {\n // Exit early if we don't have media or if the media hasn't buffered anything yet (readyState 0)\n return;\n }\n\n this.lastCurrentTime = media.currentTime;\n }\n\n private doTickIdle() {\n const { hls, levels, media, trackId } = this;\n const config = hls.config;\n\n if (!levels?.[trackId]) {\n return;\n }\n\n // if video not attached AND\n // start fragment already requested OR start frag prefetch not enabled\n // exit loop\n // => if media not attached but start frag prefetch is enabled and start frag not requested yet, we will not exit loop\n if (!media && (this.startFragRequested || !config.startFragPrefetch)) {\n return;\n }\n\n const levelInfo = levels[trackId];\n\n const trackDetails = levelInfo.details;\n if (\n !trackDetails ||\n (trackDetails.live && this.levelLastLoaded !== trackId) ||\n this.waitForCdnTuneIn(trackDetails)\n ) {\n this.state = State.WAITING_TRACK;\n return;\n }\n\n const bufferable = this.mediaBuffer ? this.mediaBuffer : this.media;\n if (this.bufferFlushed && bufferable) {\n this.bufferFlushed = false;\n this.afterBufferFlushed(\n bufferable,\n ElementaryStreamTypes.AUDIO,\n PlaylistLevelType.AUDIO\n );\n }\n\n const bufferInfo = this.getFwdBufferInfo(\n bufferable,\n PlaylistLevelType.AUDIO\n );\n if (bufferInfo === null) {\n return;\n }\n const { bufferedTrack, switchingTrack } = this;\n\n if (!switchingTrack && this._streamEnded(bufferInfo, trackDetails)) {\n hls.trigger(Events.BUFFER_EOS, { type: 'audio' });\n this.state = State.ENDED;\n return;\n }\n\n const mainBufferInfo = this.getFwdBufferInfo(\n this.videoBuffer ? this.videoBuffer : this.media,\n PlaylistLevelType.MAIN\n );\n const bufferLen = bufferInfo.len;\n const maxBufLen = this.getMaxBufferLength(mainBufferInfo?.len);\n\n // if buffer length is less than maxBufLen try to load a new fragment\n if (bufferLen >= maxBufLen && !switchingTrack) {\n return;\n }\n const fragments = trackDetails.fragments;\n const start = fragments[0].start;\n let targetBufferTime = bufferInfo.end;\n\n if (switchingTrack && media) {\n const pos = this.getLoadPosition();\n if (bufferedTrack && switchingTrack.attrs !== bufferedTrack.attrs) {\n targetBufferTime = pos;\n }\n // if currentTime (pos) is less than alt audio playlist start time, it means that alt audio is ahead of currentTime\n if (trackDetails.PTSKnown && pos < start) {\n // if everything is buffered from pos to start or if audio buffer upfront, let's seek to start\n if (bufferInfo.end > start || bufferInfo.nextStart) {\n this.log(\n 'Alt audio track ahead of main track, seek to start of alt audio track'\n );\n media.currentTime = start + 0.05;\n }\n }\n }\n\n let frag = this.getNextFragment(targetBufferTime, trackDetails);\n let atGap = false;\n // Avoid loop loading by using nextLoadPosition set for backtracking and skipping consecutive GAP tags\n if (frag && this.isLoopLoading(frag, targetBufferTime)) {\n atGap = !!frag.gap;\n frag = this.getNextFragmentLoopLoading(\n frag,\n trackDetails,\n bufferInfo,\n PlaylistLevelType.MAIN,\n maxBufLen\n );\n }\n if (!frag) {\n this.bufferFlushed = true;\n return;\n }\n\n // Buffer audio up to one target duration ahead of main buffer\n const atBufferSyncLimit =\n mainBufferInfo &&\n frag.start > mainBufferInfo.end + trackDetails.targetduration;\n if (\n atBufferSyncLimit ||\n // Or wait for main buffer after buffing some audio\n (!mainBufferInfo?.len && bufferInfo.len)\n ) {\n // Check fragment-tracker for main fragments since GAP segments do not show up in bufferInfo\n const mainFrag = this.getAppendedFrag(frag.start, PlaylistLevelType.MAIN);\n if (mainFrag === null) {\n return;\n }\n // Bridge gaps in main buffer\n atGap ||=\n !!mainFrag.gap || (!!atBufferSyncLimit && mainBufferInfo.len === 0);\n if (\n (atBufferSyncLimit && !atGap) ||\n (atGap && bufferInfo.nextStart && bufferInfo.nextStart < mainFrag.end)\n ) {\n return;\n }\n }\n\n this.loadFragment(frag, levelInfo, targetBufferTime);\n }\n\n protected getMaxBufferLength(mainBufferLength?: number): number {\n const maxConfigBuffer = super.getMaxBufferLength();\n if (!mainBufferLength) {\n return maxConfigBuffer;\n }\n return Math.min(\n Math.max(maxConfigBuffer, mainBufferLength),\n this.config.maxMaxBufferLength\n );\n }\n\n onMediaDetaching() {\n this.videoBuffer = null;\n super.onMediaDetaching();\n }\n\n onAudioTracksUpdated(\n event: Events.AUDIO_TRACKS_UPDATED,\n { audioTracks }: AudioTracksUpdatedData\n ) {\n this.resetTransmuxer();\n this.levels = audioTracks.map((mediaPlaylist) => new Level(mediaPlaylist));\n }\n\n onAudioTrackSwitching(\n event: Events.AUDIO_TRACK_SWITCHING,\n data: AudioTrackSwitchingData\n ) {\n // if any URL found on new audio track, it is an alternate audio track\n const altAudio = !!data.url;\n this.trackId = data.id;\n const { fragCurrent } = this;\n\n if (fragCurrent) {\n fragCurrent.abortRequests();\n this.removeUnbufferedFrags(fragCurrent.start);\n }\n this.resetLoadingState();\n // destroy useless transmuxer when switching audio to main\n if (!altAudio) {\n this.resetTransmuxer();\n } else {\n // switching to audio track, start timer if not already started\n this.setInterval(TICK_INTERVAL);\n }\n\n // should we switch tracks ?\n if (altAudio) {\n this.switchingTrack = data;\n // main audio track are handled by stream-controller, just do something if switching to alt audio track\n this.state = State.IDLE;\n } else {\n this.switchingTrack = null;\n this.bufferedTrack = data;\n this.state = State.STOPPED;\n }\n this.tick();\n }\n\n onManifestLoading() {\n this.fragmentTracker.removeAllFragments();\n this.startPosition = this.lastCurrentTime = 0;\n this.bufferFlushed = false;\n this.levels =\n this.mainDetails =\n this.waitingData =\n this.bufferedTrack =\n this.cachedTrackLoadedData =\n this.switchingTrack =\n null;\n this.startFragRequested = false;\n this.trackId = this.videoTrackCC = this.waitingVideoCC = -1;\n }\n\n onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n this.mainDetails = data.details;\n if (this.cachedTrackLoadedData !== null) {\n this.hls.trigger(Events.AUDIO_TRACK_LOADED, this.cachedTrackLoadedData);\n this.cachedTrackLoadedData = null;\n }\n }\n\n onAudioTrackLoaded(event: Events.AUDIO_TRACK_LOADED, data: TrackLoadedData) {\n if (this.mainDetails == null) {\n this.cachedTrackLoadedData = data;\n return;\n }\n const { levels } = this;\n const { details: newDetails, id: trackId } = data;\n if (!levels) {\n this.warn(`Audio tracks were reset while loading level ${trackId}`);\n return;\n }\n this.log(\n `Track ${trackId} loaded [${newDetails.startSN},${newDetails.endSN}]${\n newDetails.lastPartSn\n ? `[part-${newDetails.lastPartSn}-${newDetails.lastPartIndex}]`\n : ''\n },duration:${newDetails.totalduration}`\n );\n\n const track = levels[trackId];\n let sliding = 0;\n if (newDetails.live || track.details?.live) {\n this.checkLiveUpdate(newDetails);\n const mainDetails = this.mainDetails;\n if (newDetails.deltaUpdateFailed || !mainDetails) {\n return;\n }\n if (\n !track.details &&\n newDetails.hasProgramDateTime &&\n mainDetails.hasProgramDateTime\n ) {\n // Make sure our audio rendition is aligned with the \"main\" rendition, using\n // pdt as our reference times.\n alignMediaPlaylistByPDT(newDetails, mainDetails);\n sliding = newDetails.fragments[0].start;\n } else {\n sliding = this.alignPlaylists(newDetails, track.details);\n }\n }\n track.details = newDetails;\n this.levelLastLoaded = trackId;\n\n // compute start position if we are aligned with the main playlist\n if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n this.setStartPosition(track.details, sliding);\n }\n // only switch back to IDLE state if we were waiting for track to start downloading a new fragment\n if (\n this.state === State.WAITING_TRACK &&\n !this.waitForCdnTuneIn(newDetails)\n ) {\n this.state = State.IDLE;\n }\n\n // trigger handler right now\n this.tick();\n }\n\n _handleFragmentLoadProgress(data: FragLoadedData) {\n const { frag, part, payload } = data;\n const { config, trackId, levels } = this;\n if (!levels) {\n this.warn(\n `Audio tracks were reset while fragment load was in progress. Fragment ${frag.sn} of level ${frag.level} will not be buffered`\n );\n return;\n }\n\n const track = levels[trackId] as Level;\n if (!track) {\n this.warn('Audio track is undefined on fragment load progress');\n return;\n }\n const details = track.details as LevelDetails;\n if (!details) {\n this.warn('Audio track details undefined on fragment load progress');\n this.removeUnbufferedFrags(frag.start);\n return;\n }\n const audioCodec =\n config.defaultAudioCodec || track.audioCodec || 'mp4a.40.2';\n\n let transmuxer = this.transmuxer;\n if (!transmuxer) {\n transmuxer = this.transmuxer = new TransmuxerInterface(\n this.hls,\n PlaylistLevelType.AUDIO,\n this._handleTransmuxComplete.bind(this),\n this._handleTransmuxerFlush.bind(this)\n );\n }\n\n // Check if we have video initPTS\n // If not we need to wait for it\n const initPTS = this.initPTS[frag.cc];\n const initSegmentData = frag.initSegment?.data;\n if (initPTS !== undefined) {\n // this.log(`Transmuxing ${sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`);\n // time Offset is accurate if level PTS is known, or if playlist is not sliding (not live)\n const accurateTimeOffset = false; // details.PTSKnown || !details.live;\n const partIndex = part ? part.index : -1;\n const partial = partIndex !== -1;\n const chunkMeta = new ChunkMetadata(\n frag.level,\n frag.sn as number,\n frag.stats.chunkCount,\n payload.byteLength,\n partIndex,\n partial\n );\n transmuxer.push(\n payload,\n initSegmentData,\n audioCodec,\n '',\n frag,\n part,\n details.totalduration,\n accurateTimeOffset,\n chunkMeta,\n initPTS\n );\n } else {\n this.log(\n `Unknown video PTS for cc ${frag.cc}, waiting for video PTS before demuxing audio frag ${frag.sn} of [${details.startSN} ,${details.endSN}],track ${trackId}`\n );\n const { cache } = (this.waitingData = this.waitingData || {\n frag,\n part,\n cache: new ChunkCache(),\n complete: false,\n });\n cache.push(new Uint8Array(payload));\n this.waitingVideoCC = this.videoTrackCC;\n this.state = State.WAITING_INIT_PTS;\n }\n }\n\n protected _handleFragmentLoadComplete(fragLoadedData: FragLoadedData) {\n if (this.waitingData) {\n this.waitingData.complete = true;\n return;\n }\n super._handleFragmentLoadComplete(fragLoadedData);\n }\n\n onBufferReset(/* event: Events.BUFFER_RESET */) {\n // reset reference to sourcebuffers\n this.mediaBuffer = this.videoBuffer = null;\n this.loadedmetadata = false;\n }\n\n onBufferCreated(event: Events.BUFFER_CREATED, data: BufferCreatedData) {\n const audioTrack = data.tracks.audio;\n if (audioTrack) {\n this.mediaBuffer = audioTrack.buffer || null;\n }\n if (data.tracks.video) {\n this.videoBuffer = data.tracks.video.buffer || null;\n }\n }\n\n onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n const { frag, part } = data;\n if (frag.type !== PlaylistLevelType.AUDIO) {\n if (!this.loadedmetadata && frag.type === PlaylistLevelType.MAIN) {\n const bufferable = this.videoBuffer || this.media;\n if (bufferable) {\n const bufferedTimeRanges = BufferHelper.getBuffered(bufferable);\n if (bufferedTimeRanges.length) {\n this.loadedmetadata = true;\n }\n }\n }\n return;\n }\n if (this.fragContextChanged(frag)) {\n // If a level switch was requested while a fragment was buffering, it will emit the FRAG_BUFFERED event upon completion\n // Avoid setting state back to IDLE or concluding the audio switch; otherwise, the switched-to track will not buffer\n this.warn(\n `Fragment ${frag.sn}${part ? ' p: ' + part.index : ''} of level ${\n frag.level\n } finished buffering, but was aborted. state: ${\n this.state\n }, audioSwitch: ${\n this.switchingTrack ? this.switchingTrack.name : 'false'\n }`\n );\n return;\n }\n if (frag.sn !== 'initSegment') {\n this.fragPrevious = frag;\n const track = this.switchingTrack;\n if (track) {\n this.bufferedTrack = track;\n this.switchingTrack = null;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHED, { ...track });\n }\n }\n this.fragBufferedComplete(frag, part);\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n if (data.fatal) {\n this.state = State.ERROR;\n return;\n }\n switch (data.details) {\n case ErrorDetails.FRAG_GAP:\n case ErrorDetails.FRAG_PARSING_ERROR:\n case ErrorDetails.FRAG_DECRYPT_ERROR:\n case ErrorDetails.FRAG_LOAD_ERROR:\n case ErrorDetails.FRAG_LOAD_TIMEOUT:\n case ErrorDetails.KEY_LOAD_ERROR:\n case ErrorDetails.KEY_LOAD_TIMEOUT:\n this.onFragmentOrKeyLoadError(PlaylistLevelType.AUDIO, data);\n break;\n case ErrorDetails.AUDIO_TRACK_LOAD_ERROR:\n case ErrorDetails.AUDIO_TRACK_LOAD_TIMEOUT:\n case ErrorDetails.LEVEL_PARSING_ERROR:\n // in case of non fatal error while loading track, if not retrying to load track, switch back to IDLE\n if (\n !data.levelRetry &&\n this.state === State.WAITING_TRACK &&\n data.context?.type === PlaylistContextType.AUDIO_TRACK\n ) {\n this.state = State.IDLE;\n }\n break;\n case ErrorDetails.BUFFER_FULL_ERROR:\n if (!data.parent || data.parent !== 'audio') {\n return;\n }\n if (this.reduceLengthAndFlushBuffer(data)) {\n this.bufferedTrack = null;\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n }\n break;\n case ErrorDetails.INTERNAL_EXCEPTION:\n this.recoverWorkerError(data);\n break;\n default:\n break;\n }\n }\n\n private onBufferFlushed(\n event: Events.BUFFER_FLUSHED,\n { type }: BufferFlushedData\n ) {\n if (type === ElementaryStreamTypes.AUDIO) {\n this.bufferFlushed = true;\n if (this.state === State.ENDED) {\n this.state = State.IDLE;\n }\n }\n }\n\n private _handleTransmuxComplete(transmuxResult: TransmuxerResult) {\n const id = 'audio';\n const { hls } = this;\n const { remuxResult, chunkMeta } = transmuxResult;\n\n const context = this.getCurrentContext(chunkMeta);\n if (!context) {\n this.resetWhenMissingContext(chunkMeta);\n return;\n }\n const { frag, part, level } = context;\n const { details } = level;\n const { audio, text, id3, initSegment } = remuxResult;\n\n // Check if the current fragment has been aborted. We check this by first seeing if we're still playing the current level.\n // If we are, subsequently check if the currently loading fragment (fragCurrent) has changed.\n if (this.fragContextChanged(frag) || !details) {\n this.fragmentTracker.removeFragment(frag);\n return;\n }\n\n this.state = State.PARSING;\n if (this.switchingTrack && audio) {\n this.completeAudioSwitch(this.switchingTrack);\n }\n\n if (initSegment?.tracks) {\n const mapFragment = frag.initSegment || frag;\n this._bufferInitSegment(initSegment.tracks, mapFragment, chunkMeta);\n hls.trigger(Events.FRAG_PARSING_INIT_SEGMENT, {\n frag: mapFragment,\n id,\n tracks: initSegment.tracks,\n });\n // Only flush audio from old audio tracks when PTS is known on new audio track\n }\n if (audio) {\n const { startPTS, endPTS, startDTS, endDTS } = audio;\n if (part) {\n part.elementaryStreams[ElementaryStreamTypes.AUDIO] = {\n startPTS,\n endPTS,\n startDTS,\n endDTS,\n };\n }\n frag.setElementaryStreamInfo(\n ElementaryStreamTypes.AUDIO,\n startPTS,\n endPTS,\n startDTS,\n endDTS\n );\n this.bufferFragmentData(audio, frag, part, chunkMeta);\n }\n\n if (id3?.samples?.length) {\n const emittedID3: FragParsingMetadataData = Object.assign(\n {\n id,\n frag,\n details,\n },\n id3\n );\n hls.trigger(Events.FRAG_PARSING_METADATA, emittedID3);\n }\n if (text) {\n const emittedText: FragParsingUserdataData = Object.assign(\n {\n id,\n frag,\n details,\n },\n text\n );\n hls.trigger(Events.FRAG_PARSING_USERDATA, emittedText);\n }\n }\n\n private _bufferInitSegment(\n tracks: TrackSet,\n frag: Fragment,\n chunkMeta: ChunkMetadata\n ) {\n if (this.state !== State.PARSING) {\n return;\n }\n // delete any video track found on audio transmuxer\n if (tracks.video) {\n delete tracks.video;\n }\n\n // include levelCodec in audio and video tracks\n const track = tracks.audio;\n if (!track) {\n return;\n }\n\n track.levelCodec = track.codec;\n track.id = 'audio';\n this.log(\n `Init audio buffer, container:${track.container}, codecs[parsed]=[${track.codec}]`\n );\n this.hls.trigger(Events.BUFFER_CODECS, tracks);\n const initSegment = track.initSegment;\n if (initSegment?.byteLength) {\n const segment: BufferAppendingData = {\n type: 'audio',\n frag,\n part: null,\n chunkMeta,\n parent: frag.type,\n data: initSegment,\n };\n this.hls.trigger(Events.BUFFER_APPENDING, segment);\n }\n // trigger handler right now\n this.tick();\n }\n\n protected loadFragment(\n frag: Fragment,\n track: Level,\n targetBufferTime: number\n ) {\n // only load if fragment is not loaded or if in audio switch\n const fragState = this.fragmentTracker.getState(frag);\n this.fragCurrent = frag;\n\n // we force a frag loading in audio switch as fragment tracker might not have evicted previous frags in case of quick audio switch\n if (\n this.switchingTrack ||\n fragState === FragmentState.NOT_LOADED ||\n fragState === FragmentState.PARTIAL\n ) {\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, track);\n } else if (track.details?.live && !this.initPTS[frag.cc]) {\n this.log(\n `Waiting for video PTS in continuity counter ${frag.cc} of live stream before loading audio fragment ${frag.sn} of level ${this.trackId}`\n );\n this.state = State.WAITING_INIT_PTS;\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, track, targetBufferTime);\n }\n } else {\n this.clearTrackerIfNeeded(frag);\n }\n }\n\n private completeAudioSwitch(switchingTrack: MediaPlaylist) {\n const { hls, media, bufferedTrack } = this;\n const bufferedAttributes = bufferedTrack?.attrs;\n const switchAttributes = switchingTrack.attrs;\n if (\n media &&\n bufferedAttributes &&\n (bufferedAttributes.CHANNELS !== switchAttributes.CHANNELS ||\n bufferedAttributes.NAME !== switchAttributes.NAME ||\n bufferedAttributes.LANGUAGE !== switchAttributes.LANGUAGE)\n ) {\n this.log('Switching audio track : flushing all audio');\n super.flushMainBuffer(0, Number.POSITIVE_INFINITY, 'audio');\n }\n this.bufferedTrack = switchingTrack;\n this.switchingTrack = null;\n hls.trigger(Events.AUDIO_TRACK_SWITCHED, { ...switchingTrack });\n }\n}\nexport default AudioStreamController;\n","import { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport {\n ManifestParsedData,\n AudioTracksUpdatedData,\n ErrorData,\n LevelLoadingData,\n AudioTrackLoadedData,\n LevelSwitchingData,\n} from '../types/events';\nimport BasePlaylistController from './base-playlist-controller';\nimport { PlaylistContextType } from '../types/loader';\nimport type Hls from '../hls';\nimport type { HlsUrlParameters } from '../types/level';\nimport type { MediaPlaylist } from '../types/media-playlist';\n\nclass AudioTrackController extends BasePlaylistController {\n private tracks: MediaPlaylist[] = [];\n private groupId: string | null = null;\n private tracksInGroup: MediaPlaylist[] = [];\n private trackId: number = -1;\n private currentTrack: MediaPlaylist | null = null;\n private selectDefaultTrack: boolean = true;\n\n constructor(hls: Hls) {\n super(hls, '[audio-track-controller]');\n this.registerListeners();\n }\n\n private registerListeners() {\n const { hls } = this;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.AUDIO_TRACK_LOADED, this.onAudioTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n public destroy() {\n this.unregisterListeners();\n this.tracks.length = 0;\n this.tracksInGroup.length = 0;\n this.currentTrack = null;\n super.destroy();\n }\n\n protected onManifestLoading(): void {\n this.tracks = [];\n this.groupId = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.currentTrack = null;\n this.selectDefaultTrack = true;\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ): void {\n this.tracks = data.audioTracks || [];\n }\n\n protected onAudioTrackLoaded(\n event: Events.AUDIO_TRACK_LOADED,\n data: AudioTrackLoadedData\n ): void {\n const { id, groupId, details } = data;\n const trackInActiveGroup = this.tracksInGroup[id];\n\n if (!trackInActiveGroup || trackInActiveGroup.groupId !== groupId) {\n this.warn(\n `Track with id:${id} and group:${groupId} not found in active group ${trackInActiveGroup.groupId}`\n );\n return;\n }\n\n const curDetails = trackInActiveGroup.details;\n trackInActiveGroup.details = data.details;\n this.log(\n `audio-track ${id} \"${trackInActiveGroup.name}\" lang:${trackInActiveGroup.lang} group:${groupId} loaded [${details.startSN}-${details.endSN}]`\n );\n\n if (id === this.trackId) {\n this.playlistLoaded(id, data, curDetails);\n }\n }\n\n protected onLevelLoading(\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData\n ): void {\n this.switchLevel(data.level);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.switchLevel(data.level);\n }\n\n private switchLevel(levelIndex: number) {\n const levelInfo = this.hls.levels[levelIndex];\n\n if (!levelInfo?.audioGroupIds) {\n return;\n }\n\n const audioGroupId = levelInfo.audioGroupIds[levelInfo.urlId];\n if (this.groupId !== audioGroupId) {\n this.groupId = audioGroupId || null;\n\n const audioTracks = this.tracks.filter(\n (track): boolean => !audioGroupId || track.groupId === audioGroupId\n );\n\n // Disable selectDefaultTrack if there are no default tracks\n if (\n this.selectDefaultTrack &&\n !audioTracks.some((track) => track.default)\n ) {\n this.selectDefaultTrack = false;\n }\n\n this.tracksInGroup = audioTracks;\n const audioTracksUpdated: AudioTracksUpdatedData = { audioTracks };\n this.log(\n `Updating audio tracks, ${audioTracks.length} track(s) found in group:${audioGroupId}`\n );\n this.hls.trigger(Events.AUDIO_TRACKS_UPDATED, audioTracksUpdated);\n\n this.selectInitialTrack();\n } else if (this.shouldReloadPlaylist(this.currentTrack)) {\n // Retry playlist loading if no playlist is or has been loaded yet\n this.setAudioTrack(this.trackId);\n }\n }\n\n protected onError(event: Events.ERROR, data: ErrorData): void {\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.AUDIO_TRACK &&\n data.context.id === this.trackId &&\n data.context.groupId === this.groupId\n ) {\n this.requestScheduled = -1;\n this.checkRetry(data);\n }\n }\n\n get audioTracks(): MediaPlaylist[] {\n return this.tracksInGroup;\n }\n\n get audioTrack(): number {\n return this.trackId;\n }\n\n set audioTrack(newId: number) {\n // If audio track is selected from API then don't choose from the manifest default track\n this.selectDefaultTrack = false;\n this.setAudioTrack(newId);\n }\n\n private setAudioTrack(newId: number): void {\n const tracks = this.tracksInGroup;\n\n // check if level idx is valid\n if (newId < 0 || newId >= tracks.length) {\n this.warn('Invalid id passed to audio-track controller');\n return;\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n const lastTrack = this.currentTrack;\n tracks[this.trackId];\n const track = tracks[newId];\n const { groupId, name } = track;\n this.log(\n `Switching to audio-track ${newId} \"${name}\" lang:${track.lang} group:${groupId}`\n );\n this.trackId = newId;\n this.currentTrack = track;\n this.selectDefaultTrack = false;\n this.hls.trigger(Events.AUDIO_TRACK_SWITCHING, { ...track });\n // Do not reload track unless live\n if (track.details && !track.details.live) {\n return;\n }\n const hlsUrlParameters = this.switchParams(track.url, lastTrack?.details);\n this.loadPlaylist(hlsUrlParameters);\n }\n\n private selectInitialTrack(): void {\n const audioTracks = this.tracksInGroup;\n const trackId =\n this.findTrackId(this.currentTrack) | this.findTrackId(null);\n\n if (trackId !== -1) {\n this.setAudioTrack(trackId);\n } else {\n const error = new Error(\n `No track found for running audio group-ID: ${this.groupId} track count: ${audioTracks.length}`\n );\n this.warn(error.message);\n\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.AUDIO_TRACK_LOAD_ERROR,\n fatal: true,\n error,\n });\n }\n }\n\n private findTrackId(currentTrack: MediaPlaylist | null): number {\n const audioTracks = this.tracksInGroup;\n for (let i = 0; i < audioTracks.length; i++) {\n const track = audioTracks[i];\n if (!this.selectDefaultTrack || track.default) {\n if (\n !currentTrack ||\n (currentTrack.attrs['STABLE-RENDITION-ID'] !== undefined &&\n currentTrack.attrs['STABLE-RENDITION-ID'] ===\n track.attrs['STABLE-RENDITION-ID'])\n ) {\n return track.id;\n }\n if (\n currentTrack.name === track.name &&\n currentTrack.lang === track.lang\n ) {\n return track.id;\n }\n }\n }\n return -1;\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n super.loadPlaylist();\n const audioTrack = this.tracksInGroup[this.trackId];\n if (this.shouldLoadPlaylist(audioTrack)) {\n const id = audioTrack.id;\n const groupId = audioTrack.groupId as string;\n let url = audioTrack.url;\n if (hlsUrlParameters) {\n try {\n url = hlsUrlParameters.addDirectives(url);\n } catch (error) {\n this.warn(\n `Could not construct new URL with HLS Delivery Directives: ${error}`\n );\n }\n }\n // track not retrieved yet, or live playlist we need to (re)load it\n this.log(\n `loading audio-track playlist ${id} \"${audioTrack.name}\" lang:${audioTrack.lang} group:${groupId}`\n );\n this.clearTimer();\n this.hls.trigger(Events.AUDIO_TRACK_LOADING, {\n url,\n id,\n groupId,\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n}\n\nexport default AudioTrackController;\n","import type { Level } from '../types/level';\nimport type { MediaAttributes, MediaPlaylist } from '../types/media-playlist';\n\nexport function subtitleOptionsIdentical(\n trackList1: MediaPlaylist[] | Level[],\n trackList2: MediaPlaylist[]\n): boolean {\n if (trackList1.length !== trackList2.length) {\n return false;\n }\n for (let i = 0; i < trackList1.length; i++) {\n if (\n !subtitleAttributesIdentical(\n trackList1[i].attrs as MediaAttributes,\n trackList2[i].attrs\n )\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport function subtitleAttributesIdentical(\n attrs1: MediaAttributes,\n attrs2: MediaAttributes\n): boolean {\n // Media options with the same rendition ID must be bit identical\n const stableRenditionId = attrs1['STABLE-RENDITION-ID'];\n if (stableRenditionId) {\n return stableRenditionId === attrs2['STABLE-RENDITION-ID'];\n }\n // When rendition ID is not present, compare attributes\n return ![\n 'LANGUAGE',\n 'NAME',\n 'CHARACTERISTICS',\n 'AUTOSELECT',\n 'DEFAULT',\n 'FORCED',\n ].some(\n (subtitleAttribute) =>\n attrs1[subtitleAttribute] !== attrs2[subtitleAttribute]\n );\n}\n","import { Events } from '../events';\nimport { Bufferable, BufferHelper } from '../utils/buffer-helper';\nimport { findFragmentByPTS } from './fragment-finders';\nimport { alignMediaPlaylistByPDT } from '../utils/discontinuities';\nimport { addSliding } from './level-helper';\nimport { FragmentState } from './fragment-tracker';\nimport BaseStreamController, { State } from './base-stream-controller';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Level } from '../types/level';\nimport { subtitleOptionsIdentical } from '../utils/media-option-attributes';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { FragmentTracker } from './fragment-tracker';\nimport type KeyLoader from '../loader/key-loader';\nimport type { LevelDetails } from '../loader/level-details';\nimport type { Fragment } from '../loader/fragment';\nimport type {\n ErrorData,\n FragLoadedData,\n SubtitleFragProcessed,\n SubtitleTracksUpdatedData,\n TrackLoadedData,\n TrackSwitchedData,\n BufferFlushingData,\n LevelLoadedData,\n FragBufferedData,\n} from '../types/events';\n\nconst TICK_INTERVAL = 500; // how often to tick in ms\n\ninterface TimeRange {\n start: number;\n end: number;\n}\n\nexport class SubtitleStreamController\n extends BaseStreamController\n implements NetworkComponentAPI\n{\n protected levels: Array<Level> = [];\n\n private currentTrackId: number = -1;\n private tracksBuffered: Array<TimeRange[]> = [];\n private mainDetails: LevelDetails | null = null;\n\n constructor(\n hls: Hls,\n fragmentTracker: FragmentTracker,\n keyLoader: KeyLoader\n ) {\n super(\n hls,\n fragmentTracker,\n keyLoader,\n '[subtitle-stream-controller]',\n PlaylistLevelType.SUBTITLE\n );\n this._registerListeners();\n }\n\n protected onHandlerDestroying() {\n this._unregisterListeners();\n this.mainDetails = null;\n }\n\n private _registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.on(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.on(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n private _unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.LEVEL_LOADED, this.onLevelLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.off(Events.SUBTITLE_TRACK_SWITCH, this.onSubtitleTrackSwitch, this);\n hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.off(Events.SUBTITLE_FRAG_PROCESSED, this.onSubtitleFragProcessed, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.FRAG_BUFFERED, this.onFragBuffered, this);\n }\n\n startLoad(startPosition: number) {\n this.stopLoad();\n this.state = State.IDLE;\n\n this.setInterval(TICK_INTERVAL);\n\n this.nextLoadPosition =\n this.startPosition =\n this.lastCurrentTime =\n startPosition;\n\n this.tick();\n }\n\n onManifestLoading() {\n this.mainDetails = null;\n this.fragmentTracker.removeAllFragments();\n }\n\n onMediaDetaching(): void {\n this.tracksBuffered = [];\n super.onMediaDetaching();\n }\n\n onLevelLoaded(event: Events.LEVEL_LOADED, data: LevelLoadedData) {\n this.mainDetails = data.details;\n }\n\n onSubtitleFragProcessed(\n event: Events.SUBTITLE_FRAG_PROCESSED,\n data: SubtitleFragProcessed\n ) {\n const { frag, success } = data;\n this.fragPrevious = frag;\n this.state = State.IDLE;\n if (!success) {\n return;\n }\n\n const buffered = this.tracksBuffered[this.currentTrackId];\n if (!buffered) {\n return;\n }\n\n // Create/update a buffered array matching the interface used by BufferHelper.bufferedInfo\n // so we can re-use the logic used to detect how much has been buffered\n let timeRange: TimeRange | undefined;\n const fragStart = frag.start;\n for (let i = 0; i < buffered.length; i++) {\n if (fragStart >= buffered[i].start && fragStart <= buffered[i].end) {\n timeRange = buffered[i];\n break;\n }\n }\n\n const fragEnd = frag.start + frag.duration;\n if (timeRange) {\n timeRange.end = fragEnd;\n } else {\n timeRange = {\n start: fragStart,\n end: fragEnd,\n };\n buffered.push(timeRange);\n }\n this.fragmentTracker.fragBuffered(frag);\n }\n\n onBufferFlushing(event: Events.BUFFER_FLUSHING, data: BufferFlushingData) {\n const { startOffset, endOffset } = data;\n if (startOffset === 0 && endOffset !== Number.POSITIVE_INFINITY) {\n const endOffsetSubtitles = endOffset - 1;\n if (endOffsetSubtitles <= 0) {\n return;\n }\n data.endOffsetSubtitles = Math.max(0, endOffsetSubtitles);\n this.tracksBuffered.forEach((buffered) => {\n for (let i = 0; i < buffered.length; ) {\n if (buffered[i].end <= endOffsetSubtitles) {\n buffered.shift();\n continue;\n } else if (buffered[i].start < endOffsetSubtitles) {\n buffered[i].start = endOffsetSubtitles;\n } else {\n break;\n }\n i++;\n }\n });\n this.fragmentTracker.removeFragmentsInRange(\n startOffset,\n endOffsetSubtitles,\n PlaylistLevelType.SUBTITLE\n );\n }\n }\n\n onFragBuffered(event: Events.FRAG_BUFFERED, data: FragBufferedData) {\n if (!this.loadedmetadata && data.frag.type === PlaylistLevelType.MAIN) {\n if (this.media?.buffered.length) {\n this.loadedmetadata = true;\n }\n }\n }\n\n // If something goes wrong, proceed to next frag, if we were processing one.\n onError(event: Events.ERROR, data: ErrorData) {\n const frag = data.frag;\n\n if (frag?.type === PlaylistLevelType.SUBTITLE) {\n if (this.fragCurrent) {\n this.fragCurrent.abortRequests();\n }\n if (this.state !== State.STOPPED) {\n this.state = State.IDLE;\n }\n }\n }\n\n // Got all new subtitle levels.\n onSubtitleTracksUpdated(\n event: Events.SUBTITLE_TRACKS_UPDATED,\n { subtitleTracks }: SubtitleTracksUpdatedData\n ) {\n if (subtitleOptionsIdentical(this.levels, subtitleTracks)) {\n this.levels = subtitleTracks.map(\n (mediaPlaylist) => new Level(mediaPlaylist)\n );\n return;\n }\n this.tracksBuffered = [];\n this.levels = subtitleTracks.map((mediaPlaylist) => {\n const level = new Level(mediaPlaylist);\n this.tracksBuffered[level.id] = [];\n return level;\n });\n this.fragmentTracker.removeFragmentsInRange(\n 0,\n Number.POSITIVE_INFINITY,\n PlaylistLevelType.SUBTITLE\n );\n this.fragPrevious = null;\n this.mediaBuffer = null;\n }\n\n onSubtitleTrackSwitch(\n event: Events.SUBTITLE_TRACK_SWITCH,\n data: TrackSwitchedData\n ) {\n this.currentTrackId = data.id;\n\n if (!this.levels.length || this.currentTrackId === -1) {\n this.clearInterval();\n return;\n }\n\n // Check if track has the necessary details to load fragments\n const currentTrack = this.levels[this.currentTrackId];\n if (currentTrack?.details) {\n this.mediaBuffer = this.mediaBufferTimeRanges;\n } else {\n this.mediaBuffer = null;\n }\n if (currentTrack) {\n this.setInterval(TICK_INTERVAL);\n }\n }\n\n // Got a new set of subtitle fragments.\n onSubtitleTrackLoaded(\n event: Events.SUBTITLE_TRACK_LOADED,\n data: TrackLoadedData\n ) {\n const { details: newDetails, id: trackId } = data;\n const { currentTrackId, levels } = this;\n if (!levels.length) {\n return;\n }\n const track: Level = levels[currentTrackId];\n if (trackId >= levels.length || trackId !== currentTrackId || !track) {\n return;\n }\n this.mediaBuffer = this.mediaBufferTimeRanges;\n let sliding = 0;\n if (newDetails.live || track.details?.live) {\n const mainDetails = this.mainDetails;\n if (newDetails.deltaUpdateFailed || !mainDetails) {\n return;\n }\n const mainSlidingStartFragment = mainDetails.fragments[0];\n if (!track.details) {\n if (newDetails.hasProgramDateTime && mainDetails.hasProgramDateTime) {\n alignMediaPlaylistByPDT(newDetails, mainDetails);\n sliding = newDetails.fragments[0].start;\n } else if (mainSlidingStartFragment) {\n // line up live playlist with main so that fragments in range are loaded\n sliding = mainSlidingStartFragment.start;\n addSliding(newDetails, sliding);\n }\n } else {\n sliding = this.alignPlaylists(newDetails, track.details);\n if (sliding === 0 && mainSlidingStartFragment) {\n // realign with main when there is no overlap with last refresh\n sliding = mainSlidingStartFragment.start;\n addSliding(newDetails, sliding);\n }\n }\n }\n track.details = newDetails;\n this.levelLastLoaded = trackId;\n\n if (!this.startFragRequested && (this.mainDetails || !newDetails.live)) {\n this.setStartPosition(track.details, sliding);\n }\n\n // trigger handler right now\n this.tick();\n\n // If playlist is misaligned because of bad PDT or drift, delete details to resync with main on reload\n if (\n newDetails.live &&\n !this.fragCurrent &&\n this.media &&\n this.state === State.IDLE\n ) {\n const foundFrag = findFragmentByPTS(\n null,\n newDetails.fragments,\n this.media.currentTime,\n 0\n );\n if (!foundFrag) {\n this.warn('Subtitle playlist not aligned with playback');\n track.details = undefined;\n }\n }\n }\n\n _handleFragmentLoadComplete(fragLoadedData: FragLoadedData) {\n const { frag, payload } = fragLoadedData;\n const decryptData = frag.decryptdata;\n const hls = this.hls;\n\n if (this.fragContextChanged(frag)) {\n return;\n }\n // check to see if the payload needs to be decrypted\n if (\n payload &&\n payload.byteLength > 0 &&\n decryptData &&\n decryptData.key &&\n decryptData.iv &&\n decryptData.method === 'AES-128'\n ) {\n const startTime = performance.now();\n // decrypt the subtitles\n this.decrypter\n .decrypt(\n new Uint8Array(payload),\n decryptData.key.buffer,\n decryptData.iv.buffer\n )\n .catch((err) => {\n hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.FRAG_DECRYPT_ERROR,\n fatal: false,\n error: err,\n reason: err.message,\n frag,\n });\n throw err;\n })\n .then((decryptedData) => {\n const endTime = performance.now();\n hls.trigger(Events.FRAG_DECRYPTED, {\n frag,\n payload: decryptedData,\n stats: {\n tstart: startTime,\n tdecrypt: endTime,\n },\n });\n })\n .catch((err) => {\n this.warn(`${err.name}: ${err.message}`);\n this.state = State.IDLE;\n });\n }\n }\n\n doTick() {\n if (!this.media) {\n this.state = State.IDLE;\n return;\n }\n\n if (this.state === State.IDLE) {\n const { currentTrackId, levels } = this;\n const track = levels[currentTrackId];\n if (!levels.length || !track || !track.details) {\n return;\n }\n const { config } = this;\n const currentTime = this.getLoadPosition();\n const bufferedInfo = BufferHelper.bufferedInfo(\n this.tracksBuffered[this.currentTrackId] || [],\n currentTime,\n config.maxBufferHole\n );\n const { end: targetBufferTime, len: bufferLen } = bufferedInfo;\n\n const mainBufferInfo = this.getFwdBufferInfo(\n this.media,\n PlaylistLevelType.MAIN\n );\n const trackDetails = track.details as LevelDetails;\n const maxBufLen =\n this.getMaxBufferLength(mainBufferInfo?.len) +\n trackDetails.levelTargetDuration;\n\n if (bufferLen > maxBufLen) {\n return;\n }\n const fragments = trackDetails.fragments;\n const fragLen = fragments.length;\n const end = trackDetails.edge;\n\n let foundFrag: Fragment | null = null;\n const fragPrevious = this.fragPrevious;\n if (targetBufferTime < end) {\n const tolerance = config.maxFragLookUpTolerance;\n const lookupTolerance =\n targetBufferTime > end - tolerance ? 0 : tolerance;\n foundFrag = findFragmentByPTS(\n fragPrevious,\n fragments,\n Math.max(fragments[0].start, targetBufferTime),\n lookupTolerance\n );\n if (\n !foundFrag &&\n fragPrevious &&\n fragPrevious.start < fragments[0].start\n ) {\n foundFrag = fragments[0];\n }\n } else {\n foundFrag = fragments[fragLen - 1];\n }\n if (!foundFrag) {\n return;\n }\n foundFrag = this.mapToInitFragWhenRequired(foundFrag) as Fragment;\n if (foundFrag.sn !== 'initSegment') {\n // Load earlier fragment in same discontinuity to make up for misaligned playlists and cues that extend beyond end of segment\n const curSNIdx = foundFrag.sn - trackDetails.startSN;\n const prevFrag = fragments[curSNIdx - 1];\n if (\n prevFrag &&\n prevFrag.cc === foundFrag.cc &&\n this.fragmentTracker.getState(prevFrag) === FragmentState.NOT_LOADED\n ) {\n foundFrag = prevFrag;\n }\n }\n if (\n this.fragmentTracker.getState(foundFrag) === FragmentState.NOT_LOADED\n ) {\n // only load if fragment is not loaded\n this.loadFragment(foundFrag, track, targetBufferTime);\n }\n }\n }\n\n protected getMaxBufferLength(mainBufferLength?: number): number {\n const maxConfigBuffer = super.getMaxBufferLength();\n if (!mainBufferLength) {\n return maxConfigBuffer;\n }\n return Math.max(maxConfigBuffer, mainBufferLength);\n }\n\n protected loadFragment(\n frag: Fragment,\n level: Level,\n targetBufferTime: number\n ) {\n this.fragCurrent = frag;\n if (frag.sn === 'initSegment') {\n this._loadInitSegment(frag, level);\n } else {\n this.startFragRequested = true;\n super.loadFragment(frag, level, targetBufferTime);\n }\n }\n\n get mediaBufferTimeRanges(): Bufferable {\n return new BufferableInstance(\n this.tracksBuffered[this.currentTrackId] || []\n );\n }\n}\n\nclass BufferableInstance implements Bufferable {\n public readonly buffered: TimeRanges;\n\n constructor(timeranges: TimeRange[]) {\n const getRange = (\n name: 'start' | 'end',\n index: number,\n length: number\n ): number => {\n index = index >>> 0;\n if (index > length - 1) {\n throw new DOMException(\n `Failed to execute '${name}' on 'TimeRanges': The index provided (${index}) is greater than the maximum bound (${length})`\n );\n }\n return timeranges[index][name];\n };\n this.buffered = {\n get length() {\n return timeranges.length;\n },\n end(index: number): number {\n return getRange('end', index, timeranges.length);\n },\n start(index: number): number {\n return getRange('start', index, timeranges.length);\n },\n };\n }\n}\n","import { Events } from '../events';\nimport { clearCurrentCues } from '../utils/texttrack-utils';\nimport BasePlaylistController from './base-playlist-controller';\nimport type { HlsUrlParameters } from '../types/level';\nimport type Hls from '../hls';\nimport type {\n TrackLoadedData,\n MediaAttachedData,\n SubtitleTracksUpdatedData,\n ManifestParsedData,\n LevelSwitchingData,\n} from '../types/events';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport { ErrorData, LevelLoadingData } from '../types/events';\nimport { PlaylistContextType } from '../types/loader';\n\nclass SubtitleTrackController extends BasePlaylistController {\n private media: HTMLMediaElement | null = null;\n private tracks: MediaPlaylist[] = [];\n private groupId: string | null = null;\n private tracksInGroup: MediaPlaylist[] = [];\n private trackId: number = -1;\n private selectDefaultTrack: boolean = true;\n private queuedDefaultTrack: number = -1;\n private trackChangeListener: () => void = () => this.onTextTracksChanged();\n private asyncPollTrackChange: () => void = () => this.pollTrackChange(0);\n private useTextTrackPolling: boolean = false;\n private subtitlePollingInterval: number = -1;\n private _subtitleDisplay: boolean = true;\n\n constructor(hls: Hls) {\n super(hls, '[subtitle-track-controller]');\n this.registerListeners();\n }\n\n public destroy() {\n this.unregisterListeners();\n this.tracks.length = 0;\n this.tracksInGroup.length = 0;\n this.trackChangeListener = this.asyncPollTrackChange = null as any;\n super.destroy();\n }\n\n public get subtitleDisplay(): boolean {\n return this._subtitleDisplay;\n }\n\n public set subtitleDisplay(value: boolean) {\n this._subtitleDisplay = value;\n if (this.trackId > -1) {\n this.toggleTrackModes(this.trackId);\n }\n }\n\n private registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.on(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.on(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.LEVEL_LOADING, this.onLevelLoading, this);\n hls.off(Events.LEVEL_SWITCHING, this.onLevelSwitching, this);\n hls.off(Events.SUBTITLE_TRACK_LOADED, this.onSubtitleTrackLoaded, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n // Listen for subtitle track change, then extract the current track ID.\n protected onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ): void {\n this.media = data.media;\n if (!this.media) {\n return;\n }\n\n if (this.queuedDefaultTrack > -1) {\n this.subtitleTrack = this.queuedDefaultTrack;\n this.queuedDefaultTrack = -1;\n }\n\n this.useTextTrackPolling = !(\n this.media.textTracks && 'onchange' in this.media.textTracks\n );\n if (this.useTextTrackPolling) {\n this.pollTrackChange(500);\n } else {\n this.media.textTracks.addEventListener(\n 'change',\n this.asyncPollTrackChange\n );\n }\n }\n\n private pollTrackChange(timeout: number) {\n self.clearInterval(this.subtitlePollingInterval);\n this.subtitlePollingInterval = self.setInterval(\n this.trackChangeListener,\n timeout\n );\n }\n\n protected onMediaDetaching(): void {\n if (!this.media) {\n return;\n }\n\n self.clearInterval(this.subtitlePollingInterval);\n if (!this.useTextTrackPolling) {\n this.media.textTracks.removeEventListener(\n 'change',\n this.asyncPollTrackChange\n );\n }\n\n if (this.trackId > -1) {\n this.queuedDefaultTrack = this.trackId;\n }\n\n const textTracks = filterSubtitleTracks(this.media.textTracks);\n // Clear loaded cues on media detachment from tracks\n textTracks.forEach((track) => {\n clearCurrentCues(track);\n });\n // Disable all subtitle tracks before detachment so when reattached only tracks in that content are enabled.\n this.subtitleTrack = -1;\n this.media = null;\n }\n\n protected onManifestLoading(): void {\n this.tracks = [];\n this.groupId = null;\n this.tracksInGroup = [];\n this.trackId = -1;\n this.selectDefaultTrack = true;\n }\n\n // Fired whenever a new manifest is loaded.\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ): void {\n this.tracks = data.subtitleTracks;\n }\n\n protected onSubtitleTrackLoaded(\n event: Events.SUBTITLE_TRACK_LOADED,\n data: TrackLoadedData\n ): void {\n const { id, details } = data;\n const { trackId } = this;\n const currentTrack = this.tracksInGroup[trackId];\n\n if (!currentTrack) {\n this.warn(`Invalid subtitle track id ${id}`);\n return;\n }\n\n const curDetails = currentTrack.details;\n currentTrack.details = data.details;\n this.log(\n `subtitle track ${id} loaded [${details.startSN}-${details.endSN}]`\n );\n\n if (id === this.trackId) {\n this.playlistLoaded(id, data, curDetails);\n }\n }\n\n protected onLevelLoading(\n event: Events.LEVEL_LOADING,\n data: LevelLoadingData\n ): void {\n this.switchLevel(data.level);\n }\n\n protected onLevelSwitching(\n event: Events.LEVEL_SWITCHING,\n data: LevelSwitchingData\n ): void {\n this.switchLevel(data.level);\n }\n\n private switchLevel(levelIndex: number) {\n const levelInfo = this.hls.levels[levelIndex];\n if (!levelInfo?.textGroupIds) {\n return;\n }\n const textGroupId = levelInfo.textGroupIds[levelInfo.urlId];\n const lastTrack = this.tracksInGroup\n ? this.tracksInGroup[this.trackId]\n : undefined;\n if (this.groupId !== textGroupId) {\n const subtitleTracks = this.tracks.filter(\n (track): boolean => !textGroupId || track.groupId === textGroupId\n );\n this.tracksInGroup = subtitleTracks;\n const initialTrackId =\n this.findTrackId(lastTrack?.name) || this.findTrackId();\n this.groupId = textGroupId || null;\n\n const subtitleTracksUpdated: SubtitleTracksUpdatedData = {\n subtitleTracks,\n };\n this.log(\n `Updating subtitle tracks, ${subtitleTracks.length} track(s) found in \"${textGroupId}\" group-id`\n );\n this.hls.trigger(Events.SUBTITLE_TRACKS_UPDATED, subtitleTracksUpdated);\n\n if (initialTrackId !== -1) {\n this.setSubtitleTrack(initialTrackId, lastTrack);\n }\n } else if (this.shouldReloadPlaylist(lastTrack)) {\n // Retry playlist loading if no playlist is or has been loaded yet\n this.setSubtitleTrack(this.trackId, lastTrack);\n }\n }\n\n private findTrackId(name?: string): number {\n const textTracks = this.tracksInGroup;\n for (let i = 0; i < textTracks.length; i++) {\n const track = textTracks[i];\n if (!this.selectDefaultTrack || track.default) {\n if (!name || name === track.name) {\n return track.id;\n }\n }\n }\n return -1;\n }\n\n protected onError(event: Events.ERROR, data: ErrorData): void {\n if (data.fatal || !data.context) {\n return;\n }\n\n if (\n data.context.type === PlaylistContextType.SUBTITLE_TRACK &&\n data.context.id === this.trackId &&\n data.context.groupId === this.groupId\n ) {\n this.checkRetry(data);\n }\n }\n\n /** get alternate subtitle tracks list from playlist **/\n get subtitleTracks(): MediaPlaylist[] {\n return this.tracksInGroup;\n }\n\n /** get/set index of the selected subtitle track (based on index in subtitle track lists) **/\n get subtitleTrack(): number {\n return this.trackId;\n }\n\n set subtitleTrack(newId: number) {\n this.selectDefaultTrack = false;\n const lastTrack = this.tracksInGroup\n ? this.tracksInGroup[this.trackId]\n : undefined;\n this.setSubtitleTrack(newId, lastTrack);\n }\n\n protected loadPlaylist(hlsUrlParameters?: HlsUrlParameters): void {\n super.loadPlaylist();\n const currentTrack = this.tracksInGroup[this.trackId];\n if (this.shouldLoadPlaylist(currentTrack)) {\n const id = currentTrack.id;\n const groupId = currentTrack.groupId as string;\n let url = currentTrack.url;\n if (hlsUrlParameters) {\n try {\n url = hlsUrlParameters.addDirectives(url);\n } catch (error) {\n this.warn(\n `Could not construct new URL with HLS Delivery Directives: ${error}`\n );\n }\n }\n this.log(`Loading subtitle playlist for id ${id}`);\n this.hls.trigger(Events.SUBTITLE_TRACK_LOADING, {\n url,\n id,\n groupId,\n deliveryDirectives: hlsUrlParameters || null,\n });\n }\n }\n\n /**\n * Disables the old subtitleTrack and sets current mode on the next subtitleTrack.\n * This operates on the DOM textTracks.\n * A value of -1 will disable all subtitle tracks.\n */\n private toggleTrackModes(newId: number): void {\n const { media, trackId } = this;\n if (!media) {\n return;\n }\n\n const textTracks = filterSubtitleTracks(media.textTracks);\n const groupTracks = textTracks.filter(\n (track) => (track as any).groupId === this.groupId\n );\n if (newId === -1) {\n [].slice.call(textTracks).forEach((track) => {\n track.mode = 'disabled';\n });\n } else {\n const oldTrack = groupTracks[trackId];\n if (oldTrack) {\n oldTrack.mode = 'disabled';\n }\n }\n\n const nextTrack = groupTracks[newId];\n if (nextTrack) {\n nextTrack.mode = this.subtitleDisplay ? 'showing' : 'hidden';\n }\n }\n\n /**\n * This method is responsible for validating the subtitle index and periodically reloading if live.\n * Dispatches the SUBTITLE_TRACK_SWITCH event, which instructs the subtitle-stream-controller to load the selected track.\n */\n private setSubtitleTrack(\n newId: number,\n lastTrack: MediaPlaylist | undefined\n ): void {\n const tracks = this.tracksInGroup;\n\n // setting this.subtitleTrack will trigger internal logic\n // if media has not been attached yet, it will fail\n // we keep a reference to the default track id\n // and we'll set subtitleTrack when onMediaAttached is triggered\n if (!this.media) {\n this.queuedDefaultTrack = newId;\n return;\n }\n\n if (this.trackId !== newId) {\n this.toggleTrackModes(newId);\n }\n\n // exit if track id as already set or invalid\n if (\n (this.trackId === newId && (newId === -1 || tracks[newId]?.details)) ||\n newId < -1 ||\n newId >= tracks.length\n ) {\n return;\n }\n\n // stopping live reloading timer if any\n this.clearTimer();\n\n const track = tracks[newId];\n\n this.log(\n `Switching to subtitle-track ${newId}` +\n (track\n ? ` \"${track.name}\" lang:${track.lang} group:${track.groupId}`\n : '')\n );\n this.trackId = newId;\n if (track) {\n const { id, groupId = '', name, type, url } = track;\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, {\n id,\n groupId,\n name,\n type,\n url,\n });\n const hlsUrlParameters = this.switchParams(track.url, lastTrack?.details);\n this.loadPlaylist(hlsUrlParameters);\n } else {\n // switch to -1\n this.hls.trigger(Events.SUBTITLE_TRACK_SWITCH, { id: newId });\n }\n }\n\n private onTextTracksChanged(): void {\n if (!this.useTextTrackPolling) {\n self.clearInterval(this.subtitlePollingInterval);\n }\n // Media is undefined when switching streams via loadSource()\n if (!this.media || !this.hls.config.renderTextTracksNatively) {\n return;\n }\n\n let trackId: number = -1;\n const tracks = filterSubtitleTracks(this.media.textTracks);\n for (let id = 0; id < tracks.length; id++) {\n if (tracks[id].mode === 'hidden') {\n // Do not break in case there is a following track with showing.\n trackId = id;\n } else if (tracks[id].mode === 'showing') {\n trackId = id;\n break;\n }\n }\n\n // Setting current subtitleTrack will invoke code.\n if (this.subtitleTrack !== trackId) {\n this.subtitleTrack = trackId;\n }\n }\n}\n\nfunction filterSubtitleTracks(textTrackList: TextTrackList): TextTrack[] {\n const tracks: TextTrack[] = [];\n for (let i = 0; i < textTrackList.length; i++) {\n const track = textTrackList[i];\n // Edge adds a track without a label; we don't want to use it\n if (\n (track.kind === 'subtitles' || track.kind === 'captions') &&\n track.label\n ) {\n tracks.push(textTrackList[i]);\n }\n }\n return tracks;\n}\n\nexport default SubtitleTrackController;\n","import { logger } from '../utils/logger';\nimport type {\n BufferOperation,\n BufferOperationQueues,\n SourceBuffers,\n SourceBufferName,\n} from '../types/buffer';\n\nexport default class BufferOperationQueue {\n private buffers: SourceBuffers;\n private queues: BufferOperationQueues = {\n video: [],\n audio: [],\n audiovideo: [],\n };\n\n constructor(sourceBufferReference: SourceBuffers) {\n this.buffers = sourceBufferReference;\n }\n\n public append(operation: BufferOperation, type: SourceBufferName) {\n const queue = this.queues[type];\n queue.push(operation);\n if (queue.length === 1 && this.buffers[type]) {\n this.executeNext(type);\n }\n }\n\n public insertAbort(operation: BufferOperation, type: SourceBufferName) {\n const queue = this.queues[type];\n queue.unshift(operation);\n this.executeNext(type);\n }\n\n public appendBlocker(type: SourceBufferName): Promise<{}> {\n let execute;\n const promise: Promise<{}> = new Promise((resolve) => {\n execute = resolve;\n });\n const operation: BufferOperation = {\n execute,\n onStart: () => {},\n onComplete: () => {},\n onError: () => {},\n };\n\n this.append(operation, type);\n return promise;\n }\n\n public executeNext(type: SourceBufferName) {\n const { buffers, queues } = this;\n const sb = buffers[type];\n const queue = queues[type];\n if (queue.length) {\n const operation: BufferOperation = queue[0];\n try {\n // Operations are expected to result in an 'updateend' event being fired. If not, the queue will lock. Operations\n // which do not end with this event must call _onSBUpdateEnd manually\n operation.execute();\n } catch (e) {\n logger.warn(\n '[buffer-operation-queue]: Unhandled exception executing the current operation'\n );\n operation.onError(e);\n\n // Only shift the current operation off, otherwise the updateend handler will do this for us\n if (!sb?.updating) {\n queue.shift();\n this.executeNext(type);\n }\n }\n }\n }\n\n public shiftAndExecuteNext(type: SourceBufferName) {\n this.queues[type].shift();\n this.executeNext(type);\n }\n\n public current(type: SourceBufferName) {\n return this.queues[type][0];\n }\n}\n","import { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport { ErrorDetails, ErrorTypes } from '../errors';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { getMediaSource } from '../utils/mediasource-helper';\nimport { ElementaryStreamTypes } from '../loader/fragment';\nimport type { TrackSet } from '../types/track';\nimport BufferOperationQueue from './buffer-operation-queue';\nimport {\n BufferOperation,\n SourceBuffers,\n SourceBufferName,\n SourceBufferListeners,\n} from '../types/buffer';\nimport type {\n LevelUpdatedData,\n BufferAppendingData,\n MediaAttachingData,\n ManifestParsedData,\n BufferCodecsData,\n BufferEOSData,\n BufferFlushingData,\n FragParsedData,\n FragChangedData,\n} from '../types/events';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { ChunkMetadata } from '../types/transmuxer';\nimport type Hls from '../hls';\nimport type { LevelDetails } from '../loader/level-details';\n\nconst MediaSource = getMediaSource();\nconst VIDEO_CODEC_PROFILE_REPACE = /([ha]vc.)(?:\\.[^.,]+)+/;\n\nexport default class BufferController implements ComponentAPI {\n // The level details used to determine duration, target-duration and live\n private details: LevelDetails | null = null;\n // cache the self generated object url to detect hijack of video tag\n private _objectUrl: string | null = null;\n // A queue of buffer operations which require the SourceBuffer to not be updating upon execution\n private operationQueue!: BufferOperationQueue;\n // References to event listeners for each SourceBuffer, so that they can be referenced for event removal\n private listeners!: SourceBufferListeners;\n\n private hls: Hls;\n\n // The number of BUFFER_CODEC events received before any sourceBuffers are created\n public bufferCodecEventsExpected: number = 0;\n\n // The total number of BUFFER_CODEC events received\n private _bufferCodecEventsTotal: number = 0;\n\n // A reference to the attached media element\n public media: HTMLMediaElement | null = null;\n\n // A reference to the active media source\n public mediaSource: MediaSource | null = null;\n\n // Last MP3 audio chunk appended\n private lastMpegAudioChunk: ChunkMetadata | null = null;\n\n // counters\n public appendError: number = 0;\n\n public tracks: TrackSet = {};\n public pendingTracks: TrackSet = {};\n public sourceBuffer!: SourceBuffers;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this._initSourceBuffer();\n this.registerListeners();\n }\n\n public hasSourceTypes(): boolean {\n return (\n this.getSourceBufferTypes().length > 0 ||\n Object.keys(this.pendingTracks).length > 0\n );\n }\n\n public destroy() {\n this.unregisterListeners();\n this.details = null;\n this.lastMpegAudioChunk = null;\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.on(Events.BUFFER_APPENDING, this.onBufferAppending, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.BUFFER_EOS, this.onBufferEos, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.on(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.on(Events.FRAG_PARSED, this.onFragParsed, this);\n hls.on(Events.FRAG_CHANGED, this.onFragChanged, this);\n }\n\n protected unregisterListeners() {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.BUFFER_RESET, this.onBufferReset, this);\n hls.off(Events.BUFFER_APPENDING, this.onBufferAppending, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.BUFFER_EOS, this.onBufferEos, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n hls.off(Events.LEVEL_UPDATED, this.onLevelUpdated, this);\n hls.off(Events.FRAG_PARSED, this.onFragParsed, this);\n hls.off(Events.FRAG_CHANGED, this.onFragChanged, this);\n }\n\n private _initSourceBuffer() {\n this.sourceBuffer = {};\n this.operationQueue = new BufferOperationQueue(this.sourceBuffer);\n this.listeners = {\n audio: [],\n video: [],\n audiovideo: [],\n };\n this.lastMpegAudioChunk = null;\n }\n\n private onManifestLoading() {\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = 0;\n this.details = null;\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) {\n // in case of alt audio 2 BUFFER_CODECS events will be triggered, one per stream controller\n // sourcebuffers will be created all at once when the expected nb of tracks will be reached\n // in case alt audio is not used, only one BUFFER_CODEC event will be fired from main stream controller\n // it will contain the expected nb of source buffers, no need to compute it\n let codecEvents: number = 2;\n if ((data.audio && !data.video) || !data.altAudio || !__USE_ALT_AUDIO__) {\n codecEvents = 1;\n }\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal = codecEvents;\n logger.log(\n `${this.bufferCodecEventsExpected} bufferCodec event(s) expected`\n );\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n const media = (this.media = data.media);\n if (media && MediaSource) {\n const ms = (this.mediaSource = new MediaSource());\n // MediaSource listeners are arrow functions with a lexical scope, and do not need to be bound\n ms.addEventListener('sourceopen', this._onMediaSourceOpen);\n ms.addEventListener('sourceended', this._onMediaSourceEnded);\n ms.addEventListener('sourceclose', this._onMediaSourceClose);\n // link video and media Source\n media.src = self.URL.createObjectURL(ms);\n // cache the locally generated object url\n this._objectUrl = media.src;\n media.addEventListener('emptied', this._onMediaEmptied);\n }\n }\n\n protected onMediaDetaching() {\n const { media, mediaSource, _objectUrl } = this;\n if (mediaSource) {\n logger.log('[buffer-controller]: media source detaching');\n if (mediaSource.readyState === 'open') {\n try {\n // endOfStream could trigger exception if any sourcebuffer is in updating state\n // we don't really care about checking sourcebuffer state here,\n // as we are anyway detaching the MediaSource\n // let's just avoid this exception to propagate\n mediaSource.endOfStream();\n } catch (err) {\n logger.warn(\n `[buffer-controller]: onMediaDetaching: ${err.message} while calling endOfStream`\n );\n }\n }\n // Clean up the SourceBuffers by invoking onBufferReset\n this.onBufferReset();\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n mediaSource.removeEventListener('sourceended', this._onMediaSourceEnded);\n mediaSource.removeEventListener('sourceclose', this._onMediaSourceClose);\n\n // Detach properly the MediaSource from the HTMLMediaElement as\n // suggested in https://github.com/w3c/media-source/issues/53.\n if (media) {\n media.removeEventListener('emptied', this._onMediaEmptied);\n if (_objectUrl) {\n self.URL.revokeObjectURL(_objectUrl);\n }\n\n // clean up video tag src only if it's our own url. some external libraries might\n // hijack the video tag and change its 'src' without destroying the Hls instance first\n if (media.src === _objectUrl) {\n media.removeAttribute('src');\n media.load();\n } else {\n logger.warn(\n '[buffer-controller]: media.src was changed by a third party - skip cleanup'\n );\n }\n }\n\n this.mediaSource = null;\n this.media = null;\n this._objectUrl = null;\n this.bufferCodecEventsExpected = this._bufferCodecEventsTotal;\n this.pendingTracks = {};\n this.tracks = {};\n }\n\n this.hls.trigger(Events.MEDIA_DETACHED, undefined);\n }\n\n protected onBufferReset() {\n this.getSourceBufferTypes().forEach((type) => {\n const sb = this.sourceBuffer[type];\n try {\n if (sb) {\n this.removeBufferListeners(type);\n if (this.mediaSource) {\n this.mediaSource.removeSourceBuffer(sb);\n }\n // Synchronously remove the SB from the map before the next call in order to prevent an async function from\n // accessing it\n this.sourceBuffer[type] = undefined;\n }\n } catch (err) {\n logger.warn(\n `[buffer-controller]: Failed to reset the ${type} buffer`,\n err\n );\n }\n });\n this._initSourceBuffer();\n }\n\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData\n ) {\n const sourceBufferCount = this.getSourceBufferTypes().length;\n\n Object.keys(data).forEach((trackName) => {\n if (sourceBufferCount) {\n // check if SourceBuffer codec needs to change\n const track = this.tracks[trackName];\n if (track && typeof track.buffer.changeType === 'function') {\n const { id, codec, levelCodec, container, metadata } =\n data[trackName];\n const currentCodec = (track.levelCodec || track.codec).replace(\n VIDEO_CODEC_PROFILE_REPACE,\n '$1'\n );\n const nextCodec = (levelCodec || codec).replace(\n VIDEO_CODEC_PROFILE_REPACE,\n '$1'\n );\n if (currentCodec !== nextCodec) {\n const mimeType = `${container};codecs=${levelCodec || codec}`;\n this.appendChangeType(trackName, mimeType);\n logger.log(\n `[buffer-controller]: switching codec ${currentCodec} to ${nextCodec}`\n );\n this.tracks[trackName] = {\n buffer: track.buffer,\n codec,\n container,\n levelCodec,\n metadata,\n id,\n };\n }\n }\n } else {\n // if source buffer(s) not created yet, appended buffer tracks in this.pendingTracks\n this.pendingTracks[trackName] = data[trackName];\n }\n });\n\n // if sourcebuffers already created, do nothing ...\n if (sourceBufferCount) {\n return;\n }\n\n this.bufferCodecEventsExpected = Math.max(\n this.bufferCodecEventsExpected - 1,\n 0\n );\n if (this.mediaSource && this.mediaSource.readyState === 'open') {\n this.checkPendingTracks();\n }\n }\n\n protected appendChangeType(type, mimeType) {\n const { operationQueue } = this;\n const operation: BufferOperation = {\n execute: () => {\n const sb = this.sourceBuffer[type];\n if (sb) {\n logger.log(\n `[buffer-controller]: changing ${type} sourceBuffer type to ${mimeType}`\n );\n sb.changeType(mimeType);\n }\n operationQueue.shiftAndExecuteNext(type);\n },\n onStart: () => {},\n onComplete: () => {},\n onError: (e) => {\n logger.warn(\n `[buffer-controller]: Failed to change ${type} SourceBuffer type`,\n e\n );\n },\n };\n\n operationQueue.append(operation, type);\n }\n\n protected onBufferAppending(\n event: Events.BUFFER_APPENDING,\n eventData: BufferAppendingData\n ) {\n const { hls, operationQueue, tracks } = this;\n const { data, type, frag, part, chunkMeta } = eventData;\n const chunkStats = chunkMeta.buffering[type];\n\n const bufferAppendingStart = self.performance.now();\n chunkStats.start = bufferAppendingStart;\n const fragBuffering = frag.stats.buffering;\n const partBuffering = part ? part.stats.buffering : null;\n if (fragBuffering.start === 0) {\n fragBuffering.start = bufferAppendingStart;\n }\n if (partBuffering && partBuffering.start === 0) {\n partBuffering.start = bufferAppendingStart;\n }\n\n // TODO: Only update timestampOffset when audio/mpeg fragment or part is not contiguous with previously appended\n // Adjusting `SourceBuffer.timestampOffset` (desired point in the timeline where the next frames should be appended)\n // in Chrome browser when we detect MPEG audio container and time delta between level PTS and `SourceBuffer.timestampOffset`\n // is greater than 100ms (this is enough to handle seek for VOD or level change for LIVE videos).\n // More info here: https://github.com/video-dev/hls.js/issues/332#issuecomment-257986486\n const audioTrack = tracks.audio;\n let checkTimestampOffset = false;\n if (type === 'audio' && audioTrack?.container === 'audio/mpeg') {\n checkTimestampOffset =\n !this.lastMpegAudioChunk ||\n chunkMeta.id === 1 ||\n this.lastMpegAudioChunk.sn !== chunkMeta.sn;\n this.lastMpegAudioChunk = chunkMeta;\n }\n\n const fragStart = frag.start;\n const operation: BufferOperation = {\n execute: () => {\n chunkStats.executeStart = self.performance.now();\n if (checkTimestampOffset) {\n const sb = this.sourceBuffer[type];\n if (sb) {\n const delta = fragStart - sb.timestampOffset;\n if (Math.abs(delta) >= 0.1) {\n logger.log(\n `[buffer-controller]: Updating audio SourceBuffer timestampOffset to ${fragStart} (delta: ${delta}) sn: ${frag.sn})`\n );\n sb.timestampOffset = fragStart;\n }\n }\n }\n this.appendExecutor(data, type);\n },\n onStart: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updatestart`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: ${type} SourceBuffer updateend`);\n const end = self.performance.now();\n chunkStats.executeEnd = chunkStats.end = end;\n if (fragBuffering.first === 0) {\n fragBuffering.first = end;\n }\n if (partBuffering && partBuffering.first === 0) {\n partBuffering.first = end;\n }\n\n const { sourceBuffer } = this;\n const timeRanges = {};\n for (const type in sourceBuffer) {\n timeRanges[type] = BufferHelper.getBuffered(sourceBuffer[type]);\n }\n this.appendError = 0;\n this.hls.trigger(Events.BUFFER_APPENDED, {\n type,\n frag,\n part,\n chunkMeta,\n parent: frag.type,\n timeRanges,\n });\n },\n onError: (err) => {\n // in case any error occured while appending, put back segment in segments table\n logger.error(\n `[buffer-controller]: Error encountered while trying to append to the ${type} SourceBuffer`,\n err\n );\n const event = {\n type: ErrorTypes.MEDIA_ERROR,\n parent: frag.type,\n details: ErrorDetails.BUFFER_APPEND_ERROR,\n frag,\n part,\n chunkMeta,\n error: err,\n err,\n fatal: false,\n };\n\n if (err.code === DOMException.QUOTA_EXCEEDED_ERR) {\n // QuotaExceededError: http://www.w3.org/TR/html5/infrastructure.html#quotaexceedederror\n // let's stop appending any segments, and report BUFFER_FULL_ERROR error\n event.details = ErrorDetails.BUFFER_FULL_ERROR;\n } else {\n this.appendError++;\n event.details = ErrorDetails.BUFFER_APPEND_ERROR;\n /* with UHD content, we could get loop of quota exceeded error until\n browser is able to evict some data from sourcebuffer. Retrying can help recover.\n */\n if (this.appendError > hls.config.appendErrorMaxRetry) {\n logger.error(\n `[buffer-controller]: Failed ${hls.config.appendErrorMaxRetry} times to append segment in sourceBuffer`\n );\n event.fatal = true;\n }\n }\n hls.trigger(Events.ERROR, event);\n },\n };\n operationQueue.append(operation, type);\n }\n\n protected onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n data: BufferFlushingData\n ) {\n const { operationQueue } = this;\n const flushOperation = (type: SourceBufferName): BufferOperation => ({\n execute: this.removeExecutor.bind(\n this,\n type,\n data.startOffset,\n data.endOffset\n ),\n onStart: () => {\n // logger.debug(`[buffer-controller]: Started flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n },\n onComplete: () => {\n // logger.debug(`[buffer-controller]: Finished flushing ${data.startOffset} -> ${data.endOffset} for ${type} Source Buffer`);\n this.hls.trigger(Events.BUFFER_FLUSHED, { type });\n },\n onError: (e) => {\n logger.warn(\n `[buffer-controller]: Failed to remove from ${type} SourceBuffer`,\n e\n );\n },\n });\n\n if (data.type) {\n operationQueue.append(flushOperation(data.type), data.type);\n } else {\n this.getSourceBufferTypes().forEach((type: SourceBufferName) => {\n operationQueue.append(flushOperation(type), type);\n });\n }\n }\n\n protected onFragParsed(event: Events.FRAG_PARSED, data: FragParsedData) {\n const { frag, part } = data;\n const buffersAppendedTo: Array<SourceBufferName> = [];\n const elementaryStreams = part\n ? part.elementaryStreams\n : frag.elementaryStreams;\n if (elementaryStreams[ElementaryStreamTypes.AUDIOVIDEO]) {\n buffersAppendedTo.push('audiovideo');\n } else {\n if (elementaryStreams[ElementaryStreamTypes.AUDIO]) {\n buffersAppendedTo.push('audio');\n }\n if (elementaryStreams[ElementaryStreamTypes.VIDEO]) {\n buffersAppendedTo.push('video');\n }\n }\n\n const onUnblocked = () => {\n const now = self.performance.now();\n frag.stats.buffering.end = now;\n if (part) {\n part.stats.buffering.end = now;\n }\n const stats = part ? part.stats : frag.stats;\n this.hls.trigger(Events.FRAG_BUFFERED, {\n frag,\n part,\n stats,\n id: frag.type,\n });\n };\n\n if (buffersAppendedTo.length === 0) {\n logger.warn(\n `Fragments must have at least one ElementaryStreamType set. type: ${frag.type} level: ${frag.level} sn: ${frag.sn}`\n );\n }\n\n this.blockBuffers(onUnblocked, buffersAppendedTo);\n }\n\n private onFragChanged(event: Events.FRAG_CHANGED, data: FragChangedData) {\n this.flushBackBuffer();\n }\n\n // on BUFFER_EOS mark matching sourcebuffer(s) as ended and trigger checkEos()\n // an undefined data.type will mark all buffers as EOS.\n protected onBufferEos(event: Events.BUFFER_EOS, data: BufferEOSData) {\n const ended = this.getSourceBufferTypes().reduce((acc, type) => {\n const sb = this.sourceBuffer[type];\n if (sb && (!data.type || data.type === type)) {\n sb.ending = true;\n if (!sb.ended) {\n sb.ended = true;\n logger.log(`[buffer-controller]: ${type} sourceBuffer now EOS`);\n }\n }\n return acc && !!(!sb || sb.ended);\n }, true);\n\n if (ended) {\n logger.log(`[buffer-controller]: Queueing mediaSource.endOfStream()`);\n this.blockBuffers(() => {\n this.getSourceBufferTypes().forEach((type) => {\n const sb = this.sourceBuffer[type];\n if (sb) {\n sb.ending = false;\n }\n });\n const { mediaSource } = this;\n if (!mediaSource || mediaSource.readyState !== 'open') {\n if (mediaSource) {\n logger.info(\n `[buffer-controller]: Could not call mediaSource.endOfStream(). mediaSource.readyState: ${mediaSource.readyState}`\n );\n }\n return;\n }\n logger.log(`[buffer-controller]: Calling mediaSource.endOfStream()`);\n // Allow this to throw and be caught by the enqueueing function\n mediaSource.endOfStream();\n });\n }\n }\n\n protected onLevelUpdated(\n event: Events.LEVEL_UPDATED,\n { details }: LevelUpdatedData\n ) {\n if (!details.fragments.length) {\n return;\n }\n this.details = details;\n\n if (this.getSourceBufferTypes().length) {\n this.blockBuffers(this.updateMediaElementDuration.bind(this));\n } else {\n this.updateMediaElementDuration();\n }\n }\n\n flushBackBuffer() {\n const { hls, details, media, sourceBuffer } = this;\n if (!media || details === null) {\n return;\n }\n\n const sourceBufferTypes = this.getSourceBufferTypes();\n if (!sourceBufferTypes.length) {\n return;\n }\n\n // Support for deprecated liveBackBufferLength\n const backBufferLength =\n details.live && hls.config.liveBackBufferLength !== null\n ? hls.config.liveBackBufferLength\n : hls.config.backBufferLength;\n\n if (!Number.isFinite(backBufferLength) || backBufferLength < 0) {\n return;\n }\n\n const currentTime = media.currentTime;\n const targetDuration = details.levelTargetDuration;\n const maxBackBufferLength = Math.max(backBufferLength, targetDuration);\n const targetBackBufferPosition =\n Math.floor(currentTime / targetDuration) * targetDuration -\n maxBackBufferLength;\n sourceBufferTypes.forEach((type: SourceBufferName) => {\n const sb = sourceBuffer[type];\n if (sb) {\n const buffered = BufferHelper.getBuffered(sb);\n // when target buffer start exceeds actual buffer start\n if (\n buffered.length > 0 &&\n targetBackBufferPosition > buffered.start(0)\n ) {\n hls.trigger(Events.BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n\n // Support for deprecated event:\n if (details.live) {\n hls.trigger(Events.LIVE_BACK_BUFFER_REACHED, {\n bufferEnd: targetBackBufferPosition,\n });\n } else if (\n sb.ended &&\n buffered.end(buffered.length - 1) - currentTime < targetDuration * 2\n ) {\n logger.info(\n `[buffer-controller]: Cannot flush ${type} back buffer while SourceBuffer is in ended state`\n );\n return;\n }\n\n hls.trigger(Events.BUFFER_FLUSHING, {\n startOffset: 0,\n endOffset: targetBackBufferPosition,\n type,\n });\n }\n }\n });\n }\n\n /**\n * Update Media Source duration to current level duration or override to Infinity if configuration parameter\n * 'liveDurationInfinity` is set to `true`\n * More details: https://github.com/video-dev/hls.js/issues/355\n */\n private updateMediaElementDuration() {\n if (\n !this.details ||\n !this.media ||\n !this.mediaSource ||\n this.mediaSource.readyState !== 'open'\n ) {\n return;\n }\n const { details, hls, media, mediaSource } = this;\n const levelDuration = details.fragments[0].start + details.totalduration;\n const mediaDuration = media.duration;\n const msDuration = Number.isFinite(mediaSource.duration)\n ? mediaSource.duration\n : 0;\n\n if (details.live && hls.config.liveDurationInfinity) {\n // Override duration to Infinity\n logger.log(\n '[buffer-controller]: Media Source duration is set to Infinity'\n );\n mediaSource.duration = Infinity;\n this.updateSeekableRange(details);\n } else if (\n (levelDuration > msDuration && levelDuration > mediaDuration) ||\n !Number.isFinite(mediaDuration)\n ) {\n // levelDuration was the last value we set.\n // not using mediaSource.duration as the browser may tweak this value\n // only update Media Source duration if its value increase, this is to avoid\n // flushing already buffered portion when switching between quality level\n logger.log(\n `[buffer-controller]: Updating Media Source duration to ${levelDuration.toFixed(\n 3\n )}`\n );\n mediaSource.duration = levelDuration;\n }\n }\n\n updateSeekableRange(levelDetails) {\n const mediaSource = this.mediaSource;\n const fragments = levelDetails.fragments;\n const len = fragments.length;\n if (len && levelDetails.live && mediaSource?.setLiveSeekableRange) {\n const start = Math.max(0, fragments[0].start);\n const end = Math.max(start, start + levelDetails.totalduration);\n mediaSource.setLiveSeekableRange(start, end);\n }\n }\n\n protected checkPendingTracks() {\n const { bufferCodecEventsExpected, operationQueue, pendingTracks } = this;\n\n // Check if we've received all of the expected bufferCodec events. When none remain, create all the sourceBuffers at once.\n // This is important because the MSE spec allows implementations to throw QuotaExceededErrors if creating new sourceBuffers after\n // data has been appended to existing ones.\n // 2 tracks is the max (one for audio, one for video). If we've reach this max go ahead and create the buffers.\n const pendingTracksCount = Object.keys(pendingTracks).length;\n if (\n (pendingTracksCount && !bufferCodecEventsExpected) ||\n pendingTracksCount === 2\n ) {\n // ok, let's create them now !\n this.createSourceBuffers(pendingTracks);\n this.pendingTracks = {};\n // append any pending segments now !\n const buffers = this.getSourceBufferTypes();\n if (buffers.length) {\n this.hls.trigger(Events.BUFFER_CREATED, { tracks: this.tracks });\n buffers.forEach((type: SourceBufferName) => {\n operationQueue.executeNext(type);\n });\n } else {\n const error = new Error(\n 'could not create source buffer for media codec(s)'\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_INCOMPATIBLE_CODECS_ERROR,\n fatal: true,\n error,\n reason: error.message,\n });\n }\n }\n }\n\n protected createSourceBuffers(tracks: TrackSet) {\n const { sourceBuffer, mediaSource } = this;\n if (!mediaSource) {\n throw Error('createSourceBuffers called when mediaSource was null');\n }\n for (const trackName in tracks) {\n if (!sourceBuffer[trackName]) {\n const track = tracks[trackName as keyof TrackSet];\n if (!track) {\n throw Error(\n `source buffer exists for track ${trackName}, however track does not`\n );\n }\n // use levelCodec as first priority\n const codec = track.levelCodec || track.codec;\n const mimeType = `${track.container};codecs=${codec}`;\n logger.log(`[buffer-controller]: creating sourceBuffer(${mimeType})`);\n try {\n const sb = (sourceBuffer[trackName] =\n mediaSource.addSourceBuffer(mimeType));\n const sbName = trackName as SourceBufferName;\n this.addBufferListener(sbName, 'updatestart', this._onSBUpdateStart);\n this.addBufferListener(sbName, 'updateend', this._onSBUpdateEnd);\n this.addBufferListener(sbName, 'error', this._onSBUpdateError);\n this.tracks[trackName] = {\n buffer: sb,\n codec: codec,\n container: track.container,\n levelCodec: track.levelCodec,\n metadata: track.metadata,\n id: track.id,\n };\n } catch (err) {\n logger.error(\n `[buffer-controller]: error while trying to add sourceBuffer: ${err.message}`\n );\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_ADD_CODEC_ERROR,\n fatal: false,\n error: err,\n mimeType: mimeType,\n });\n }\n }\n }\n }\n\n // Keep as arrow functions so that we can directly reference these functions directly as event listeners\n private _onMediaSourceOpen = () => {\n const { media, mediaSource } = this;\n logger.log('[buffer-controller]: Media source opened');\n if (media) {\n media.removeEventListener('emptied', this._onMediaEmptied);\n this.updateMediaElementDuration();\n this.hls.trigger(Events.MEDIA_ATTACHED, { media });\n }\n\n if (mediaSource) {\n // once received, don't listen anymore to sourceopen event\n mediaSource.removeEventListener('sourceopen', this._onMediaSourceOpen);\n }\n this.checkPendingTracks();\n };\n\n private _onMediaSourceClose = () => {\n logger.log('[buffer-controller]: Media source closed');\n };\n\n private _onMediaSourceEnded = () => {\n logger.log('[buffer-controller]: Media source ended');\n };\n\n private _onMediaEmptied = () => {\n const { media, _objectUrl } = this;\n if (media && media.src !== _objectUrl) {\n logger.error(\n `Media element src was set while attaching MediaSource (${_objectUrl} > ${media.src})`\n );\n }\n };\n\n private _onSBUpdateStart(type: SourceBufferName) {\n const { operationQueue } = this;\n const operation = operationQueue.current(type);\n operation.onStart();\n }\n\n private _onSBUpdateEnd(type: SourceBufferName) {\n const { operationQueue } = this;\n const operation = operationQueue.current(type);\n operation.onComplete();\n operationQueue.shiftAndExecuteNext(type);\n }\n\n private _onSBUpdateError(type: SourceBufferName, event: Event) {\n const error = new Error(`${type} SourceBuffer error`);\n logger.error(`[buffer-controller]: ${error}`, event);\n // according to http://www.w3.org/TR/media-source/#sourcebuffer-append-error\n // SourceBuffer errors are not necessarily fatal; if so, the HTMLMediaElement will fire an error event\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.MEDIA_ERROR,\n details: ErrorDetails.BUFFER_APPENDING_ERROR,\n error,\n fatal: false,\n });\n // updateend is always fired after error, so we'll allow that to shift the current operation off of the queue\n const operation = this.operationQueue.current(type);\n if (operation) {\n operation.onError(event);\n }\n }\n\n // This method must result in an updateend event; if remove is not called, _onSBUpdateEnd must be called manually\n private removeExecutor(\n type: SourceBufferName,\n startOffset: number,\n endOffset: number\n ) {\n const { media, mediaSource, operationQueue, sourceBuffer } = this;\n const sb = sourceBuffer[type];\n if (!media || !mediaSource || !sb) {\n logger.warn(\n `[buffer-controller]: Attempting to remove from the ${type} SourceBuffer, but it does not exist`\n );\n operationQueue.shiftAndExecuteNext(type);\n return;\n }\n const mediaDuration = Number.isFinite(media.duration)\n ? media.duration\n : Infinity;\n const msDuration = Number.isFinite(mediaSource.duration)\n ? mediaSource.duration\n : Infinity;\n const removeStart = Math.max(0, startOffset);\n const removeEnd = Math.min(endOffset, mediaDuration, msDuration);\n if (removeEnd > removeStart && !sb.ending) {\n sb.ended = false;\n logger.log(\n `[buffer-controller]: Removing [${removeStart},${removeEnd}] from the ${type} SourceBuffer`\n );\n sb.remove(removeStart, removeEnd);\n } else {\n // Cycle the queue\n operationQueue.shiftAndExecuteNext(type);\n }\n }\n\n // This method must result in an updateend event; if append is not called, _onSBUpdateEnd must be called manually\n private appendExecutor(data: Uint8Array, type: SourceBufferName) {\n const { operationQueue, sourceBuffer } = this;\n const sb = sourceBuffer[type];\n if (!sb) {\n logger.warn(\n `[buffer-controller]: Attempting to append to the ${type} SourceBuffer, but it does not exist`\n );\n operationQueue.shiftAndExecuteNext(type);\n return;\n }\n\n sb.ended = false;\n sb.appendBuffer(data);\n }\n\n // Enqueues an operation to each SourceBuffer queue which, upon execution, resolves a promise. When all promises\n // resolve, the onUnblocked function is executed. Functions calling this method do not need to unblock the queue\n // upon completion, since we already do it here\n private blockBuffers(\n onUnblocked: () => void,\n buffers: Array<SourceBufferName> = this.getSourceBufferTypes()\n ) {\n if (!buffers.length) {\n logger.log(\n '[buffer-controller]: Blocking operation requested, but no SourceBuffers exist'\n );\n Promise.resolve().then(onUnblocked);\n return;\n }\n const { operationQueue } = this;\n\n // logger.debug(`[buffer-controller]: Blocking ${buffers} SourceBuffer`);\n const blockingOperations = buffers.map((type) =>\n operationQueue.appendBlocker(type as SourceBufferName)\n );\n Promise.all(blockingOperations).then(() => {\n // logger.debug(`[buffer-controller]: Blocking operation resolved; unblocking ${buffers} SourceBuffer`);\n onUnblocked();\n buffers.forEach((type) => {\n const sb = this.sourceBuffer[type];\n // Only cycle the queue if the SB is not updating. There's a bug in Chrome which sets the SB updating flag to\n // true when changing the MediaSource duration (https://bugs.chromium.org/p/chromium/issues/detail?id=959359&can=2&q=mediasource%20duration)\n // While this is a workaround, it's probably useful to have around\n if (!sb?.updating) {\n operationQueue.shiftAndExecuteNext(type);\n }\n });\n });\n }\n\n private getSourceBufferTypes(): Array<SourceBufferName> {\n return Object.keys(this.sourceBuffer) as Array<SourceBufferName>;\n }\n\n private addBufferListener(\n type: SourceBufferName,\n event: string,\n fn: Function\n ) {\n const buffer = this.sourceBuffer[type];\n if (!buffer) {\n return;\n }\n const listener = fn.bind(this, type);\n this.listeners[type].push({ event, listener });\n buffer.addEventListener(event, listener);\n }\n\n private removeBufferListeners(type: SourceBufferName) {\n const buffer = this.sourceBuffer[type];\n if (!buffer) {\n return;\n }\n this.listeners[type].forEach((l) => {\n buffer.removeEventListener(l.event, l.listener);\n });\n }\n}\n","import OutputFilter from './output-filter';\nimport { logger } from '../utils/logger';\n\n/**\n *\n * This code was ported from the dash.js project at:\n * https://github.com/Dash-Industry-Forum/dash.js/blob/development/externals/cea608-parser.js\n * https://github.com/Dash-Industry-Forum/dash.js/commit/8269b26a761e0853bb21d78780ed945144ecdd4d#diff-71bc295a2d6b6b7093a1d3290d53a4b2\n *\n * The original copyright appears below:\n *\n * The copyright in this software is being made available under the BSD License,\n * included below. This software may be subject to other third party and contributor\n * rights, including patent rights, and no such rights are granted under this license.\n *\n * Copyright (c) 2015-2016, DASH Industry Forum.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification,\n * are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation and/or\n * other materials provided with the distribution.\n * 2. Neither the name of Dash Industry Forum nor the names of its\n * contributors may be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND ANY\n * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.\n * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT\n * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n/**\n * Exceptions from regular ASCII. CodePoints are mapped to UTF-16 codes\n */\n\nconst specialCea608CharsCodes = {\n 0x2a: 0xe1, // lowercase a, acute accent\n 0x5c: 0xe9, // lowercase e, acute accent\n 0x5e: 0xed, // lowercase i, acute accent\n 0x5f: 0xf3, // lowercase o, acute accent\n 0x60: 0xfa, // lowercase u, acute accent\n 0x7b: 0xe7, // lowercase c with cedilla\n 0x7c: 0xf7, // division symbol\n 0x7d: 0xd1, // uppercase N tilde\n 0x7e: 0xf1, // lowercase n tilde\n 0x7f: 0x2588, // Full block\n // THIS BLOCK INCLUDES THE 16 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x11 AND LOW BETWEEN 0x30 AND 0x3F\n // THIS MEANS THAT \\x50 MUST BE ADDED TO THE VALUES\n 0x80: 0xae, // Registered symbol (R)\n 0x81: 0xb0, // degree sign\n 0x82: 0xbd, // 1/2 symbol\n 0x83: 0xbf, // Inverted (open) question mark\n 0x84: 0x2122, // Trademark symbol (TM)\n 0x85: 0xa2, // Cents symbol\n 0x86: 0xa3, // Pounds sterling\n 0x87: 0x266a, // Music 8'th note\n 0x88: 0xe0, // lowercase a, grave accent\n 0x89: 0x20, // transparent space (regular)\n 0x8a: 0xe8, // lowercase e, grave accent\n 0x8b: 0xe2, // lowercase a, circumflex accent\n 0x8c: 0xea, // lowercase e, circumflex accent\n 0x8d: 0xee, // lowercase i, circumflex accent\n 0x8e: 0xf4, // lowercase o, circumflex accent\n 0x8f: 0xfb, // lowercase u, circumflex accent\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x12 AND LOW BETWEEN 0x20 AND 0x3F\n 0x90: 0xc1, // capital letter A with acute\n 0x91: 0xc9, // capital letter E with acute\n 0x92: 0xd3, // capital letter O with acute\n 0x93: 0xda, // capital letter U with acute\n 0x94: 0xdc, // capital letter U with diaresis\n 0x95: 0xfc, // lowercase letter U with diaeresis\n 0x96: 0x2018, // opening single quote\n 0x97: 0xa1, // inverted exclamation mark\n 0x98: 0x2a, // asterisk\n 0x99: 0x2019, // closing single quote\n 0x9a: 0x2501, // box drawings heavy horizontal\n 0x9b: 0xa9, // copyright sign\n 0x9c: 0x2120, // Service mark\n 0x9d: 0x2022, // (round) bullet\n 0x9e: 0x201c, // Left double quotation mark\n 0x9f: 0x201d, // Right double quotation mark\n 0xa0: 0xc0, // uppercase A, grave accent\n 0xa1: 0xc2, // uppercase A, circumflex\n 0xa2: 0xc7, // uppercase C with cedilla\n 0xa3: 0xc8, // uppercase E, grave accent\n 0xa4: 0xca, // uppercase E, circumflex\n 0xa5: 0xcb, // capital letter E with diaresis\n 0xa6: 0xeb, // lowercase letter e with diaresis\n 0xa7: 0xce, // uppercase I, circumflex\n 0xa8: 0xcf, // uppercase I, with diaresis\n 0xa9: 0xef, // lowercase i, with diaresis\n 0xaa: 0xd4, // uppercase O, circumflex\n 0xab: 0xd9, // uppercase U, grave accent\n 0xac: 0xf9, // lowercase u, grave accent\n 0xad: 0xdb, // uppercase U, circumflex\n 0xae: 0xab, // left-pointing double angle quotation mark\n 0xaf: 0xbb, // right-pointing double angle quotation mark\n // THIS BLOCK INCLUDES THE 32 EXTENDED (TWO-BYTE) LINE 21 CHARACTERS\n // THAT COME FROM HI BYTE=0x13 AND LOW BETWEEN 0x20 AND 0x3F\n 0xb0: 0xc3, // Uppercase A, tilde\n 0xb1: 0xe3, // Lowercase a, tilde\n 0xb2: 0xcd, // Uppercase I, acute accent\n 0xb3: 0xcc, // Uppercase I, grave accent\n 0xb4: 0xec, // Lowercase i, grave accent\n 0xb5: 0xd2, // Uppercase O, grave accent\n 0xb6: 0xf2, // Lowercase o, grave accent\n 0xb7: 0xd5, // Uppercase O, tilde\n 0xb8: 0xf5, // Lowercase o, tilde\n 0xb9: 0x7b, // Open curly brace\n 0xba: 0x7d, // Closing curly brace\n 0xbb: 0x5c, // Backslash\n 0xbc: 0x5e, // Caret\n 0xbd: 0x5f, // Underscore\n 0xbe: 0x7c, // Pipe (vertical line)\n 0xbf: 0x223c, // Tilde operator\n 0xc0: 0xc4, // Uppercase A, umlaut\n 0xc1: 0xe4, // Lowercase A, umlaut\n 0xc2: 0xd6, // Uppercase O, umlaut\n 0xc3: 0xf6, // Lowercase o, umlaut\n 0xc4: 0xdf, // Esszett (sharp S)\n 0xc5: 0xa5, // Yen symbol\n 0xc6: 0xa4, // Generic currency sign\n 0xc7: 0x2503, // Box drawings heavy vertical\n 0xc8: 0xc5, // Uppercase A, ring\n 0xc9: 0xe5, // Lowercase A, ring\n 0xca: 0xd8, // Uppercase O, stroke\n 0xcb: 0xf8, // Lowercase o, strok\n 0xcc: 0x250f, // Box drawings heavy down and right\n 0xcd: 0x2513, // Box drawings heavy down and left\n 0xce: 0x2517, // Box drawings heavy up and right\n 0xcf: 0x251b, // Box drawings heavy up and left\n};\n\n/**\n * Utils\n */\nconst getCharForByte = function (byte: number) {\n let charCode = byte;\n if (specialCea608CharsCodes.hasOwnProperty(byte)) {\n charCode = specialCea608CharsCodes[byte];\n }\n\n return String.fromCharCode(charCode);\n};\n\nconst NR_ROWS = 15;\nconst NR_COLS = 100;\n// Tables to look up row from PAC data\nconst rowsLowCh1 = {\n 0x11: 1,\n 0x12: 3,\n 0x15: 5,\n 0x16: 7,\n 0x17: 9,\n 0x10: 11,\n 0x13: 12,\n 0x14: 14,\n};\nconst rowsHighCh1 = {\n 0x11: 2,\n 0x12: 4,\n 0x15: 6,\n 0x16: 8,\n 0x17: 10,\n 0x13: 13,\n 0x14: 15,\n};\nconst rowsLowCh2 = {\n 0x19: 1,\n 0x1a: 3,\n 0x1d: 5,\n 0x1e: 7,\n 0x1f: 9,\n 0x18: 11,\n 0x1b: 12,\n 0x1c: 14,\n};\nconst rowsHighCh2 = {\n 0x19: 2,\n 0x1a: 4,\n 0x1d: 6,\n 0x1e: 8,\n 0x1f: 10,\n 0x1b: 13,\n 0x1c: 15,\n};\n\nconst backgroundColors = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n 'black',\n 'transparent',\n];\n\nconst enum VerboseLevel {\n ERROR = 0,\n TEXT = 1,\n WARNING = 2,\n INFO = 2,\n DEBUG = 3,\n DATA = 3,\n}\n\nclass CaptionsLogger {\n public time: number | null = null;\n public verboseLevel: VerboseLevel = VerboseLevel.ERROR;\n\n log(severity: VerboseLevel, msg: string | (() => string)): void {\n if (this.verboseLevel >= severity) {\n const m: string = typeof msg === 'function' ? msg() : msg;\n logger.log(`${this.time} [${severity}] ${m}`);\n }\n }\n}\n\nconst numArrayToHexArray = function (numArray: number[]): string[] {\n const hexArray: string[] = [];\n for (let j = 0; j < numArray.length; j++) {\n hexArray.push(numArray[j].toString(16));\n }\n\n return hexArray;\n};\n\ntype PenStyles = {\n foreground: string | null;\n underline: boolean;\n italics: boolean;\n background: string;\n flash: boolean;\n};\n\nclass PenState {\n public foreground: string;\n public underline: boolean;\n public italics: boolean;\n public background: string;\n public flash: boolean;\n\n constructor(\n foreground?: string,\n underline?: boolean,\n italics?: boolean,\n background?: string,\n flash?: boolean\n ) {\n this.foreground = foreground || 'white';\n this.underline = underline || false;\n this.italics = italics || false;\n this.background = background || 'black';\n this.flash = flash || false;\n }\n\n reset() {\n this.foreground = 'white';\n this.underline = false;\n this.italics = false;\n this.background = 'black';\n this.flash = false;\n }\n\n setStyles(styles: Partial<PenStyles>) {\n const attribs = [\n 'foreground',\n 'underline',\n 'italics',\n 'background',\n 'flash',\n ];\n for (let i = 0; i < attribs.length; i++) {\n const style = attribs[i];\n if (styles.hasOwnProperty(style)) {\n this[style] = styles[style];\n }\n }\n }\n\n isDefault() {\n return (\n this.foreground === 'white' &&\n !this.underline &&\n !this.italics &&\n this.background === 'black' &&\n !this.flash\n );\n }\n\n equals(other: PenState) {\n return (\n this.foreground === other.foreground &&\n this.underline === other.underline &&\n this.italics === other.italics &&\n this.background === other.background &&\n this.flash === other.flash\n );\n }\n\n copy(newPenState: PenState) {\n this.foreground = newPenState.foreground;\n this.underline = newPenState.underline;\n this.italics = newPenState.italics;\n this.background = newPenState.background;\n this.flash = newPenState.flash;\n }\n\n toString(): string {\n return (\n 'color=' +\n this.foreground +\n ', underline=' +\n this.underline +\n ', italics=' +\n this.italics +\n ', background=' +\n this.background +\n ', flash=' +\n this.flash\n );\n }\n}\n\n/**\n * Unicode character with styling and background.\n * @constructor\n */\nclass StyledUnicodeChar {\n uchar: string;\n penState: PenState;\n\n constructor(\n uchar?: string,\n foreground?: string,\n underline?: boolean,\n italics?: boolean,\n background?: string,\n flash?: boolean\n ) {\n this.uchar = uchar || ' '; // unicode character\n this.penState = new PenState(\n foreground,\n underline,\n italics,\n background,\n flash\n );\n }\n\n reset() {\n this.uchar = ' ';\n this.penState.reset();\n }\n\n setChar(uchar: string, newPenState: PenState) {\n this.uchar = uchar;\n this.penState.copy(newPenState);\n }\n\n setPenState(newPenState: PenState) {\n this.penState.copy(newPenState);\n }\n\n equals(other: StyledUnicodeChar) {\n return this.uchar === other.uchar && this.penState.equals(other.penState);\n }\n\n copy(newChar: StyledUnicodeChar) {\n this.uchar = newChar.uchar;\n this.penState.copy(newChar.penState);\n }\n\n isEmpty(): boolean {\n return this.uchar === ' ' && this.penState.isDefault();\n }\n}\n\n/**\n * CEA-608 row consisting of NR_COLS instances of StyledUnicodeChar.\n * @constructor\n */\nexport class Row {\n public chars: StyledUnicodeChar[];\n public pos: number;\n public currPenState: PenState;\n public cueStartTime?: number;\n logger: CaptionsLogger;\n\n constructor(logger: CaptionsLogger) {\n this.chars = [];\n for (let i = 0; i < NR_COLS; i++) {\n this.chars.push(new StyledUnicodeChar());\n }\n\n this.logger = logger;\n this.pos = 0;\n this.currPenState = new PenState();\n }\n\n equals(other: Row) {\n let equal = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].equals(other.chars[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other: Row) {\n for (let i = 0; i < NR_COLS; i++) {\n this.chars[i].copy(other.chars[i]);\n }\n }\n\n isEmpty(): boolean {\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n if (!this.chars[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n /**\n * Set the cursor to a valid column.\n */\n setCursor(absPos: number) {\n if (this.pos !== absPos) {\n this.pos = absPos;\n }\n\n if (this.pos < 0) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Negative cursor position ' + this.pos\n );\n this.pos = 0;\n } else if (this.pos > NR_COLS) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Too large cursor position ' + this.pos\n );\n this.pos = NR_COLS;\n }\n }\n\n /**\n * Move the cursor relative to current position.\n */\n moveCursor(relPos: number) {\n const newPos = this.pos + relPos;\n if (relPos > 1) {\n for (let i = this.pos + 1; i < newPos + 1; i++) {\n this.chars[i].setPenState(this.currPenState);\n }\n }\n this.setCursor(newPos);\n }\n\n /**\n * Backspace, move one step back and clear character.\n */\n backSpace() {\n this.moveCursor(-1);\n this.chars[this.pos].setChar(' ', this.currPenState);\n }\n\n insertChar(byte: number) {\n if (byte >= 0x90) {\n // Extended char\n this.backSpace();\n }\n const char = getCharForByte(byte);\n if (this.pos >= NR_COLS) {\n this.logger.log(\n VerboseLevel.ERROR,\n () =>\n 'Cannot insert ' +\n byte.toString(16) +\n ' (' +\n char +\n ') at position ' +\n this.pos +\n '. Skipping it!'\n );\n return;\n }\n this.chars[this.pos].setChar(char, this.currPenState);\n this.moveCursor(1);\n }\n\n clearFromPos(startPos: number) {\n let i: number;\n for (i = startPos; i < NR_COLS; i++) {\n this.chars[i].reset();\n }\n }\n\n clear() {\n this.clearFromPos(0);\n this.pos = 0;\n this.currPenState.reset();\n }\n\n clearToEndOfRow() {\n this.clearFromPos(this.pos);\n }\n\n getTextString() {\n const chars: string[] = [];\n let empty = true;\n for (let i = 0; i < NR_COLS; i++) {\n const char = this.chars[i].uchar;\n if (char !== ' ') {\n empty = false;\n }\n\n chars.push(char);\n }\n if (empty) {\n return '';\n } else {\n return chars.join('');\n }\n }\n\n setPenStyles(styles: Partial<PenStyles>) {\n this.currPenState.setStyles(styles);\n const currChar = this.chars[this.pos];\n currChar.setPenState(this.currPenState);\n }\n}\n\n/**\n * Keep a CEA-608 screen of 32x15 styled characters\n * @constructor\n */\nexport class CaptionScreen {\n rows: Row[];\n currRow: number;\n nrRollUpRows: number | null;\n lastOutputScreen: CaptionScreen | null;\n logger: CaptionsLogger;\n\n constructor(logger: CaptionsLogger) {\n this.rows = [];\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows.push(new Row(logger));\n } // Note that we use zero-based numbering (0-14)\n\n this.logger = logger;\n this.currRow = NR_ROWS - 1;\n this.nrRollUpRows = null;\n this.lastOutputScreen = null;\n this.reset();\n }\n\n reset() {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n this.currRow = NR_ROWS - 1;\n }\n\n equals(other: CaptionScreen): boolean {\n let equal = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].equals(other.rows[i])) {\n equal = false;\n break;\n }\n }\n return equal;\n }\n\n copy(other: CaptionScreen) {\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].copy(other.rows[i]);\n }\n }\n\n isEmpty(): boolean {\n let empty = true;\n for (let i = 0; i < NR_ROWS; i++) {\n if (!this.rows[i].isEmpty()) {\n empty = false;\n break;\n }\n }\n return empty;\n }\n\n backSpace() {\n const row = this.rows[this.currRow];\n row.backSpace();\n }\n\n clearToEndOfRow() {\n const row = this.rows[this.currRow];\n row.clearToEndOfRow();\n }\n\n /**\n * Insert a character (without styling) in the current row.\n */\n insertChar(char: number) {\n const row = this.rows[this.currRow];\n row.insertChar(char);\n }\n\n setPen(styles: Partial<PenStyles>) {\n const row = this.rows[this.currRow];\n row.setPenStyles(styles);\n }\n\n moveCursor(relPos: number) {\n const row = this.rows[this.currRow];\n row.moveCursor(relPos);\n }\n\n setCursor(absPos: number) {\n this.logger.log(VerboseLevel.INFO, 'setCursor: ' + absPos);\n const row = this.rows[this.currRow];\n row.setCursor(absPos);\n }\n\n setPAC(pacData: PACData) {\n this.logger.log(\n VerboseLevel.INFO,\n () => 'pacData = ' + JSON.stringify(pacData)\n );\n let newRow = pacData.row - 1;\n if (this.nrRollUpRows && newRow < this.nrRollUpRows - 1) {\n newRow = this.nrRollUpRows - 1;\n }\n\n // Make sure this only affects Roll-up Captions by checking this.nrRollUpRows\n if (this.nrRollUpRows && this.currRow !== newRow) {\n // clear all rows first\n for (let i = 0; i < NR_ROWS; i++) {\n this.rows[i].clear();\n }\n\n // Copy this.nrRollUpRows rows from lastOutputScreen and place it in the newRow location\n // topRowIndex - the start of rows to copy (inclusive index)\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n // We only copy if the last position was already shown.\n // We use the cueStartTime value to check this.\n const lastOutputScreen = this.lastOutputScreen;\n if (lastOutputScreen) {\n const prevLineTime = lastOutputScreen.rows[topRowIndex].cueStartTime;\n const time = this.logger.time;\n if (prevLineTime && time !== null && prevLineTime < time) {\n for (let i = 0; i < this.nrRollUpRows; i++) {\n this.rows[newRow - this.nrRollUpRows + i + 1].copy(\n lastOutputScreen.rows[topRowIndex + i]\n );\n }\n }\n }\n }\n\n this.currRow = newRow;\n const row = this.rows[this.currRow];\n if (pacData.indent !== null) {\n const indent = pacData.indent;\n const prevPos = Math.max(indent - 1, 0);\n row.setCursor(pacData.indent);\n pacData.color = row.chars[prevPos].penState.foreground;\n }\n const styles: PenStyles = {\n foreground: pacData.color,\n underline: pacData.underline,\n italics: pacData.italics,\n background: 'black',\n flash: false,\n };\n this.setPen(styles);\n }\n\n /**\n * Set background/extra foreground, but first do back_space, and then insert space (backwards compatibility).\n */\n setBkgData(bkgData: Partial<PenStyles>) {\n this.logger.log(\n VerboseLevel.INFO,\n () => 'bkgData = ' + JSON.stringify(bkgData)\n );\n this.backSpace();\n this.setPen(bkgData);\n this.insertChar(0x20); // Space\n }\n\n setRollUpRows(nrRows: number | null) {\n this.nrRollUpRows = nrRows;\n }\n\n rollUp() {\n if (this.nrRollUpRows === null) {\n this.logger.log(\n VerboseLevel.DEBUG,\n 'roll_up but nrRollUpRows not set yet'\n );\n return; // Not properly setup\n }\n this.logger.log(VerboseLevel.TEXT, () => this.getDisplayText());\n const topRowIndex = this.currRow + 1 - this.nrRollUpRows;\n const topRow = this.rows.splice(topRowIndex, 1)[0];\n topRow.clear();\n this.rows.splice(this.currRow, 0, topRow);\n this.logger.log(VerboseLevel.INFO, 'Rolling up');\n // this.logger.log(VerboseLevel.TEXT, this.get_display_text())\n }\n\n /**\n * Get all non-empty rows with as unicode text.\n */\n getDisplayText(asOneRow?: boolean) {\n asOneRow = asOneRow || false;\n const displayText: string[] = [];\n let text = '';\n let rowNr = -1;\n for (let i = 0; i < NR_ROWS; i++) {\n const rowText = this.rows[i].getTextString();\n if (rowText) {\n rowNr = i + 1;\n if (asOneRow) {\n displayText.push('Row ' + rowNr + \": '\" + rowText + \"'\");\n } else {\n displayText.push(rowText.trim());\n }\n }\n }\n if (displayText.length > 0) {\n if (asOneRow) {\n text = '[' + displayText.join(' | ') + ']';\n } else {\n text = displayText.join('\\n');\n }\n }\n return text;\n }\n\n getTextAndFormat() {\n return this.rows;\n }\n}\n\n// var modes = ['MODE_ROLL-UP', 'MODE_POP-ON', 'MODE_PAINT-ON', 'MODE_TEXT'];\n\ntype CaptionModes =\n | 'MODE_ROLL-UP'\n | 'MODE_POP-ON'\n | 'MODE_PAINT-ON'\n | 'MODE_TEXT'\n | null;\n\nclass Cea608Channel {\n chNr: number;\n outputFilter: OutputFilter;\n mode: CaptionModes;\n verbose: number;\n displayedMemory: CaptionScreen;\n nonDisplayedMemory: CaptionScreen;\n lastOutputScreen: CaptionScreen;\n currRollUpRow: Row;\n writeScreen: CaptionScreen;\n cueStartTime: number | null;\n logger: CaptionsLogger;\n\n constructor(\n channelNumber: number,\n outputFilter: OutputFilter,\n logger: CaptionsLogger\n ) {\n this.chNr = channelNumber;\n this.outputFilter = outputFilter;\n this.mode = null;\n this.verbose = 0;\n this.displayedMemory = new CaptionScreen(logger);\n this.nonDisplayedMemory = new CaptionScreen(logger);\n this.lastOutputScreen = new CaptionScreen(logger);\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null; // Keeps track of where a cue started.\n this.logger = logger;\n }\n\n reset() {\n this.mode = null;\n this.displayedMemory.reset();\n this.nonDisplayedMemory.reset();\n this.lastOutputScreen.reset();\n this.outputFilter.reset();\n this.currRollUpRow = this.displayedMemory.rows[NR_ROWS - 1];\n this.writeScreen = this.displayedMemory;\n this.mode = null;\n this.cueStartTime = null;\n }\n\n getHandler(): OutputFilter {\n return this.outputFilter;\n }\n\n setHandler(newHandler: OutputFilter) {\n this.outputFilter = newHandler;\n }\n\n setPAC(pacData: PACData) {\n this.writeScreen.setPAC(pacData);\n }\n\n setBkgData(bkgData: Partial<PenStyles>) {\n this.writeScreen.setBkgData(bkgData);\n }\n\n setMode(newMode: CaptionModes) {\n if (newMode === this.mode) {\n return;\n }\n\n this.mode = newMode;\n this.logger.log(VerboseLevel.INFO, () => 'MODE=' + newMode);\n if (this.mode === 'MODE_POP-ON') {\n this.writeScreen = this.nonDisplayedMemory;\n } else {\n this.writeScreen = this.displayedMemory;\n this.writeScreen.reset();\n }\n if (this.mode !== 'MODE_ROLL-UP') {\n this.displayedMemory.nrRollUpRows = null;\n this.nonDisplayedMemory.nrRollUpRows = null;\n }\n this.mode = newMode;\n }\n\n insertChars(chars: number[]) {\n for (let i = 0; i < chars.length; i++) {\n this.writeScreen.insertChar(chars[i]);\n }\n\n const screen =\n this.writeScreen === this.displayedMemory ? 'DISP' : 'NON_DISP';\n this.logger.log(\n VerboseLevel.INFO,\n () => screen + ': ' + this.writeScreen.getDisplayText(true)\n );\n if (this.mode === 'MODE_PAINT-ON' || this.mode === 'MODE_ROLL-UP') {\n this.logger.log(\n VerboseLevel.TEXT,\n () => 'DISPLAYED: ' + this.displayedMemory.getDisplayText(true)\n );\n this.outputDataUpdate();\n }\n }\n\n ccRCL() {\n // Resume Caption Loading (switch mode to Pop On)\n this.logger.log(VerboseLevel.INFO, 'RCL - Resume Caption Loading');\n this.setMode('MODE_POP-ON');\n }\n\n ccBS() {\n // BackSpace\n this.logger.log(VerboseLevel.INFO, 'BS - BackSpace');\n if (this.mode === 'MODE_TEXT') {\n return;\n }\n\n this.writeScreen.backSpace();\n if (this.writeScreen === this.displayedMemory) {\n this.outputDataUpdate();\n }\n }\n\n ccAOF() {\n // Reserved (formerly Alarm Off)\n }\n\n ccAON() {\n // Reserved (formerly Alarm On)\n }\n\n ccDER() {\n // Delete to End of Row\n this.logger.log(VerboseLevel.INFO, 'DER- Delete to End of Row');\n this.writeScreen.clearToEndOfRow();\n this.outputDataUpdate();\n }\n\n ccRU(nrRows: number | null) {\n // Roll-Up Captions-2,3,or 4 Rows\n this.logger.log(VerboseLevel.INFO, 'RU(' + nrRows + ') - Roll Up');\n this.writeScreen = this.displayedMemory;\n this.setMode('MODE_ROLL-UP');\n this.writeScreen.setRollUpRows(nrRows);\n }\n\n ccFON() {\n // Flash On\n this.logger.log(VerboseLevel.INFO, 'FON - Flash On');\n this.writeScreen.setPen({ flash: true });\n }\n\n ccRDC() {\n // Resume Direct Captioning (switch mode to PaintOn)\n this.logger.log(VerboseLevel.INFO, 'RDC - Resume Direct Captioning');\n this.setMode('MODE_PAINT-ON');\n }\n\n ccTR() {\n // Text Restart in text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'TR');\n this.setMode('MODE_TEXT');\n }\n\n ccRTD() {\n // Resume Text Display in Text mode (not supported, however)\n this.logger.log(VerboseLevel.INFO, 'RTD');\n this.setMode('MODE_TEXT');\n }\n\n ccEDM() {\n // Erase Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'EDM - Erase Displayed Memory');\n this.displayedMemory.reset();\n this.outputDataUpdate(true);\n }\n\n ccCR() {\n // Carriage Return\n this.logger.log(VerboseLevel.INFO, 'CR - Carriage Return');\n this.writeScreen.rollUp();\n this.outputDataUpdate(true);\n }\n\n ccENM() {\n // Erase Non-Displayed Memory\n this.logger.log(VerboseLevel.INFO, 'ENM - Erase Non-displayed Memory');\n this.nonDisplayedMemory.reset();\n }\n\n ccEOC() {\n // End of Caption (Flip Memories)\n this.logger.log(VerboseLevel.INFO, 'EOC - End Of Caption');\n if (this.mode === 'MODE_POP-ON') {\n const tmp = this.displayedMemory;\n this.displayedMemory = this.nonDisplayedMemory;\n this.nonDisplayedMemory = tmp;\n this.writeScreen = this.nonDisplayedMemory;\n this.logger.log(\n VerboseLevel.TEXT,\n () => 'DISP: ' + this.displayedMemory.getDisplayText()\n );\n }\n this.outputDataUpdate(true);\n }\n\n ccTO(nrCols: number) {\n // Tab Offset 1,2, or 3 columns\n this.logger.log(VerboseLevel.INFO, 'TO(' + nrCols + ') - Tab Offset');\n this.writeScreen.moveCursor(nrCols);\n }\n\n ccMIDROW(secondByte: number) {\n // Parse MIDROW command\n const styles: Partial<PenStyles> = { flash: false };\n styles.underline = secondByte % 2 === 1;\n styles.italics = secondByte >= 0x2e;\n if (!styles.italics) {\n const colorIndex = Math.floor(secondByte / 2) - 0x10;\n const colors = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n ];\n styles.foreground = colors[colorIndex];\n } else {\n styles.foreground = 'white';\n }\n this.logger.log(VerboseLevel.INFO, 'MIDROW: ' + JSON.stringify(styles));\n this.writeScreen.setPen(styles);\n }\n\n outputDataUpdate(dispatch: boolean = false) {\n const time = this.logger.time;\n if (time === null) {\n return;\n }\n\n if (this.outputFilter) {\n if (this.cueStartTime === null && !this.displayedMemory.isEmpty()) {\n // Start of a new cue\n this.cueStartTime = time;\n } else {\n if (!this.displayedMemory.equals(this.lastOutputScreen)) {\n this.outputFilter.newCue(\n this.cueStartTime!,\n time,\n this.lastOutputScreen\n );\n if (dispatch && this.outputFilter.dispatchCue) {\n this.outputFilter.dispatchCue();\n }\n\n this.cueStartTime = this.displayedMemory.isEmpty() ? null : time;\n }\n }\n this.lastOutputScreen.copy(this.displayedMemory);\n }\n }\n\n cueSplitAtTime(t: number) {\n if (this.outputFilter) {\n if (!this.displayedMemory.isEmpty()) {\n if (this.outputFilter.newCue) {\n this.outputFilter.newCue(this.cueStartTime!, t, this.displayedMemory);\n }\n\n this.cueStartTime = t;\n }\n }\n }\n}\n\ninterface PACData {\n row: number;\n indent: number | null;\n color: string | null;\n underline: boolean;\n italics: boolean;\n}\n\ntype SupportedField = 1 | 3;\n\ntype Channels = 0 | 1 | 2; // Will be 1 or 2 when parsing captions\n\ntype CmdHistory = {\n a: number | null;\n b: number | null;\n};\n\nclass Cea608Parser {\n channels: Array<Cea608Channel | null>;\n currentChannel: Channels = 0;\n cmdHistory: CmdHistory;\n logger: CaptionsLogger;\n\n constructor(field: SupportedField, out1: OutputFilter, out2: OutputFilter) {\n const logger = new CaptionsLogger();\n this.channels = [\n null,\n new Cea608Channel(field, out1, logger),\n new Cea608Channel(field + 1, out2, logger),\n ];\n this.cmdHistory = createCmdHistory();\n this.logger = logger;\n }\n\n getHandler(channel: number) {\n return (this.channels[channel] as Cea608Channel).getHandler();\n }\n\n setHandler(channel: number, newHandler: OutputFilter) {\n (this.channels[channel] as Cea608Channel).setHandler(newHandler);\n }\n\n /**\n * Add data for time t in forms of list of bytes (unsigned ints). The bytes are treated as pairs.\n */\n addData(time: number | null, byteList: number[]) {\n let cmdFound: boolean;\n let a: number;\n let b: number;\n let charsFound: number[] | boolean | null = false;\n\n this.logger.time = time;\n\n for (let i = 0; i < byteList.length; i += 2) {\n a = byteList[i] & 0x7f;\n b = byteList[i + 1] & 0x7f;\n if (a === 0 && b === 0) {\n continue;\n } else {\n this.logger.log(\n VerboseLevel.DATA,\n '[' +\n numArrayToHexArray([byteList[i], byteList[i + 1]]) +\n '] -> (' +\n numArrayToHexArray([a, b]) +\n ')'\n );\n }\n\n cmdFound = this.parseCmd(a, b);\n\n if (!cmdFound) {\n cmdFound = this.parseMidrow(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parsePAC(a, b);\n }\n\n if (!cmdFound) {\n cmdFound = this.parseBackgroundAttributes(a, b);\n }\n\n if (!cmdFound) {\n charsFound = this.parseChars(a, b);\n if (charsFound) {\n const currChNr = this.currentChannel;\n if (currChNr && currChNr > 0) {\n const channel = this.channels[currChNr] as Cea608Channel;\n channel.insertChars(charsFound);\n } else {\n this.logger.log(\n VerboseLevel.WARNING,\n 'No channel found yet. TEXT-MODE?'\n );\n }\n }\n }\n if (!cmdFound && !charsFound) {\n this.logger.log(\n VerboseLevel.WARNING,\n \"Couldn't parse cleaned data \" +\n numArrayToHexArray([a, b]) +\n ' orig: ' +\n numArrayToHexArray([byteList[i], byteList[i + 1]])\n );\n }\n }\n }\n\n /**\n * Parse Command.\n * @returns True if a command was found\n */\n parseCmd(a: number, b: number): boolean {\n const { cmdHistory } = this;\n const cond1 =\n (a === 0x14 || a === 0x1c || a === 0x15 || a === 0x1d) &&\n b >= 0x20 &&\n b <= 0x2f;\n const cond2 = (a === 0x17 || a === 0x1f) && b >= 0x21 && b <= 0x23;\n if (!(cond1 || cond2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Repeated command (' + numArrayToHexArray([a, b]) + ') is dropped'\n );\n return true;\n }\n\n const chNr = a === 0x14 || a === 0x15 || a === 0x17 ? 1 : 2;\n const channel = this.channels[chNr] as Cea608Channel;\n\n if (a === 0x14 || a === 0x15 || a === 0x1c || a === 0x1d) {\n if (b === 0x20) {\n channel.ccRCL();\n } else if (b === 0x21) {\n channel.ccBS();\n } else if (b === 0x22) {\n channel.ccAOF();\n } else if (b === 0x23) {\n channel.ccAON();\n } else if (b === 0x24) {\n channel.ccDER();\n } else if (b === 0x25) {\n channel.ccRU(2);\n } else if (b === 0x26) {\n channel.ccRU(3);\n } else if (b === 0x27) {\n channel.ccRU(4);\n } else if (b === 0x28) {\n channel.ccFON();\n } else if (b === 0x29) {\n channel.ccRDC();\n } else if (b === 0x2a) {\n channel.ccTR();\n } else if (b === 0x2b) {\n channel.ccRTD();\n } else if (b === 0x2c) {\n channel.ccEDM();\n } else if (b === 0x2d) {\n channel.ccCR();\n } else if (b === 0x2e) {\n channel.ccENM();\n } else if (b === 0x2f) {\n channel.ccEOC();\n }\n } else {\n // a == 0x17 || a == 0x1F\n channel.ccTO(b - 0x20);\n }\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Parse midrow styling command\n */\n parseMidrow(a: number, b: number): boolean {\n let chNr: number = 0;\n\n if ((a === 0x11 || a === 0x19) && b >= 0x20 && b <= 0x2f) {\n if (a === 0x11) {\n chNr = 1;\n } else {\n chNr = 2;\n }\n\n if (chNr !== this.currentChannel) {\n this.logger.log(\n VerboseLevel.ERROR,\n 'Mismatch channel in midrow parsing'\n );\n return false;\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.ccMIDROW(b);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'MIDROW (' + numArrayToHexArray([a, b]) + ')'\n );\n return true;\n }\n return false;\n }\n\n /**\n * Parse Preable Access Codes (Table 53).\n * @returns {Boolean} Tells if PAC found\n */\n parsePAC(a: number, b: number): boolean {\n let row: number;\n const cmdHistory = this.cmdHistory;\n\n const case1 =\n ((a >= 0x11 && a <= 0x17) || (a >= 0x19 && a <= 0x1f)) &&\n b >= 0x40 &&\n b <= 0x7f;\n const case2 = (a === 0x10 || a === 0x18) && b >= 0x40 && b <= 0x5f;\n if (!(case1 || case2)) {\n return false;\n }\n\n if (hasCmdRepeated(a, b, cmdHistory)) {\n setLastCmd(null, null, cmdHistory);\n return true; // Repeated commands are dropped (once)\n }\n\n const chNr: Channels = a <= 0x17 ? 1 : 2;\n\n if (b >= 0x40 && b <= 0x5f) {\n row = chNr === 1 ? rowsLowCh1[a] : rowsLowCh2[a];\n } else {\n // 0x60 <= b <= 0x7F\n row = chNr === 1 ? rowsHighCh1[a] : rowsHighCh2[a];\n }\n const channel = this.channels[chNr];\n if (!channel) {\n return false;\n }\n channel.setPAC(this.interpretPAC(row, b));\n setLastCmd(a, b, cmdHistory);\n this.currentChannel = chNr;\n return true;\n }\n\n /**\n * Interpret the second byte of the pac, and return the information.\n * @returns pacData with style parameters\n */\n interpretPAC(row: number, byte: number): PACData {\n let pacIndex;\n const pacData: PACData = {\n color: null,\n italics: false,\n indent: null,\n underline: false,\n row: row,\n };\n\n if (byte > 0x5f) {\n pacIndex = byte - 0x60;\n } else {\n pacIndex = byte - 0x40;\n }\n\n pacData.underline = (pacIndex & 1) === 1;\n if (pacIndex <= 0xd) {\n pacData.color = [\n 'white',\n 'green',\n 'blue',\n 'cyan',\n 'red',\n 'yellow',\n 'magenta',\n 'white',\n ][Math.floor(pacIndex / 2)];\n } else if (pacIndex <= 0xf) {\n pacData.italics = true;\n pacData.color = 'white';\n } else {\n pacData.indent = Math.floor((pacIndex - 0x10) / 2) * 4;\n }\n return pacData; // Note that row has zero offset. The spec uses 1.\n }\n\n /**\n * Parse characters.\n * @returns An array with 1 to 2 codes corresponding to chars, if found. null otherwise.\n */\n parseChars(a: number, b: number): number[] | null {\n let channelNr: Channels;\n let charCodes: number[] | null = null;\n let charCode1: number | null = null;\n\n if (a >= 0x19) {\n channelNr = 2;\n charCode1 = a - 8;\n } else {\n channelNr = 1;\n charCode1 = a;\n }\n if (charCode1 >= 0x11 && charCode1 <= 0x13) {\n // Special character\n let oneCode;\n if (charCode1 === 0x11) {\n oneCode = b + 0x50;\n } else if (charCode1 === 0x12) {\n oneCode = b + 0x70;\n } else {\n oneCode = b + 0x90;\n }\n\n this.logger.log(\n VerboseLevel.INFO,\n \"Special char '\" + getCharForByte(oneCode) + \"' in channel \" + channelNr\n );\n charCodes = [oneCode];\n } else if (a >= 0x20 && a <= 0x7f) {\n charCodes = b === 0 ? [a] : [a, b];\n }\n if (charCodes) {\n const hexCodes = numArrayToHexArray(charCodes);\n this.logger.log(\n VerboseLevel.DEBUG,\n 'Char codes = ' + hexCodes.join(',')\n );\n setLastCmd(a, b, this.cmdHistory);\n }\n return charCodes;\n }\n\n /**\n * Parse extended background attributes as well as new foreground color black.\n * @returns True if background attributes are found\n */\n parseBackgroundAttributes(a: number, b: number): boolean {\n const case1 = (a === 0x10 || a === 0x18) && b >= 0x20 && b <= 0x2f;\n const case2 = (a === 0x17 || a === 0x1f) && b >= 0x2d && b <= 0x2f;\n if (!(case1 || case2)) {\n return false;\n }\n let index: number;\n const bkgData: Partial<PenStyles> = {};\n if (a === 0x10 || a === 0x18) {\n index = Math.floor((b - 0x20) / 2);\n bkgData.background = backgroundColors[index];\n if (b % 2 === 1) {\n bkgData.background = bkgData.background + '_semi';\n }\n } else if (b === 0x2d) {\n bkgData.background = 'transparent';\n } else {\n bkgData.foreground = 'black';\n if (b === 0x2f) {\n bkgData.underline = true;\n }\n }\n const chNr: Channels = a <= 0x17 ? 1 : 2;\n const channel: Cea608Channel = this.channels[chNr] as Cea608Channel;\n channel.setBkgData(bkgData);\n setLastCmd(a, b, this.cmdHistory);\n return true;\n }\n\n /**\n * Reset state of parser and its channels.\n */\n reset() {\n for (let i = 0; i < Object.keys(this.channels).length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.reset();\n }\n }\n this.cmdHistory = createCmdHistory();\n }\n\n /**\n * Trigger the generation of a cue, and the start of a new one if displayScreens are not empty.\n */\n cueSplitAtTime(t: number) {\n for (let i = 0; i < this.channels.length; i++) {\n const channel = this.channels[i];\n if (channel) {\n channel.cueSplitAtTime(t);\n }\n }\n }\n}\n\nfunction setLastCmd(\n a: number | null,\n b: number | null,\n cmdHistory: CmdHistory\n) {\n cmdHistory.a = a;\n cmdHistory.b = b;\n}\n\nfunction hasCmdRepeated(a: number, b: number, cmdHistory: CmdHistory) {\n return cmdHistory.a === a && cmdHistory.b === b;\n}\n\nfunction createCmdHistory(): CmdHistory {\n return {\n a: null,\n b: null,\n };\n}\n\nexport default Cea608Parser;\n","import type { TimelineController } from '../controller/timeline-controller';\nimport type { CaptionScreen } from './cea-608-parser';\n\nexport default class OutputFilter {\n private timelineController: TimelineController;\n private cueRanges: Array<[number, number]> = [];\n private trackName: string;\n private startTime: number | null = null;\n private endTime: number | null = null;\n private screen: CaptionScreen | null = null;\n\n constructor(timelineController: TimelineController, trackName: string) {\n this.timelineController = timelineController;\n this.trackName = trackName;\n }\n\n dispatchCue() {\n if (this.startTime === null) {\n return;\n }\n\n this.timelineController.addCues(\n this.trackName,\n this.startTime,\n this.endTime as number,\n this.screen as CaptionScreen,\n this.cueRanges\n );\n this.startTime = null;\n }\n\n newCue(startTime: number, endTime: number, screen: CaptionScreen) {\n if (this.startTime === null || this.startTime > startTime) {\n this.startTime = startTime;\n }\n\n this.endTime = endTime;\n this.screen = screen;\n this.timelineController.createCaptionsTrack(this.trackName);\n }\n\n reset() {\n this.cueRanges = [];\n this.startTime = null;\n }\n}\n","/**\n * Copyright 2013 vtt.js Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the 'License');\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an 'AS IS' BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\ndeclare interface VTTCuePolyfill extends VTTCue {\n new (...args): VTTCuePolyfill;\n hasBeenReset: boolean;\n displayState: void;\n}\n\nexport default (function () {\n if (typeof self !== 'undefined' && self.VTTCue) {\n return self.VTTCue;\n }\n\n const AllowedDirections = ['', 'lr', 'rl'] as const;\n type Direction = (typeof AllowedDirections)[number];\n\n const AllowedAlignments = [\n 'start',\n 'middle',\n 'end',\n 'left',\n 'right',\n ] as const;\n type Alignment = (typeof AllowedAlignments)[number];\n\n function isAllowedValue<T, A>(allowed: T, value: string): A | false {\n if (typeof value !== 'string') {\n return false;\n }\n // necessary for assuring the generic conforms to the Array interface\n if (!Array.isArray(allowed)) {\n return false;\n }\n // reset the type so that the next narrowing works well\n const lcValue = value.toLowerCase() as any;\n // use the allow list to narrow the type to a specific subset of strings\n if (~allowed.indexOf(lcValue)) {\n return lcValue;\n }\n\n return false;\n }\n\n function findDirectionSetting(value: string) {\n return isAllowedValue<typeof AllowedDirections, Direction>(\n AllowedDirections,\n value\n );\n }\n\n function findAlignSetting(value: string) {\n return isAllowedValue<typeof AllowedAlignments, Alignment>(\n AllowedAlignments,\n value\n );\n }\n\n function extend(obj: Record<string, any>, ...rest: Record<string, any>[]) {\n let i = 1;\n for (; i < arguments.length; i++) {\n const cobj = arguments[i];\n for (const p in cobj) {\n obj[p] = cobj[p];\n }\n }\n\n return obj;\n }\n\n function VTTCue(startTime: number, endTime: number, text: string) {\n const cue = this as VTTCuePolyfill;\n const baseObj = { enumerable: true };\n /**\n * Shim implementation specific properties. These properties are not in\n * the spec.\n */\n\n // Lets us know when the VTTCue's data has changed in such a way that we need\n // to recompute its display state. This lets us compute its display state\n // lazily.\n cue.hasBeenReset = false;\n\n /**\n * VTTCue and TextTrackCue properties\n * http://dev.w3.org/html5/webvtt/#vttcue-interface\n */\n\n let _id = '';\n let _pauseOnExit = false;\n let _startTime = startTime;\n let _endTime = endTime;\n let _text = text;\n let _region = null;\n let _vertical: Direction = '';\n let _snapToLines = true;\n let _line: number | 'auto' = 'auto';\n let _lineAlign: Alignment = 'start';\n let _position = 50;\n let _positionAlign: Alignment = 'middle';\n let _size = 50;\n let _align: Alignment = 'middle';\n\n Object.defineProperty(\n cue,\n 'id',\n extend({}, baseObj, {\n get: function () {\n return _id;\n },\n set: function (value: string) {\n _id = '' + value;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'pauseOnExit',\n extend({}, baseObj, {\n get: function () {\n return _pauseOnExit;\n },\n set: function (value: boolean) {\n _pauseOnExit = !!value;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'startTime',\n extend({}, baseObj, {\n get: function () {\n return _startTime;\n },\n set: function (value: number) {\n if (typeof value !== 'number') {\n throw new TypeError('Start time must be set to a number.');\n }\n\n _startTime = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'endTime',\n extend({}, baseObj, {\n get: function () {\n return _endTime;\n },\n set: function (value: number) {\n if (typeof value !== 'number') {\n throw new TypeError('End time must be set to a number.');\n }\n\n _endTime = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'text',\n extend({}, baseObj, {\n get: function () {\n return _text;\n },\n set: function (value: string) {\n _text = '' + value;\n this.hasBeenReset = true;\n },\n })\n );\n\n // todo: implement VTTRegion polyfill?\n Object.defineProperty(\n cue,\n 'region',\n extend({}, baseObj, {\n get: function () {\n return _region;\n },\n set: function (value: any) {\n _region = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'vertical',\n extend({}, baseObj, {\n get: function () {\n return _vertical;\n },\n set: function (value: string) {\n const setting = findDirectionSetting(value);\n // Have to check for false because the setting an be an empty string.\n if (setting === false) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _vertical = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'snapToLines',\n extend({}, baseObj, {\n get: function () {\n return _snapToLines;\n },\n set: function (value: boolean) {\n _snapToLines = !!value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'line',\n extend({}, baseObj, {\n get: function () {\n return _line;\n },\n set: function (value: number | 'auto') {\n if (typeof value !== 'number' && value !== 'auto') {\n throw new SyntaxError(\n 'An invalid number or illegal string was specified.'\n );\n }\n\n _line = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'lineAlign',\n extend({}, baseObj, {\n get: function () {\n return _lineAlign;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _lineAlign = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'position',\n extend({}, baseObj, {\n get: function () {\n return _position;\n },\n set: function (value: number) {\n if (value < 0 || value > 100) {\n throw new Error('Position must be between 0 and 100.');\n }\n\n _position = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'positionAlign',\n extend({}, baseObj, {\n get: function () {\n return _positionAlign;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _positionAlign = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'size',\n extend({}, baseObj, {\n get: function () {\n return _size;\n },\n set: function (value: number) {\n if (value < 0 || value > 100) {\n throw new Error('Size must be between 0 and 100.');\n }\n\n _size = value;\n this.hasBeenReset = true;\n },\n })\n );\n\n Object.defineProperty(\n cue,\n 'align',\n extend({}, baseObj, {\n get: function () {\n return _align;\n },\n set: function (value: string) {\n const setting = findAlignSetting(value);\n if (!setting) {\n throw new SyntaxError(\n 'An invalid or illegal string was specified.'\n );\n }\n\n _align = setting;\n this.hasBeenReset = true;\n },\n })\n );\n\n /**\n * Other <track> spec defined properties\n */\n\n // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#text-track-cue-display-state\n cue.displayState = undefined;\n }\n\n /**\n * VTTCue methods\n */\n\n VTTCue.prototype.getCueAsHTML = function () {\n // Assume WebVTT.convertCueToDOMTree is on the global.\n const WebVTT = (self as any).WebVTT;\n return WebVTT.convertCueToDOMTree(self, this.text);\n };\n // this is a polyfill hack\n return VTTCue as any as VTTCuePolyfill;\n})();\n","/*\n * Source: https://github.com/mozilla/vtt.js/blob/master/dist/vtt.js\n */\n\nimport VTTCue from './vttcue';\n\nclass StringDecoder {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n decode(data: string | any, options?: Object): string | never {\n if (!data) {\n return '';\n }\n\n if (typeof data !== 'string') {\n throw new Error('Error - expected string data.');\n }\n\n return decodeURIComponent(encodeURIComponent(data));\n }\n}\n\n// Try to parse input as a time stamp.\nexport function parseTimeStamp(input: string) {\n function computeSeconds(h, m, s, f) {\n return (h | 0) * 3600 + (m | 0) * 60 + (s | 0) + parseFloat(f || 0);\n }\n\n const m = input.match(/^(?:(\\d+):)?(\\d{2}):(\\d{2})(\\.\\d+)?/);\n if (!m) {\n return null;\n }\n\n if (parseFloat(m[2]) > 59) {\n // Timestamp takes the form of [hours]:[minutes].[milliseconds]\n // First position is hours as it's over 59.\n return computeSeconds(m[2], m[3], 0, m[4]);\n }\n // Timestamp takes the form of [hours (optional)]:[minutes]:[seconds].[milliseconds]\n return computeSeconds(m[1], m[2], m[3], m[4]);\n}\n\n// A settings object holds key/value pairs and will ignore anything but the first\n// assignment to a specific key.\nclass Settings {\n private readonly values: { [key: string]: any } = Object.create(null);\n\n // Only accept the first assignment to any key.\n set(k: string, v: any) {\n if (!this.get(k) && v !== '') {\n this.values[k] = v;\n }\n }\n // Return the value for a key, or a default value.\n // If 'defaultKey' is passed then 'dflt' is assumed to be an object with\n // a number of possible default values as properties where 'defaultKey' is\n // the key of the property that will be chosen; otherwise it's assumed to be\n // a single value.\n get(k: string, dflt?: any, defaultKey?: string): any {\n if (defaultKey) {\n return this.has(k) ? this.values[k] : dflt[defaultKey];\n }\n\n return this.has(k) ? this.values[k] : dflt;\n }\n // Check whether we have a value for a key.\n has(k: string): boolean {\n return k in this.values;\n }\n // Accept a setting if its one of the given alternatives.\n alt(k: string, v: any, a: any[]) {\n for (let n = 0; n < a.length; ++n) {\n if (v === a[n]) {\n this.set(k, v);\n break;\n }\n }\n }\n // Accept a setting if its a valid (signed) integer.\n integer(k: string, v: any) {\n if (/^-?\\d+$/.test(v)) {\n // integer\n this.set(k, parseInt(v, 10));\n }\n }\n // Accept a setting if its a valid percentage.\n percent(k: string, v: any): boolean {\n if (/^([\\d]{1,3})(\\.[\\d]*)?%$/.test(v)) {\n const percent = parseFloat(v);\n if (percent >= 0 && percent <= 100) {\n this.set(k, percent);\n return true;\n }\n }\n return false;\n }\n}\n\n// Helper function to parse input into groups separated by 'groupDelim', and\n// interpret each group as a key/value pair separated by 'keyValueDelim'.\nfunction parseOptions(\n input: string,\n callback: (k: string, v: any) => void,\n keyValueDelim: RegExp,\n groupDelim?: RegExp\n) {\n const groups = groupDelim ? input.split(groupDelim) : [input];\n for (const i in groups) {\n if (typeof groups[i] !== 'string') {\n continue;\n }\n\n const kv = groups[i].split(keyValueDelim);\n if (kv.length !== 2) {\n continue;\n }\n\n const k = kv[0];\n const v = kv[1];\n callback(k, v);\n }\n}\n\nconst defaults = new VTTCue(0, 0, '');\n// 'middle' was changed to 'center' in the spec: https://github.com/w3c/webvtt/pull/244\n// Safari doesn't yet support this change, but FF and Chrome do.\nconst center = (defaults.align as string) === 'middle' ? 'middle' : 'center';\n\nfunction parseCue(input: string, cue: VTTCue, regionList: Region[]) {\n // Remember the original input if we need to throw an error.\n const oInput = input;\n // 4.1 WebVTT timestamp\n function consumeTimeStamp(): number | never {\n const ts = parseTimeStamp(input);\n if (ts === null) {\n throw new Error('Malformed timestamp: ' + oInput);\n }\n\n // Remove time stamp from input.\n input = input.replace(/^[^\\sa-zA-Z-]+/, '');\n return ts;\n }\n\n // 4.4.2 WebVTT cue settings\n function consumeCueSettings(input: string, cue: VTTCue) {\n const settings = new Settings();\n\n parseOptions(\n input,\n function (k, v) {\n let vals;\n switch (k) {\n case 'region':\n // Find the last region we parsed with the same region id.\n for (let i = regionList.length - 1; i >= 0; i--) {\n if (regionList[i].id === v) {\n settings.set(k, regionList[i].region);\n break;\n }\n }\n break;\n case 'vertical':\n settings.alt(k, v, ['rl', 'lr']);\n break;\n case 'line':\n vals = v.split(',');\n settings.integer(k, vals[0]);\n if (settings.percent(k, vals[0])) {\n settings.set('snapToLines', false);\n }\n\n settings.alt(k, vals[0], ['auto']);\n if (vals.length === 2) {\n settings.alt('lineAlign', vals[1], ['start', center, 'end']);\n }\n\n break;\n case 'position':\n vals = v.split(',');\n settings.percent(k, vals[0]);\n if (vals.length === 2) {\n settings.alt('positionAlign', vals[1], [\n 'start',\n center,\n 'end',\n 'line-left',\n 'line-right',\n 'auto',\n ]);\n }\n\n break;\n case 'size':\n settings.percent(k, v);\n break;\n case 'align':\n settings.alt(k, v, ['start', center, 'end', 'left', 'right']);\n break;\n }\n },\n /:/,\n /\\s/\n );\n\n // Apply default values for any missing fields.\n cue.region = settings.get('region', null);\n cue.vertical = settings.get('vertical', '');\n let line = settings.get('line', 'auto');\n if (line === 'auto' && defaults.line === -1) {\n // set numeric line number for Safari\n line = -1;\n }\n cue.line = line;\n cue.lineAlign = settings.get('lineAlign', 'start');\n cue.snapToLines = settings.get('snapToLines', true);\n cue.size = settings.get('size', 100);\n cue.align = settings.get('align', center);\n let position = settings.get('position', 'auto');\n if (position === 'auto' && defaults.position === 50) {\n // set numeric position for Safari\n position =\n cue.align === 'start' || cue.align === 'left'\n ? 0\n : cue.align === 'end' || cue.align === 'right'\n ? 100\n : 50;\n }\n cue.position = position;\n }\n\n function skipWhitespace() {\n input = input.replace(/^\\s+/, '');\n }\n\n // 4.1 WebVTT cue timings.\n skipWhitespace();\n cue.startTime = consumeTimeStamp(); // (1) collect cue start time\n skipWhitespace();\n if (input.slice(0, 3) !== '-->') {\n // (3) next characters must match '-->'\n throw new Error(\n \"Malformed time stamp (time stamps must be separated by '-->'): \" + oInput\n );\n }\n input = input.slice(3);\n skipWhitespace();\n cue.endTime = consumeTimeStamp(); // (5) collect cue end time\n\n // 4.1 WebVTT cue settings list.\n skipWhitespace();\n consumeCueSettings(input, cue);\n}\n\nexport function fixLineBreaks(input: string): string {\n return input.replace(/<br(?: \\/)?>/gi, '\\n');\n}\n\ntype Region = {\n id: string;\n region: any;\n};\n\nexport class VTTParser {\n private state:\n | 'INITIAL'\n | 'HEADER'\n | 'ID'\n | 'CUE'\n | 'CUETEXT'\n | 'NOTE'\n | 'BADWEBVTT'\n | 'BADCUE' = 'INITIAL';\n private buffer: string = '';\n private decoder: StringDecoder = new StringDecoder();\n private regionList: Region[] = [];\n private cue: VTTCue | null = null;\n public oncue?: (cue: VTTCue) => void;\n public onparsingerror?: (error: Error) => void;\n public onflush?: () => void;\n\n parse(data?: string): VTTParser {\n const _this = this;\n\n // If there is no data then we won't decode it, but will just try to parse\n // whatever is in buffer already. This may occur in circumstances, for\n // example when flush() is called.\n if (data) {\n // Try to decode the data that we received.\n _this.buffer += _this.decoder.decode(data, { stream: true });\n }\n\n function collectNextLine(): string {\n let buffer: string = _this.buffer;\n let pos = 0;\n\n buffer = fixLineBreaks(buffer);\n\n while (\n pos < buffer.length &&\n buffer[pos] !== '\\r' &&\n buffer[pos] !== '\\n'\n ) {\n ++pos;\n }\n\n const line: string = buffer.slice(0, pos);\n // Advance the buffer early in case we fail below.\n if (buffer[pos] === '\\r') {\n ++pos;\n }\n\n if (buffer[pos] === '\\n') {\n ++pos;\n }\n\n _this.buffer = buffer.slice(pos);\n return line;\n }\n\n // 3.2 WebVTT metadata header syntax\n function parseHeader(input) {\n parseOptions(\n input,\n function (k, v) {\n // switch (k) {\n // case 'region':\n // 3.3 WebVTT region metadata header syntax\n // console.log('parse region', v);\n // parseRegion(v);\n // break;\n // }\n },\n /:/\n );\n }\n\n // 5.1 WebVTT file parsing.\n try {\n let line: string = '';\n if (_this.state === 'INITIAL') {\n // We can't start parsing until we have the first line.\n if (!/\\r\\n|\\n/.test(_this.buffer)) {\n return this;\n }\n\n line = collectNextLine();\n // strip of UTF-8 BOM if any\n // https://en.wikipedia.org/wiki/Byte_order_mark#UTF-8\n const m = line.match(/^()?WEBVTT([ \\t].*)?$/);\n if (!m?.[0]) {\n throw new Error('Malformed WebVTT signature.');\n }\n\n _this.state = 'HEADER';\n }\n\n let alreadyCollectedLine = false;\n while (_this.buffer) {\n // We can't parse a line until we have the full line.\n if (!/\\r\\n|\\n/.test(_this.buffer)) {\n return this;\n }\n\n if (!alreadyCollectedLine) {\n line = collectNextLine();\n } else {\n alreadyCollectedLine = false;\n }\n\n switch (_this.state) {\n case 'HEADER':\n // 13-18 - Allow a header (metadata) under the WEBVTT line.\n if (/:/.test(line)) {\n parseHeader(line);\n } else if (!line) {\n // An empty line terminates the header and starts the body (cues).\n _this.state = 'ID';\n }\n continue;\n case 'NOTE':\n // Ignore NOTE blocks.\n if (!line) {\n _this.state = 'ID';\n }\n\n continue;\n case 'ID':\n // Check for the start of NOTE blocks.\n if (/^NOTE($|[ \\t])/.test(line)) {\n _this.state = 'NOTE';\n break;\n }\n // 19-29 - Allow any number of line terminators, then initialize new cue values.\n if (!line) {\n continue;\n }\n\n _this.cue = new VTTCue(0, 0, '');\n _this.state = 'CUE';\n // 30-39 - Check if self line contains an optional identifier or timing data.\n if (line.indexOf('-->') === -1) {\n _this.cue.id = line;\n continue;\n }\n // Process line as start of a cue.\n /* falls through */\n case 'CUE':\n // 40 - Collect cue timings and settings.\n if (!_this.cue) {\n _this.state = 'BADCUE';\n continue;\n }\n try {\n parseCue(line, _this.cue, _this.regionList);\n } catch (e) {\n // In case of an error ignore rest of the cue.\n _this.cue = null;\n _this.state = 'BADCUE';\n continue;\n }\n _this.state = 'CUETEXT';\n continue;\n case 'CUETEXT':\n {\n const hasSubstring = line.indexOf('-->') !== -1;\n // 34 - If we have an empty line then report the cue.\n // 35 - If we have the special substring '-->' then report the cue,\n // but do not collect the line as we need to process the current\n // one as a new cue.\n if (!line || (hasSubstring && (alreadyCollectedLine = true))) {\n // We are done parsing self cue.\n if (_this.oncue && _this.cue) {\n _this.oncue(_this.cue);\n }\n\n _this.cue = null;\n _this.state = 'ID';\n continue;\n }\n if (_this.cue === null) {\n continue;\n }\n\n if (_this.cue.text) {\n _this.cue.text += '\\n';\n }\n _this.cue.text += line;\n }\n continue;\n case 'BADCUE':\n // 54-62 - Collect and discard the remaining cue.\n if (!line) {\n _this.state = 'ID';\n }\n }\n }\n } catch (e) {\n // If we are currently parsing a cue, report what we have.\n if (_this.state === 'CUETEXT' && _this.cue && _this.oncue) {\n _this.oncue(_this.cue);\n }\n\n _this.cue = null;\n // Enter BADWEBVTT state if header was not parsed correctly otherwise\n // another exception occurred so enter BADCUE state.\n _this.state = _this.state === 'INITIAL' ? 'BADWEBVTT' : 'BADCUE';\n }\n return this;\n }\n\n flush(): VTTParser {\n const _this = this;\n try {\n // Finish decoding the stream.\n // _this.buffer += _this.decoder.decode();\n // Synthesize the end of the current cue or region.\n if (_this.cue || _this.state === 'HEADER') {\n _this.buffer += '\\n\\n';\n _this.parse();\n }\n // If we've flushed, parsed, and we're still on the INITIAL state then\n // that means we don't have enough of the stream to parse the first\n // line.\n if (_this.state === 'INITIAL' || _this.state === 'BADWEBVTT') {\n throw new Error('Malformed WebVTT signature.');\n }\n } catch (e) {\n if (_this.onparsingerror) {\n _this.onparsingerror(e);\n }\n }\n if (_this.onflush) {\n _this.onflush();\n }\n\n return this;\n }\n}\n","import { VTTParser } from './vttparser';\nimport { utf8ArrayToStr } from '../demux/id3';\nimport {\n RationalTimestamp,\n toMpegTsClockFromTimescale,\n} from './timescale-conversion';\nimport { normalizePts } from '../remux/mp4-remuxer';\nimport type { VTTCCs } from '../types/vtt';\n\nconst LINEBREAKS = /\\r\\n|\\n\\r|\\n|\\r/g;\n\n// String.prototype.startsWith is not supported in IE11\nconst startsWith = function (\n inputString: string,\n searchString: string,\n position: number = 0\n) {\n return (\n inputString.slice(position, position + searchString.length) === searchString\n );\n};\n\nconst cueString2millis = function (timeString: string) {\n let ts = parseInt(timeString.slice(-3));\n const secs = parseInt(timeString.slice(-6, -4));\n const mins = parseInt(timeString.slice(-9, -7));\n const hours =\n timeString.length > 9\n ? parseInt(timeString.substring(0, timeString.indexOf(':')))\n : 0;\n\n if (\n !Number.isFinite(ts) ||\n !Number.isFinite(secs) ||\n !Number.isFinite(mins) ||\n !Number.isFinite(hours)\n ) {\n throw Error(`Malformed X-TIMESTAMP-MAP: Local:${timeString}`);\n }\n\n ts += 1000 * secs;\n ts += 60 * 1000 * mins;\n ts += 60 * 60 * 1000 * hours;\n\n return ts;\n};\n\n// From https://github.com/darkskyapp/string-hash\nconst hash = function (text: string) {\n let hash = 5381;\n let i = text.length;\n while (i) {\n hash = (hash * 33) ^ text.charCodeAt(--i);\n }\n\n return (hash >>> 0).toString();\n};\n\n// Create a unique hash id for a cue based on start/end times and text.\n// This helps timeline-controller to avoid showing repeated captions.\nexport function generateCueId(\n startTime: number,\n endTime: number,\n text: string\n) {\n return hash(startTime.toString()) + hash(endTime.toString()) + hash(text);\n}\n\nconst calculateOffset = function (vttCCs: VTTCCs, cc, presentationTime) {\n let currCC = vttCCs[cc];\n let prevCC = vttCCs[currCC.prevCC];\n\n // This is the first discontinuity or cues have been processed since the last discontinuity\n // Offset = current discontinuity time\n if (!prevCC || (!prevCC.new && currCC.new)) {\n vttCCs.ccOffset = vttCCs.presentationOffset = currCC.start;\n currCC.new = false;\n return;\n }\n\n // There have been discontinuities since cues were last parsed.\n // Offset = time elapsed\n while (prevCC?.new) {\n vttCCs.ccOffset += currCC.start - prevCC.start;\n currCC.new = false;\n currCC = prevCC;\n prevCC = vttCCs[currCC.prevCC];\n }\n\n vttCCs.presentationOffset = presentationTime;\n};\n\nexport function parseWebVTT(\n vttByteArray: ArrayBuffer,\n initPTS: RationalTimestamp | undefined,\n vttCCs: VTTCCs,\n cc: number,\n timeOffset: number,\n callBack: (cues: VTTCue[]) => void,\n errorCallBack: (error: Error) => void\n) {\n const parser = new VTTParser();\n // Convert byteArray into string, replacing any somewhat exotic linefeeds with \"\\n\", then split on that character.\n // Uint8Array.prototype.reduce is not implemented in IE11\n const vttLines = utf8ArrayToStr(new Uint8Array(vttByteArray))\n .trim()\n .replace(LINEBREAKS, '\\n')\n .split('\\n');\n const cues: VTTCue[] = [];\n const init90kHz = initPTS\n ? toMpegTsClockFromTimescale(initPTS.baseTime, initPTS.timescale)\n : 0;\n let cueTime = '00:00.000';\n let timestampMapMPEGTS = 0;\n let timestampMapLOCAL = 0;\n let parsingError: Error;\n let inHeader = true;\n\n parser.oncue = function (cue: VTTCue) {\n // Adjust cue timing; clamp cues to start no earlier than - and drop cues that don't end after - 0 on timeline.\n const currCC = vttCCs[cc];\n let cueOffset = vttCCs.ccOffset;\n\n // Calculate subtitle PTS offset\n const webVttMpegTsMapOffset = (timestampMapMPEGTS - init90kHz) / 90000;\n\n // Update offsets for new discontinuities\n if (currCC?.new) {\n if (timestampMapLOCAL !== undefined) {\n // When local time is provided, offset = discontinuity start time - local time\n cueOffset = vttCCs.ccOffset = currCC.start;\n } else {\n calculateOffset(vttCCs, cc, webVttMpegTsMapOffset);\n }\n }\n if (webVttMpegTsMapOffset) {\n if (!initPTS) {\n parsingError = new Error('Missing initPTS for VTT MPEGTS');\n return;\n }\n // If we have MPEGTS, offset = presentation time + discontinuity offset\n cueOffset = webVttMpegTsMapOffset - vttCCs.presentationOffset;\n }\n\n const duration = cue.endTime - cue.startTime;\n const startTime =\n normalizePts(\n (cue.startTime + cueOffset - timestampMapLOCAL) * 90000,\n timeOffset * 90000\n ) / 90000;\n cue.startTime = Math.max(startTime, 0);\n cue.endTime = Math.max(startTime + duration, 0);\n\n //trim trailing webvtt block whitespaces\n const text = cue.text.trim();\n\n // Fix encoding of special characters\n cue.text = decodeURIComponent(encodeURIComponent(text));\n\n // If the cue was not assigned an id from the VTT file (line above the content), create one.\n if (!cue.id) {\n cue.id = generateCueId(cue.startTime, cue.endTime, text);\n }\n\n if (cue.endTime > 0) {\n cues.push(cue);\n }\n };\n\n parser.onparsingerror = function (error: Error) {\n parsingError = error;\n };\n\n parser.onflush = function () {\n if (parsingError) {\n errorCallBack(parsingError);\n return;\n }\n callBack(cues);\n };\n\n // Go through contents line by line.\n vttLines.forEach((line) => {\n if (inHeader) {\n // Look for X-TIMESTAMP-MAP in header.\n if (startsWith(line, 'X-TIMESTAMP-MAP=')) {\n // Once found, no more are allowed anyway, so stop searching.\n inHeader = false;\n // Extract LOCAL and MPEGTS.\n line\n .slice(16)\n .split(',')\n .forEach((timestamp) => {\n if (startsWith(timestamp, 'LOCAL:')) {\n cueTime = timestamp.slice(6);\n } else if (startsWith(timestamp, 'MPEGTS:')) {\n timestampMapMPEGTS = parseInt(timestamp.slice(7));\n }\n });\n try {\n // Convert cue time to seconds\n timestampMapLOCAL = cueString2millis(cueTime) / 1000;\n } catch (error) {\n parsingError = error;\n }\n // Return without parsing X-TIMESTAMP-MAP line.\n return;\n } else if (line === '') {\n inHeader = false;\n }\n }\n // Parse line by default.\n parser.parse(line + '\\n');\n });\n\n parser.flush();\n}\n","import { findBox } from './mp4-tools';\nimport { parseTimeStamp } from './vttparser';\nimport VTTCue from './vttcue';\nimport { utf8ArrayToStr } from '../demux/id3';\nimport {\n RationalTimestamp,\n toTimescaleFromScale,\n} from './timescale-conversion';\nimport { generateCueId } from './webvtt-parser';\n\nexport const IMSC1_CODEC = 'stpp.ttml.im1t';\n\n// Time format: h:m:s:frames(.subframes)\nconst HMSF_REGEX = /^(\\d{2,}):(\\d{2}):(\\d{2}):(\\d{2})\\.?(\\d+)?$/;\n\n// Time format: hours, minutes, seconds, milliseconds, frames, ticks\nconst TIME_UNIT_REGEX = /^(\\d*(?:\\.\\d*)?)(h|m|s|ms|f|t)$/;\n\nconst textAlignToLineAlign: Partial<Record<string, LineAlignSetting>> = {\n left: 'start',\n center: 'center',\n right: 'end',\n start: 'start',\n end: 'end',\n};\n\nexport function parseIMSC1(\n payload: ArrayBuffer,\n initPTS: RationalTimestamp,\n callBack: (cues: Array<VTTCue>) => any,\n errorCallBack: (error: Error) => any\n) {\n const results = findBox(new Uint8Array(payload), ['mdat']);\n if (results.length === 0) {\n errorCallBack(new Error('Could not parse IMSC1 mdat'));\n return;\n }\n\n const ttmlList = results.map((mdat) => utf8ArrayToStr(mdat));\n\n const syncTime = toTimescaleFromScale(initPTS.baseTime, 1, initPTS.timescale);\n\n try {\n ttmlList.forEach((ttml) => callBack(parseTTML(ttml, syncTime)));\n } catch (error) {\n errorCallBack(error);\n }\n}\n\nfunction parseTTML(ttml: string, syncTime: number): Array<VTTCue> {\n const parser = new DOMParser();\n const xmlDoc = parser.parseFromString(ttml, 'text/xml');\n const tt = xmlDoc.getElementsByTagName('tt')[0];\n if (!tt) {\n throw new Error('Invalid ttml');\n }\n const defaultRateInfo = {\n frameRate: 30,\n subFrameRate: 1,\n frameRateMultiplier: 0,\n tickRate: 0,\n };\n const rateInfo: Object = Object.keys(defaultRateInfo).reduce(\n (result, key) => {\n result[key] = tt.getAttribute(`ttp:${key}`) || defaultRateInfo[key];\n return result;\n },\n {}\n );\n\n const trim = tt.getAttribute('xml:space') !== 'preserve';\n\n const styleElements = collectionToDictionary(\n getElementCollection(tt, 'styling', 'style')\n );\n const regionElements = collectionToDictionary(\n getElementCollection(tt, 'layout', 'region')\n );\n const cueElements = getElementCollection(tt, 'body', '[begin]');\n\n return [].map\n .call(cueElements, (cueElement) => {\n const cueText = getTextContent(cueElement, trim);\n\n if (!cueText || !cueElement.hasAttribute('begin')) {\n return null;\n }\n const startTime = parseTtmlTime(\n cueElement.getAttribute('begin'),\n rateInfo\n );\n const duration = parseTtmlTime(cueElement.getAttribute('dur'), rateInfo);\n let endTime = parseTtmlTime(cueElement.getAttribute('end'), rateInfo);\n if (startTime === null) {\n throw timestampParsingError(cueElement);\n }\n if (endTime === null) {\n if (duration === null) {\n throw timestampParsingError(cueElement);\n }\n endTime = startTime + duration;\n }\n const cue = new VTTCue(startTime - syncTime, endTime - syncTime, cueText);\n cue.id = generateCueId(cue.startTime, cue.endTime, cue.text);\n\n const region = regionElements[cueElement.getAttribute('region')];\n const style = styleElements[cueElement.getAttribute('style')];\n\n // Apply styles to cue\n const styles = getTtmlStyles(region, style, styleElements);\n const { textAlign } = styles;\n if (textAlign) {\n // cue.positionAlign not settable in FF~2016\n const lineAlign = textAlignToLineAlign[textAlign];\n if (lineAlign) {\n cue.lineAlign = lineAlign;\n }\n cue.align = textAlign as AlignSetting;\n }\n Object.assign(cue, styles);\n\n return cue;\n })\n .filter((cue) => cue !== null);\n}\n\nfunction getElementCollection(\n fromElement,\n parentName,\n childName\n): Array<HTMLElement> {\n const parent = fromElement.getElementsByTagName(parentName)[0];\n if (parent) {\n return [].slice.call(parent.querySelectorAll(childName));\n }\n return [];\n}\n\nfunction collectionToDictionary(elementsWithId: Array<HTMLElement>): {\n [id: string]: HTMLElement;\n} {\n return elementsWithId.reduce((dict, element: HTMLElement) => {\n const id = element.getAttribute('xml:id');\n if (id) {\n dict[id] = element;\n }\n return dict;\n }, {});\n}\n\nfunction getTextContent(element, trim): string {\n return [].slice.call(element.childNodes).reduce((str, node, i) => {\n if (node.nodeName === 'br' && i) {\n return str + '\\n';\n }\n if (node.childNodes?.length) {\n return getTextContent(node, trim);\n } else if (trim) {\n return str + node.textContent.trim().replace(/\\s+/g, ' ');\n }\n return str + node.textContent;\n }, '');\n}\n\nfunction getTtmlStyles(\n region,\n style,\n styleElements\n): { [style: string]: string } {\n const ttsNs = 'http://www.w3.org/ns/ttml#styling';\n let regionStyle = null;\n const styleAttributes = [\n 'displayAlign',\n 'textAlign',\n 'color',\n 'backgroundColor',\n 'fontSize',\n 'fontFamily',\n // 'fontWeight',\n // 'lineHeight',\n // 'wrapOption',\n // 'fontStyle',\n // 'direction',\n // 'writingMode'\n ];\n\n const regionStyleName = region?.hasAttribute('style')\n ? region.getAttribute('style')\n : null;\n\n if (regionStyleName && styleElements.hasOwnProperty(regionStyleName)) {\n regionStyle = styleElements[regionStyleName];\n }\n\n return styleAttributes.reduce((styles, name) => {\n const value =\n getAttributeNS(style, ttsNs, name) ||\n getAttributeNS(region, ttsNs, name) ||\n getAttributeNS(regionStyle, ttsNs, name);\n if (value) {\n styles[name] = value;\n }\n return styles;\n }, {});\n}\n\nfunction getAttributeNS(element, ns, name): string | null {\n if (!element) {\n return null;\n }\n return element.hasAttributeNS(ns, name)\n ? element.getAttributeNS(ns, name)\n : null;\n}\n\nfunction timestampParsingError(node) {\n return new Error(`Could not parse ttml timestamp ${node}`);\n}\n\nfunction parseTtmlTime(timeAttributeValue, rateInfo): number | null {\n if (!timeAttributeValue) {\n return null;\n }\n let seconds: number | null = parseTimeStamp(timeAttributeValue);\n if (seconds === null) {\n if (HMSF_REGEX.test(timeAttributeValue)) {\n seconds = parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo);\n } else if (TIME_UNIT_REGEX.test(timeAttributeValue)) {\n seconds = parseTimeUnits(timeAttributeValue, rateInfo);\n }\n }\n return seconds;\n}\n\nfunction parseHoursMinutesSecondsFrames(timeAttributeValue, rateInfo): number {\n const m = HMSF_REGEX.exec(timeAttributeValue) as Array<any>;\n const frames = (m[4] | 0) + (m[5] | 0) / rateInfo.subFrameRate;\n return (\n (m[1] | 0) * 3600 +\n (m[2] | 0) * 60 +\n (m[3] | 0) +\n frames / rateInfo.frameRate\n );\n}\n\nfunction parseTimeUnits(timeAttributeValue, rateInfo): number {\n const m = TIME_UNIT_REGEX.exec(timeAttributeValue) as Array<any>;\n const value = Number(m[1]);\n const unit = m[2];\n switch (unit) {\n case 'h':\n return value * 3600;\n case 'm':\n return value * 60;\n case 'ms':\n return value * 1000;\n case 'f':\n return value / rateInfo.frameRate;\n case 't':\n return value / rateInfo.tickRate;\n }\n return value;\n}\n","import { Events } from '../events';\nimport Cea608Parser, { CaptionScreen } from '../utils/cea-608-parser';\nimport OutputFilter from '../utils/output-filter';\nimport { parseWebVTT } from '../utils/webvtt-parser';\nimport {\n sendAddTrackEvent,\n clearCurrentCues,\n addCueToTrack,\n removeCuesInRange,\n} from '../utils/texttrack-utils';\nimport { subtitleOptionsIdentical } from '../utils/media-option-attributes';\nimport { parseIMSC1, IMSC1_CODEC } from '../utils/imsc1-ttml-parser';\nimport { appendUint8Array } from '../utils/mp4-tools';\nimport { PlaylistLevelType } from '../types/loader';\nimport { Fragment } from '../loader/fragment';\nimport {\n FragParsingUserdataData,\n FragLoadedData,\n FragDecryptedData,\n MediaAttachingData,\n ManifestLoadedData,\n InitPTSFoundData,\n SubtitleTracksUpdatedData,\n BufferFlushingData,\n FragLoadingData,\n} from '../types/events';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { HlsConfig } from '../config';\nimport type { CuesInterface } from '../utils/cues';\nimport type { MediaPlaylist } from '../types/media-playlist';\nimport type { VTTCCs } from '../types/vtt';\nimport type { RationalTimestamp } from '../utils/timescale-conversion';\n\ntype TrackProperties = {\n label: string;\n languageCode: string;\n media?: MediaPlaylist;\n};\n\ntype NonNativeCaptionsTrack = {\n _id?: string;\n label: string;\n kind: string;\n default: boolean;\n closedCaptions?: MediaPlaylist;\n subtitleTrack?: MediaPlaylist;\n};\n\nexport class TimelineController implements ComponentAPI {\n private hls: Hls;\n private media: HTMLMediaElement | null = null;\n private config: HlsConfig;\n private enabled: boolean = true;\n private Cues: CuesInterface;\n private textTracks: Array<TextTrack> = [];\n private tracks: Array<MediaPlaylist> = [];\n private initPTS: RationalTimestamp[] = [];\n private unparsedVttFrags: Array<FragLoadedData | FragDecryptedData> = [];\n private captionsTracks: Record<string, TextTrack> = {};\n private nonNativeCaptionsTracks: Record<string, NonNativeCaptionsTrack> = {};\n private cea608Parser1!: Cea608Parser;\n private cea608Parser2!: Cea608Parser;\n private lastSn: number = -1;\n private lastPartIndex: number = -1;\n private prevCC: number = -1;\n private vttCCs: VTTCCs = newVTTCCs();\n private captionsProperties: {\n textTrack1: TrackProperties;\n textTrack2: TrackProperties;\n textTrack3: TrackProperties;\n textTrack4: TrackProperties;\n };\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.Cues = hls.config.cueHandler;\n\n this.captionsProperties = {\n textTrack1: {\n label: this.config.captionsTextTrack1Label,\n languageCode: this.config.captionsTextTrack1LanguageCode,\n },\n textTrack2: {\n label: this.config.captionsTextTrack2Label,\n languageCode: this.config.captionsTextTrack2LanguageCode,\n },\n textTrack3: {\n label: this.config.captionsTextTrack3Label,\n languageCode: this.config.captionsTextTrack3LanguageCode,\n },\n textTrack4: {\n label: this.config.captionsTextTrack4Label,\n languageCode: this.config.captionsTextTrack4LanguageCode,\n },\n };\n\n if (this.config.enableCEA708Captions) {\n const channel1 = new OutputFilter(this, 'textTrack1');\n const channel2 = new OutputFilter(this, 'textTrack2');\n const channel3 = new OutputFilter(this, 'textTrack3');\n const channel4 = new OutputFilter(this, 'textTrack4');\n this.cea608Parser1 = new Cea608Parser(1, channel1, channel2);\n this.cea608Parser2 = new Cea608Parser(3, channel3, channel4);\n }\n\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.on(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.on(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.on(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n hls.on(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);\n hls.on(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.on(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n hls.on(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n }\n\n public destroy(): void {\n const { hls } = this;\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.SUBTITLE_TRACKS_UPDATED, this.onSubtitleTracksUpdated, this);\n hls.off(Events.FRAG_LOADING, this.onFragLoading, this);\n hls.off(Events.FRAG_LOADED, this.onFragLoaded, this);\n hls.off(Events.FRAG_PARSING_USERDATA, this.onFragParsingUserdata, this);\n hls.off(Events.FRAG_DECRYPTED, this.onFragDecrypted, this);\n hls.off(Events.INIT_PTS_FOUND, this.onInitPtsFound, this);\n hls.off(Events.SUBTITLE_TRACKS_CLEARED, this.onSubtitleTracksCleared, this);\n hls.off(Events.BUFFER_FLUSHING, this.onBufferFlushing, this);\n // @ts-ignore\n this.hls = this.config = this.cea608Parser1 = this.cea608Parser2 = null;\n }\n\n public addCues(\n trackName: string,\n startTime: number,\n endTime: number,\n screen: CaptionScreen,\n cueRanges: Array<[number, number]>\n ) {\n // skip cues which overlap more than 50% with previously parsed time ranges\n let merged = false;\n for (let i = cueRanges.length; i--; ) {\n const cueRange = cueRanges[i];\n const overlap = intersection(\n cueRange[0],\n cueRange[1],\n startTime,\n endTime\n );\n if (overlap >= 0) {\n cueRange[0] = Math.min(cueRange[0], startTime);\n cueRange[1] = Math.max(cueRange[1], endTime);\n merged = true;\n if (overlap / (endTime - startTime) > 0.5) {\n return;\n }\n }\n }\n if (!merged) {\n cueRanges.push([startTime, endTime]);\n }\n\n if (this.config.renderTextTracksNatively) {\n const track = this.captionsTracks[trackName];\n this.Cues.newCue(track, startTime, endTime, screen);\n } else {\n const cues = this.Cues.newCue(null, startTime, endTime, screen);\n this.hls.trigger(Events.CUES_PARSED, {\n type: 'captions',\n cues,\n track: trackName,\n });\n }\n }\n\n // Triggered when an initial PTS is found; used for synchronisation of WebVTT.\n private onInitPtsFound(\n event: Events.INIT_PTS_FOUND,\n { frag, id, initPTS, timescale }: InitPTSFoundData\n ) {\n const { unparsedVttFrags } = this;\n if (id === 'main') {\n this.initPTS[frag.cc] = { baseTime: initPTS, timescale };\n }\n\n // Due to asynchronous processing, initial PTS may arrive later than the first VTT fragments are loaded.\n // Parse any unparsed fragments upon receiving the initial PTS.\n if (unparsedVttFrags.length) {\n this.unparsedVttFrags = [];\n unparsedVttFrags.forEach((frag) => {\n this.onFragLoaded(Events.FRAG_LOADED, frag as FragLoadedData);\n });\n }\n }\n\n private getExistingTrack(trackName: string): TextTrack | null {\n const { media } = this;\n if (media) {\n for (let i = 0; i < media.textTracks.length; i++) {\n const textTrack = media.textTracks[i];\n if (textTrack[trackName]) {\n return textTrack;\n }\n }\n }\n return null;\n }\n\n public createCaptionsTrack(trackName: string) {\n if (this.config.renderTextTracksNatively) {\n this.createNativeTrack(trackName);\n } else {\n this.createNonNativeTrack(trackName);\n }\n }\n\n private createNativeTrack(trackName: string) {\n if (this.captionsTracks[trackName]) {\n return;\n }\n const { captionsProperties, captionsTracks, media } = this;\n const { label, languageCode } = captionsProperties[trackName];\n // Enable reuse of existing text track.\n const existingTrack = this.getExistingTrack(trackName);\n if (!existingTrack) {\n const textTrack = this.createTextTrack('captions', label, languageCode);\n if (textTrack) {\n // Set a special property on the track so we know it's managed by Hls.js\n textTrack[trackName] = true;\n captionsTracks[trackName] = textTrack;\n }\n } else {\n captionsTracks[trackName] = existingTrack;\n clearCurrentCues(captionsTracks[trackName]);\n sendAddTrackEvent(captionsTracks[trackName], media as HTMLMediaElement);\n }\n }\n\n private createNonNativeTrack(trackName: string) {\n if (this.nonNativeCaptionsTracks[trackName]) {\n return;\n }\n // Create a list of a single track for the provider to consume\n const trackProperties: TrackProperties = this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n const label = trackProperties.label as string;\n const track = {\n _id: trackName,\n label,\n kind: 'captions',\n default: trackProperties.media ? !!trackProperties.media.default : false,\n closedCaptions: trackProperties.media,\n };\n this.nonNativeCaptionsTracks[trackName] = track;\n this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, { tracks: [track] });\n }\n\n private createTextTrack(\n kind: TextTrackKind,\n label: string,\n lang?: string\n ): TextTrack | undefined {\n const media = this.media;\n if (!media) {\n return;\n }\n return media.addTextTrack(kind, label, lang);\n }\n\n private onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n this.media = data.media;\n this._cleanTracks();\n }\n\n private onMediaDetaching() {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach((trackName) => {\n clearCurrentCues(captionsTracks[trackName]);\n delete captionsTracks[trackName];\n });\n this.nonNativeCaptionsTracks = {};\n }\n\n private onManifestLoading() {\n this.lastSn = -1; // Detect discontinuity in fragment parsing\n this.lastPartIndex = -1;\n this.prevCC = -1;\n this.vttCCs = newVTTCCs(); // Detect discontinuity in subtitle manifests\n this._cleanTracks();\n this.tracks = [];\n this.captionsTracks = {};\n this.nonNativeCaptionsTracks = {};\n this.textTracks = [];\n this.unparsedVttFrags = [];\n this.initPTS = [];\n if (this.cea608Parser1 && this.cea608Parser2) {\n this.cea608Parser1.reset();\n this.cea608Parser2.reset();\n }\n }\n\n private _cleanTracks() {\n // clear outdated subtitles\n const { media } = this;\n if (!media) {\n return;\n }\n const textTracks = media.textTracks;\n if (textTracks) {\n for (let i = 0; i < textTracks.length; i++) {\n clearCurrentCues(textTracks[i]);\n }\n }\n }\n\n private onSubtitleTracksUpdated(\n event: Events.SUBTITLE_TRACKS_UPDATED,\n data: SubtitleTracksUpdatedData\n ) {\n const tracks: Array<MediaPlaylist> = data.subtitleTracks || [];\n const hasIMSC1 = tracks.some((track) => track.textCodec === IMSC1_CODEC);\n if (this.config.enableWebVTT || (hasIMSC1 && this.config.enableIMSC1)) {\n const listIsIdentical = subtitleOptionsIdentical(this.tracks, tracks);\n if (listIsIdentical) {\n this.tracks = tracks;\n return;\n }\n this.textTracks = [];\n this.tracks = tracks;\n\n if (this.config.renderTextTracksNatively) {\n const inUseTracks = this.media ? this.media.textTracks : null;\n\n this.tracks.forEach((track, index) => {\n let textTrack: TextTrack | undefined;\n if (inUseTracks && index < inUseTracks.length) {\n let inUseTrack: TextTrack | null = null;\n\n for (let i = 0; i < inUseTracks.length; i++) {\n if (canReuseVttTextTrack(inUseTracks[i], track)) {\n inUseTrack = inUseTracks[i];\n break;\n }\n }\n\n // Reuse tracks with the same label, but do not reuse 608/708 tracks\n if (inUseTrack) {\n textTrack = inUseTrack;\n }\n }\n if (textTrack) {\n clearCurrentCues(textTrack);\n } else {\n const textTrackKind =\n this._captionsOrSubtitlesFromCharacteristics(track);\n textTrack = this.createTextTrack(\n textTrackKind,\n track.name,\n track.lang\n );\n if (textTrack) {\n textTrack.mode = 'disabled';\n }\n }\n if (textTrack) {\n (textTrack as any).groupId = track.groupId;\n this.textTracks.push(textTrack);\n }\n });\n } else if (this.tracks.length) {\n // Create a list of tracks for the provider to consume\n const tracksList = this.tracks.map((track) => {\n return {\n label: track.name,\n kind: track.type.toLowerCase(),\n default: track.default,\n subtitleTrack: track,\n };\n });\n this.hls.trigger(Events.NON_NATIVE_TEXT_TRACKS_FOUND, {\n tracks: tracksList,\n });\n }\n }\n }\n\n private _captionsOrSubtitlesFromCharacteristics(\n track: MediaPlaylist\n ): TextTrackKind {\n if (track.attrs.CHARACTERISTICS) {\n const transcribesSpokenDialog = /transcribes-spoken-dialog/gi.test(\n track.attrs.CHARACTERISTICS\n );\n const describesMusicAndSound = /describes-music-and-sound/gi.test(\n track.attrs.CHARACTERISTICS\n );\n\n if (transcribesSpokenDialog && describesMusicAndSound) {\n return 'captions';\n }\n }\n\n return 'subtitles';\n }\n\n private onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ) {\n if (this.config.enableCEA708Captions && data.captions) {\n data.captions.forEach((captionsTrack) => {\n const instreamIdMatch = /(?:CC|SERVICE)([1-4])/.exec(\n captionsTrack.instreamId as string\n );\n if (!instreamIdMatch) {\n return;\n }\n const trackName = `textTrack${instreamIdMatch[1]}`;\n const trackProperties: TrackProperties =\n this.captionsProperties[trackName];\n if (!trackProperties) {\n return;\n }\n trackProperties.label = captionsTrack.name;\n if (captionsTrack.lang) {\n // optional attribute\n trackProperties.languageCode = captionsTrack.lang;\n }\n trackProperties.media = captionsTrack;\n });\n }\n }\n\n private closedCaptionsForLevel(frag: Fragment): string | undefined {\n const level = this.hls.levels[frag.level];\n return level?.attrs['CLOSED-CAPTIONS'];\n }\n\n private onFragLoading(event: Events.FRAG_LOADING, data: FragLoadingData) {\n const { cea608Parser1, cea608Parser2, lastSn, lastPartIndex } = this;\n if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n return;\n }\n // if this frag isn't contiguous, clear the parser so cues with bad start/end times aren't added to the textTrack\n if (data.frag.type === PlaylistLevelType.MAIN) {\n const sn = data.frag.sn;\n const partIndex = data?.part?.index ?? -1;\n if (\n !(\n sn === lastSn + 1 ||\n (sn === lastSn && partIndex === lastPartIndex + 1)\n )\n ) {\n cea608Parser1.reset();\n cea608Parser2.reset();\n }\n this.lastSn = sn as number;\n this.lastPartIndex = partIndex;\n }\n }\n\n private onFragLoaded(\n event: Events.FRAG_LOADED,\n data: FragDecryptedData | FragLoadedData\n ) {\n const { frag, payload } = data;\n if (frag.type === PlaylistLevelType.SUBTITLE) {\n // If fragment is subtitle type, parse as WebVTT.\n if (payload.byteLength) {\n const decryptData = frag.decryptdata;\n // fragment after decryption has a stats object\n const decrypted = 'stats' in data;\n // If the subtitles are not encrypted, parse VTTs now. Otherwise, we need to wait.\n if (decryptData == null || !decryptData.encrypted || decrypted) {\n const trackPlaylistMedia = this.tracks[frag.level];\n const vttCCs = this.vttCCs;\n if (!vttCCs[frag.cc]) {\n vttCCs[frag.cc] = {\n start: frag.start,\n prevCC: this.prevCC,\n new: true,\n };\n this.prevCC = frag.cc;\n }\n if (\n trackPlaylistMedia &&\n trackPlaylistMedia.textCodec === IMSC1_CODEC\n ) {\n this._parseIMSC1(frag, payload);\n } else {\n this._parseVTTs(data);\n }\n }\n } else {\n // In case there is no payload, finish unsuccessfully.\n this.hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag,\n error: new Error('Empty subtitle payload'),\n });\n }\n }\n }\n\n private _parseIMSC1(frag: Fragment, payload: ArrayBuffer) {\n const hls = this.hls;\n parseIMSC1(\n payload,\n this.initPTS[frag.cc],\n (cues) => {\n this._appendCues(cues, frag.level);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: true,\n frag: frag,\n });\n },\n (error) => {\n logger.log(`Failed to parse IMSC1: ${error}`);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag: frag,\n error,\n });\n }\n );\n }\n\n private _parseVTTs(data: FragDecryptedData | FragLoadedData) {\n const { frag, payload } = data;\n // We need an initial synchronisation PTS. Store fragments as long as none has arrived\n const { initPTS, unparsedVttFrags } = this;\n const maxAvCC = initPTS.length - 1;\n if (!initPTS[frag.cc] && maxAvCC === -1) {\n unparsedVttFrags.push(data);\n return;\n }\n\n const hls = this.hls;\n // Parse the WebVTT file contents.\n const payloadWebVTT = frag.initSegment?.data\n ? appendUint8Array(frag.initSegment.data, new Uint8Array(payload))\n : payload;\n parseWebVTT(\n payloadWebVTT,\n this.initPTS[frag.cc],\n this.vttCCs,\n frag.cc,\n frag.start,\n (cues) => {\n this._appendCues(cues, frag.level);\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: true,\n frag: frag,\n });\n },\n (error) => {\n const missingInitPTS =\n error.message === 'Missing initPTS for VTT MPEGTS';\n if (missingInitPTS) {\n unparsedVttFrags.push(data);\n } else {\n this._fallbackToIMSC1(frag, payload);\n }\n // Something went wrong while parsing. Trigger event with success false.\n logger.log(`Failed to parse VTT cue: ${error}`);\n if (missingInitPTS && maxAvCC > frag.cc) {\n return;\n }\n hls.trigger(Events.SUBTITLE_FRAG_PROCESSED, {\n success: false,\n frag: frag,\n error,\n });\n }\n );\n }\n\n private _fallbackToIMSC1(frag: Fragment, payload: ArrayBuffer) {\n // If textCodec is unknown, try parsing as IMSC1. Set textCodec based on the result\n const trackPlaylistMedia = this.tracks[frag.level];\n if (!trackPlaylistMedia.textCodec) {\n parseIMSC1(\n payload,\n this.initPTS[frag.cc],\n () => {\n trackPlaylistMedia.textCodec = IMSC1_CODEC;\n this._parseIMSC1(frag, payload);\n },\n () => {\n trackPlaylistMedia.textCodec = 'wvtt';\n }\n );\n }\n }\n\n private _appendCues(cues: VTTCue[], fragLevel: number) {\n const hls = this.hls;\n if (this.config.renderTextTracksNatively) {\n const textTrack = this.textTracks[fragLevel];\n // WebVTTParser.parse is an async method and if the currently selected text track mode is set to \"disabled\"\n // before parsing is done then don't try to access currentTrack.cues.getCueById as cues will be null\n // and trying to access getCueById method of cues will throw an exception\n // Because we check if the mode is disabled, we can force check `cues` below. They can't be null.\n if (!textTrack || textTrack.mode === 'disabled') {\n return;\n }\n cues.forEach((cue) => addCueToTrack(textTrack, cue));\n } else {\n const currentTrack = this.tracks[fragLevel];\n if (!currentTrack) {\n return;\n }\n const track = currentTrack.default ? 'default' : 'subtitles' + fragLevel;\n hls.trigger(Events.CUES_PARSED, { type: 'subtitles', cues, track });\n }\n }\n\n private onFragDecrypted(\n event: Events.FRAG_DECRYPTED,\n data: FragDecryptedData\n ) {\n const { frag } = data;\n if (frag.type === PlaylistLevelType.SUBTITLE) {\n this.onFragLoaded(Events.FRAG_LOADED, data as unknown as FragLoadedData);\n }\n }\n\n private onSubtitleTracksCleared() {\n this.tracks = [];\n this.captionsTracks = {};\n }\n\n private onFragParsingUserdata(\n event: Events.FRAG_PARSING_USERDATA,\n data: FragParsingUserdataData\n ) {\n const { cea608Parser1, cea608Parser2 } = this;\n if (!this.enabled || !(cea608Parser1 && cea608Parser2)) {\n return;\n }\n\n const { frag, samples } = data;\n if (\n frag.type === PlaylistLevelType.MAIN &&\n this.closedCaptionsForLevel(frag) === 'NONE'\n ) {\n return;\n }\n // If the event contains captions (found in the bytes property), push all bytes into the parser immediately\n // It will create the proper timestamps based on the PTS value\n for (let i = 0; i < samples.length; i++) {\n const ccBytes = samples[i].bytes;\n if (ccBytes) {\n const ccdatas = this.extractCea608Data(ccBytes);\n cea608Parser1.addData(samples[i].pts, ccdatas[0]);\n cea608Parser2.addData(samples[i].pts, ccdatas[1]);\n }\n }\n }\n\n onBufferFlushing(\n event: Events.BUFFER_FLUSHING,\n { startOffset, endOffset, endOffsetSubtitles, type }: BufferFlushingData\n ) {\n const { media } = this;\n if (!media || media.currentTime < endOffset) {\n return;\n }\n // Clear 608 caption cues from the captions TextTracks when the video back buffer is flushed\n // Forward cues are never removed because we can loose streamed 608 content from recent fragments\n if (!type || type === 'video') {\n const { captionsTracks } = this;\n Object.keys(captionsTracks).forEach((trackName) =>\n removeCuesInRange(captionsTracks[trackName], startOffset, endOffset)\n );\n }\n if (this.config.renderTextTracksNatively) {\n // Clear VTT/IMSC1 subtitle cues from the subtitle TextTracks when the back buffer is flushed\n if (startOffset === 0 && endOffsetSubtitles !== undefined) {\n const { textTracks } = this;\n Object.keys(textTracks).forEach((trackName) =>\n removeCuesInRange(\n textTracks[trackName],\n startOffset,\n endOffsetSubtitles\n )\n );\n }\n }\n }\n\n private extractCea608Data(byteArray: Uint8Array): number[][] {\n const actualCCBytes: number[][] = [[], []];\n const count = byteArray[0] & 0x1f;\n let position = 2;\n\n for (let j = 0; j < count; j++) {\n const tmpByte = byteArray[position++];\n const ccbyte1 = 0x7f & byteArray[position++];\n const ccbyte2 = 0x7f & byteArray[position++];\n if (ccbyte1 === 0 && ccbyte2 === 0) {\n continue;\n }\n const ccValid = (0x04 & tmpByte) !== 0; // Support all four channels\n if (ccValid) {\n const ccType = 0x03 & tmpByte;\n if (\n 0x00 /* CEA608 field1*/ === ccType ||\n 0x01 /* CEA608 field2*/ === ccType\n ) {\n // Exclude CEA708 CC data.\n actualCCBytes[ccType].push(ccbyte1);\n actualCCBytes[ccType].push(ccbyte2);\n }\n }\n }\n return actualCCBytes;\n }\n}\n\nfunction canReuseVttTextTrack(\n inUseTrack: (TextTrack & { textTrack1?; textTrack2? }) | null,\n manifestTrack: MediaPlaylist\n): boolean {\n return (\n !!inUseTrack &&\n inUseTrack.label === manifestTrack.name &&\n !(inUseTrack.textTrack1 || inUseTrack.textTrack2)\n );\n}\n\nfunction intersection(x1: number, x2: number, y1: number, y2: number): number {\n return Math.min(x2, y2) - Math.max(x1, y1);\n}\n\nfunction newVTTCCs(): VTTCCs {\n return {\n ccOffset: 0,\n presentationOffset: 0,\n 0: {\n start: 0,\n prevCC: -1,\n new: true,\n },\n };\n}\n","/*\n * cap stream level to media size dimension controller\n */\n\nimport { Events } from '../events';\nimport type { Level } from '../types/level';\nimport type {\n ManifestParsedData,\n BufferCodecsData,\n MediaAttachingData,\n FPSDropLevelCappingData,\n} from '../types/events';\nimport StreamController from './stream-controller';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\n\ntype RestrictedLevel = { width: number; height: number; bitrate: number };\nclass CapLevelController implements ComponentAPI {\n private hls: Hls;\n private autoLevelCapping: number;\n private firstLevel: number;\n private media: HTMLVideoElement | null;\n private restrictedLevels: RestrictedLevel[];\n private timer: number | undefined;\n private clientRect: { width: number; height: number } | null;\n private streamController?: StreamController;\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.firstLevel = -1;\n this.media = null;\n this.restrictedLevels = [];\n this.timer = undefined;\n this.clientRect = null;\n\n this.registerListeners();\n }\n\n public setStreamController(streamController: StreamController) {\n this.streamController = streamController;\n }\n\n public destroy() {\n this.unregisterListener();\n if (this.hls.config.capLevelToPlayerSize) {\n this.stopCapping();\n }\n this.media = null;\n this.clientRect = null;\n // @ts-ignore\n this.hls = this.streamController = null;\n }\n\n protected registerListeners() {\n const { hls } = this;\n hls.on(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.on(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n\n protected unregisterListener() {\n const { hls } = this;\n hls.off(Events.FPS_DROP_LEVEL_CAPPING, this.onFpsDropLevelCapping, this);\n hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.BUFFER_CODECS, this.onBufferCodecs, this);\n hls.off(Events.MEDIA_DETACHING, this.onMediaDetaching, this);\n }\n\n protected onFpsDropLevelCapping(\n event: Events.FPS_DROP_LEVEL_CAPPING,\n data: FPSDropLevelCappingData\n ) {\n // Don't add a restricted level more than once\n const level = this.hls.levels[data.droppedLevel];\n if (this.isLevelAllowed(level)) {\n this.restrictedLevels.push({\n bitrate: level.bitrate,\n height: level.height,\n width: level.width,\n });\n }\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n this.media = data.media instanceof HTMLVideoElement ? data.media : null;\n this.clientRect = null;\n }\n\n protected onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) {\n const hls = this.hls;\n this.restrictedLevels = [];\n this.firstLevel = data.firstLevel;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // Start capping immediately if the manifest has signaled video codecs\n this.startCapping();\n }\n }\n\n // Only activate capping when playing a video stream; otherwise, multi-bitrate audio-only streams will be restricted\n // to the first level\n protected onBufferCodecs(\n event: Events.BUFFER_CODECS,\n data: BufferCodecsData\n ) {\n const hls = this.hls;\n if (hls.config.capLevelToPlayerSize && data.video) {\n // If the manifest did not signal a video codec capping has been deferred until we're certain video is present\n this.startCapping();\n }\n }\n\n protected onMediaDetaching() {\n this.stopCapping();\n }\n\n detectPlayerSize() {\n if (this.media && this.mediaHeight > 0 && this.mediaWidth > 0) {\n const levels = this.hls.levels;\n if (levels.length) {\n const hls = this.hls;\n hls.autoLevelCapping = this.getMaxLevel(levels.length - 1);\n if (\n hls.autoLevelCapping > this.autoLevelCapping &&\n this.streamController\n ) {\n // if auto level capping has a higher value for the previous one, flush the buffer using nextLevelSwitch\n // usually happen when the user go to the fullscreen mode.\n this.streamController.nextLevelSwitch();\n }\n this.autoLevelCapping = hls.autoLevelCapping;\n }\n }\n }\n\n /*\n * returns level should be the one with the dimensions equal or greater than the media (player) dimensions (so the video will be downscaled)\n */\n getMaxLevel(capLevelIndex: number): number {\n const levels = this.hls.levels;\n if (!levels.length) {\n return -1;\n }\n\n const validLevels = levels.filter(\n (level, index) => this.isLevelAllowed(level) && index <= capLevelIndex\n );\n\n this.clientRect = null;\n return CapLevelController.getMaxLevelByMediaSize(\n validLevels,\n this.mediaWidth,\n this.mediaHeight\n );\n }\n\n startCapping() {\n if (this.timer) {\n // Don't reset capping if started twice; this can happen if the manifest signals a video codec\n return;\n }\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n this.hls.firstLevel = this.getMaxLevel(this.firstLevel);\n self.clearInterval(this.timer);\n this.timer = self.setInterval(this.detectPlayerSize.bind(this), 1000);\n this.detectPlayerSize();\n }\n\n stopCapping() {\n this.restrictedLevels = [];\n this.firstLevel = -1;\n this.autoLevelCapping = Number.POSITIVE_INFINITY;\n if (this.timer) {\n self.clearInterval(this.timer);\n this.timer = undefined;\n }\n }\n\n getDimensions(): { width: number; height: number } {\n if (this.clientRect) {\n return this.clientRect;\n }\n const media = this.media;\n const boundsRect = {\n width: 0,\n height: 0,\n };\n\n if (media) {\n const clientRect = media.getBoundingClientRect();\n boundsRect.width = clientRect.width;\n boundsRect.height = clientRect.height;\n if (!boundsRect.width && !boundsRect.height) {\n // When the media element has no width or height (equivalent to not being in the DOM),\n // then use its width and height attributes (media.width, media.height)\n boundsRect.width =\n clientRect.right - clientRect.left || media.width || 0;\n boundsRect.height =\n clientRect.bottom - clientRect.top || media.height || 0;\n }\n }\n this.clientRect = boundsRect;\n return boundsRect;\n }\n\n get mediaWidth(): number {\n return this.getDimensions().width * this.contentScaleFactor;\n }\n\n get mediaHeight(): number {\n return this.getDimensions().height * this.contentScaleFactor;\n }\n\n get contentScaleFactor(): number {\n let pixelRatio = 1;\n if (!this.hls.config.ignoreDevicePixelRatio) {\n try {\n pixelRatio = self.devicePixelRatio;\n } catch (e) {\n /* no-op */\n }\n }\n\n return pixelRatio;\n }\n\n private isLevelAllowed(level: Level): boolean {\n const restrictedLevels = this.restrictedLevels;\n return !restrictedLevels.some((restrictedLevel) => {\n return (\n level.bitrate === restrictedLevel.bitrate &&\n level.width === restrictedLevel.width &&\n level.height === restrictedLevel.height\n );\n });\n }\n\n static getMaxLevelByMediaSize(\n levels: Array<Level>,\n width: number,\n height: number\n ): number {\n if (!levels?.length) {\n return -1;\n }\n\n // Levels can have the same dimensions but differing bandwidths - since levels are ordered, we can look to the next\n // to determine whether we've chosen the greatest bandwidth for the media's dimensions\n const atGreatestBandwidth = (curLevel, nextLevel) => {\n if (!nextLevel) {\n return true;\n }\n\n return (\n curLevel.width !== nextLevel.width ||\n curLevel.height !== nextLevel.height\n );\n };\n\n // If we run through the loop without breaking, the media's dimensions are greater than every level, so default to\n // the max level\n let maxLevelIndex = levels.length - 1;\n\n for (let i = 0; i < levels.length; i += 1) {\n const level = levels[i];\n if (\n (level.width >= width || level.height >= height) &&\n atGreatestBandwidth(level, levels[i + 1])\n ) {\n maxLevelIndex = i;\n break;\n }\n }\n\n return maxLevelIndex;\n }\n}\n\nexport default CapLevelController;\n","import { Events } from '../events';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type Hls from '../hls';\nimport type { MediaAttachingData } from '../types/events';\nimport StreamController from './stream-controller';\n\nclass FPSController implements ComponentAPI {\n private hls: Hls;\n private isVideoPlaybackQualityAvailable: boolean = false;\n private timer?: number;\n private media: HTMLVideoElement | null = null;\n private lastTime: any;\n private lastDroppedFrames: number = 0;\n private lastDecodedFrames: number = 0;\n // stream controller must be provided as a dependency!\n private streamController!: StreamController;\n\n constructor(hls: Hls) {\n this.hls = hls;\n\n this.registerListeners();\n }\n\n public setStreamController(streamController: StreamController) {\n this.streamController = streamController;\n }\n\n protected registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n }\n\n protected unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHING, this.onMediaAttaching, this);\n }\n\n destroy() {\n if (this.timer) {\n clearInterval(this.timer);\n }\n\n this.unregisterListeners();\n this.isVideoPlaybackQualityAvailable = false;\n this.media = null;\n }\n\n protected onMediaAttaching(\n event: Events.MEDIA_ATTACHING,\n data: MediaAttachingData\n ) {\n const config = this.hls.config;\n if (config.capLevelOnFPSDrop) {\n const media =\n data.media instanceof self.HTMLVideoElement ? data.media : null;\n this.media = media;\n if (media && typeof media.getVideoPlaybackQuality === 'function') {\n this.isVideoPlaybackQualityAvailable = true;\n }\n\n self.clearInterval(this.timer);\n this.timer = self.setInterval(\n this.checkFPSInterval.bind(this),\n config.fpsDroppedMonitoringPeriod\n );\n }\n }\n\n checkFPS(\n video: HTMLVideoElement,\n decodedFrames: number,\n droppedFrames: number\n ) {\n const currentTime = performance.now();\n if (decodedFrames) {\n if (this.lastTime) {\n const currentPeriod = currentTime - this.lastTime;\n const currentDropped = droppedFrames - this.lastDroppedFrames;\n const currentDecoded = decodedFrames - this.lastDecodedFrames;\n const droppedFPS = (1000 * currentDropped) / currentPeriod;\n const hls = this.hls;\n hls.trigger(Events.FPS_DROP, {\n currentDropped: currentDropped,\n currentDecoded: currentDecoded,\n totalDroppedFrames: droppedFrames,\n });\n if (droppedFPS > 0) {\n // logger.log('checkFPS : droppedFPS/decodedFPS:' + droppedFPS/(1000 * currentDecoded / currentPeriod));\n if (\n currentDropped >\n hls.config.fpsDroppedMonitoringThreshold * currentDecoded\n ) {\n let currentLevel = hls.currentLevel;\n logger.warn(\n 'drop FPS ratio greater than max allowed value for currentLevel: ' +\n currentLevel\n );\n if (\n currentLevel > 0 &&\n (hls.autoLevelCapping === -1 ||\n hls.autoLevelCapping >= currentLevel)\n ) {\n currentLevel = currentLevel - 1;\n hls.trigger(Events.FPS_DROP_LEVEL_CAPPING, {\n level: currentLevel,\n droppedLevel: hls.currentLevel,\n });\n hls.autoLevelCapping = currentLevel;\n this.streamController.nextLevelSwitch();\n }\n }\n }\n }\n this.lastTime = currentTime;\n this.lastDroppedFrames = droppedFrames;\n this.lastDecodedFrames = decodedFrames;\n }\n }\n\n checkFPSInterval() {\n const video = this.media;\n if (video) {\n if (this.isVideoPlaybackQualityAvailable) {\n const videoPlaybackQuality = video.getVideoPlaybackQuality();\n this.checkFPS(\n video,\n videoPlaybackQuality.totalVideoFrames,\n videoPlaybackQuality.droppedVideoFrames\n );\n } else {\n // HTMLVideoElement doesn't include the webkit types\n this.checkFPS(\n video,\n (video as any).webkitDecodedFrameCount as number,\n (video as any).webkitDroppedFrameCount as number\n );\n }\n }\n }\n}\n\nexport default FPSController;\n","/**\n * @author Stephan Hesse <disparat@gmail.com> | <tchakabam@gmail.com>\n *\n * DRM support for Hls.js\n */\nimport { Events } from '../events';\nimport { ErrorTypes, ErrorDetails } from '../errors';\nimport { logger } from '../utils/logger';\nimport {\n getKeySystemsForConfig,\n getSupportedMediaKeySystemConfigurations,\n keySystemDomainToKeySystemFormat as keySystemToKeySystemFormat,\n KeySystemFormats,\n keySystemFormatToKeySystemDomain,\n KeySystemIds,\n keySystemIdToKeySystemDomain,\n} from '../utils/mediakeys-helper';\nimport {\n KeySystems,\n requestMediaKeySystemAccess,\n} from '../utils/mediakeys-helper';\nimport { strToUtf8array } from '../utils/keysystem-util';\nimport { base64Decode } from '../utils/numeric-encoding-utils';\nimport { DecryptData, LevelKey } from '../loader/level-key';\nimport Hex from '../utils/hex';\nimport { bin2str, parsePssh, parseSinf } from '../utils/mp4-tools';\nimport { EventEmitter } from 'eventemitter3';\nimport type Hls from '../hls';\nimport type { ComponentAPI } from '../types/component-api';\nimport type {\n MediaAttachedData,\n KeyLoadedData,\n ErrorData,\n ManifestLoadedData,\n} from '../types/events';\nimport type { EMEControllerConfig, HlsConfig, LoadPolicy } from '../config';\nimport type { Fragment } from '../loader/fragment';\nimport type {\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n} from '../types/loader';\n\nconst LOGGER_PREFIX = '[eme]';\n\ninterface KeySystemAccessPromises {\n keySystemAccess: Promise<MediaKeySystemAccess>;\n mediaKeys?: Promise<MediaKeys>;\n certificate?: Promise<BufferSource | void>;\n}\n\nexport interface MediaKeySessionContext {\n keySystem: KeySystems;\n mediaKeys: MediaKeys;\n decryptdata: LevelKey;\n mediaKeysSession: MediaKeySession;\n keyStatus: MediaKeyStatus;\n licenseXhr?: XMLHttpRequest;\n}\n\n/**\n * Controller to deal with encrypted media extensions (EME)\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Encrypted_Media_Extensions_API\n *\n * @class\n * @constructor\n */\nclass EMEController implements ComponentAPI {\n public static CDMCleanupPromise: Promise<void> | void;\n\n private readonly hls: Hls;\n private readonly config: EMEControllerConfig & {\n loader: { new (confg: HlsConfig): Loader<LoaderContext> };\n certLoadPolicy: LoadPolicy;\n keyLoadPolicy: LoadPolicy;\n };\n private media: HTMLMediaElement | null = null;\n private keyFormatPromise: Promise<KeySystemFormats> | null = null;\n private keySystemAccessPromises: {\n [keysystem: string]: KeySystemAccessPromises;\n } = {};\n private _requestLicenseFailureCount: number = 0;\n private mediaKeySessions: MediaKeySessionContext[] = [];\n private keyIdToKeySessionPromise: {\n [keyId: string]: Promise<MediaKeySessionContext>;\n } = {};\n private setMediaKeysQueue: Promise<void>[] = EMEController.CDMCleanupPromise\n ? [EMEController.CDMCleanupPromise]\n : [];\n private onMediaEncrypted = this._onMediaEncrypted.bind(this);\n private onWaitingForKey = this._onWaitingForKey.bind(this);\n\n private debug: (msg: any) => void = logger.debug.bind(logger, LOGGER_PREFIX);\n private log: (msg: any) => void = logger.log.bind(logger, LOGGER_PREFIX);\n private warn: (msg: any) => void = logger.warn.bind(logger, LOGGER_PREFIX);\n private error: (msg: any) => void = logger.error.bind(logger, LOGGER_PREFIX);\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.config = hls.config;\n this.registerListeners();\n }\n\n public destroy() {\n this.unregisterListeners();\n this.onMediaDetached();\n // Remove any references that could be held in config options or callbacks\n const config = this.config;\n config.requestMediaKeySystemAccessFunc = null;\n config.licenseXhrSetup = config.licenseResponseCallback = undefined;\n config.drmSystems = config.drmSystemOptions = {};\n // @ts-ignore\n this.hls =\n this.onMediaEncrypted =\n this.onWaitingForKey =\n this.keyIdToKeySessionPromise =\n null as any;\n // @ts-ignore\n this.config = null;\n }\n\n private registerListeners() {\n this.hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n this.hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n\n private unregisterListeners() {\n this.hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n this.hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n this.hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n this.hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n }\n\n private getLicenseServerUrl(keySystem: KeySystems): string | never {\n const { drmSystems, widevineLicenseUrl } = this.config;\n const keySystemConfiguration = drmSystems[keySystem];\n\n if (keySystemConfiguration) {\n return keySystemConfiguration.licenseUrl;\n }\n\n // For backward compatibility\n if (keySystem === KeySystems.WIDEVINE && widevineLicenseUrl) {\n return widevineLicenseUrl;\n }\n\n throw new Error(\n `no license server URL configured for key-system \"${keySystem}\"`\n );\n }\n\n private getServerCertificateUrl(keySystem: KeySystems): string | void {\n const { drmSystems } = this.config;\n const keySystemConfiguration = drmSystems[keySystem];\n\n if (keySystemConfiguration) {\n return keySystemConfiguration.serverCertificateUrl;\n } else {\n this.log(`No Server Certificate in config.drmSystems[\"${keySystem}\"]`);\n }\n }\n\n private attemptKeySystemAccess(\n keySystemsToAttempt: KeySystems[]\n ): Promise<{ keySystem: KeySystems; mediaKeys: MediaKeys }> {\n const levels = this.hls.levels;\n const uniqueCodec = (value: string | undefined, i, a): value is string =>\n !!value && a.indexOf(value) === i;\n const audioCodecs = levels\n .map((level) => level.audioCodec)\n .filter(uniqueCodec);\n const videoCodecs = levels\n .map((level) => level.videoCodec)\n .filter(uniqueCodec);\n if (audioCodecs.length + videoCodecs.length === 0) {\n videoCodecs.push('avc1.42e01e');\n }\n\n return new Promise(\n (\n resolve: (result: {\n keySystem: KeySystems;\n mediaKeys: MediaKeys;\n }) => void,\n reject: (Error) => void\n ) => {\n const attempt = (keySystems) => {\n const keySystem = keySystems.shift();\n this.getMediaKeysPromise(keySystem, audioCodecs, videoCodecs)\n .then((mediaKeys) => resolve({ keySystem, mediaKeys }))\n .catch((error) => {\n if (keySystems.length) {\n attempt(keySystems);\n } else if (error instanceof EMEKeyError) {\n reject(error);\n } else {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_ACCESS,\n error,\n fatal: true,\n },\n error.message\n )\n );\n }\n });\n };\n attempt(keySystemsToAttempt);\n }\n );\n }\n\n private requestMediaKeySystemAccess(\n keySystem: KeySystems,\n supportedConfigurations: MediaKeySystemConfiguration[]\n ): Promise<MediaKeySystemAccess> {\n const { requestMediaKeySystemAccessFunc } = this.config;\n if (!(typeof requestMediaKeySystemAccessFunc === 'function')) {\n let errMessage = `Configured requestMediaKeySystemAccess is not a function ${requestMediaKeySystemAccessFunc}`;\n if (\n requestMediaKeySystemAccess === null &&\n self.location.protocol === 'http:'\n ) {\n errMessage = `navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`;\n }\n return Promise.reject(new Error(errMessage));\n }\n\n return requestMediaKeySystemAccessFunc(keySystem, supportedConfigurations);\n }\n\n private getMediaKeysPromise(\n keySystem: KeySystems,\n audioCodecs: string[],\n videoCodecs: string[]\n ): Promise<MediaKeys> {\n // This can throw, but is caught in event handler callpath\n const mediaKeySystemConfigs = getSupportedMediaKeySystemConfigurations(\n keySystem,\n audioCodecs,\n videoCodecs,\n this.config.drmSystemOptions\n );\n const keySystemAccessPromises: KeySystemAccessPromises =\n this.keySystemAccessPromises[keySystem];\n let keySystemAccess = keySystemAccessPromises?.keySystemAccess;\n if (!keySystemAccess) {\n this.log(\n `Requesting encrypted media \"${keySystem}\" key-system access with config: ${JSON.stringify(\n mediaKeySystemConfigs\n )}`\n );\n keySystemAccess = this.requestMediaKeySystemAccess(\n keySystem,\n mediaKeySystemConfigs\n );\n const keySystemAccessPromises: KeySystemAccessPromises =\n (this.keySystemAccessPromises[keySystem] = {\n keySystemAccess,\n });\n keySystemAccess.catch((error) => {\n this.log(\n `Failed to obtain access to key-system \"${keySystem}\": ${error}`\n );\n });\n return keySystemAccess.then((mediaKeySystemAccess) => {\n this.log(\n `Access for key-system \"${mediaKeySystemAccess.keySystem}\" obtained`\n );\n\n const certificateRequest = this.fetchServerCertificate(keySystem);\n\n this.log(`Create media-keys for \"${keySystem}\"`);\n keySystemAccessPromises.mediaKeys = mediaKeySystemAccess\n .createMediaKeys()\n .then((mediaKeys) => {\n this.log(`Media-keys created for \"${keySystem}\"`);\n return certificateRequest.then((certificate) => {\n if (certificate) {\n return this.setMediaKeysServerCertificate(\n mediaKeys,\n keySystem,\n certificate\n );\n }\n return mediaKeys;\n });\n });\n\n keySystemAccessPromises.mediaKeys.catch((error) => {\n this.error(\n `Failed to create media-keys for \"${keySystem}\"}: ${error}`\n );\n });\n\n return keySystemAccessPromises.mediaKeys;\n });\n }\n return keySystemAccess.then(() => keySystemAccessPromises.mediaKeys!);\n }\n\n private createMediaKeySessionContext({\n decryptdata,\n keySystem,\n mediaKeys,\n }: {\n decryptdata: LevelKey;\n keySystem: KeySystems;\n mediaKeys: MediaKeys;\n }): MediaKeySessionContext {\n this.log(\n `Creating key-system session \"${keySystem}\" keyId: ${Hex.hexDump(\n decryptdata.keyId! || []\n )}`\n );\n\n const mediaKeysSession = mediaKeys.createSession();\n\n const mediaKeySessionContext: MediaKeySessionContext = {\n decryptdata,\n keySystem,\n mediaKeys,\n mediaKeysSession,\n keyStatus: 'status-pending',\n };\n\n this.mediaKeySessions.push(mediaKeySessionContext);\n\n return mediaKeySessionContext;\n }\n\n private renewKeySession(mediaKeySessionContext: MediaKeySessionContext) {\n const decryptdata = mediaKeySessionContext.decryptdata;\n if (decryptdata.pssh) {\n const keySessionContext = this.createMediaKeySessionContext(\n mediaKeySessionContext\n );\n const keyId = this.getKeyIdString(decryptdata);\n const scheme = 'cenc';\n this.keyIdToKeySessionPromise[keyId] =\n this.generateRequestWithPreferredKeySession(\n keySessionContext,\n scheme,\n decryptdata.pssh,\n 'expired'\n );\n } else {\n this.warn(`Could not renew expired session. Missing pssh initData.`);\n }\n this.removeSession(mediaKeySessionContext);\n }\n\n private getKeyIdString(decryptdata: DecryptData | undefined): string | never {\n if (!decryptdata) {\n throw new Error('Could not read keyId of undefined decryptdata');\n }\n if (decryptdata.keyId === null) {\n throw new Error('keyId is null');\n }\n return Hex.hexDump(decryptdata.keyId);\n }\n\n private updateKeySession(\n mediaKeySessionContext: MediaKeySessionContext,\n data: Uint8Array\n ): Promise<void> {\n const keySession = mediaKeySessionContext.mediaKeysSession;\n this.log(\n `Updating key-session \"${keySession.sessionId}\" for keyID ${Hex.hexDump(\n mediaKeySessionContext.decryptdata?.keyId! || []\n )}\n } (data length: ${data ? data.byteLength : data})`\n );\n return keySession.update(data);\n }\n\n public selectKeySystemFormat(frag: Fragment): Promise<KeySystemFormats> {\n const keyFormats = Object.keys(frag.levelkeys || {}) as KeySystemFormats[];\n if (!this.keyFormatPromise) {\n this.log(\n `Selecting key-system from fragment (sn: ${frag.sn} ${frag.type}: ${\n frag.level\n }) key formats ${keyFormats.join(', ')}`\n );\n this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);\n }\n return this.keyFormatPromise;\n }\n\n private getKeyFormatPromise(\n keyFormats: KeySystemFormats[]\n ): Promise<KeySystemFormats> {\n return new Promise((resolve, reject) => {\n const keySystemsInConfig = getKeySystemsForConfig(this.config);\n const keySystemsToAttempt = keyFormats\n .map(keySystemFormatToKeySystemDomain)\n .filter(\n (value) => !!value && keySystemsInConfig.indexOf(value) !== -1\n ) as any as KeySystems[];\n return this.getKeySystemSelectionPromise(keySystemsToAttempt)\n .then(({ keySystem }) => {\n const keySystemFormat = keySystemToKeySystemFormat(keySystem);\n if (keySystemFormat) {\n resolve(keySystemFormat);\n } else {\n reject(\n new Error(`Unable to find format for key-system \"${keySystem}\"`)\n );\n }\n })\n .catch(reject);\n });\n }\n\n public loadKey(data: KeyLoadedData): Promise<MediaKeySessionContext> {\n const decryptdata = data.keyInfo.decryptdata;\n\n const keyId = this.getKeyIdString(decryptdata);\n const keyDetails = `(keyId: ${keyId} format: \"${decryptdata.keyFormat}\" method: ${decryptdata.method} uri: ${decryptdata.uri})`;\n\n this.log(`Starting session for key ${keyDetails}`);\n\n let keySessionContextPromise = this.keyIdToKeySessionPromise[keyId];\n if (!keySessionContextPromise) {\n keySessionContextPromise = this.keyIdToKeySessionPromise[keyId] =\n this.getKeySystemForKeyPromise(decryptdata).then(\n ({ keySystem, mediaKeys }) => {\n this.throwIfDestroyed();\n this.log(\n `Handle encrypted media sn: ${data.frag.sn} ${data.frag.type}: ${data.frag.level} using key ${keyDetails}`\n );\n\n return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {\n this.throwIfDestroyed();\n const keySessionContext = this.createMediaKeySessionContext({\n keySystem,\n mediaKeys,\n decryptdata,\n });\n const scheme = 'cenc';\n return this.generateRequestWithPreferredKeySession(\n keySessionContext,\n scheme,\n decryptdata.pssh,\n 'playlist-key'\n );\n });\n }\n );\n\n keySessionContextPromise.catch((error) => this.handleError(error));\n }\n\n return keySessionContextPromise;\n }\n\n private throwIfDestroyed(message = 'Invalid state'): void | never {\n if (!this.hls) {\n throw new Error('invalid state');\n }\n }\n\n private handleError(error: EMEKeyError | Error) {\n if (!this.hls) {\n return;\n }\n this.error(error.message);\n if (error instanceof EMEKeyError) {\n this.hls.trigger(Events.ERROR, error.data);\n } else {\n this.hls.trigger(Events.ERROR, {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_KEYS,\n error,\n fatal: true,\n });\n }\n }\n\n private getKeySystemForKeyPromise(\n decryptdata: LevelKey\n ): Promise<{ keySystem: KeySystems; mediaKeys: MediaKeys }> {\n const keyId = this.getKeyIdString(decryptdata);\n const mediaKeySessionContext = this.keyIdToKeySessionPromise[keyId];\n if (!mediaKeySessionContext) {\n const keySystem = keySystemFormatToKeySystemDomain(\n decryptdata.keyFormat as KeySystemFormats\n );\n const keySystemsToAttempt = keySystem\n ? [keySystem]\n : getKeySystemsForConfig(this.config);\n return this.attemptKeySystemAccess(keySystemsToAttempt);\n }\n return mediaKeySessionContext;\n }\n\n private getKeySystemSelectionPromise(\n keySystemsToAttempt: KeySystems[]\n ): Promise<{ keySystem: KeySystems; mediaKeys: MediaKeys }> | never {\n if (!keySystemsToAttempt.length) {\n keySystemsToAttempt = getKeySystemsForConfig(this.config);\n }\n if (keySystemsToAttempt.length === 0) {\n throw new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_CONFIGURED_LICENSE,\n fatal: true,\n },\n `Missing key-system license configuration options ${JSON.stringify({\n drmSystems: this.config.drmSystems,\n })}`\n );\n }\n return this.attemptKeySystemAccess(keySystemsToAttempt);\n }\n\n private _onMediaEncrypted(event: MediaEncryptedEvent) {\n const { initDataType, initData } = event;\n this.debug(`\"${event.type}\" event: init data type: \"${initDataType}\"`);\n\n // Ignore event when initData is null\n if (initData === null) {\n return;\n }\n\n let keyId: Uint8Array | undefined;\n let keySystemDomain: KeySystems | undefined;\n\n if (\n initDataType === 'sinf' &&\n this.config.drmSystems[KeySystems.FAIRPLAY]\n ) {\n // Match sinf keyId to playlist skd://keyId=\n const json = bin2str(new Uint8Array(initData));\n try {\n const sinf = base64Decode(JSON.parse(json).sinf);\n const tenc = parseSinf(new Uint8Array(sinf));\n if (!tenc) {\n return;\n }\n keyId = tenc.subarray(8, 24);\n keySystemDomain = KeySystems.FAIRPLAY;\n } catch (error) {\n this.warn('Failed to parse sinf \"encrypted\" event message initData');\n return;\n }\n } else {\n // Support clear-lead key-session creation (otherwise depend on playlist keys)\n const psshInfo = parsePssh(initData);\n if (psshInfo === null) {\n return;\n }\n if (\n psshInfo.version === 0 &&\n psshInfo.systemId === KeySystemIds.WIDEVINE &&\n psshInfo.data\n ) {\n keyId = psshInfo.data.subarray(8, 24);\n }\n keySystemDomain = keySystemIdToKeySystemDomain(\n psshInfo.systemId as KeySystemIds\n );\n }\n\n if (!keySystemDomain || !keyId) {\n return;\n }\n\n const keyIdHex = Hex.hexDump(keyId);\n const { keyIdToKeySessionPromise, mediaKeySessions } = this;\n\n let keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex];\n for (let i = 0; i < mediaKeySessions.length; i++) {\n // Match playlist key\n const keyContext = mediaKeySessions[i];\n const decryptdata = keyContext.decryptdata;\n if (decryptdata.pssh || !decryptdata.keyId) {\n continue;\n }\n const oldKeyIdHex = Hex.hexDump(decryptdata.keyId);\n if (\n keyIdHex === oldKeyIdHex ||\n decryptdata.uri.replace(/-/g, '').indexOf(keyIdHex) !== -1\n ) {\n keySessionContextPromise = keyIdToKeySessionPromise[oldKeyIdHex];\n delete keyIdToKeySessionPromise[oldKeyIdHex];\n decryptdata.pssh = new Uint8Array(initData);\n decryptdata.keyId = keyId;\n keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] =\n keySessionContextPromise.then(() => {\n return this.generateRequestWithPreferredKeySession(\n keyContext,\n initDataType,\n initData,\n 'encrypted-event-key-match'\n );\n });\n break;\n }\n }\n\n if (!keySessionContextPromise) {\n // Clear-lead key (not encountered in playlist)\n keySessionContextPromise = keyIdToKeySessionPromise[keyIdHex] =\n this.getKeySystemSelectionPromise([keySystemDomain]).then(\n ({ keySystem, mediaKeys }) => {\n this.throwIfDestroyed();\n const decryptdata = new LevelKey(\n 'ISO-23001-7',\n keyIdHex,\n keySystemToKeySystemFormat(keySystem) ?? ''\n );\n decryptdata.pssh = new Uint8Array(initData);\n decryptdata.keyId = keyId as Uint8Array;\n return this.attemptSetMediaKeys(keySystem, mediaKeys).then(() => {\n this.throwIfDestroyed();\n const keySessionContext = this.createMediaKeySessionContext({\n decryptdata,\n keySystem,\n mediaKeys,\n });\n return this.generateRequestWithPreferredKeySession(\n keySessionContext,\n initDataType,\n initData,\n 'encrypted-event-no-match'\n );\n });\n }\n );\n }\n keySessionContextPromise.catch((error) => this.handleError(error));\n }\n\n private _onWaitingForKey(event: Event) {\n this.log(`\"${event.type}\" event`);\n }\n\n private attemptSetMediaKeys(\n keySystem: KeySystems,\n mediaKeys: MediaKeys\n ): Promise<void> {\n const queue = this.setMediaKeysQueue.slice();\n\n this.log(`Setting media-keys for \"${keySystem}\"`);\n // Only one setMediaKeys() can run at one time, and multiple setMediaKeys() operations\n // can be queued for execution for multiple key sessions.\n const setMediaKeysPromise = Promise.all(queue).then(() => {\n if (!this.media) {\n throw new Error(\n 'Attempted to set mediaKeys without media element attached'\n );\n }\n return this.media.setMediaKeys(mediaKeys);\n });\n this.setMediaKeysQueue.push(setMediaKeysPromise);\n return setMediaKeysPromise.then(() => {\n this.log(`Media-keys set for \"${keySystem}\"`);\n queue.push(setMediaKeysPromise!);\n this.setMediaKeysQueue = this.setMediaKeysQueue.filter(\n (p) => queue.indexOf(p) === -1\n );\n });\n }\n\n private generateRequestWithPreferredKeySession(\n context: MediaKeySessionContext,\n initDataType: string,\n initData: ArrayBuffer | null,\n reason:\n | 'playlist-key'\n | 'encrypted-event-key-match'\n | 'encrypted-event-no-match'\n | 'expired'\n ): Promise<MediaKeySessionContext> | never {\n const generateRequestFilter =\n this.config.drmSystems?.[context.keySystem]?.generateRequest;\n if (generateRequestFilter) {\n try {\n const mappedInitData: ReturnType<typeof generateRequestFilter> =\n generateRequestFilter.call(this.hls, initDataType, initData, context);\n if (!mappedInitData) {\n throw new Error(\n 'Invalid response from configured generateRequest filter'\n );\n }\n initDataType = mappedInitData.initDataType;\n initData = context.decryptdata.pssh = mappedInitData.initData\n ? new Uint8Array(mappedInitData.initData)\n : null;\n } catch (error) {\n this.warn(error.message);\n if (this.hls?.config.debug) {\n throw error;\n }\n }\n }\n\n if (initData === null) {\n this.log(`Skipping key-session request for \"${reason}\" (no initData)`);\n return Promise.resolve(context);\n }\n\n const keyId = this.getKeyIdString(context.decryptdata);\n this.log(\n `Generating key-session request for \"${reason}\": ${keyId} (init data type: ${initDataType} length: ${\n initData ? initData.byteLength : null\n })`\n );\n\n const licenseStatus = new EventEmitter();\n\n context.mediaKeysSession.onmessage = (event: MediaKeyMessageEvent) => {\n const keySession = context.mediaKeysSession;\n if (!keySession) {\n licenseStatus.emit('error', new Error('invalid state'));\n return;\n }\n const { messageType, message } = event;\n this.log(\n `\"${messageType}\" message event for session \"${keySession.sessionId}\" message size: ${message.byteLength}`\n );\n if (\n messageType === 'license-request' ||\n messageType === 'license-renewal'\n ) {\n this.renewLicense(context, message).catch((error) => {\n this.handleError(error);\n licenseStatus.emit('error', error);\n });\n } else if (messageType === 'license-release') {\n if (context.keySystem === KeySystems.FAIRPLAY) {\n this.updateKeySession(context, strToUtf8array('acknowledged'));\n this.removeSession(context);\n }\n } else {\n this.warn(`unhandled media key message type \"${messageType}\"`);\n }\n };\n\n context.mediaKeysSession.onkeystatuseschange = (\n event: MediaKeyMessageEvent\n ) => {\n const keySession = context.mediaKeysSession;\n if (!keySession) {\n licenseStatus.emit('error', new Error('invalid state'));\n return;\n }\n this.onKeyStatusChange(context);\n const keyStatus = context.keyStatus;\n licenseStatus.emit('keyStatus', keyStatus);\n if (keyStatus === 'expired') {\n this.warn(`${context.keySystem} expired for key ${keyId}`);\n this.renewKeySession(context);\n }\n };\n\n const keyUsablePromise = new Promise(\n (resolve: (value?: void) => void, reject) => {\n licenseStatus.on('error', reject);\n\n licenseStatus.on('keyStatus', (keyStatus) => {\n if (keyStatus.startsWith('usable')) {\n resolve();\n } else if (keyStatus === 'output-restricted') {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,\n fatal: false,\n },\n 'HDCP level output restricted'\n )\n );\n } else if (keyStatus === 'internal-error') {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_STATUS_INTERNAL_ERROR,\n fatal: true,\n },\n `key status changed to \"${keyStatus}\"`\n )\n );\n } else if (keyStatus === 'expired') {\n reject(new Error('key expired while generating request'));\n } else {\n this.warn(`unhandled key status change \"${keyStatus}\"`);\n }\n });\n }\n );\n\n return context.mediaKeysSession\n .generateRequest(initDataType, initData)\n .then(() => {\n this.log(\n `Request generated for key-session \"${context.mediaKeysSession?.sessionId}\" keyId: ${keyId}`\n );\n })\n .catch((error) => {\n throw new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_NO_SESSION,\n error,\n fatal: false,\n },\n `Error generating key-session request: ${error}`\n );\n })\n .then(() => keyUsablePromise)\n .catch((error) => {\n licenseStatus.removeAllListeners();\n this.removeSession(context);\n throw error;\n })\n .then(() => {\n licenseStatus.removeAllListeners();\n return context;\n });\n }\n\n private onKeyStatusChange(mediaKeySessionContext: MediaKeySessionContext) {\n mediaKeySessionContext.mediaKeysSession.keyStatuses.forEach(\n (status: MediaKeyStatus, keyId: BufferSource) => {\n this.log(\n `key status change \"${status}\" for keyStatuses keyId: ${Hex.hexDump(\n 'buffer' in keyId\n ? new Uint8Array(keyId.buffer, keyId.byteOffset, keyId.byteLength)\n : new Uint8Array(keyId)\n )} session keyId: ${Hex.hexDump(\n new Uint8Array(mediaKeySessionContext.decryptdata.keyId || [])\n )} uri: ${mediaKeySessionContext.decryptdata.uri}`\n );\n mediaKeySessionContext.keyStatus = status;\n }\n );\n }\n\n private fetchServerCertificate(\n keySystem: KeySystems\n ): Promise<BufferSource | void> {\n const config = this.config;\n const Loader = config.loader;\n const certLoader = new Loader(config as HlsConfig) as Loader<LoaderContext>;\n const url = this.getServerCertificateUrl(keySystem);\n if (!url) {\n return Promise.resolve();\n }\n this.log(`Fetching serverCertificate for \"${keySystem}\"`);\n return new Promise((resolve, reject) => {\n const loaderContext: LoaderContext = {\n responseType: 'arraybuffer',\n url,\n };\n const loadPolicy = config.certLoadPolicy.default;\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: 0,\n retryDelay: 0,\n maxRetryDelay: 0,\n };\n const loaderCallbacks: LoaderCallbacks<LoaderContext> = {\n onSuccess: (response, stats, context, networkDetails) => {\n resolve(response.data as ArrayBuffer);\n },\n onError: (response, contex, networkDetails, stats) => {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details:\n ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,\n fatal: true,\n networkDetails,\n response: {\n url: loaderContext.url,\n data: undefined,\n ...response,\n },\n },\n `\"${keySystem}\" certificate request failed (${url}). Status: ${response.code} (${response.text})`\n )\n );\n },\n onTimeout: (stats, context, networkDetails) => {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details:\n ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,\n fatal: true,\n networkDetails,\n response: {\n url: loaderContext.url,\n data: undefined,\n },\n },\n `\"${keySystem}\" certificate request timed out (${url})`\n )\n );\n },\n onAbort: (stats, context, networkDetails) => {\n reject(new Error('aborted'));\n },\n };\n certLoader.load(loaderContext, loaderConfig, loaderCallbacks);\n });\n }\n\n private setMediaKeysServerCertificate(\n mediaKeys: MediaKeys,\n keySystem: KeySystems,\n cert: BufferSource\n ): Promise<MediaKeys> {\n return new Promise((resolve, reject) => {\n mediaKeys\n .setServerCertificate(cert)\n .then((success) => {\n this.log(\n `setServerCertificate ${\n success ? 'success' : 'not supported by CDM'\n } (${cert?.byteLength}) on \"${keySystem}\"`\n );\n resolve(mediaKeys);\n })\n .catch((error) => {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details:\n ErrorDetails.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,\n error,\n fatal: true,\n },\n error.message\n )\n );\n });\n });\n }\n\n private renewLicense(\n context: MediaKeySessionContext,\n keyMessage: ArrayBuffer\n ): Promise<void> {\n return this.requestLicense(context, new Uint8Array(keyMessage)).then(\n (data: ArrayBuffer) => {\n return this.updateKeySession(context, new Uint8Array(data)).catch(\n (error) => {\n throw new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_SESSION_UPDATE_FAILED,\n error,\n fatal: true,\n },\n error.message\n );\n }\n );\n }\n );\n }\n\n private setupLicenseXHR(\n xhr: XMLHttpRequest,\n url: string,\n keysListItem: MediaKeySessionContext,\n licenseChallenge: Uint8Array\n ): Promise<{ xhr: XMLHttpRequest; licenseChallenge: Uint8Array }> {\n const licenseXhrSetup = this.config.licenseXhrSetup;\n\n if (!licenseXhrSetup) {\n xhr.open('POST', url, true);\n\n return Promise.resolve({ xhr, licenseChallenge });\n }\n\n return Promise.resolve()\n .then(() => {\n if (!keysListItem.decryptdata) {\n throw new Error('Key removed');\n }\n return licenseXhrSetup.call(\n this.hls,\n xhr,\n url,\n keysListItem,\n licenseChallenge\n );\n })\n .catch((error: Error) => {\n if (!keysListItem.decryptdata) {\n // Key session removed. Cancel license request.\n throw error;\n }\n // let's try to open before running setup\n xhr.open('POST', url, true);\n\n return licenseXhrSetup.call(\n this.hls,\n xhr,\n url,\n keysListItem,\n licenseChallenge\n );\n })\n .then((licenseXhrSetupResult) => {\n // if licenseXhrSetup did not yet call open, let's do it now\n if (!xhr.readyState) {\n xhr.open('POST', url, true);\n }\n const finalLicenseChallenge = licenseXhrSetupResult\n ? licenseXhrSetupResult\n : licenseChallenge;\n return { xhr, licenseChallenge: finalLicenseChallenge };\n });\n }\n\n private requestLicense(\n keySessionContext: MediaKeySessionContext,\n licenseChallenge: Uint8Array\n ): Promise<ArrayBuffer> {\n const keyLoadPolicy = this.config.keyLoadPolicy.default;\n return new Promise((resolve, reject) => {\n const url = this.getLicenseServerUrl(keySessionContext.keySystem);\n this.log(`Sending license request to URL: ${url}`);\n const xhr = new XMLHttpRequest();\n xhr.responseType = 'arraybuffer';\n xhr.onreadystatechange = () => {\n if (!this.hls || !keySessionContext.mediaKeysSession) {\n return reject(new Error('invalid state'));\n }\n if (xhr.readyState === 4) {\n if (xhr.status === 200) {\n this._requestLicenseFailureCount = 0;\n let data = xhr.response;\n this.log(\n `License received ${\n data instanceof ArrayBuffer ? data.byteLength : data\n }`\n );\n const licenseResponseCallback = this.config.licenseResponseCallback;\n if (licenseResponseCallback) {\n try {\n data = licenseResponseCallback.call(\n this.hls,\n xhr,\n url,\n keySessionContext\n );\n } catch (error) {\n this.error(error);\n }\n }\n resolve(data);\n } else {\n const retryConfig = keyLoadPolicy.errorRetry;\n const maxNumRetry = retryConfig ? retryConfig.maxNumRetry : 0;\n this._requestLicenseFailureCount++;\n if (\n this._requestLicenseFailureCount > maxNumRetry ||\n (xhr.status >= 400 && xhr.status < 500)\n ) {\n reject(\n new EMEKeyError(\n {\n type: ErrorTypes.KEY_SYSTEM_ERROR,\n details: ErrorDetails.KEY_SYSTEM_LICENSE_REQUEST_FAILED,\n fatal: true,\n networkDetails: xhr,\n response: {\n url,\n data: undefined as any,\n code: xhr.status,\n text: xhr.statusText,\n },\n },\n `License Request XHR failed (${url}). Status: ${xhr.status} (${xhr.statusText})`\n )\n );\n } else {\n const attemptsLeft =\n maxNumRetry - this._requestLicenseFailureCount + 1;\n this.warn(\n `Retrying license request, ${attemptsLeft} attempts left`\n );\n this.requestLicense(keySessionContext, licenseChallenge).then(\n resolve,\n reject\n );\n }\n }\n }\n };\n if (\n keySessionContext.licenseXhr &&\n keySessionContext.licenseXhr.readyState !== XMLHttpRequest.DONE\n ) {\n keySessionContext.licenseXhr.abort();\n }\n keySessionContext.licenseXhr = xhr;\n\n this.setupLicenseXHR(xhr, url, keySessionContext, licenseChallenge).then(\n ({ xhr, licenseChallenge }) => {\n xhr.send(licenseChallenge);\n }\n );\n });\n }\n\n private onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) {\n if (!this.config.emeEnabled) {\n return;\n }\n\n const media = data.media;\n\n // keep reference of media\n this.media = media;\n\n media.addEventListener('encrypted', this.onMediaEncrypted);\n media.addEventListener('waitingforkey', this.onWaitingForKey);\n }\n\n private onMediaDetached() {\n const media = this.media;\n const mediaKeysList = this.mediaKeySessions;\n if (media) {\n media.removeEventListener('encrypted', this.onMediaEncrypted);\n media.removeEventListener('waitingforkey', this.onWaitingForKey);\n this.media = null;\n }\n\n this._requestLicenseFailureCount = 0;\n this.setMediaKeysQueue = [];\n this.mediaKeySessions = [];\n this.keyIdToKeySessionPromise = {};\n LevelKey.clearKeyUriToKeyIdMap();\n\n // Close all sessions and remove media keys from the video element.\n const keySessionCount = mediaKeysList.length;\n EMEController.CDMCleanupPromise = Promise.all(\n mediaKeysList\n .map((mediaKeySessionContext) =>\n this.removeSession(mediaKeySessionContext)\n )\n .concat(\n media?.setMediaKeys(null).catch((error) => {\n this.log(\n `Could not clear media keys: ${error}. media.src: ${media?.src}`\n );\n })\n )\n )\n .then(() => {\n if (keySessionCount) {\n this.log('finished closing key sessions and clearing media keys');\n mediaKeysList.length = 0;\n }\n })\n .catch((error) => {\n this.log(\n `Could not close sessions and clear media keys: ${error}. media.src: ${media?.src}`\n );\n });\n }\n\n private onManifestLoading() {\n this.keyFormatPromise = null;\n }\n\n private onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n { sessionKeys }: ManifestLoadedData\n ) {\n if (!sessionKeys || !this.config.emeEnabled) {\n return;\n }\n if (!this.keyFormatPromise) {\n const keyFormats: KeySystemFormats[] = sessionKeys.reduce(\n (formats: KeySystemFormats[], sessionKey: LevelKey) => {\n if (\n formats.indexOf(sessionKey.keyFormat as KeySystemFormats) === -1\n ) {\n formats.push(sessionKey.keyFormat as KeySystemFormats);\n }\n return formats;\n },\n []\n );\n this.log(\n `Selecting key-system from session-keys ${keyFormats.join(', ')}`\n );\n this.keyFormatPromise = this.getKeyFormatPromise(keyFormats);\n }\n }\n\n private removeSession(\n mediaKeySessionContext: MediaKeySessionContext\n ): Promise<void> | void {\n const { mediaKeysSession, licenseXhr } = mediaKeySessionContext;\n if (mediaKeysSession) {\n this.log(\n `Remove licenses and keys and close session ${mediaKeysSession.sessionId}`\n );\n mediaKeysSession.onmessage = null;\n mediaKeysSession.onkeystatuseschange = null;\n if (licenseXhr && licenseXhr.readyState !== XMLHttpRequest.DONE) {\n licenseXhr.abort();\n }\n mediaKeySessionContext.mediaKeysSession =\n mediaKeySessionContext.decryptdata =\n mediaKeySessionContext.licenseXhr =\n undefined!;\n const index = this.mediaKeySessions.indexOf(mediaKeySessionContext);\n if (index > -1) {\n this.mediaKeySessions.splice(index, 1);\n }\n return mediaKeysSession\n .remove()\n .catch((error) => {\n this.log(`Could not remove session: ${error}`);\n })\n .then(() => {\n return mediaKeysSession.close();\n })\n .catch((error) => {\n this.log(`Could not close session: ${error}`);\n });\n }\n }\n}\n\nclass EMEKeyError extends Error {\n public readonly data: ErrorData;\n constructor(\n data: Omit<ErrorData, 'error'> & { error?: Error },\n message: string\n ) {\n super(message);\n data.error ||= new Error(message);\n this.data = data as ErrorData;\n data.err = data.error;\n }\n}\n\nexport default EMEController;\n","/**\n * CMCD spec version\n */\nexport const CMCDVersion = 1;\n\n/**\n * CMCD Object Type\n */\nexport const enum CMCDObjectType {\n MANIFEST = 'm',\n AUDIO = 'a',\n VIDEO = 'v',\n MUXED = 'av',\n INIT = 'i',\n CAPTION = 'c',\n TIMED_TEXT = 'tt',\n KEY = 'k',\n OTHER = 'o',\n}\n\n/**\n * CMCD Streaming Format\n */\nexport const CMCDStreamingFormatHLS = 'h';\n\n/**\n * CMCD Streaming Type\n */\nconst enum CMCDStreamType {\n VOD = 'v',\n LIVE = 'l',\n}\n\n/**\n * CMCD Headers\n */\nexport interface CMCDHeaders {\n 'CMCD-Object': string;\n 'CMCD-Request': string;\n 'CMCD-Session': string;\n 'CMCD-Status': string;\n}\n\n/**\n * CMCD\n */\nexport interface CMCD {\n /////////////////\n // CMCD Object //\n /////////////////\n\n /**\n * Encoded bitrate\n *\n * The encoded bitrate of the audio or video object being requested. This may not be known precisely by the player; however,\n * it MAY be estimated based upon playlist/manifest declarations. If the playlist declares both peak and average bitrate values,\n * the peak value should be transmitted.\n *\n * Integer kbps\n */\n br?: number;\n\n /**\n * Object duration\n *\n * The playback duration in milliseconds of the object being requested. If a partial segment is being requested, then this value\n * MUST indicate the playback duration of that part and not that of its parent segment. This value can be an approximation of the\n * estimated duration if the explicit value is not known.\n *\n * Integer milliseconds\n */\n d?: number;\n\n /**\n * Object type\n *\n * The media type of the current object being requested:\n * - `m` = text file, such as a manifest or playlist\n * - `a` = audio only\n * - `v` = video only\n * - `av` = muxed audio and video\n * - `i` = init segment\n * - `c` = caption or subtitle\n * - `tt` = ISOBMFF timed text track\n * - `k` = cryptographic key, license or certificate.\n * - `o` = other\n *\n * If the object type being requested is unknown, then this key MUST NOT be used.\n */\n ot?: CMCDObjectType;\n\n /**\n * Top bitrate\n *\n * The highest bitrate rendition in the manifest or playlist that the client is allowed to play, given current codec, licensing and\n * sizing constraints.\n *\n * Integer Kbps\n */\n tb?: number;\n\n //////////////////\n // CMCD Request //\n //////////////////\n /**\n * Buffer length\n *\n * The buffer length associated with the media object being requested. This value MUST be rounded to the nearest 100 ms. This key SHOULD only be\n * sent with an object type of ‘a’, ‘v’ or ‘av’.\n *\n * Integer milliseconds\n */\n bl?: number;\n\n /**\n * Deadline\n *\n * Deadline from the request time until the first sample of this Segment/Object needs to be available in order to not create a buffer underrun or\n * any other playback problems. This value MUST be rounded to the nearest 100ms. For a playback rate of 1, this may be equivalent to the player’s\n * remaining buffer length.\n *\n * Integer milliseconds\n */\n dl?: number;\n\n /**\n * Measured mtp CMCD throughput\n *\n * The throughput between client and server, as measured by the client and MUST be rounded to the nearest 100 kbps. This value, however derived,\n * SHOULD be the value that the client is using to make its next Adaptive Bitrate switching decision. If the client is connected to multiple\n * servers concurrently, it must take care to report only the throughput measured against the receiving server. If the client has multiple concurrent\n * connections to the server, then the intent is that this value communicates the aggregate throughput the client sees across all those connections.\n *\n * Integer kbps\n */\n mtp?: number;\n\n /**\n * Next object request\n *\n * Relative path of the next object to be requested. This can be used to trigger pre-fetching by the CDN. This MUST be a path relative to the current\n * request. This string MUST be URLEncoded. The client SHOULD NOT depend upon any pre-fetch action being taken - it is merely a request for such a\n * pre-fetch to take place.\n *\n * String\n */\n nor?: string;\n\n /**\n * Next range request\n *\n * If the next request will be a partial object request, then this string denotes the byte range to be requested. If the ‘nor’ field is not set, then the\n * object is assumed to match the object currently being requested. The client SHOULD NOT depend upon any pre-fetch action being taken – it is merely a\n * request for such a pre-fetch to take place. Formatting is similar to the HTTP Range header, except that the unit MUST be ‘byte’, the ‘Range:’ prefix is\n * NOT required and specifying multiple ranges is NOT allowed. Valid combinations are:\n *\n * - `\"\\<range-start\\>-\"`\n * - `\"\\<range-start\\>-\\<range-end\\>\"`\n * - `\"-\\<suffix-length\\>\"`\n *\n * String\n */\n nrr?: string;\n\n /**\n * Startup\n *\n * Key is included without a value if the object is needed urgently due to startup, seeking or recovery after a buffer-empty event. The media SHOULD not be\n * rendering when this request is made. This key MUST not be sent if it is FALSE.\n *\n * Boolean\n */\n su?: boolean;\n\n //////////////////\n // CMCD Session //\n //////////////////\n\n /**\n * Content ID\n *\n * A unique string identifying the current content. Maximum length is 64 characters. This value is consistent across multiple different\n * sessions and devices and is defined and updated at the discretion of the service provider.\n *\n * String\n */\n cid?: string;\n\n /**\n * Playback rate\n *\n * `1` if real-time, `2` if double speed, `0` if not playing. SHOULD only be sent if not equal to `1`.\n *\n * Decimal\n */\n pr?: number;\n\n /**\n * Streaming format\n *\n * The streaming format that defines the current request.\n *\n * - `d` = MPEG DASH\n * - `h` = HTTP Live Streaming (HLS)\n * - `s` = Smooth Streaming\n * - `o` = other\n *\n * If the streaming format being requested is unknown, then this key MUST NOT be used.\n */\n sf?: typeof CMCDStreamingFormatHLS;\n\n /**\n * Session ID\n *\n * A GUID identifying the current playback session. A playback session typically ties together segments belonging to a single media asset.\n * Maximum length is 64 characters. It is RECOMMENDED to conform to the UUID specification.\n *\n * String\n */\n sid?: string;\n\n /**\n * Stream type\n * - `v` = all segments are available – e.g., VOD\n * - `l` = segments become available over time – e.g., LIVE\n */\n st?: CMCDStreamType;\n\n /**\n * CMCD version\n *\n * The version of this specification used for interpreting the defined key names and values. If this key is omitted, the client and server MUST\n * interpret the values as being defined by version 1. Client SHOULD omit this field if the version is 1.\n *\n * Integer\n */\n v?: number;\n\n /////////////////\n // CMCD Status //\n /////////////////\n\n /**\n * Buffer starvation\n *\n * Key is included without a value if the buffer was starved at some point between the prior request and this object request,\n * resulting in the player being in a rebuffering state and the video or audio playback being stalled. This key MUST NOT be\n * sent if the buffer was not starved since the prior request.\n *\n * If the object type `ot` key is sent along with this key, then the `bs` key refers to the buffer associated with the particular\n * object type. If no object type is communicated, then the buffer state applies to the current session.\n *\n * Boolean\n */\n bs?: boolean;\n\n /**\n * Requested maximum throughput\n *\n * The requested maximum throughput that the client considers sufficient for delivery of the asset. Values MUST be rounded to the\n * nearest 100kbps. For example, a client would indicate that the current segment, encoded at 2Mbps, is to be delivered at no more\n * than 10Mbps, by using rtp=10000.\n *\n * Note: This can benefit clients by preventing buffer saturation through over-delivery and can also deliver a community benefit\n * through fair-share delivery. The concept is that each client receives the throughput necessary for great performance, but no more.\n * The CDN may not support the rtp feature.\n *\n * Integer kbps\n */\n rtp?: number;\n}\n","import { Events } from '../events';\nimport Hls from '../hls';\nimport {\n CMCD,\n CMCDHeaders,\n CMCDObjectType,\n CMCDStreamingFormatHLS,\n CMCDVersion,\n} from '../types/cmcd';\nimport { BufferHelper } from '../utils/buffer-helper';\nimport { logger } from '../utils/logger';\nimport type { ComponentAPI } from '../types/component-api';\nimport type { Fragment } from '../loader/fragment';\nimport type { BufferCreatedData, MediaAttachedData } from '../types/events';\nimport type {\n FragmentLoaderContext,\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n PlaylistLoaderContext,\n} from '../types/loader';\nimport type {\n FragmentLoaderConstructor,\n HlsConfig,\n PlaylistLoaderConstructor,\n} from '../config';\n\n/**\n * Controller to deal with Common Media Client Data (CMCD)\n * @see https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf\n */\nexport default class CMCDController implements ComponentAPI {\n private hls: Hls;\n private config: HlsConfig;\n private media?: HTMLMediaElement;\n private sid?: string;\n private cid?: string;\n private useHeaders: boolean = false;\n private initialized: boolean = false;\n private starved: boolean = false;\n private buffering: boolean = true;\n private audioBuffer?: SourceBuffer; // eslint-disable-line no-restricted-globals\n private videoBuffer?: SourceBuffer; // eslint-disable-line no-restricted-globals\n\n constructor(hls: Hls) {\n this.hls = hls;\n const config = (this.config = hls.config);\n const { cmcd } = config;\n\n if (cmcd != null) {\n config.pLoader = this.createPlaylistLoader();\n config.fLoader = this.createFragmentLoader();\n\n this.sid = cmcd.sessionId || CMCDController.uuid();\n this.cid = cmcd.contentId;\n this.useHeaders = cmcd.useHeaders === true;\n this.registerListeners();\n }\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.on(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n hls.on(Events.BUFFER_CREATED, this.onBufferCreated, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n hls.off(Events.MEDIA_ATTACHED, this.onMediaAttached, this);\n hls.off(Events.MEDIA_DETACHED, this.onMediaDetached, this);\n hls.off(Events.BUFFER_CREATED, this.onBufferCreated, this);\n }\n\n destroy() {\n this.unregisterListeners();\n this.onMediaDetached();\n\n // @ts-ignore\n this.hls = this.config = this.audioBuffer = this.videoBuffer = null;\n }\n\n private onMediaAttached(\n event: Events.MEDIA_ATTACHED,\n data: MediaAttachedData\n ) {\n this.media = data.media;\n this.media.addEventListener('waiting', this.onWaiting);\n this.media.addEventListener('playing', this.onPlaying);\n }\n\n private onMediaDetached() {\n if (!this.media) {\n return;\n }\n\n this.media.removeEventListener('waiting', this.onWaiting);\n this.media.removeEventListener('playing', this.onPlaying);\n\n // @ts-ignore\n this.media = null;\n }\n\n private onBufferCreated(\n event: Events.BUFFER_CREATED,\n data: BufferCreatedData\n ) {\n this.audioBuffer = data.tracks.audio?.buffer;\n this.videoBuffer = data.tracks.video?.buffer;\n }\n\n private onWaiting = () => {\n if (this.initialized) {\n this.starved = true;\n }\n\n this.buffering = true;\n };\n\n private onPlaying = () => {\n if (!this.initialized) {\n this.initialized = true;\n }\n\n this.buffering = false;\n };\n\n /**\n * Create baseline CMCD data\n */\n private createData(): CMCD {\n return {\n v: CMCDVersion,\n sf: CMCDStreamingFormatHLS,\n sid: this.sid,\n cid: this.cid,\n pr: this.media?.playbackRate,\n mtp: this.hls.bandwidthEstimate / 1000,\n };\n }\n\n /**\n * Apply CMCD data to a request.\n */\n private apply(context: LoaderContext, data: CMCD = {}) {\n // apply baseline data\n Object.assign(data, this.createData());\n\n const isVideo =\n data.ot === CMCDObjectType.INIT ||\n data.ot === CMCDObjectType.VIDEO ||\n data.ot === CMCDObjectType.MUXED;\n\n if (this.starved && isVideo) {\n data.bs = true;\n data.su = true;\n this.starved = false;\n }\n\n if (data.su == null) {\n data.su = this.buffering;\n }\n\n // TODO: Implement rtp, nrr, nor, dl\n\n if (this.useHeaders) {\n const headers = CMCDController.toHeaders(data);\n if (!Object.keys(headers).length) {\n return;\n }\n\n if (!context.headers) {\n context.headers = {};\n }\n\n Object.assign(context.headers, headers);\n } else {\n const query = CMCDController.toQuery(data);\n if (!query) {\n return;\n }\n\n context.url = CMCDController.appendQueryToUri(context.url, query);\n }\n }\n\n /**\n * Apply CMCD data to a manifest request.\n */\n private applyPlaylistData = (context: PlaylistLoaderContext) => {\n try {\n this.apply(context, {\n ot: CMCDObjectType.MANIFEST,\n su: !this.initialized,\n });\n } catch (error) {\n logger.warn('Could not generate manifest CMCD data.', error);\n }\n };\n\n /**\n * Apply CMCD data to a segment request\n */\n private applyFragmentData = (context: FragmentLoaderContext) => {\n try {\n const fragment = context.frag;\n const level = this.hls.levels[fragment.level];\n const ot = this.getObjectType(fragment);\n const data: CMCD = {\n d: fragment.duration * 1000,\n ot,\n };\n\n if (\n ot === CMCDObjectType.VIDEO ||\n ot === CMCDObjectType.AUDIO ||\n ot == CMCDObjectType.MUXED\n ) {\n data.br = level.bitrate / 1000;\n data.tb = this.getTopBandwidth(ot) / 1000;\n data.bl = this.getBufferLength(ot);\n }\n\n this.apply(context, data);\n } catch (error) {\n logger.warn('Could not generate segment CMCD data.', error);\n }\n };\n\n /**\n * The CMCD object type.\n */\n private getObjectType(fragment: Fragment): CMCDObjectType | undefined {\n const { type } = fragment;\n\n if (type === 'subtitle') {\n return CMCDObjectType.TIMED_TEXT;\n }\n\n if (fragment.sn === 'initSegment') {\n return CMCDObjectType.INIT;\n }\n\n if (type === 'audio') {\n return CMCDObjectType.AUDIO;\n }\n\n if (type === 'main') {\n if (!this.hls.audioTracks.length) {\n return CMCDObjectType.MUXED;\n }\n\n return CMCDObjectType.VIDEO;\n }\n\n return undefined;\n }\n\n /**\n * Get the highest bitrate.\n */\n private getTopBandwidth(type: CMCDObjectType) {\n let bitrate: number = 0;\n let levels;\n const hls = this.hls;\n\n if (type === CMCDObjectType.AUDIO) {\n levels = hls.audioTracks;\n } else {\n const max = hls.maxAutoLevel;\n const len = max > -1 ? max + 1 : hls.levels.length;\n levels = hls.levels.slice(0, len);\n }\n\n for (const level of levels) {\n if (level.bitrate > bitrate) {\n bitrate = level.bitrate;\n }\n }\n\n return bitrate > 0 ? bitrate : NaN;\n }\n\n /**\n * Get the buffer length for a media type in milliseconds\n */\n private getBufferLength(type: CMCDObjectType) {\n const media = this.hls.media;\n const buffer =\n type === CMCDObjectType.AUDIO ? this.audioBuffer : this.videoBuffer;\n\n if (!buffer || !media) {\n return NaN;\n }\n\n const info = BufferHelper.bufferInfo(\n buffer,\n media.currentTime,\n this.config.maxBufferHole\n );\n\n return info.len * 1000;\n }\n\n /**\n * Create a playlist loader\n */\n private createPlaylistLoader(): PlaylistLoaderConstructor | undefined {\n const { pLoader } = this.config;\n const apply = this.applyPlaylistData;\n const Ctor = pLoader || (this.config.loader as PlaylistLoaderConstructor);\n\n return class CmcdPlaylistLoader {\n private loader: Loader<PlaylistLoaderContext>;\n\n constructor(config: HlsConfig) {\n this.loader = new Ctor(config);\n }\n\n get stats() {\n return this.loader.stats;\n }\n\n get context() {\n return this.loader.context;\n }\n\n destroy() {\n this.loader.destroy();\n }\n\n abort() {\n this.loader.abort();\n }\n\n load(\n context: PlaylistLoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<PlaylistLoaderContext>\n ) {\n apply(context);\n this.loader.load(context, config, callbacks);\n }\n };\n }\n\n /**\n * Create a playlist loader\n */\n private createFragmentLoader(): FragmentLoaderConstructor | undefined {\n const { fLoader } = this.config;\n const apply = this.applyFragmentData;\n const Ctor = fLoader || (this.config.loader as FragmentLoaderConstructor);\n\n return class CmcdFragmentLoader {\n private loader: Loader<FragmentLoaderContext>;\n\n constructor(config: HlsConfig) {\n this.loader = new Ctor(config);\n }\n\n get stats() {\n return this.loader.stats;\n }\n\n get context() {\n return this.loader.context;\n }\n\n destroy() {\n this.loader.destroy();\n }\n\n abort() {\n this.loader.abort();\n }\n\n load(\n context: FragmentLoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<FragmentLoaderContext>\n ) {\n apply(context);\n this.loader.load(context, config, callbacks);\n }\n };\n }\n\n /**\n * Generate a random v4 UUI\n *\n * @returns {string}\n */\n static uuid(): string {\n const url = URL.createObjectURL(new Blob());\n const uuid = url.toString();\n URL.revokeObjectURL(url);\n return uuid.slice(uuid.lastIndexOf('/') + 1);\n }\n\n /**\n * Serialize a CMCD data object according to the rules defined in the\n * section 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static serialize(data: CMCD): string {\n const results: string[] = [];\n const isValid = (value: any) =>\n !Number.isNaN(value) && value != null && value !== '' && value !== false;\n const toRounded = (value: number) => Math.round(value);\n const toHundred = (value: number) => toRounded(value / 100) * 100;\n const toUrlSafe = (value: string) => encodeURIComponent(value);\n const formatters = {\n br: toRounded,\n d: toRounded,\n bl: toHundred,\n dl: toHundred,\n mtp: toHundred,\n nor: toUrlSafe,\n rtp: toHundred,\n tb: toRounded,\n };\n\n const keys = Object.keys(data || {}).sort();\n\n for (const key of keys) {\n let value = data[key];\n\n // ignore invalid values\n if (!isValid(value)) {\n continue;\n }\n\n // Version should only be reported if not equal to 1.\n if (key === 'v' && value === 1) {\n continue;\n }\n\n // Playback rate should only be sent if not equal to 1.\n if (key == 'pr' && value === 1) {\n continue;\n }\n\n // Certain values require special formatting\n const formatter = formatters[key];\n if (formatter) {\n value = formatter(value);\n }\n\n // Serialize the key/value pair\n const type = typeof value;\n let result: string;\n\n if (key === 'ot' || key === 'sf' || key === 'st') {\n result = `${key}=${value}`;\n } else if (type === 'boolean') {\n result = key;\n } else if (type === 'number') {\n result = `${key}=${value}`;\n } else {\n result = `${key}=${JSON.stringify(value)}`;\n }\n\n results.push(result);\n }\n\n return results.join(',');\n }\n\n /**\n * Convert a CMCD data object to request headers according to the rules\n * defined in the section 2.1 and 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static toHeaders(data: CMCD): Partial<CMCDHeaders> {\n const keys = Object.keys(data);\n const headers = {};\n const headerNames = ['Object', 'Request', 'Session', 'Status'];\n const headerGroups = [{}, {}, {}, {}];\n const headerMap = {\n br: 0,\n d: 0,\n ot: 0,\n tb: 0,\n bl: 1,\n dl: 1,\n mtp: 1,\n nor: 1,\n nrr: 1,\n su: 1,\n cid: 2,\n pr: 2,\n sf: 2,\n sid: 2,\n st: 2,\n v: 2,\n bs: 3,\n rtp: 3,\n };\n\n for (const key of keys) {\n // Unmapped fields are mapped to the Request header\n const index = headerMap[key] != null ? headerMap[key] : 1;\n headerGroups[index][key] = data[key];\n }\n\n for (let i = 0; i < headerGroups.length; i++) {\n const value = CMCDController.serialize(headerGroups[i]);\n if (value) {\n headers[`CMCD-${headerNames[i]}`] = value;\n }\n }\n\n return headers;\n }\n\n /**\n * Convert a CMCD data object to query args according to the rules\n * defined in the section 2.2 and 3.2 of\n * [CTA-5004](https://cdn.cta.tech/cta/media/media/resources/standards/pdfs/cta-5004-final.pdf).\n */\n static toQuery(data: CMCD): string {\n return `CMCD=${encodeURIComponent(CMCDController.serialize(data))}`;\n }\n\n /**\n * Append query args to a uri.\n */\n static appendQueryToUri(uri, query) {\n if (!query) {\n return uri;\n }\n\n const separator = uri.includes('?') ? '&' : '?';\n return `${uri}${separator}${query}`;\n }\n}\n","import { Events } from '../events';\nimport { Level } from '../types/level';\nimport { AttrList } from '../utils/attr-list';\nimport { addGroupId } from './level-controller';\nimport { ErrorActionFlags, NetworkErrorAction } from './error-controller';\nimport { logger } from '../utils/logger';\nimport type Hls from '../hls';\nimport type { NetworkComponentAPI } from '../types/component-api';\nimport type {\n ErrorData,\n ManifestLoadedData,\n ManifestParsedData,\n} from '../types/events';\nimport type { RetryConfig } from '../config';\nimport type {\n Loader,\n LoaderCallbacks,\n LoaderConfiguration,\n LoaderContext,\n LoaderResponse,\n LoaderStats,\n} from '../types/loader';\nimport type { LevelParsed } from '../types/level';\nimport type { MediaAttributes, MediaPlaylist } from '../types/media-playlist';\n\nexport type SteeringManifest = {\n VERSION: 1;\n TTL: number;\n 'RELOAD-URI'?: string;\n 'PATHWAY-PRIORITY': string[];\n 'PATHWAY-CLONES'?: PathwayClone[];\n};\n\ntype PathwayClone = {\n 'BASE-ID': string;\n ID: string;\n 'URI-REPLACEMENT': UriReplacement;\n};\n\ntype UriReplacement = {\n HOST?: string;\n PARAMS?: { [queryParameter: string]: string };\n 'PER-VARIANT-URIS'?: { [stableVariantId: string]: string };\n 'PER-RENDITION-URIS'?: { [stableRenditionId: string]: string };\n};\n\nconst PATHWAY_PENALTY_DURATION_MS = 300000;\n\nexport default class ContentSteeringController implements NetworkComponentAPI {\n private readonly hls: Hls;\n private log: (msg: any) => void;\n private loader: Loader<LoaderContext> | null = null;\n private uri: string | null = null;\n private pathwayId: string = '.';\n private pathwayPriority: string[] | null = null;\n private timeToLoad: number = 300;\n private reloadTimer: number = -1;\n private updated: number = 0;\n private started: boolean = false;\n private enabled: boolean = true;\n private levels: Level[] | null = null;\n private audioTracks: MediaPlaylist[] | null = null;\n private subtitleTracks: MediaPlaylist[] | null = null;\n private penalizedPathways: { [pathwayId: string]: number } = {};\n\n constructor(hls: Hls) {\n this.hls = hls;\n this.log = logger.log.bind(logger, `[content-steering]:`);\n this.registerListeners();\n }\n\n private registerListeners() {\n const hls = this.hls;\n hls.on(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.on(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.on(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.on(Events.ERROR, this.onError, this);\n }\n\n private unregisterListeners() {\n const hls = this.hls;\n if (!hls) {\n return;\n }\n hls.off(Events.MANIFEST_LOADING, this.onManifestLoading, this);\n hls.off(Events.MANIFEST_LOADED, this.onManifestLoaded, this);\n hls.off(Events.MANIFEST_PARSED, this.onManifestParsed, this);\n hls.off(Events.ERROR, this.onError, this);\n }\n\n startLoad(): void {\n this.started = true;\n self.clearTimeout(this.reloadTimer);\n if (this.enabled && this.uri) {\n if (this.updated) {\n const ttl = Math.max(\n this.timeToLoad * 1000 - (performance.now() - this.updated),\n 0\n );\n this.scheduleRefresh(this.uri, ttl);\n } else {\n this.loadSteeringManifest(this.uri);\n }\n }\n }\n\n stopLoad(): void {\n this.started = false;\n if (this.loader) {\n this.loader.destroy();\n this.loader = null;\n }\n self.clearTimeout(this.reloadTimer);\n }\n\n destroy() {\n this.unregisterListeners();\n this.stopLoad();\n // @ts-ignore\n this.hls = null;\n this.levels = this.audioTracks = this.subtitleTracks = null;\n }\n\n removeLevel(levelToRemove: Level) {\n const levels = this.levels;\n if (levels) {\n this.levels = levels.filter((level) => level !== levelToRemove);\n }\n }\n\n private onManifestLoading() {\n this.stopLoad();\n this.enabled = true;\n this.timeToLoad = 300;\n this.updated = 0;\n this.uri = null;\n this.pathwayId = '.';\n this.levels = this.audioTracks = this.subtitleTracks = null;\n }\n\n private onManifestLoaded(\n event: Events.MANIFEST_LOADED,\n data: ManifestLoadedData\n ) {\n const { contentSteering } = data;\n if (contentSteering === null) {\n return;\n }\n this.pathwayId = contentSteering.pathwayId;\n this.uri = contentSteering.uri;\n if (this.started) {\n this.startLoad();\n }\n }\n\n private onManifestParsed(\n event: Events.MANIFEST_PARSED,\n data: ManifestParsedData\n ) {\n this.audioTracks = data.audioTracks;\n this.subtitleTracks = data.subtitleTracks;\n }\n\n private onError(event: Events.ERROR, data: ErrorData) {\n const { errorAction } = data;\n if (\n errorAction?.action === NetworkErrorAction.SendAlternateToPenaltyBox &&\n errorAction.flags === ErrorActionFlags.MoveAllAlternatesMatchingHost\n ) {\n let pathwayPriority = this.pathwayPriority;\n const pathwayId = this.pathwayId;\n if (!this.penalizedPathways[pathwayId]) {\n this.penalizedPathways[pathwayId] = performance.now();\n }\n if (!pathwayPriority && this.levels) {\n // If PATHWAY-PRIORITY was not provided, list pathways for error handling\n pathwayPriority = this.levels.reduce((pathways, level) => {\n if (pathways.indexOf(level.pathwayId) === -1) {\n pathways.push(level.pathwayId);\n }\n return pathways;\n }, [] as string[]);\n }\n if (pathwayPriority && pathwayPriority.length > 1) {\n this.updatePathwayPriority(pathwayPriority);\n errorAction.resolved = this.pathwayId !== pathwayId;\n }\n }\n }\n\n public filterParsedLevels(levels: Level[]): Level[] {\n // Filter levels to only include those that are in the initial pathway\n this.levels = levels;\n let pathwayLevels = this.getLevelsForPathway(this.pathwayId);\n if (pathwayLevels.length === 0) {\n const pathwayId = levels[0].pathwayId;\n this.log(\n `No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to \"${pathwayId}\"`\n );\n pathwayLevels = this.getLevelsForPathway(pathwayId);\n this.pathwayId = pathwayId;\n }\n if (pathwayLevels.length !== levels.length) {\n this.log(\n `Found ${pathwayLevels.length}/${levels.length} levels in Pathway \"${this.pathwayId}\"`\n );\n return pathwayLevels;\n }\n return levels;\n }\n\n private getLevelsForPathway(pathwayId: string): Level[] {\n if (this.levels === null) {\n return [];\n }\n return this.levels.filter((level) => pathwayId === level.pathwayId);\n }\n\n private updatePathwayPriority(pathwayPriority: string[]) {\n this.pathwayPriority = pathwayPriority;\n let levels: Level[] | undefined;\n\n // Evaluate if we should remove the pathway from the penalized list\n const penalizedPathways = this.penalizedPathways;\n const now = performance.now();\n Object.keys(penalizedPathways).forEach((pathwayId) => {\n if (now - penalizedPathways[pathwayId] > PATHWAY_PENALTY_DURATION_MS) {\n delete penalizedPathways[pathwayId];\n }\n });\n for (let i = 0; i < pathwayPriority.length; i++) {\n const pathwayId = pathwayPriority[i];\n if (penalizedPathways[pathwayId]) {\n continue;\n }\n if (pathwayId === this.pathwayId) {\n return;\n }\n const selectedIndex = this.hls.nextLoadLevel;\n const selectedLevel: Level = this.hls.levels[selectedIndex];\n levels = this.getLevelsForPathway(pathwayId);\n if (levels.length > 0) {\n this.log(`Setting Pathway to \"${pathwayId}\"`);\n this.pathwayId = pathwayId;\n this.hls.trigger(Events.LEVELS_UPDATED, { levels });\n // Set LevelController's level to trigger LEVEL_SWITCHING which loads playlist if needed\n const levelAfterChange = this.hls.levels[selectedIndex];\n if (selectedLevel && levelAfterChange && this.levels) {\n if (\n levelAfterChange.attrs['STABLE-VARIANT-ID'] !==\n selectedLevel.attrs['STABLE-VARIANT-ID'] &&\n levelAfterChange.bitrate !== selectedLevel.bitrate\n ) {\n this.log(\n `Unstable Pathways change from bitrate ${selectedLevel.bitrate} to ${levelAfterChange.bitrate}`\n );\n }\n this.hls.nextLoadLevel = selectedIndex;\n }\n break;\n }\n }\n }\n\n private clonePathways(pathwayClones: PathwayClone[]) {\n const levels = this.levels;\n if (!levels) {\n return;\n }\n const audioGroupCloneMap: Record<string, string> = {};\n const subtitleGroupCloneMap: Record<string, string> = {};\n pathwayClones.forEach((pathwayClone) => {\n const {\n ID: cloneId,\n 'BASE-ID': baseId,\n 'URI-REPLACEMENT': uriReplacement,\n } = pathwayClone;\n if (levels.some((level) => level.pathwayId === cloneId)) {\n return;\n }\n const clonedVariants = this.getLevelsForPathway(baseId).map(\n (baseLevel) => {\n const levelParsed: LevelParsed = Object.assign({}, baseLevel as any);\n levelParsed.details = undefined;\n levelParsed.url = performUriReplacement(\n baseLevel.uri,\n baseLevel.attrs['STABLE-VARIANT-ID'],\n 'PER-VARIANT-URIS',\n uriReplacement\n );\n const attributes = new AttrList(baseLevel.attrs);\n attributes['PATHWAY-ID'] = cloneId;\n const clonedAudioGroupId: string | undefined =\n attributes.AUDIO && `${attributes.AUDIO}_clone_${cloneId}`;\n const clonedSubtitleGroupId: string | undefined =\n attributes.SUBTITLES && `${attributes.SUBTITLES}_clone_${cloneId}`;\n if (clonedAudioGroupId) {\n audioGroupCloneMap[attributes.AUDIO] = clonedAudioGroupId;\n attributes.AUDIO = clonedAudioGroupId;\n }\n if (clonedSubtitleGroupId) {\n subtitleGroupCloneMap[attributes.SUBTITLES] = clonedSubtitleGroupId;\n attributes.SUBTITLES = clonedSubtitleGroupId;\n }\n levelParsed.attrs = attributes;\n const clonedLevel = new Level(levelParsed);\n addGroupId(clonedLevel, 'audio', clonedAudioGroupId);\n addGroupId(clonedLevel, 'text', clonedSubtitleGroupId);\n return clonedLevel;\n }\n );\n levels.push(...clonedVariants);\n cloneRenditionGroups(\n this.audioTracks,\n audioGroupCloneMap,\n uriReplacement,\n cloneId\n );\n cloneRenditionGroups(\n this.subtitleTracks,\n subtitleGroupCloneMap,\n uriReplacement,\n cloneId\n );\n });\n }\n\n private loadSteeringManifest(uri: string) {\n const config = this.hls.config;\n const Loader = config.loader;\n if (this.loader) {\n this.loader.destroy();\n }\n this.loader = new Loader(config) as Loader<LoaderContext>;\n\n let url: URL;\n try {\n url = new self.URL(uri);\n } catch (error) {\n this.enabled = false;\n this.log(`Failed to parse Steering Manifest URI: ${uri}`);\n return;\n }\n if (url.protocol !== 'data:') {\n const throughput =\n (this.hls.bandwidthEstimate || config.abrEwmaDefaultEstimate) | 0;\n url.searchParams.set('_HLS_pathway', this.pathwayId);\n url.searchParams.set('_HLS_throughput', '' + throughput);\n }\n const context: LoaderContext = {\n responseType: 'json',\n url: url.href,\n };\n\n const loadPolicy = config.steeringManifestLoadPolicy.default;\n const legacyRetryCompatibility: RetryConfig | Record<string, void> =\n loadPolicy.errorRetry || loadPolicy.timeoutRetry || {};\n const loaderConfig: LoaderConfiguration = {\n loadPolicy,\n timeout: loadPolicy.maxLoadTimeMs,\n maxRetry: legacyRetryCompatibility.maxNumRetry || 0,\n retryDelay: legacyRetryCompatibility.retryDelayMs || 0,\n maxRetryDelay: legacyRetryCompatibility.maxRetryDelayMs || 0,\n };\n\n const callbacks: LoaderCallbacks<LoaderContext> = {\n onSuccess: (\n response: LoaderResponse,\n stats: LoaderStats,\n context: LoaderContext,\n networkDetails: any\n ) => {\n this.log(`Loaded steering manifest: \"${url}\"`);\n const steeringData = response.data as SteeringManifest;\n if (steeringData.VERSION !== 1) {\n this.log(`Steering VERSION ${steeringData.VERSION} not supported!`);\n return;\n }\n this.updated = performance.now();\n this.timeToLoad = steeringData.TTL;\n const {\n 'RELOAD-URI': reloadUri,\n 'PATHWAY-CLONES': pathwayClones,\n 'PATHWAY-PRIORITY': pathwayPriority,\n } = steeringData;\n if (reloadUri) {\n try {\n this.uri = new self.URL(reloadUri, url).href;\n } catch (error) {\n this.enabled = false;\n this.log(\n `Failed to parse Steering Manifest RELOAD-URI: ${reloadUri}`\n );\n return;\n }\n }\n this.scheduleRefresh(this.uri || context.url);\n if (pathwayClones) {\n this.clonePathways(pathwayClones);\n }\n if (pathwayPriority) {\n this.updatePathwayPriority(pathwayPriority);\n }\n },\n\n onError: (\n error: { code: number; text: string },\n context: LoaderContext,\n networkDetails: any,\n stats: LoaderStats\n ) => {\n this.log(\n `Error loading steering manifest: ${error.code} ${error.text} (${context.url})`\n );\n this.stopLoad();\n if (error.code === 410) {\n this.enabled = false;\n this.log(`Steering manifest ${context.url} no longer available`);\n return;\n }\n let ttl = this.timeToLoad * 1000;\n if (error.code === 429) {\n const loader = this.loader;\n if (typeof loader?.getResponseHeader === 'function') {\n const retryAfter = loader.getResponseHeader('Retry-After');\n if (retryAfter) {\n ttl = parseFloat(retryAfter) * 1000;\n }\n }\n this.log(`Steering manifest ${context.url} rate limited`);\n return;\n }\n this.scheduleRefresh(this.uri || context.url, ttl);\n },\n\n onTimeout: (\n stats: LoaderStats,\n context: LoaderContext,\n networkDetails: any\n ) => {\n this.log(`Timeout loading steering manifest (${context.url})`);\n this.scheduleRefresh(this.uri || context.url);\n },\n };\n\n this.log(`Requesting steering manifest: ${url}`);\n this.loader.load(context, loaderConfig, callbacks);\n }\n\n private scheduleRefresh(uri: string, ttlMs: number = this.timeToLoad * 1000) {\n self.clearTimeout(this.reloadTimer);\n this.reloadTimer = self.setTimeout(() => {\n this.loadSteeringManifest(uri);\n }, ttlMs);\n }\n}\n\nfunction cloneRenditionGroups(\n tracks: MediaPlaylist[] | null,\n groupCloneMap: Record<string, string>,\n uriReplacement: UriReplacement,\n cloneId: string\n) {\n if (!tracks) {\n return;\n }\n Object.keys(groupCloneMap).forEach((audioGroupId) => {\n const clonedTracks = tracks\n .filter((track) => track.groupId === audioGroupId)\n .map((track) => {\n const clonedTrack = Object.assign({}, track);\n clonedTrack.details = undefined;\n clonedTrack.attrs = new AttrList(clonedTrack.attrs) as MediaAttributes;\n clonedTrack.url = clonedTrack.attrs.URI = performUriReplacement(\n track.url,\n track.attrs['STABLE-RENDITION-ID'],\n 'PER-RENDITION-URIS',\n uriReplacement\n );\n clonedTrack.groupId = clonedTrack.attrs['GROUP-ID'] =\n groupCloneMap[audioGroupId];\n clonedTrack.attrs['PATHWAY-ID'] = cloneId;\n return clonedTrack;\n });\n tracks.push(...clonedTracks);\n });\n}\n\nfunction performUriReplacement(\n uri: string,\n stableId: string | undefined,\n perOptionKey: 'PER-VARIANT-URIS' | 'PER-RENDITION-URIS',\n uriReplacement: UriReplacement\n): string {\n const {\n HOST: host,\n PARAMS: params,\n [perOptionKey]: perOptionUris,\n } = uriReplacement;\n let perVariantUri;\n if (stableId) {\n perVariantUri = perOptionUris?.[stableId];\n if (perVariantUri) {\n uri = perVariantUri;\n }\n }\n const url = new self.URL(uri);\n if (host && !perVariantUri) {\n url.host = host;\n }\n if (params) {\n Object.keys(params)\n .sort()\n .forEach((key) => {\n if (key) {\n url.searchParams.set(key, params[key]);\n }\n });\n }\n return url.href;\n}\n","import { logger } from '../utils/logger';\nimport type {\n LoaderCallbacks,\n LoaderContext,\n LoaderStats,\n Loader,\n LoaderConfiguration,\n LoaderResponse,\n} from '../types/loader';\nimport { LoadStats } from '../loader/load-stats';\nimport { type HlsConfig, RetryConfig } from '../config';\nimport { getRetryDelay, shouldRetry } from './error-helper';\n\nconst AGE_HEADER_LINE_REGEX = /^age:\\s*[\\d.]+\\s*$/im;\n\nclass XhrLoader implements Loader<LoaderContext> {\n private xhrSetup:\n | ((xhr: XMLHttpRequest, url: string) => Promise<void> | void)\n | null;\n private requestTimeout?: number;\n private retryTimeout?: number;\n private retryDelay: number;\n private config: LoaderConfiguration | null = null;\n private callbacks: LoaderCallbacks<LoaderContext> | null = null;\n public context!: LoaderContext;\n\n private loader: XMLHttpRequest | null = null;\n public stats: LoaderStats;\n\n constructor(config: HlsConfig) {\n this.xhrSetup = config ? config.xhrSetup || null : null;\n this.stats = new LoadStats();\n this.retryDelay = 0;\n }\n\n destroy() {\n this.callbacks = null;\n this.abortInternal();\n this.loader = null;\n this.config = null;\n }\n\n abortInternal() {\n const loader = this.loader;\n self.clearTimeout(this.requestTimeout);\n self.clearTimeout(this.retryTimeout);\n if (loader) {\n loader.onreadystatechange = null;\n loader.onprogress = null;\n if (loader.readyState !== 4) {\n this.stats.aborted = true;\n loader.abort();\n }\n }\n }\n\n abort() {\n this.abortInternal();\n if (this.callbacks?.onAbort) {\n this.callbacks.onAbort(this.stats, this.context, this.loader);\n }\n }\n\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<LoaderContext>\n ) {\n if (this.stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n this.stats.loading.start = self.performance.now();\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.loadInternal();\n }\n\n loadInternal() {\n const { config, context } = this;\n if (!config) {\n return;\n }\n const xhr = (this.loader = new self.XMLHttpRequest());\n\n const stats = this.stats;\n stats.loading.first = 0;\n stats.loaded = 0;\n stats.aborted = false;\n const xhrSetup = this.xhrSetup;\n\n if (xhrSetup) {\n Promise.resolve()\n .then(() => {\n if (this.stats.aborted) return;\n return xhrSetup(xhr, context.url);\n })\n .catch((error: Error) => {\n xhr.open('GET', context.url, true);\n return xhrSetup(xhr, context.url);\n })\n .then(() => {\n if (this.stats.aborted) return;\n this.openAndSendXhr(xhr, context, config);\n })\n .catch((error: Error) => {\n // IE11 throws an exception on xhr.open if attempting to access an HTTP resource over HTTPS\n this.callbacks!.onError(\n { code: xhr.status, text: error.message },\n context,\n xhr,\n stats\n );\n return;\n });\n } else {\n this.openAndSendXhr(xhr, context, config);\n }\n }\n\n openAndSendXhr(\n xhr: XMLHttpRequest,\n context: LoaderContext,\n config: LoaderConfiguration\n ) {\n if (!xhr.readyState) {\n xhr.open('GET', context.url, true);\n }\n\n const headers = this.context.headers;\n const { maxTimeToFirstByteMs, maxLoadTimeMs } = config.loadPolicy;\n if (headers) {\n for (const header in headers) {\n xhr.setRequestHeader(header, headers[header]);\n }\n }\n\n if (context.rangeEnd) {\n xhr.setRequestHeader(\n 'Range',\n 'bytes=' + context.rangeStart + '-' + (context.rangeEnd - 1)\n );\n }\n\n xhr.onreadystatechange = this.readystatechange.bind(this);\n xhr.onprogress = this.loadprogress.bind(this);\n xhr.responseType = context.responseType as XMLHttpRequestResponseType;\n // setup timeout before we perform request\n self.clearTimeout(this.requestTimeout);\n config.timeout =\n maxTimeToFirstByteMs && Number.isFinite(maxTimeToFirstByteMs)\n ? maxTimeToFirstByteMs\n : maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(\n this.loadtimeout.bind(this),\n config.timeout\n );\n xhr.send();\n }\n\n readystatechange() {\n const { context, loader: xhr, stats } = this;\n if (!context || !xhr) {\n return;\n }\n const readyState = xhr.readyState;\n const config = this.config as LoaderConfiguration;\n\n // don't proceed if xhr has been aborted\n if (stats.aborted) {\n return;\n }\n\n // >= HEADERS_RECEIVED\n if (readyState >= 2) {\n if (stats.loading.first === 0) {\n stats.loading.first = Math.max(\n self.performance.now(),\n stats.loading.start\n );\n // readyState >= 2 AND readyState !==4 (readyState = HEADERS_RECEIVED || LOADING) rearm timeout as xhr not finished yet\n if (config.timeout !== config.loadPolicy.maxLoadTimeMs) {\n self.clearTimeout(this.requestTimeout);\n config.timeout = config.loadPolicy.maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(\n this.loadtimeout.bind(this),\n config.loadPolicy.maxLoadTimeMs -\n (stats.loading.first - stats.loading.start)\n );\n }\n }\n\n if (readyState === 4) {\n self.clearTimeout(this.requestTimeout);\n xhr.onreadystatechange = null;\n xhr.onprogress = null;\n const status = xhr.status;\n // http status between 200 to 299 are all successful\n const useResponse = xhr.responseType !== 'text';\n if (\n status >= 200 &&\n status < 300 &&\n ((useResponse && xhr.response) || xhr.responseText !== null)\n ) {\n stats.loading.end = Math.max(\n self.performance.now(),\n stats.loading.first\n );\n const data = useResponse ? xhr.response : xhr.responseText;\n const len =\n xhr.responseType === 'arraybuffer' ? data.byteLength : data.length;\n stats.loaded = stats.total = len;\n stats.bwEstimate =\n (stats.total * 8000) / (stats.loading.end - stats.loading.first);\n if (!this.callbacks) {\n return;\n }\n const onProgress = this.callbacks.onProgress;\n if (onProgress) {\n onProgress(stats, context, data, xhr);\n }\n if (!this.callbacks) {\n return;\n }\n const response: LoaderResponse = {\n url: xhr.responseURL,\n data: data,\n code: status,\n };\n\n this.callbacks.onSuccess(response, stats, context, xhr);\n } else {\n const retryConfig = config.loadPolicy.errorRetry;\n const retryCount = stats.retry;\n // if max nb of retries reached or if http status between 400 and 499 (such error cannot be recovered, retrying is useless), return error\n if (shouldRetry(retryConfig, retryCount, false, status)) {\n this.retry(retryConfig);\n } else {\n logger.error(`${status} while loading ${context.url}`);\n this.callbacks!.onError(\n { code: status, text: xhr.statusText },\n context,\n xhr,\n stats\n );\n }\n }\n }\n }\n }\n\n loadtimeout() {\n const retryConfig = this.config?.loadPolicy.timeoutRetry;\n const retryCount = this.stats.retry;\n if (shouldRetry(retryConfig, retryCount, true)) {\n this.retry(retryConfig);\n } else {\n logger.warn(`timeout while loading ${this.context.url}`);\n const callbacks = this.callbacks;\n if (callbacks) {\n this.abortInternal();\n callbacks.onTimeout(this.stats, this.context, this.loader);\n }\n }\n }\n\n retry(retryConfig: RetryConfig) {\n const { context, stats } = this;\n this.retryDelay = getRetryDelay(retryConfig, stats.retry);\n stats.retry++;\n logger.warn(\n `${status ? 'HTTP Status ' + status : 'Timeout'} while loading ${\n context.url\n }, retrying ${stats.retry}/${retryConfig.maxNumRetry} in ${\n this.retryDelay\n }ms`\n );\n // abort and reset internal state\n this.abortInternal();\n this.loader = null;\n // schedule retry\n self.clearTimeout(this.retryTimeout);\n this.retryTimeout = self.setTimeout(\n this.loadInternal.bind(this),\n this.retryDelay\n );\n }\n\n loadprogress(event: ProgressEvent) {\n const stats = this.stats;\n\n stats.loaded = event.loaded;\n if (event.lengthComputable) {\n stats.total = event.total;\n }\n }\n\n getCacheAge(): number | null {\n let result: number | null = null;\n if (\n this.loader &&\n AGE_HEADER_LINE_REGEX.test(this.loader.getAllResponseHeaders())\n ) {\n const ageHeader = this.loader.getResponseHeader('age');\n result = ageHeader ? parseFloat(ageHeader) : null;\n }\n return result;\n }\n\n getResponseHeader(name: string): string | null {\n if (\n this.loader &&\n new RegExp(`^${name}:\\\\s*[\\\\d.]+\\\\s*$`, 'im').test(\n this.loader.getAllResponseHeaders()\n )\n ) {\n return this.loader.getResponseHeader(name);\n }\n return null;\n }\n}\n\nexport default XhrLoader;\n","import {\n LoaderCallbacks,\n LoaderContext,\n Loader,\n LoaderStats,\n LoaderConfiguration,\n LoaderOnProgress,\n LoaderResponse,\n} from '../types/loader';\nimport { LoadStats } from '../loader/load-stats';\nimport ChunkCache from '../demux/chunk-cache';\n\nexport function fetchSupported() {\n if (\n // @ts-ignore\n self.fetch &&\n self.AbortController &&\n self.ReadableStream &&\n self.Request\n ) {\n try {\n new self.ReadableStream({}); // eslint-disable-line no-new\n return true;\n } catch (e) {\n /* noop */\n }\n }\n return false;\n}\n\nconst BYTERANGE = /(\\d+)-(\\d+)\\/(\\d+)/;\n\nclass FetchLoader implements Loader<LoaderContext> {\n private fetchSetup: Function;\n private requestTimeout?: number;\n private request!: Request;\n private response!: Response;\n private controller: AbortController;\n public context!: LoaderContext;\n private config: LoaderConfiguration | null = null;\n private callbacks: LoaderCallbacks<LoaderContext> | null = null;\n public stats: LoaderStats;\n private loader: Response | null = null;\n\n constructor(config /* HlsConfig */) {\n this.fetchSetup = config.fetchSetup || getRequest;\n this.controller = new self.AbortController();\n this.stats = new LoadStats();\n }\n\n destroy(): void {\n this.loader = this.callbacks = null;\n this.abortInternal();\n }\n\n abortInternal(): void {\n const response = this.response;\n if (!response?.ok) {\n this.stats.aborted = true;\n this.controller.abort();\n }\n }\n\n abort(): void {\n this.abortInternal();\n if (this.callbacks?.onAbort) {\n this.callbacks.onAbort(this.stats, this.context, this.response);\n }\n }\n\n load(\n context: LoaderContext,\n config: LoaderConfiguration,\n callbacks: LoaderCallbacks<LoaderContext>\n ): void {\n const stats = this.stats;\n if (stats.loading.start) {\n throw new Error('Loader can only be used once.');\n }\n stats.loading.start = self.performance.now();\n\n const initParams = getRequestParameters(context, this.controller.signal);\n const onProgress: LoaderOnProgress<LoaderContext> | undefined =\n callbacks.onProgress;\n const isArrayBuffer = context.responseType === 'arraybuffer';\n const LENGTH = isArrayBuffer ? 'byteLength' : 'length';\n const { maxTimeToFirstByteMs, maxLoadTimeMs } = config.loadPolicy;\n\n this.context = context;\n this.config = config;\n this.callbacks = callbacks;\n this.request = this.fetchSetup(context, initParams);\n self.clearTimeout(this.requestTimeout);\n config.timeout =\n maxTimeToFirstByteMs && Number.isFinite(maxTimeToFirstByteMs)\n ? maxTimeToFirstByteMs\n : maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(() => {\n this.abortInternal();\n callbacks.onTimeout(stats, context, this.response);\n }, config.timeout);\n\n self\n .fetch(this.request)\n .then((response: Response): Promise<string | ArrayBuffer> => {\n this.response = this.loader = response;\n\n const first = Math.max(self.performance.now(), stats.loading.start);\n\n self.clearTimeout(this.requestTimeout);\n config.timeout = maxLoadTimeMs;\n this.requestTimeout = self.setTimeout(() => {\n this.abortInternal();\n callbacks.onTimeout(stats, context, this.response);\n }, maxLoadTimeMs - (first - stats.loading.start));\n\n if (!response.ok) {\n const { status, statusText } = response;\n throw new FetchError(\n statusText || 'fetch, bad network response',\n status,\n response\n );\n }\n stats.loading.first = first;\n\n stats.total = getContentLength(response.headers) || stats.total;\n\n if (onProgress && Number.isFinite(config.highWaterMark)) {\n return this.loadProgressively(\n response,\n stats,\n context,\n config.highWaterMark,\n onProgress\n );\n }\n\n if (isArrayBuffer) {\n return response.arrayBuffer();\n }\n if (context.responseType === 'json') {\n return response.json();\n }\n return response.text();\n })\n .then((responseData: string | ArrayBuffer) => {\n const { response } = this;\n self.clearTimeout(this.requestTimeout);\n stats.loading.end = Math.max(\n self.performance.now(),\n stats.loading.first\n );\n const total = responseData[LENGTH];\n if (total) {\n stats.loaded = stats.total = total;\n }\n\n const loaderResponse: LoaderResponse = {\n url: response.url,\n data: responseData,\n code: response.status,\n };\n\n if (onProgress && !Number.isFinite(config.highWaterMark)) {\n onProgress(stats, context, responseData, response);\n }\n\n callbacks.onSuccess(loaderResponse, stats, context, response);\n })\n .catch((error) => {\n self.clearTimeout(this.requestTimeout);\n if (stats.aborted) {\n return;\n }\n // CORS errors result in an undefined code. Set it to 0 here to align with XHR's behavior\n // when destroying, 'error' itself can be undefined\n const code: number = !error ? 0 : error.code || 0;\n const text: string = !error ? null : error.message;\n callbacks.onError(\n { code, text },\n context,\n error ? error.details : null,\n stats\n );\n });\n }\n\n getCacheAge(): number | null {\n let result: number | null = null;\n if (this.response) {\n const ageHeader = this.response.headers.get('age');\n result = ageHeader ? parseFloat(ageHeader) : null;\n }\n return result;\n }\n\n getResponseHeader(name: string): string | null {\n return this.response ? this.response.headers.get(name) : null;\n }\n\n private loadProgressively(\n response: Response,\n stats: LoaderStats,\n context: LoaderContext,\n highWaterMark: number = 0,\n onProgress: LoaderOnProgress<LoaderContext>\n ): Promise<ArrayBuffer> {\n const chunkCache = new ChunkCache();\n const reader = (response.body as ReadableStream).getReader();\n\n const pump = (): Promise<ArrayBuffer> => {\n return reader\n .read()\n .then((data) => {\n if (data.done) {\n if (chunkCache.dataLength) {\n onProgress(stats, context, chunkCache.flush(), response);\n }\n\n return Promise.resolve(new ArrayBuffer(0));\n }\n const chunk: Uint8Array = data.value;\n const len = chunk.length;\n stats.loaded += len;\n if (len < highWaterMark || chunkCache.dataLength) {\n // The current chunk is too small to to be emitted or the cache already has data\n // Push it to the cache\n chunkCache.push(chunk);\n if (chunkCache.dataLength >= highWaterMark) {\n // flush in order to join the typed arrays\n onProgress(stats, context, chunkCache.flush(), response);\n }\n } else {\n // If there's nothing cached already, and the chache is large enough\n // just emit the progress event\n onProgress(stats, context, chunk, response);\n }\n return pump();\n })\n .catch(() => {\n /* aborted */\n return Promise.reject();\n });\n };\n\n return pump();\n }\n}\n\nfunction getRequestParameters(context: LoaderContext, signal): any {\n const initParams: any = {\n method: 'GET',\n mode: 'cors',\n credentials: 'same-origin',\n signal,\n headers: new self.Headers(Object.assign({}, context.headers)),\n };\n\n if (context.rangeEnd) {\n initParams.headers.set(\n 'Range',\n 'bytes=' + context.rangeStart + '-' + String(context.rangeEnd - 1)\n );\n }\n\n return initParams;\n}\n\nfunction getByteRangeLength(byteRangeHeader: string): number | undefined {\n const result = BYTERANGE.exec(byteRangeHeader);\n if (result) {\n return parseInt(result[2]) - parseInt(result[1]) + 1;\n }\n}\n\nfunction getContentLength(headers: Headers): number | undefined {\n const contentRange = headers.get('Content-Range');\n if (contentRange) {\n const byteRangeLength = getByteRangeLength(contentRange);\n if (Number.isFinite(byteRangeLength)) {\n return byteRangeLength;\n }\n }\n const contentLength = headers.get('Content-Length');\n if (contentLength) {\n return parseInt(contentLength);\n }\n}\n\nfunction getRequest(context: LoaderContext, initParams: any): Request {\n return new self.Request(context.url, initParams);\n}\n\nclass FetchError extends Error {\n public code: number;\n public details: any;\n constructor(message: string, code: number, details: any) {\n super(message);\n this.code = code;\n this.details = details;\n }\n}\n\nexport default FetchLoader;\n","import { fixLineBreaks } from './vttparser';\nimport type { CaptionScreen, Row } from './cea-608-parser';\nimport { generateCueId } from './webvtt-parser';\nimport { addCueToTrack } from './texttrack-utils';\n\nconst WHITESPACE_CHAR = /\\s/;\n\nexport interface CuesInterface {\n newCue(\n track: TextTrack | null,\n startTime: number,\n endTime: number,\n captionScreen: CaptionScreen\n ): VTTCue[];\n}\n\nconst Cues: CuesInterface = {\n newCue(\n track: TextTrack | null,\n startTime: number,\n endTime: number,\n captionScreen: CaptionScreen\n ): VTTCue[] {\n const result: VTTCue[] = [];\n let row: Row;\n // the type data states this is VTTCue, but it can potentially be a TextTrackCue on old browsers\n let cue: VTTCue;\n let indenting: boolean;\n let indent: number;\n let text: string;\n const Cue = (self.VTTCue || self.TextTrackCue) as any;\n\n for (let r = 0; r < captionScreen.rows.length; r++) {\n row = captionScreen.rows[r];\n indenting = true;\n indent = 0;\n text = '';\n\n if (!row.isEmpty()) {\n for (let c = 0; c < row.chars.length; c++) {\n if (WHITESPACE_CHAR.test(row.chars[c].uchar) && indenting) {\n indent++;\n } else {\n text += row.chars[c].uchar;\n indenting = false;\n }\n }\n // To be used for cleaning-up orphaned roll-up captions\n row.cueStartTime = startTime;\n\n // Give a slight bump to the endTime if it's equal to startTime to avoid a SyntaxError in IE\n if (startTime === endTime) {\n endTime += 0.0001;\n }\n\n if (indent >= 16) {\n indent--;\n } else {\n indent++;\n }\n\n const cueText = fixLineBreaks(text.trim());\n const id = generateCueId(startTime, endTime, cueText);\n\n // If this cue already exists in the track do not push it\n if (!track?.cues?.getCueById(id)) {\n cue = new Cue(startTime, endTime, cueText);\n cue.id = id;\n cue.line = r + 1;\n cue.align = 'left';\n // Clamp the position between 10 and 80 percent (CEA-608 PAC indent code)\n // https://dvcs.w3.org/hg/text-tracks/raw-file/default/608toVTT/608toVTT.html#positioning-in-cea-608\n // Firefox throws an exception and captions break with out of bounds 0-100 values\n cue.position = 10 + Math.min(80, Math.floor((indent * 8) / 32) * 10);\n result.push(cue);\n }\n }\n }\n if (track && result.length) {\n // Sort bottom cues in reverse order so that they render in line order when overlapping in Chrome\n result.sort((cueA, cueB) => {\n if (cueA.line === 'auto' || cueB.line === 'auto') {\n return 0;\n }\n if (cueA.line > 8 && cueB.line > 8) {\n return cueB.line - cueA.line;\n }\n return cueA.line - cueB.line;\n });\n result.forEach((cue) => addCueToTrack(track, cue));\n }\n return result;\n },\n};\n\nexport default Cues;\n","import AbrController from './controller/abr-controller';\nimport AudioStreamController from './controller/audio-stream-controller';\nimport AudioTrackController from './controller/audio-track-controller';\nimport { SubtitleStreamController } from './controller/subtitle-stream-controller';\nimport SubtitleTrackController from './controller/subtitle-track-controller';\nimport BufferController from './controller/buffer-controller';\nimport { TimelineController } from './controller/timeline-controller';\nimport CapLevelController from './controller/cap-level-controller';\nimport FPSController from './controller/fps-controller';\nimport EMEController, {\n MediaKeySessionContext,\n} from './controller/eme-controller';\nimport CMCDController from './controller/cmcd-controller';\nimport ContentSteeringController from './controller/content-steering-controller';\nimport ErrorController from './controller/error-controller';\nimport XhrLoader from './utils/xhr-loader';\nimport FetchLoader, { fetchSupported } from './utils/fetch-loader';\nimport Cues from './utils/cues';\nimport { requestMediaKeySystemAccess } from './utils/mediakeys-helper';\nimport { ILogger, logger } from './utils/logger';\n\nimport type Hls from './hls';\nimport type { CuesInterface } from './utils/cues';\nimport type { MediaKeyFunc, KeySystems } from './utils/mediakeys-helper';\nimport type {\n FragmentLoaderContext,\n Loader,\n LoaderContext,\n PlaylistLoaderContext,\n} from './types/loader';\n\nexport type ABRControllerConfig = {\n abrEwmaFastLive: number;\n abrEwmaSlowLive: number;\n abrEwmaFastVoD: number;\n abrEwmaSlowVoD: number;\n /**\n * Default bandwidth estimate in bits/s prior to collecting fragment bandwidth samples\n */\n abrEwmaDefaultEstimate: number;\n abrBandWidthFactor: number;\n abrBandWidthUpFactor: number;\n abrMaxWithRealBitrate: boolean;\n maxStarvationDelay: number;\n maxLoadingDelay: number;\n};\n\nexport type BufferControllerConfig = {\n appendErrorMaxRetry: number;\n backBufferLength: number;\n liveDurationInfinity: boolean;\n /**\n * @deprecated use backBufferLength\n */\n liveBackBufferLength: number | null;\n};\n\nexport type CapLevelControllerConfig = {\n capLevelToPlayerSize: boolean;\n};\n\nexport type CMCDControllerConfig = {\n sessionId?: string;\n contentId?: string;\n useHeaders?: boolean;\n};\n\nexport type DRMSystemOptions = {\n audioRobustness?: string;\n videoRobustness?: string;\n audioEncryptionScheme?: string | null;\n videoEncryptionScheme?: string | null;\n persistentState?: MediaKeysRequirement;\n distinctiveIdentifier?: MediaKeysRequirement;\n sessionTypes?: string[];\n sessionType?: string;\n};\n\nexport type DRMSystemConfiguration = {\n licenseUrl: string;\n serverCertificateUrl?: string;\n generateRequest?: (\n this: Hls,\n initDataType: string,\n initData: ArrayBuffer | null,\n keyContext: MediaKeySessionContext\n ) =>\n | { initDataType: string; initData: ArrayBuffer | null }\n | undefined\n | never;\n};\n\nexport type DRMSystemsConfiguration = Partial<\n Record<KeySystems, DRMSystemConfiguration>\n>;\n\nexport type EMEControllerConfig = {\n licenseXhrSetup?: (\n this: Hls,\n xhr: XMLHttpRequest,\n url: string,\n keyContext: MediaKeySessionContext,\n licenseChallenge: Uint8Array\n ) => void | Uint8Array | Promise<Uint8Array | void>;\n licenseResponseCallback?: (\n this: Hls,\n xhr: XMLHttpRequest,\n url: string,\n keyContext: MediaKeySessionContext\n ) => ArrayBuffer;\n emeEnabled: boolean;\n widevineLicenseUrl?: string;\n drmSystems: DRMSystemsConfiguration;\n drmSystemOptions: DRMSystemOptions;\n requestMediaKeySystemAccessFunc: MediaKeyFunc | null;\n};\n\nexport interface FragmentLoaderConstructor {\n new (confg: HlsConfig): Loader<FragmentLoaderContext>;\n}\n\n/**\n * @deprecated use fragLoadPolicy.default\n */\nexport type FragmentLoaderConfig = {\n fragLoadingTimeOut: number;\n fragLoadingMaxRetry: number;\n fragLoadingRetryDelay: number;\n fragLoadingMaxRetryTimeout: number;\n};\n\nexport type FPSControllerConfig = {\n capLevelOnFPSDrop: boolean;\n fpsDroppedMonitoringPeriod: number;\n fpsDroppedMonitoringThreshold: number;\n};\n\nexport type LevelControllerConfig = {\n startLevel?: number;\n};\n\nexport type MP4RemuxerConfig = {\n stretchShortVideoTrack: boolean;\n maxAudioFramesDrift: number;\n};\n\nexport interface PlaylistLoaderConstructor {\n new (confg: HlsConfig): Loader<PlaylistLoaderContext>;\n}\n\n/**\n * @deprecated use manifestLoadPolicy.default and playlistLoadPolicy.default\n */\nexport type PlaylistLoaderConfig = {\n manifestLoadingTimeOut: number;\n manifestLoadingMaxRetry: number;\n manifestLoadingRetryDelay: number;\n manifestLoadingMaxRetryTimeout: number;\n\n levelLoadingTimeOut: number;\n levelLoadingMaxRetry: number;\n levelLoadingRetryDelay: number;\n levelLoadingMaxRetryTimeout: number;\n};\n\nexport type HlsLoadPolicies = {\n fragLoadPolicy: LoadPolicy;\n keyLoadPolicy: LoadPolicy;\n certLoadPolicy: LoadPolicy;\n playlistLoadPolicy: LoadPolicy;\n manifestLoadPolicy: LoadPolicy;\n steeringManifestLoadPolicy: LoadPolicy;\n};\n\nexport type LoadPolicy = {\n default: LoaderConfig;\n};\n\nexport type LoaderConfig = {\n maxTimeToFirstByteMs: number; // Max time to first byte\n maxLoadTimeMs: number; // Max time for load completion\n timeoutRetry: RetryConfig | null;\n errorRetry: RetryConfig | null;\n};\n\nexport type RetryConfig = {\n maxNumRetry: number; // Maximum number of retries\n retryDelayMs: number; // Retry delay = 2^retryCount * retryDelayMs (exponential) or retryCount * retryDelayMs (linear)\n maxRetryDelayMs: number; // Maximum delay between retries\n backoff?: 'exponential' | 'linear'; // used to determine retry backoff duration (see retryDelayMs)\n};\n\nexport type StreamControllerConfig = {\n autoStartLoad: boolean;\n startPosition: number;\n defaultAudioCodec?: string;\n initialLiveManifestSize: number;\n maxBufferLength: number;\n maxBufferSize: number;\n maxBufferHole: number;\n highBufferWatchdogPeriod: number;\n nudgeOffset: number;\n nudgeMaxRetry: number;\n maxFragLookUpTolerance: number;\n maxMaxBufferLength: number;\n startFragPrefetch: boolean;\n testBandwidth: boolean;\n};\n\nexport type LatencyControllerConfig = {\n liveSyncDurationCount: number;\n liveMaxLatencyDurationCount: number;\n liveSyncDuration?: number;\n liveMaxLatencyDuration?: number;\n maxLiveSyncPlaybackRate: number;\n};\n\nexport type MetadataControllerConfig = {\n enableDateRangeMetadataCues: boolean;\n enableEmsgMetadataCues: boolean;\n enableID3MetadataCues: boolean;\n};\n\nexport type TimelineControllerConfig = {\n cueHandler: CuesInterface;\n enableWebVTT: boolean;\n enableIMSC1: boolean;\n enableCEA708Captions: boolean;\n captionsTextTrack1Label: string;\n captionsTextTrack1LanguageCode: string;\n captionsTextTrack2Label: string;\n captionsTextTrack2LanguageCode: string;\n captionsTextTrack3Label: string;\n captionsTextTrack3LanguageCode: string;\n captionsTextTrack4Label: string;\n captionsTextTrack4LanguageCode: string;\n renderTextTracksNatively: boolean;\n};\n\nexport type TSDemuxerConfig = {\n forceKeyFrameOnDiscontinuity: boolean;\n};\n\nexport type HlsConfig = {\n debug: boolean | ILogger;\n enableWorker: boolean;\n workerPath: null | string;\n enableSoftwareAES: boolean;\n minAutoBitrate: number;\n ignoreDevicePixelRatio: boolean;\n loader: { new (confg: HlsConfig): Loader<LoaderContext> };\n fLoader?: FragmentLoaderConstructor;\n pLoader?: PlaylistLoaderConstructor;\n fetchSetup?: (context: LoaderContext, initParams: any) => Request;\n xhrSetup?: (xhr: XMLHttpRequest, url: string) => Promise<void> | void;\n\n // Alt Audio\n audioStreamController?: typeof AudioStreamController;\n audioTrackController?: typeof AudioTrackController;\n // Subtitle\n subtitleStreamController?: typeof SubtitleStreamController;\n subtitleTrackController?: typeof SubtitleTrackController;\n timelineController?: typeof TimelineController;\n // EME\n emeController?: typeof EMEController;\n // CMCD\n cmcd?: CMCDControllerConfig;\n cmcdController?: typeof CMCDController;\n // Content Steering\n contentSteeringController?: typeof ContentSteeringController;\n\n abrController: typeof AbrController;\n bufferController: typeof BufferController;\n capLevelController: typeof CapLevelController;\n errorController: typeof ErrorController;\n fpsController: typeof FPSController;\n progressive: boolean;\n lowLatencyMode: boolean;\n} & ABRControllerConfig &\n BufferControllerConfig &\n CapLevelControllerConfig &\n EMEControllerConfig &\n FPSControllerConfig &\n LevelControllerConfig &\n MP4RemuxerConfig &\n StreamControllerConfig &\n LatencyControllerConfig &\n MetadataControllerConfig &\n TimelineControllerConfig &\n TSDemuxerConfig &\n HlsLoadPolicies &\n FragmentLoaderConfig &\n PlaylistLoaderConfig;\n\nconst defaultLoadPolicy: LoaderConfig = {\n maxTimeToFirstByteMs: 8000,\n maxLoadTimeMs: 20000,\n timeoutRetry: null,\n errorRetry: null,\n};\n\n/**\n * @ignore\n * If possible, keep hlsDefaultConfig shallow\n * It is cloned whenever a new Hls instance is created, by keeping the config\n * shallow the properties are cloned, and we don't end up manipulating the default\n */\nexport const hlsDefaultConfig: HlsConfig = {\n autoStartLoad: true, // used by stream-controller\n startPosition: -1, // used by stream-controller\n defaultAudioCodec: undefined, // used by stream-controller\n debug: false, // used by logger\n capLevelOnFPSDrop: false, // used by fps-controller\n capLevelToPlayerSize: false, // used by cap-level-controller\n ignoreDevicePixelRatio: false, // used by cap-level-controller\n initialLiveManifestSize: 1, // used by stream-controller\n maxBufferLength: 30, // used by stream-controller\n backBufferLength: Infinity, // used by buffer-controller\n maxBufferSize: 60 * 1000 * 1000, // used by stream-controller\n maxBufferHole: 0.1, // used by stream-controller\n highBufferWatchdogPeriod: 2, // used by stream-controller\n nudgeOffset: 0.1, // used by stream-controller\n nudgeMaxRetry: 3, // used by stream-controller\n maxFragLookUpTolerance: 0.25, // used by stream-controller\n liveSyncDurationCount: 3, // used by latency-controller\n liveMaxLatencyDurationCount: Infinity, // used by latency-controller\n liveSyncDuration: undefined, // used by latency-controller\n liveMaxLatencyDuration: undefined, // used by latency-controller\n maxLiveSyncPlaybackRate: 1, // used by latency-controller\n liveDurationInfinity: false, // used by buffer-controller\n /**\n * @deprecated use backBufferLength\n */\n liveBackBufferLength: null, // used by buffer-controller\n maxMaxBufferLength: 600, // used by stream-controller\n enableWorker: true, // used by transmuxer\n workerPath: null, // used by transmuxer\n enableSoftwareAES: true, // used by decrypter\n startLevel: undefined, // used by level-controller\n startFragPrefetch: false, // used by stream-controller\n fpsDroppedMonitoringPeriod: 5000, // used by fps-controller\n fpsDroppedMonitoringThreshold: 0.2, // used by fps-controller\n appendErrorMaxRetry: 3, // used by buffer-controller\n loader: XhrLoader,\n // loader: FetchLoader,\n fLoader: undefined, // used by fragment-loader\n pLoader: undefined, // used by playlist-loader\n xhrSetup: undefined, // used by xhr-loader\n licenseXhrSetup: undefined, // used by eme-controller\n licenseResponseCallback: undefined, // used by eme-controller\n abrController: AbrController,\n bufferController: BufferController,\n capLevelController: CapLevelController,\n errorController: ErrorController,\n fpsController: FPSController,\n stretchShortVideoTrack: false, // used by mp4-remuxer\n maxAudioFramesDrift: 1, // used by mp4-remuxer\n forceKeyFrameOnDiscontinuity: true, // used by ts-demuxer\n abrEwmaFastLive: 3, // used by abr-controller\n abrEwmaSlowLive: 9, // used by abr-controller\n abrEwmaFastVoD: 3, // used by abr-controller\n abrEwmaSlowVoD: 9, // used by abr-controller\n abrEwmaDefaultEstimate: 5e5, // 500 kbps // used by abr-controller\n abrBandWidthFactor: 0.95, // used by abr-controller\n abrBandWidthUpFactor: 0.7, // used by abr-controller\n abrMaxWithRealBitrate: false, // used by abr-controller\n maxStarvationDelay: 4, // used by abr-controller\n maxLoadingDelay: 4, // used by abr-controller\n minAutoBitrate: 0, // used by hls\n emeEnabled: false, // used by eme-controller\n widevineLicenseUrl: undefined, // used by eme-controller\n drmSystems: {}, // used by eme-controller\n drmSystemOptions: {}, // used by eme-controller\n requestMediaKeySystemAccessFunc: __USE_EME_DRM__\n ? requestMediaKeySystemAccess\n : null, // used by eme-controller\n testBandwidth: true,\n progressive: false,\n lowLatencyMode: true,\n cmcd: undefined,\n enableDateRangeMetadataCues: true,\n enableEmsgMetadataCues: true,\n enableID3MetadataCues: true,\n\n certLoadPolicy: {\n default: defaultLoadPolicy,\n },\n keyLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 8000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 20000,\n backoff: 'linear',\n },\n errorRetry: {\n maxNumRetry: 8,\n retryDelayMs: 1000,\n maxRetryDelayMs: 20000,\n backoff: 'linear',\n },\n },\n },\n manifestLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: Infinity,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n playlistLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 2,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n fragLoadPolicy: {\n default: {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 120000,\n timeoutRetry: {\n maxNumRetry: 4,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 6,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n },\n },\n steeringManifestLoadPolicy: {\n default: __USE_CONTENT_STEERING__\n ? {\n maxTimeToFirstByteMs: 10000,\n maxLoadTimeMs: 20000,\n timeoutRetry: {\n maxNumRetry: 2,\n retryDelayMs: 0,\n maxRetryDelayMs: 0,\n },\n errorRetry: {\n maxNumRetry: 1,\n retryDelayMs: 1000,\n maxRetryDelayMs: 8000,\n },\n }\n : defaultLoadPolicy,\n },\n\n // These default settings are deprecated in favor of the above policies\n // and are maintained for backwards compatibility\n manifestLoadingTimeOut: 10000,\n manifestLoadingMaxRetry: 1,\n manifestLoadingRetryDelay: 1000,\n manifestLoadingMaxRetryTimeout: 64000,\n levelLoadingTimeOut: 10000,\n levelLoadingMaxRetry: 4,\n levelLoadingRetryDelay: 1000,\n levelLoadingMaxRetryTimeout: 64000,\n fragLoadingTimeOut: 20000,\n fragLoadingMaxRetry: 6,\n fragLoadingRetryDelay: 1000,\n fragLoadingMaxRetryTimeout: 64000,\n\n // Dynamic Modules\n ...timelineConfig(),\n subtitleStreamController: __USE_SUBTITLES__\n ? SubtitleStreamController\n : undefined,\n subtitleTrackController: __USE_SUBTITLES__\n ? SubtitleTrackController\n : undefined,\n timelineController: __USE_SUBTITLES__ ? TimelineController : undefined,\n audioStreamController: __USE_ALT_AUDIO__ ? AudioStreamController : undefined,\n audioTrackController: __USE_ALT_AUDIO__ ? AudioTrackController : undefined,\n emeController: __USE_EME_DRM__ ? EMEController : undefined,\n cmcdController: __USE_CMCD__ ? CMCDController : undefined,\n contentSteeringController: __USE_CONTENT_STEERING__\n ? ContentSteeringController\n : undefined,\n};\n\nfunction timelineConfig(): TimelineControllerConfig {\n return {\n cueHandler: Cues, // used by timeline-controller\n enableWebVTT: __USE_SUBTITLES__, // used by timeline-controller\n enableIMSC1: __USE_SUBTITLES__, // used by timeline-controller\n enableCEA708Captions: __USE_SUBTITLES__, // used by timeline-controller\n captionsTextTrack1Label: 'English', // used by timeline-controller\n captionsTextTrack1LanguageCode: 'en', // used by timeline-controller\n captionsTextTrack2Label: 'Spanish', // used by timeline-controller\n captionsTextTrack2LanguageCode: 'es', // used by timeline-controller\n captionsTextTrack3Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack3LanguageCode: '', // used by timeline-controller\n captionsTextTrack4Label: 'Unknown CC', // used by timeline-controller\n captionsTextTrack4LanguageCode: '', // used by timeline-controller\n renderTextTracksNatively: true,\n };\n}\n\n/**\n * @ignore\n */\nexport function mergeConfig(\n defaultConfig: HlsConfig,\n userConfig: Partial<HlsConfig>\n): HlsConfig {\n if (\n (userConfig.liveSyncDurationCount ||\n userConfig.liveMaxLatencyDurationCount) &&\n (userConfig.liveSyncDuration || userConfig.liveMaxLatencyDuration)\n ) {\n throw new Error(\n \"Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration\"\n );\n }\n\n if (\n userConfig.liveMaxLatencyDurationCount !== undefined &&\n (userConfig.liveSyncDurationCount === undefined ||\n userConfig.liveMaxLatencyDurationCount <=\n userConfig.liveSyncDurationCount)\n ) {\n throw new Error(\n 'Illegal hls.js config: \"liveMaxLatencyDurationCount\" must be greater than \"liveSyncDurationCount\"'\n );\n }\n\n if (\n userConfig.liveMaxLatencyDuration !== undefined &&\n (userConfig.liveSyncDuration === undefined ||\n userConfig.liveMaxLatencyDuration <= userConfig.liveSyncDuration)\n ) {\n throw new Error(\n 'Illegal hls.js config: \"liveMaxLatencyDuration\" must be greater than \"liveSyncDuration\"'\n );\n }\n\n const defaultsCopy = deepCpy(defaultConfig);\n\n // Backwards compatibility with deprecated config values\n const deprecatedSettingTypes = ['manifest', 'level', 'frag'];\n const deprecatedSettings = [\n 'TimeOut',\n 'MaxRetry',\n 'RetryDelay',\n 'MaxRetryTimeout',\n ];\n deprecatedSettingTypes.forEach((type) => {\n const policyName = `${type === 'level' ? 'playlist' : type}LoadPolicy`;\n const policyNotSet = userConfig[policyName] === undefined;\n const report: string[] = [];\n deprecatedSettings.forEach((setting) => {\n const deprecatedSetting = `${type}Loading${setting}`;\n const value = userConfig[deprecatedSetting];\n if (value !== undefined && policyNotSet) {\n report.push(deprecatedSetting);\n const settings: LoaderConfig = defaultsCopy[policyName].default;\n userConfig[policyName] = { default: settings };\n switch (setting) {\n case 'TimeOut':\n settings.maxLoadTimeMs = value;\n settings.maxTimeToFirstByteMs = value;\n break;\n case 'MaxRetry':\n settings.errorRetry!.maxNumRetry = value;\n settings.timeoutRetry!.maxNumRetry = value;\n break;\n case 'RetryDelay':\n settings.errorRetry!.retryDelayMs = value;\n settings.timeoutRetry!.retryDelayMs = value;\n break;\n case 'MaxRetryTimeout':\n settings.errorRetry!.maxRetryDelayMs = value;\n settings.timeoutRetry!.maxRetryDelayMs = value;\n break;\n }\n }\n });\n if (report.length) {\n logger.warn(\n `hls.js config: \"${report.join(\n '\", \"'\n )}\" setting(s) are deprecated, use \"${policyName}\": ${JSON.stringify(\n userConfig[policyName]\n )}`\n );\n }\n });\n\n return {\n ...defaultsCopy,\n ...userConfig,\n };\n}\n\nfunction deepCpy(obj: any): any {\n if (obj && typeof obj === 'object') {\n if (Array.isArray(obj)) {\n return obj.map(deepCpy);\n }\n return Object.keys(obj).reduce((result, key) => {\n result[key] = deepCpy(obj[key]);\n return result;\n }, {});\n }\n return obj;\n}\n\n/**\n * @ignore\n */\nexport function enableStreamingMode(config) {\n const currentLoader = config.loader;\n if (currentLoader !== FetchLoader && currentLoader !== XhrLoader) {\n // If a developer has configured their own loader, respect that choice\n logger.log(\n '[config]: Custom loader detected, cannot enable progressive streaming'\n );\n config.progressive = false;\n } else {\n const canStreamProgressively = fetchSupported();\n if (canStreamProgressively) {\n config.loader = FetchLoader;\n config.progressive = true;\n config.enableSoftwareAES = true;\n logger.log('[config]: Progressive streaming enabled, using FetchLoader');\n }\n }\n}\n","import { buildAbsoluteURL } from 'url-toolkit';\nimport PlaylistLoader from './loader/playlist-loader';\nimport ID3TrackController from './controller/id3-track-controller';\nimport LatencyController from './controller/latency-controller';\nimport LevelController from './controller/level-controller';\nimport { FragmentTracker } from './controller/fragment-tracker';\nimport KeyLoader from './loader/key-loader';\nimport StreamController from './controller/stream-controller';\nimport { isSupported } from './is-supported';\nimport { logger, enableLogs } from './utils/logger';\nimport { enableStreamingMode, hlsDefaultConfig, mergeConfig } from './config';\nimport { EventEmitter } from 'eventemitter3';\nimport { Events } from './events';\nimport { ErrorTypes, ErrorDetails } from './errors';\nimport { HdcpLevels } from './types/level';\nimport type { HlsEventEmitter, HlsListeners } from './events';\nimport type AudioTrackController from './controller/audio-track-controller';\nimport type AbrController from './controller/abr-controller';\nimport type BufferController from './controller/buffer-controller';\nimport type CapLevelController from './controller/cap-level-controller';\nimport type CMCDController from './controller/cmcd-controller';\nimport type EMEController from './controller/eme-controller';\nimport type SubtitleTrackController from './controller/subtitle-track-controller';\nimport type { ComponentAPI, NetworkComponentAPI } from './types/component-api';\nimport type { MediaPlaylist } from './types/media-playlist';\nimport type { HlsConfig } from './config';\nimport type { HdcpLevel, Level } from './types/level';\nimport type { BufferInfo } from './utils/buffer-helper';\nimport type AudioStreamController from './controller/audio-stream-controller';\nimport type BasePlaylistController from './controller/base-playlist-controller';\nimport type BaseStreamController from './controller/base-stream-controller';\nimport type ContentSteeringController from './controller/content-steering-controller';\nimport type ErrorController from './controller/error-controller';\nimport type FPSController from './controller/fps-controller';\n\n/**\n * The `Hls` class is the core of the HLS.js library used to instantiate player instances.\n * @public\n */\nexport default class Hls implements HlsEventEmitter {\n private static defaultConfig: HlsConfig | undefined;\n\n /**\n * The runtime configuration used by the player. At instantiation this is combination of `hls.userConfig` merged over `Hls.DefaultConfig`.\n */\n public readonly config: HlsConfig;\n\n /**\n * The configuration object provided on player instantiation.\n */\n public readonly userConfig: Partial<HlsConfig>;\n\n private coreComponents: ComponentAPI[];\n private networkControllers: NetworkComponentAPI[];\n private _emitter: HlsEventEmitter = new EventEmitter();\n private _autoLevelCapping: number;\n private _maxHdcpLevel: HdcpLevel = null;\n private abrController: AbrController;\n private bufferController: BufferController;\n private capLevelController: CapLevelController;\n private latencyController: LatencyController;\n private levelController: LevelController;\n private streamController: StreamController;\n private audioTrackController: AudioTrackController;\n private subtitleTrackController: SubtitleTrackController;\n private emeController: EMEController;\n private cmcdController: CMCDController;\n private _media: HTMLMediaElement | null = null;\n private url: string | null = null;\n\n /**\n * Get the video-dev/hls.js package version.\n */\n static get version(): string {\n return __VERSION__;\n }\n\n /**\n * Check if the required MediaSource Extensions are available.\n */\n static isSupported(): boolean {\n return isSupported();\n }\n\n static get Events(): typeof Events {\n return Events;\n }\n\n static get ErrorTypes(): typeof ErrorTypes {\n return ErrorTypes;\n }\n\n static get ErrorDetails(): typeof ErrorDetails {\n return ErrorDetails;\n }\n\n /**\n * Get the default configuration applied to new instances.\n */\n static get DefaultConfig(): HlsConfig {\n if (!Hls.defaultConfig) {\n return hlsDefaultConfig;\n }\n\n return Hls.defaultConfig;\n }\n\n /**\n * Replace the default configuration applied to new instances.\n */\n static set DefaultConfig(defaultConfig: HlsConfig) {\n Hls.defaultConfig = defaultConfig;\n }\n\n /**\n * Creates an instance of an HLS client that can attach to exactly one `HTMLMediaElement`.\n * @param userConfig - Configuration options applied over `Hls.DefaultConfig`\n */\n constructor(userConfig: Partial<HlsConfig> = {}) {\n enableLogs(userConfig.debug || false, 'Hls instance');\n const config = (this.config = mergeConfig(Hls.DefaultConfig, userConfig));\n this.userConfig = userConfig;\n\n this._autoLevelCapping = -1;\n\n if (config.progressive) {\n enableStreamingMode(config);\n }\n\n // core controllers and network loaders\n const {\n abrController: ConfigAbrController,\n bufferController: ConfigBufferController,\n capLevelController: ConfigCapLevelController,\n errorController: ConfigErrorController,\n fpsController: ConfigFpsController,\n } = config;\n const errorController = new ConfigErrorController(this);\n const abrController = (this.abrController = new ConfigAbrController(this));\n const bufferController = (this.bufferController =\n new ConfigBufferController(this));\n const capLevelController = (this.capLevelController =\n new ConfigCapLevelController(this));\n\n const fpsController = new ConfigFpsController(this);\n const playListLoader = new PlaylistLoader(this);\n const id3TrackController = new ID3TrackController(this);\n\n const ConfigContentSteeringController = config.contentSteeringController;\n // ConentSteeringController is defined before LevelController to receive Multivariant Playlist events first\n const contentSteering = ConfigContentSteeringController\n ? new ConfigContentSteeringController(this)\n : null;\n const levelController = (this.levelController = new LevelController(\n this,\n contentSteering\n ));\n // FragmentTracker must be defined before StreamController because the order of event handling is important\n const fragmentTracker = new FragmentTracker(this);\n const keyLoader = new KeyLoader(this.config);\n const streamController = (this.streamController = new StreamController(\n this,\n fragmentTracker,\n keyLoader\n ));\n\n // Cap level controller uses streamController to flush the buffer\n capLevelController.setStreamController(streamController);\n // fpsController uses streamController to switch when frames are being dropped\n fpsController.setStreamController(streamController);\n\n const networkControllers: NetworkComponentAPI[] = [\n playListLoader,\n levelController,\n streamController,\n ];\n if (contentSteering) {\n networkControllers.splice(1, 0, contentSteering);\n }\n\n this.networkControllers = networkControllers;\n const coreComponents: ComponentAPI[] = [\n abrController,\n bufferController,\n capLevelController,\n fpsController,\n id3TrackController,\n fragmentTracker,\n ];\n\n this.audioTrackController = this.createController(\n config.audioTrackController,\n networkControllers\n );\n const AudioStreamControllerClass = config.audioStreamController;\n if (AudioStreamControllerClass) {\n networkControllers.push(\n new AudioStreamControllerClass(this, fragmentTracker, keyLoader)\n );\n }\n // subtitleTrackController must be defined before subtitleStreamController because the order of event handling is important\n this.subtitleTrackController = this.createController(\n config.subtitleTrackController,\n networkControllers\n );\n const SubtitleStreamControllerClass = config.subtitleStreamController;\n if (SubtitleStreamControllerClass) {\n networkControllers.push(\n new SubtitleStreamControllerClass(this, fragmentTracker, keyLoader)\n );\n }\n this.createController(config.timelineController, coreComponents);\n keyLoader.emeController = this.emeController = this.createController(\n config.emeController,\n coreComponents\n );\n this.cmcdController = this.createController(\n config.cmcdController,\n coreComponents\n );\n this.latencyController = this.createController(\n LatencyController,\n coreComponents\n );\n\n this.coreComponents = coreComponents;\n\n // Error controller handles errors before and after all other controllers\n // This listener will be invoked after all other controllers error listeners\n networkControllers.push(errorController);\n const onErrorOut = errorController.onErrorOut;\n if (typeof onErrorOut === 'function') {\n this.on(Events.ERROR, onErrorOut, errorController);\n }\n }\n\n createController(ControllerClass, components) {\n if (ControllerClass) {\n const controllerInstance = new ControllerClass(this);\n if (components) {\n components.push(controllerInstance);\n }\n return controllerInstance;\n }\n return null;\n }\n\n // Delegate the EventEmitter through the public API of Hls.js\n on<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context: Context = this as any\n ) {\n this._emitter.on(event, listener, context);\n }\n\n once<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener: HlsListeners[E],\n context: Context = this as any\n ) {\n this._emitter.once(event, listener, context);\n }\n\n removeAllListeners<E extends keyof HlsListeners>(event?: E | undefined) {\n this._emitter.removeAllListeners(event);\n }\n\n off<E extends keyof HlsListeners, Context = undefined>(\n event: E,\n listener?: HlsListeners[E] | undefined,\n context: Context = this as any,\n once?: boolean | undefined\n ) {\n this._emitter.off(event, listener, context, once);\n }\n\n listeners<E extends keyof HlsListeners>(event: E): HlsListeners[E][] {\n return this._emitter.listeners(event);\n }\n\n emit<E extends keyof HlsListeners>(\n event: E,\n name: E,\n eventObject: Parameters<HlsListeners[E]>[1]\n ): boolean {\n return this._emitter.emit(event, name, eventObject);\n }\n\n trigger<E extends keyof HlsListeners>(\n event: E,\n eventObject: Parameters<HlsListeners[E]>[1]\n ): boolean {\n if (this.config.debug) {\n return this.emit(event, event, eventObject);\n } else {\n try {\n return this.emit(event, event, eventObject);\n } catch (e) {\n logger.error(\n 'An internal error happened while handling event ' +\n event +\n '. Error message: \"' +\n e.message +\n '\". Here is a stacktrace:',\n e\n );\n this.trigger(Events.ERROR, {\n type: ErrorTypes.OTHER_ERROR,\n details: ErrorDetails.INTERNAL_EXCEPTION,\n fatal: false,\n event: event,\n error: e,\n });\n }\n }\n return false;\n }\n\n listenerCount<E extends keyof HlsListeners>(event: E): number {\n return this._emitter.listenerCount(event);\n }\n\n /**\n * Dispose of the instance\n */\n destroy() {\n logger.log('destroy');\n this.trigger(Events.DESTROYING, undefined);\n this.detachMedia();\n this.removeAllListeners();\n this._autoLevelCapping = -1;\n this.url = null;\n\n this.networkControllers.forEach((component) => component.destroy());\n this.networkControllers.length = 0;\n\n this.coreComponents.forEach((component) => component.destroy());\n this.coreComponents.length = 0;\n // Remove any references that could be held in config options or callbacks\n const config = this.config;\n config.xhrSetup = config.fetchSetup = undefined;\n // @ts-ignore\n this.userConfig = null;\n }\n\n /**\n * Attaches Hls.js to a media element\n */\n attachMedia(media: HTMLMediaElement) {\n logger.log('attachMedia');\n this._media = media;\n this.trigger(Events.MEDIA_ATTACHING, { media: media });\n }\n\n /**\n * Detach Hls.js from the media\n */\n detachMedia() {\n logger.log('detachMedia');\n this.trigger(Events.MEDIA_DETACHING, undefined);\n this._media = null;\n }\n\n /**\n * Set the source URL. Can be relative or absolute.\n */\n loadSource(url: string) {\n this.stopLoad();\n const media = this.media;\n const loadedSource = this.url;\n const loadingSource = (this.url = buildAbsoluteURL(\n self.location.href,\n url,\n {\n alwaysNormalize: true,\n }\n ));\n logger.log(`loadSource:${loadingSource}`);\n if (\n media &&\n loadedSource &&\n (loadedSource !== loadingSource || this.bufferController.hasSourceTypes())\n ) {\n this.detachMedia();\n this.attachMedia(media);\n }\n // when attaching to a source URL, trigger a playlist load\n this.trigger(Events.MANIFEST_LOADING, { url: url });\n }\n\n /**\n * Start loading data from the stream source.\n * Depending on default config, client starts loading automatically when a source is set.\n *\n * @param startPosition - Set the start position to stream from.\n * Defaults to -1 (None: starts from earliest point)\n */\n startLoad(startPosition: number = -1) {\n logger.log(`startLoad(${startPosition})`);\n this.networkControllers.forEach((controller) => {\n controller.startLoad(startPosition);\n });\n }\n\n /**\n * Stop loading of any stream data.\n */\n stopLoad() {\n logger.log('stopLoad');\n this.networkControllers.forEach((controller) => {\n controller.stopLoad();\n });\n }\n\n /**\n * Swap through possible audio codecs in the stream (for example to switch from stereo to 5.1)\n */\n swapAudioCodec() {\n logger.log('swapAudioCodec');\n this.streamController.swapAudioCodec();\n }\n\n /**\n * When the media-element fails, this allows to detach and then re-attach it\n * as one call (convenience method).\n *\n * Automatic recovery of media-errors by this process is configurable.\n */\n recoverMediaError() {\n logger.log('recoverMediaError');\n const media = this._media;\n this.detachMedia();\n if (media) {\n this.attachMedia(media);\n }\n }\n\n removeLevel(levelIndex, urlId = 0) {\n this.levelController.removeLevel(levelIndex, urlId);\n }\n\n /**\n * @returns an array of levels (variants) sorted by HDCP-LEVEL, BANDWIDTH, SCORE, and RESOLUTION (height)\n */\n get levels(): Level[] {\n const levels = this.levelController.levels;\n return levels ? levels : [];\n }\n\n /**\n * Index of quality level (variant) currently played\n */\n get currentLevel(): number {\n return this.streamController.currentLevel;\n }\n\n /**\n * Set quality level index immediately. This will flush the current buffer to replace the quality asap. That means playback will interrupt at least shortly to re-buffer and re-sync eventually. Set to -1 for automatic level selection.\n */\n set currentLevel(newLevel: number) {\n logger.log(`set currentLevel:${newLevel}`);\n this.loadLevel = newLevel;\n this.abrController.clearTimer();\n this.streamController.immediateLevelSwitch();\n }\n\n /**\n * Index of next quality level loaded as scheduled by stream controller.\n */\n get nextLevel(): number {\n return this.streamController.nextLevel;\n }\n\n /**\n * Set quality level index for next loaded data.\n * This will switch the video quality asap, without interrupting playback.\n * May abort current loading of data, and flush parts of buffer (outside currently played fragment region).\n * @param newLevel - Pass -1 for automatic level selection\n */\n set nextLevel(newLevel: number) {\n logger.log(`set nextLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n this.streamController.nextLevelSwitch();\n }\n\n /**\n * Return the quality level of the currently or last (of none is loaded currently) segment\n */\n get loadLevel(): number {\n return this.levelController.level;\n }\n\n /**\n * Set quality level index for next loaded data in a conservative way.\n * This will switch the quality without flushing, but interrupt current loading.\n * Thus the moment when the quality switch will appear in effect will only be after the already existing buffer.\n * @param newLevel - Pass -1 for automatic level selection\n */\n set loadLevel(newLevel: number) {\n logger.log(`set loadLevel:${newLevel}`);\n this.levelController.manualLevel = newLevel;\n }\n\n /**\n * get next quality level loaded\n */\n get nextLoadLevel(): number {\n return this.levelController.nextLoadLevel;\n }\n\n /**\n * Set quality level of next loaded segment in a fully \"non-destructive\" way.\n * Same as `loadLevel` but will wait for next switch (until current loading is done).\n */\n set nextLoadLevel(level: number) {\n this.levelController.nextLoadLevel = level;\n }\n\n /**\n * Return \"first level\": like a default level, if not set,\n * falls back to index of first level referenced in manifest\n */\n get firstLevel(): number {\n return Math.max(this.levelController.firstLevel, this.minAutoLevel);\n }\n\n /**\n * Sets \"first-level\", see getter.\n */\n set firstLevel(newLevel: number) {\n logger.log(`set firstLevel:${newLevel}`);\n this.levelController.firstLevel = newLevel;\n }\n\n /**\n * Return start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n */\n get startLevel(): number {\n return this.levelController.startLevel;\n }\n\n /**\n * set start level (level of first fragment that will be played back)\n * if not overrided by user, first level appearing in manifest will be used as start level\n * if -1 : automatic start level selection, playback will start from level matching download bandwidth\n * (determined from download of first segment)\n */\n set startLevel(newLevel: number) {\n logger.log(`set startLevel:${newLevel}`);\n // if not in automatic start level detection, ensure startLevel is greater than minAutoLevel\n if (newLevel !== -1) {\n newLevel = Math.max(newLevel, this.minAutoLevel);\n }\n\n this.levelController.startLevel = newLevel;\n }\n\n /**\n * Whether level capping is enabled.\n * Default value is set via `config.capLevelToPlayerSize`.\n */\n get capLevelToPlayerSize(): boolean {\n return this.config.capLevelToPlayerSize;\n }\n\n /**\n * Enables or disables level capping. If disabled after previously enabled, `nextLevelSwitch` will be immediately called.\n */\n set capLevelToPlayerSize(shouldStartCapping: boolean) {\n const newCapLevelToPlayerSize = !!shouldStartCapping;\n\n if (newCapLevelToPlayerSize !== this.config.capLevelToPlayerSize) {\n if (newCapLevelToPlayerSize) {\n this.capLevelController.startCapping(); // If capping occurs, nextLevelSwitch will happen based on size.\n } else {\n this.capLevelController.stopCapping();\n this.autoLevelCapping = -1;\n this.streamController.nextLevelSwitch(); // Now we're uncapped, get the next level asap.\n }\n\n this.config.capLevelToPlayerSize = newCapLevelToPlayerSize;\n }\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n */\n get autoLevelCapping(): number {\n return this._autoLevelCapping;\n }\n\n /**\n * Returns the current bandwidth estimate in bits per second, when available. Otherwise, `NaN` is returned.\n */\n get bandwidthEstimate(): number {\n const { bwEstimator } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimate();\n }\n\n /**\n * get time to first byte estimate\n * @type {number}\n */\n get ttfbEstimate(): number {\n const { bwEstimator } = this.abrController;\n if (!bwEstimator) {\n return NaN;\n }\n return bwEstimator.getEstimateTTFB();\n }\n\n /**\n * Capping/max level value that should be used by automatic level selection algorithm (`ABRController`)\n */\n set autoLevelCapping(newLevel: number) {\n if (this._autoLevelCapping !== newLevel) {\n logger.log(`set autoLevelCapping:${newLevel}`);\n this._autoLevelCapping = newLevel;\n }\n }\n\n get maxHdcpLevel(): HdcpLevel {\n return this._maxHdcpLevel;\n }\n\n set maxHdcpLevel(value: HdcpLevel) {\n if (HdcpLevels.indexOf(value) > -1) {\n this._maxHdcpLevel = value;\n }\n }\n\n /**\n * True when automatic level selection enabled\n */\n get autoLevelEnabled(): boolean {\n return this.levelController.manualLevel === -1;\n }\n\n /**\n * Level set manually (if any)\n */\n get manualLevel(): number {\n return this.levelController.manualLevel;\n }\n\n /**\n * min level selectable in auto mode according to config.minAutoBitrate\n */\n get minAutoLevel(): number {\n const {\n levels,\n config: { minAutoBitrate },\n } = this;\n if (!levels) return 0;\n\n const len = levels.length;\n for (let i = 0; i < len; i++) {\n if (levels[i].maxBitrate >= minAutoBitrate) {\n return i;\n }\n }\n\n return 0;\n }\n\n /**\n * max level selectable in auto mode according to autoLevelCapping\n */\n get maxAutoLevel(): number {\n const { levels, autoLevelCapping, maxHdcpLevel } = this;\n\n let maxAutoLevel;\n if (autoLevelCapping === -1 && levels && levels.length) {\n maxAutoLevel = levels.length - 1;\n } else {\n maxAutoLevel = autoLevelCapping;\n }\n\n if (maxHdcpLevel) {\n for (let i = maxAutoLevel; i--; ) {\n const hdcpLevel = levels[i].attrs['HDCP-LEVEL'];\n if (hdcpLevel && hdcpLevel <= maxHdcpLevel) {\n return i;\n }\n }\n }\n\n return maxAutoLevel;\n }\n\n /**\n * next automatically selected quality level\n */\n get nextAutoLevel(): number {\n // ensure next auto level is between min and max auto level\n return Math.min(\n Math.max(this.abrController.nextAutoLevel, this.minAutoLevel),\n this.maxAutoLevel\n );\n }\n\n /**\n * this setter is used to force next auto level.\n * this is useful to force a switch down in auto mode:\n * in case of load error on level N, hls.js can set nextAutoLevel to N-1 for example)\n * forced value is valid for one fragment. upon successful frag loading at forced level,\n * this value will be resetted to -1 by ABR controller.\n */\n set nextAutoLevel(nextLevel: number) {\n this.abrController.nextAutoLevel = Math.max(this.minAutoLevel, nextLevel);\n }\n\n /**\n * get the datetime value relative to media.currentTime for the active level Program Date Time if present\n */\n public get playingDate(): Date | null {\n return this.streamController.currentProgramDateTime;\n }\n\n public get mainForwardBufferInfo(): BufferInfo | null {\n return this.streamController.getMainFwdBufferInfo();\n }\n\n /**\n * Get the list of selectable audio tracks\n */\n get audioTracks(): Array<MediaPlaylist> {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTracks : [];\n }\n\n /**\n * index of the selected audio track (index in audio track lists)\n */\n get audioTrack(): number {\n const audioTrackController = this.audioTrackController;\n return audioTrackController ? audioTrackController.audioTrack : -1;\n }\n\n /**\n * selects an audio track, based on its index in audio track lists\n */\n set audioTrack(audioTrackId: number) {\n const audioTrackController = this.audioTrackController;\n if (audioTrackController) {\n audioTrackController.audioTrack = audioTrackId;\n }\n }\n\n /**\n * get alternate subtitle tracks list from playlist\n */\n get subtitleTracks(): Array<MediaPlaylist> {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController\n ? subtitleTrackController.subtitleTracks\n : [];\n }\n\n /**\n * index of the selected subtitle track (index in subtitle track lists)\n */\n get subtitleTrack(): number {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController ? subtitleTrackController.subtitleTrack : -1;\n }\n\n get media() {\n return this._media;\n }\n\n /**\n * select an subtitle track, based on its index in subtitle track lists\n */\n set subtitleTrack(subtitleTrackId: number) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleTrack = subtitleTrackId;\n }\n }\n\n /**\n * Whether subtitle display is enabled or not\n */\n get subtitleDisplay(): boolean {\n const subtitleTrackController = this.subtitleTrackController;\n return subtitleTrackController\n ? subtitleTrackController.subtitleDisplay\n : false;\n }\n\n /**\n * Enable/disable subtitle display rendering\n */\n set subtitleDisplay(value: boolean) {\n const subtitleTrackController = this.subtitleTrackController;\n if (subtitleTrackController) {\n subtitleTrackController.subtitleDisplay = value;\n }\n }\n\n /**\n * get mode for Low-Latency HLS loading\n */\n get lowLatencyMode(): boolean {\n return this.config.lowLatencyMode;\n }\n\n /**\n * Enable/disable Low-Latency HLS part playlist and segment loading, and start live streams at playlist PART-HOLD-BACK rather than HOLD-BACK.\n */\n set lowLatencyMode(mode: boolean) {\n this.config.lowLatencyMode = mode;\n }\n\n /**\n * Position (in seconds) of live sync point (ie edge of live position minus safety delay defined by ```hls.config.liveSyncDuration```)\n * @returns null prior to loading live Playlist\n */\n get liveSyncPosition(): number | null {\n return this.latencyController.liveSyncPosition;\n }\n\n /**\n * Estimated position (in seconds) of live edge (ie edge of live playlist plus time sync playlist advanced)\n * @returns 0 before first playlist is loaded\n */\n get latency(): number {\n return this.latencyController.latency;\n }\n\n /**\n * maximum distance from the edge before the player seeks forward to ```hls.liveSyncPosition```\n * configured using ```liveMaxLatencyDurationCount``` (multiple of target duration) or ```liveMaxLatencyDuration```\n * @returns 0 before first playlist is loaded\n */\n get maxLatency(): number {\n return this.latencyController.maxLatency;\n }\n\n /**\n * target distance from the edge as calculated by the latency controller\n */\n get targetLatency(): number | null {\n return this.latencyController.targetLatency;\n }\n\n /**\n * the rate at which the edge of the current live playlist is advancing or 1 if there is none\n */\n get drift(): number | null {\n return this.latencyController.drift;\n }\n\n /**\n * set to true when startLoad is called before MANIFEST_PARSED event\n */\n get forceStartLoad(): boolean {\n return this.streamController.forceStartLoad;\n }\n}\n\nexport type {\n MediaPlaylist,\n ErrorDetails,\n ErrorTypes,\n Events,\n Level,\n HlsListeners,\n HlsEventEmitter,\n HlsConfig,\n BufferInfo,\n HdcpLevels,\n HdcpLevel,\n AbrController,\n AudioStreamController,\n AudioTrackController,\n BasePlaylistController,\n BaseStreamController,\n BufferController,\n CapLevelController,\n CMCDController,\n ContentSteeringController,\n EMEController,\n ErrorController,\n FPSController,\n SubtitleTrackController,\n};\nexport type {\n ComponentAPI,\n AbrComponentAPI,\n NetworkComponentAPI,\n} from './types/component-api';\nexport type {\n ABRControllerConfig,\n BufferControllerConfig,\n CapLevelControllerConfig,\n CMCDControllerConfig,\n EMEControllerConfig,\n DRMSystemsConfiguration,\n DRMSystemOptions,\n FPSControllerConfig,\n FragmentLoaderConfig,\n FragmentLoaderConstructor,\n HlsLoadPolicies,\n LevelControllerConfig,\n LoaderConfig,\n LoadPolicy,\n MP4RemuxerConfig,\n PlaylistLoaderConfig,\n PlaylistLoaderConstructor,\n RetryConfig,\n StreamControllerConfig,\n LatencyControllerConfig,\n MetadataControllerConfig,\n TimelineControllerConfig,\n TSDemuxerConfig,\n} from './config';\nexport type { MediaKeySessionContext } from './controller/eme-controller';\nexport type { ILogger } from './utils/logger';\nexport type { SubtitleStreamController } from './controller/subtitle-stream-controller';\nexport type { TimelineController } from './controller/timeline-controller';\nexport type { CuesInterface } from './utils/cues';\nexport type {\n MediaKeyFunc,\n KeySystems,\n KeySystemFormats,\n} from './utils/mediakeys-helper';\nexport type { DateRange } from './loader/date-range';\nexport type { LoadStats } from './loader/load-stats';\nexport type { LevelKey } from './loader/level-key';\nexport type { LevelDetails } from './loader/level-details';\nexport type { SourceBufferName } from './types/buffer';\nexport type {\n MetadataSample,\n MetadataSchema,\n UserdataSample,\n} from './types/demuxer';\nexport type {\n HlsSkip,\n HlsUrlParameters,\n LevelAttributes,\n LevelParsed,\n VariableMap,\n} from './types/level';\nexport type {\n PlaylistLevelType,\n HlsChunkPerformanceTiming,\n HlsPerformanceTiming,\n HlsProgressivePerformanceTiming,\n PlaylistContextType,\n PlaylistLoaderContext,\n FragmentLoaderContext,\n Loader,\n LoaderStats,\n LoaderContext,\n LoaderResponse,\n LoaderConfiguration,\n LoaderCallbacks,\n LoaderOnProgress,\n LoaderOnAbort,\n LoaderOnError,\n LoaderOnSuccess,\n LoaderOnTimeout,\n} from './types/loader';\nexport type {\n MediaAttributes,\n MediaPlaylistType,\n MainPlaylistType,\n AudioPlaylistType,\n SubtitlePlaylistType,\n} from './types/media-playlist';\nexport type { Track, TrackSet } from './types/track';\nexport type { ChunkMetadata } from './types/transmuxer';\nexport type {\n BaseSegment,\n Fragment,\n Part,\n ElementaryStreams,\n ElementaryStreamTypes,\n ElementaryStreamInfo,\n} from './loader/fragment';\nexport type {\n TrackLoadingData,\n TrackLoadedData,\n AudioTrackLoadedData,\n AudioTracksUpdatedData,\n AudioTrackSwitchedData,\n AudioTrackSwitchingData,\n BackBufferData,\n BufferAppendedData,\n BufferAppendingData,\n BufferCodecsData,\n BufferCreatedData,\n BufferEOSData,\n BufferFlushedData,\n BufferFlushingData,\n CuesParsedData,\n ErrorData,\n FPSDropData,\n FPSDropLevelCappingData,\n FragBufferedData,\n FragChangedData,\n FragDecryptedData,\n FragLoadedData,\n FragLoadEmergencyAbortedData,\n FragLoadingData,\n FragParsedData,\n FragParsingInitSegmentData,\n FragParsingMetadataData,\n FragParsingUserdataData,\n InitPTSFoundData,\n KeyLoadedData,\n KeyLoadingData,\n LevelLoadedData,\n LevelLoadingData,\n LevelPTSUpdatedData,\n LevelsUpdatedData,\n LevelSwitchedData,\n LevelSwitchingData,\n LevelUpdatedData,\n LiveBackBufferData,\n ContentSteeringOptions,\n ManifestLoadedData,\n ManifestLoadingData,\n ManifestParsedData,\n MediaAttachedData,\n MediaAttachingData,\n NonNativeTextTrack,\n NonNativeTextTracksData,\n SubtitleFragProcessedData,\n SubtitleTrackLoadedData,\n SubtitleTracksUpdatedData,\n SubtitleTrackSwitchData,\n} from './types/events';\nexport type {\n NetworkErrorAction,\n ErrorActionFlags,\n IErrorAction,\n} from './controller/error-controller';\nexport type { AttrList } from './utils/attr-list';\n"],"names":["URL_REGEX","FIRST_SEGMENT_REGEX","SLASH_DOT_REGEX","SLASH_DOT_DOT_REGEX","URLToolkit","buildAbsoluteURL","baseURL","relativeURL","opts","trim","alwaysNormalize","basePartsForNormalise","parseURL","Error","path","normalizePath","buildURLFromParts","relativeParts","scheme","baseParts","netLoc","pathParts","exec","builtParts","params","query","fragment","baseURLPath","newPath","substring","lastIndexOf","url","parts","split","reverse","join","replace","length","module","exports","isFiniteNumber","Number","isFinite","value","isSafeInteger","Math","abs","MAX_SAFE_INTEGER","Events","ErrorTypes","ErrorDetails","noop","fakeLogger","trace","debug","log","warn","info","error","exportedLogger","consolePrintFn","type","func","self","console","bind","enableLogs","debugConfig","id","_len","arguments","functions","Array","_key","forEach","exportLoggerFunctions","e","logger","DECIMAL_RESOLUTION_REGEX","ATTR_LIST_REGEX","AttrList","attrs","attr","parseAttrList","hasOwnProperty","this","clientAttrs","push","_proto","prototype","decimalInteger","attrName","intValue","parseInt","Infinity","hexadecimalInteger","stringValue","slice","Uint8Array","i","hexadecimalIntegerAsNumber","decimalFloatingPoint","parseFloat","optionalFloat","defaultValue","enumeratedString","bool","decimalResolution","res","width","height","input","match","lastIndex","indexOf","isSCTE35Attribute","DateRange","dateRangeAttr","dateRangeWithSameId","_startDate","_endDate","_badValueForSameId","previousAttr","key","Object","call","ID","_extends","Date","endDate","_isFiniteNumber","getTime","_createClass","get","CLASS","duration","_isFiniteNumber2","_isFiniteNumber3","startDate","endOnNext","class","LoadStats","aborted","loaded","retry","total","chunkCount","bwEstimate","loading","start","first","end","parsing","buffering","ElementaryStreamTypes","BaseSegment","baseurl","_this$elementaryStrea","_byteRange","_url","relurl","elementaryStreams","setByteRange","previous","byteRange","byteRangeEndOffset","set","Fragment","_BaseSegment","_this","_decryptdata","rawProgramDateTime","programDateTime","tagList","sn","levelkeys","loader","keyLoader","level","cc","startPTS","endPTS","startDTS","endDTS","deltaPTS","maxStartPTS","minEndPTS","stats","urlId","data","bitrateTest","title","initSegment","endList","gap","_inheritsLoose","_proto2","setKeyFormat","keyFormat","getDecryptData","abortRequests","_this$loader","_this$keyLoader","abort","setElementaryStreamInfo","partial","min","max","clearElementaryStreamInfo","NONE","identity","keyFormats","keys","_this$_decryptdata","encrypted","len","Part","_BaseSegment2","partAttrs","frag","index","_this2","fragOffset","independent","audio","video","audiovideo","LevelDetails","baseUrl","PTSKnown","alignedSliding","averagetargetduration","endCC","endSN","fragments","fragmentHint","partList","dateRanges","live","ageHeader","advancedDateTime","updated","advanced","availabilityDelay","misses","startCC","startSN","startTimeOffset","targetduration","totalduration","m3u8","version","canBlockReload","canSkipUntil","canSkipDateRanges","skippedSegments","recentlyRemovedDateranges","partHoldBack","holdBack","partTarget","preloadHint","renditionReports","tuneInGoal","deltaUpdateFailed","driftStartTime","driftEndTime","driftStart","driftEnd","encryptedFragments","playlistParsingError","variableList","hasVariableRefs","reloaded","partSnDiff","lastPartSn","partIndexDiff","lastPartIndex","floor","runTime","partEnd","fragmentEnd","_this$partList","_this$fragments","now","_this$partList2","_this$partList3","base64Decode","base64encodedStr","from","atob","c","charCodeAt","convertDataUriToArrayBytes","uri","keyIdbytes","paddedkeyIdbytes","colonsplit","keydata","semicolonsplit","commasplit","isbase64","splice","strToUtf8array","subarray","str","unescape","encodeURIComponent","KeySystems","CLEARKEY","FAIRPLAY","PLAYREADY","WIDEVINE","KeySystemFormats","keySystemFormatToKeySystemDomain","format","KeySystemIds","keySystemDomainToKeySystemFormat","keySystem","getKeySystemsForConfig","config","drmSystems","widevineLicenseUrl","keySystemsToAttempt","filter","requestMediaKeySystemAccess","navigator","sliceUint8","array","decoder","isHeader","offset","isFooter","getID3Data","front","readSize","size","canParse","isTimeStampFrame","frame","getFrameData","String","fromCharCode","getID3Frames","id3Data","frames","frameData","decodeFrame","decodePrivFrame","decodeURLFrame","decodeTextFrame","owner","utf8ArrayToStr","privateData","buffer","description","text","readTimeStamp","timeStampFrame","byteLength","pts33Bit","timestamp","round","exitOnNull","getTextDecoder","decoded","decode","idx","char2","char3","out","userAgent","includes","TextDecoder","Hex","h","toString","UINT32_MAX","pow","RemuxerTrackIdConfig","id3","bin2str","apply","readUint16","val","readUint32","readSint32","writeUint32","findBox","results","endbox","subresults","parseSegmentIndex","sidx","references","timescale","startByte","referencesCount","referenceIndex","referenceInfo","referenceSize","subsegmentDuration","earliestPresentationTime","parseInitSegment","result","traks","trak","tkhd","trackId","mdhd","hdlr","hdlrType","soun","vide","stsd","codec","trex","track","default","flags","parseSinf","sinf","schm","computeRawDurationFromSamples","trun","sampleCount","appendUint8Array","data1","data2","temp","parseSamples","timeOffset","seiSamples","videoData","samples","isHEVCFlavor","map","moof","moofOffset","byteOffset","traf","baseTime","tfdt","undefined","tfhd","tfhdFlags","defaultSampleDuration","defaultSampleSizePresent","defaultSampleSize","defaultSampleFlagsPresent","tfhdOffset","delimit","baseCodec","isHEVC","dataOffsetPresent","dataOffset","firstSampleFlagsPresent","sampleDurationPresent","sampleDuration","sampleSizePresent","sampleSize","sampleFlagsPresent","sampleCompositionOffsetsPresent","compositionOffset","trunOffset","sampleOffset","ix","naluTotalSize","naluSize","isSEIMessage","parseSEIMessageFromNALu","naluHeader","naluType","unescapedData","headerSize","pts","discardEPB","seiPtr","payloadType","payloadSize","endOfCaptions","b","leftOver","providerCode","userStructure","userDataType","firstByte","enabled","totalBytes","byteArray","bytes","uuidStrArray","userDataBytes","uuid","userData","EPBPositions","newLength","newData","sourceIndex","shift","mp4pssh","systemId","keyids","RangeError","kids","kidCount","k","DataView","setUint32","dataSize","payload","mp4Box","keyUriToKeyIdMap","LevelKey","method","formatversions","iv","keyFormatVersions","isCommonEncryption","keyId","pssh","clearKeyUriToKeyIdMap","isSupported","segmentNumber","uint8View","createInitializationVector","keyBytes","PlayReadyKeySystemUUID","keyBytesUtf16","Uint16Array","keyByteStr","xmlKeyBytes","keyData","DOMParser","parseFromString","getElementsByTagName","childNodes","nodeValue","getAttribute","keyIdArray","swap","to","cur","changeEndianness","padded","VARIABLE_REPLACEMENT_REGEX","hasVariableReferences","test","substituteVariablesInAttributes","parsed","attributeNames","name","substituteVariables","variableReference","variableName","variableValue","addVariableDefinition","parentUrl","NAME","VALUE","QUERYPARAM","searchParams","URL","has","message","importVariableDefinition","sourceVariableList","IMPORT","getMediaSource","MediaSource","WebKitMediaSource","sampleEntryCodesISO","a3ds","alac","alaw","dra1","dtsc","dtse","dtsh","enca","g719","g726","m4ae","mha1","mha2","mhm1","mhm2","mlpa","mp4a","Opus","opus","samr","sawb","sawp","sevc","sqcp","ssmv","twos","ulaw","avc1","avc2","avc3","avc4","avcp","av01","drac","dva1","dvav","dvh1","dvhe","encv","hev1","hvc1","mjp2","mp4v","mvc1","mvc2","mvc3","mvc4","resv","rv60","s263","svc1","svc2","vp08","vp09","stpp","wvtt","isCodecSupportedInMp4","_MediaSource$isTypeSu","isTypeSupported","MASTER_PLAYLIST_REGEX","MASTER_PLAYLIST_MEDIA_REGEX","IS_MEDIA_PLAYLIST","LEVEL_PLAYLIST_REGEX_FAST","RegExp","source","LEVEL_PLAYLIST_REGEX_SLOW","M3U8Parser","findGroup","groups","mediaGroupId","group","convertAVC1ToAVCOTI","avcdata","resolve","isMediaPlaylist","parseMasterPlaylist","string","contentSteering","levels","sessionData","sessionKeys","levelsWithKnownCodecs","_level$unknownCodecs","bitrate","resolution","setCodecs","CODECS","videoCodec","unknownCodecs","tag","attributes","sessionAttrs","dataId","sessionKey","parseKey","variableAttributes","contentSteeringAttributes","pathwayId","parseStartTimeOffset","stripUnknownCodecLevels","parseMasterPlaylistMedia","groupsByType","AUDIO","audioCodec","SUBTITLES","textCodec","TYPE","medias","media","groupId","instreamId","LANGUAGE","autoselect","forced","lang","URI","groupCodec","assignCodec","parseLevelPlaylist","levelUrlId","multivariantVariableList","currentInitSegment","currentSN","currentPart","discontinuityCounter","prevFrag","firstPdtIndex","createNextFrag","setFragLevelKeys","assignProgramDateTime","value1","value2","toUpperCase","skipAttrs","unshift","dateRange","isValid","levelKey","mapAttrs","init","setInitSegment","serverControlAttrs","partInfAttrs","previousFragmentPart","part","preloadHintAttrs","renditionReportAttrs","pop","fragmentLength","firstFragment","lastFragment","lastSn","fragPrev","backfillProgramDateTimes","keyTagAttributes","_keyAttrs$METHOD","_keyAttrs$KEYFORMAT","keyAttrs","decryptmethod","METHOD","decrypturi","decryptiv","decryptkeyformatversions","KEYFORMATVERSIONS","decryptkeyformat","KEYFORMAT","IV","resolvedUri","startAttributes","codecs","filtered","typeCodes","isCodecType","preferred","groupItem","codecProperty","codecValue","parse","endProgramDateTime","_isFiniteNumber4","BYTERANGE","some","PlaylistContextType","PlaylistLevelType","mapContextToLevelType","context","getResponseUrl","response","PlaylistLoader","hls","loaders","create","registerListeners","startLoad","startPosition","stopLoad","destroyInternalLoaders","on","MANIFEST_LOADING","onManifestLoading","LEVEL_LOADING","onLevelLoading","AUDIO_TRACK_LOADING","onAudioTrackLoading","SUBTITLE_TRACK_LOADING","onSubtitleTrackLoading","unregisterListeners","off","createInternalLoader","PLoader","pLoader","Loader","getInternalLoader","resetInternalLoader","contextType","destroy","event","load","responseType","deliveryDirectives","_context$deliveryDire","loadPolicy","levelDetails","loaderContext","manifestLoadPolicy","playlistLoadPolicy","timeoutRetry","errorRetry","details","audioTracks","subtitleTracks","targetDuration","maxLowLatencyPlaylistRefresh","maxTimeToFirstByteMs","maxLoadTimeMs","legacyRetryCompatibility","loaderConfig","timeout","maxRetry","maxNumRetry","retryDelay","retryDelayMs","maxRetryDelay","maxRetryDelayMs","loaderCallbacks","onSuccess","networkDetails","performance","handleTrackOrLevelPlaylist","handleMasterPlaylist","handleManifestParsingError","onError","handleNetworkError","onTimeout","parsedResult","_M3U8Parser$parseMast","_M3U8Parser$parseMast2","subtitles","captions","audioTrack","trigger","MANIFEST_LOADED","levelId","levelType","singleLevel","handlePlaylistLoaded","ERROR","NETWORK_ERROR","MANIFEST_PARSING_ERROR","fatal","err","reason","code","UNKNOWN","MANIFEST_LOAD_TIMEOUT","MANIFEST_LOAD_ERROR","LEVEL_LOAD_TIMEOUT","LEVEL_LOAD_ERROR","AUDIO_TRACK_LOAD_TIMEOUT","AUDIO_TRACK_LOAD_ERROR","SUBTITLE_TRACK_LOAD_TIMEOUT","SUBTITLE_LOAD_ERROR","errorData","_objectSpread","parent","levelIndex","LEVEL_PARSING_ERROR","getCacheAge","isNaN","LEVEL_LOADED","AUDIO_TRACK_LOADED","SUBTITLE_TRACK_LOADED","LEVEL_EMPTY_ERROR","sendAddTrackEvent","videoEl","Event","document","createEvent","initEvent","dispatchEvent","addCueToTrack","cue","mode","cues","getCueById","addCue","textTrackCue","TextTrackCue","startTime","endTime","err2","clearCurrentCues","removeCue","removeCuesInRange","predicate","cuesFound","firstCueInRange","time","left","right","mid","getFirstCueIndexAfterTime","getCuesInRange","MetadataSchema","getCueClass","VTTCue","createCueWithDataFields","Cue","JSON","stringify","MAX_CUE_ENDTIME","POSITIVE_INFINITY","MAX_VALUE","dateRangeDateToTimelineSeconds","date","ID3TrackController","id3Track","dateRangeCuesAppended","_registerListeners","_unregisterListeners","MEDIA_ATTACHED","onMediaAttached","MEDIA_DETACHING","onMediaDetaching","FRAG_PARSING_METADATA","onFragParsingMetadata","BUFFER_FLUSHING","onBufferFlushing","LEVEL_UPDATED","onLevelUpdated","createTrack","getID3Track","textTracks","textTrack","kind","label","addTextTrack","_this$hls$config","enableEmsgMetadataCues","enableID3MetadataCues","ID3","j","updateId3CueEnds","_this$id3Track","_ref","startOffset","endOffset","_hls$config","_ref2","hasProgramDateTime","enableDateRangeMetadataCues","ids","idsToRemove","_loop","dateTimeOffset","_loop2","appendedDateRangeCues","durationKnown","nextDateRangeWithSameClass","reduce","filterMapArray","candidate","sort","a","LatencyController","currentTime","stallCount","_latency","timeupdateHandler","timeupdate","addEventListener","removeEventListener","_this$levelDetails","BUFFER_STALLED_ERROR","latency","computeLatency","_this$config","lowLatencyMode","maxLiveSyncPlaybackRate","targetLatency","distanceFromTarget","inLiveRange","maxLatency","forwardBufferLength","rate","exp","edgeStalled","playbackRate","estimateLiveEdge","edge","age","liveEdge","liveMaxLatencyDuration","liveMaxLatencyDurationCount","_this$config2","liveSyncDuration","liveSyncDurationCount","userConfig","maxLiveSyncOnStallIncrease","syncPosition","drift","maxLevelUpdateAge","bufferedRanges","buffered","HdcpLevels","HlsSkip","HlsUrlParameters","msn","skip","addDirectives","href","Level","_attrs","codecSet","audioGroupIds","fragmentError","loadError","realBitrate","textGroupIds","_urlId","addFallback","newValue","_this$audioGroupIds","_this$textGroupIds","updateFromToPTS","fragFrom","fragTo","fragToPTS","updateFragPTSDTS","fragStartPts","fragEndPts","fragIdx","mergeDetails","oldDetails","newDetails","oldFragments","oldInit","PTSFrag","oldDateRanges","deltaDateRanges","ccOffset","intersectionFn","delta","newFrags","concat","oldFrags","oldFrag","newFrag","mapFragmentIntersection","_isFiniteNumber5","_currentInitSegment","newFragments","oldParts","newParts","oldPart","newPart","mapPartIntersection","adjustSliding","addSliding","getPartWith","partIndex","_level$details","findPart","isTimeoutError","FRAG_LOAD_TIMEOUT","KEY_LOAD_TIMEOUT","getRetryConfig","isTimeout","getRetryDelay","retryConfig","retryCount","backoffFactor","backoff","getLoaderConfigWithoutReties","loderConfig","shouldRetry","httpStatus","onLine","retryForHttpStatus","BinarySearch","list","comparisonFn","minIndex","maxIndex","currentIndex","currentElement","comparisonResult","findFragmentByPTS","fragPrevious","bufferEnd","maxFragLookUpTolerance","fragNext","fragmentWithinToleranceTest","foundFragment","candidateLookupTolerance","pdtWithinToleranceTest","pdtBufferEnd","chromeOrFirefox","RENDITION_PENALTY_DURATION_MS","NetworkErrorAction","ErrorActionFlags","ErrorController","playlistError","penalizedRenditions","onErrorOut","getVariantLevelIndex","loadLevel","_data$frag","_data$level","FRAG_LOAD_ERROR","KEY_LOAD_ERROR","errorAction","getFragRetryOrSwitchAction","FRAG_PARSING_ERROR","action","FRAG_GAP","FRAG_DECRYPT_ERROR","_data$context","_data$context$levelDe","getPlaylistRetryOrSwitchAction","levelRetry","getLevelSwitchAction","audioGroupId","textGroupId","KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED","restrictedHdcpLevel","hdcpLevel","BUFFER_ADD_CODEC_ERROR","REMUX_ALLOC_ERROR","INTERNAL_EXCEPTION","BUFFER_APPENDING_ERROR","BUFFER_APPEND_ERROR","BUFFER_FULL_ERROR","LEVEL_SWITCH_ERROR","BUFFER_SEEK_OVER_HOLE","BUFFER_NUDGE_ON_STALL","KEY_SYSTEM_ERROR","_data$response","variantLevelIndex","fragLoadPolicy","keyLoadPolicy","startsWith","fragmentErrors","acc","_data$response2","autoLevelEnabled","_data$frag2","_data$context2","nextLevel","minAutoLevel","maxAutoLevel","fragErrorType","playlistErrorType","playlistErrorGroupId","levelCandidate","fragCandidate","nextAutoLevel","_data$errorAction","sendAlternateToPenaltyBox","resolved","switchLevel","redundantFailover","maxHdcpLevel","nextLoadLevel","redundantLevels","errorUrlId","penalizeRendition","newUrlId","penalizedRendition","currentPenaltyState","lastErrorPerfMs","lastErrorDetails","position","candidateFrag","errors","lastCandidateError","checkExpired","lv","v","_ret","BasePlaylistController","logPrefix","timer","requestScheduled","canLoad","clearTimer","clearTimeout","loadPlaylist","switchParams","playlistUri","foundIndex","currentGoal","hlsUrlParameters","shouldLoadPlaylist","playlist","shouldReloadPlaylist","playlistLoaded","previousDetails","elapsed","endSn","lastPart","lastAdvanced","cdnAge","segments","toFixed","getDeliveryDirectives","bufferInfo","mainForwardBufferInfo","reloadInterval","distanceToLiveEdgeMs","lastSegmentDuration","computeReloadInterval","estimatedTimeUntilUpdate","setTimeout","previousDeliveryDirectives","getSkipValue","checkRetry","errorEvent","errorDetails","_ref$retryCount","_errorEvent$context","delay","LevelController","_BasePlaylistControll","contentSteeringController","_levels","_firstLevel","_startLevel","currentLevel","currentLevelIndex","manualLevelIndex","steering","onParsedComplete","onManifestLoaded","onLevelLoaded","LEVELS_UPDATED","onLevelsUpdated","AUDIO_TRACK_SWITCHED","onAudioTrackSwitched","FRAG_LOADED","onFragLoaded","resetLevels","levelFromSet","levelSet","levelParsed","_levelParsed$audioCod","FRAMERATE","PATHWAY","RESOLUTION","addGroupId","filterAndSortMediaOptions","unfilteredLevels","resolutionFound","videoCodecFound","audioCodecFound","assignTrackIdsByGroup","unsortedLevels","SCORE","firstLevelInPlaylist","filterParsedLevels","audioOnly","edata","firstLevel","altAudio","t","MANIFEST_PARSED","autoStartLoad","forceStartLoad","Promise","then","MEDIA_ERROR","MANIFEST_INCOMPATIBLE_CODECS_ERROR","_ref3","_data$deliveryDirecti2","_data$deliveryDirecti","curLevel","removeLevel","_this3","filterLevelAndGroupByIdIndex","_ref4","newLevel","OTHER_ERROR","lastLevelIndex","lastLevel","lastPathwayId","levelSwitchingData","maxBitrate","LEVEL_SWITCHING","configStartLevel","startLevel","tracks","FragmentState","FragmentTracker","activePartLists","endListFragments","timeRanges","bufferPadding","hasGaps","BUFFER_APPENDED","onBufferAppended","FRAG_BUFFERED","onFragBuffered","getAppendedFrag","activeParts","activePart","appendedPTS","getBufferedFrag","fragmentEntity","body","detectEvictedFragments","elementaryStream","timeRange","playlistType","appendedPart","appendedPartSn","esData","range","isNotBuffered","isTimeBuffered","removeFragment","detectPartialFragments","fragKey","getFragmentKey","isFragHint","streamInfo","getBufferedTimes","isPartial","removeParts","snToKeep","fragBuffered","force","getPartialFragment","timePadding","bestFragment","bestOverlap","isEndListAppended","lastFragmentEntity","getState","hasFragment","hasParts","_this$activePartLists","removeFragmentsInRange","withGapOnly","unbufferedOnly","_this4","snToRemove","removeAllFragments","_fragmentEntity$range","_fragmentEntity$range2","_fragmentEntity$range3","MIN_CHUNK_SIZE","FragmentLoader","partLoadTimeout","onProgress","reject","LoadError","FragmentILoader","fLoader","DefaultILoader","tags","createGapLoadError","createLoaderContext","highWaterMark","resetLoader","resetIV","decryptdata","onAbort","INTERNAL_ABORTED","loadPart","updateStatsFromPart","partLoadedData","fragStats","partStats","partTotal","estTotalParts","estLoadedParts","estRemainingBytes","fragLoading","partLoading","segment","headers","rangeStart","rangeEnd","byteRangeStartOffset","_frag$decryptdata","byteRangeStart","byteRangeEnd","fragmentLen","_Error","_wrapNativeSuper","KeyLoader","keyUriToKeyInfo","emeController","detach","keyInfo","mediaKeySessionContext","createKeyLoadError","loadClear","loadingFrag","emeEnabled","selectKeySystemFormat","keySystemFormat","loadInternal","_keyInfo","_keyInfo2","_keyInfo$mediaKeySess","keyLoadPromise","keyStatus","keyLoadedData","loadKeyHTTP","loadKeyEME","keySessionContextPromise","loadKey","keySessionContext","catch","TaskLoop","_boundTick","_tickTimer","_tickInterval","_tickCallCount","tick","onHandlerDestroying","onHandlerDestroyed","clearNextTick","clearInterval","hasInterval","hasNextTick","setInterval","millis","doTick","tickImmediate","noopBuffered","BufferHelper","isBuffered","getBuffered","pos","maxHoleDuration","vbuffered","bufferedInfo","nextStart","diff","buffered2","buf2len","buf2end","bufferStartNext","bufferLen","bufferStart","ChunkMetadata","transmuxing","executeStart","executeEnd","findFirstFragWithCC","firstFrag","currentFrag","adjustFragmentStart","sliding","adjustSlidingStart","alignStream","lastFrag","shouldAlignOnDiscontinuities","referenceFrag","prevDetails","curDetails","prevFrags","curFrags","prevStartFrag","findDiscontinuousReferenceFrag","alignDiscontinuities","lastDetails","lastPDT","newPDT","alignPDT","alignMediaPlaylistByPDT","refDetails","refFragments","refFrag","refPDT","targetPDT","AESCrypto","subtle","aesIV","decrypt","FastAESKey","expandKey","importKey","AESDecryptor","rcon","subMix","Uint32Array","invSubMix","sBox","invSBox","ksRows","keySize","keySchedule","invKeySchedule","initTable","uint8ArrayToUint32Array_","arrayBuffer","view","newArray","getUint32","subMix0","subMix1","subMix2","subMix3","invSubMix0","invSubMix1","invSubMix2","invSubMix3","d","x","xi","sx","x2","x4","x8","keyBuffer","sameKey","ksRow","invKsRow","prev","sbox","networkToHostOrderSwap","word","inputArrayBuffer","t0","t1","t2","t3","s0","s1","s2","s3","inputWords0","inputWords1","inputWords2","inputWords3","nRounds","invSBOX","initVector","initVector0","initVector1","initVector2","initVector3","inputInt32","Int32Array","outputInt32","swapWord","Decrypter","_temp","_ref$removePKCS7Paddi","removePKCS7Padding","logEnabled","softwareDecrypter","fastAesKey","remainderData","currentIV","currentResult","useSoftware","enableSoftwareAES","browserCrypto","crypto","webkitSubtle","isSync","flush","reset","outputBytes","paddingBytes","getUint8","softwareDecrypt","decryptResult","webCryptoDecrypt","logOnce","currentChunk","getValidChunk","aesKey","onWebCryptoError","splitPoint","msg","TimeRanges","r","State","BaseStreamController","_TaskLoop","fragmentTracker","fragCurrent","transmuxer","_state","mediaBuffer","lastCurrentTime","nextLoadPosition","loadedmetadata","retryDate","fragmentLoader","levelLastLoaded","startFragRequested","decrypter","initPTS","onvseeking","onvended","_assertThisInitialized","onTickEnd","resetTransmuxer","state","_streamEnded","getLevelDetails","_this$levels$this$lev","onMediaSeeking","onMediaEnded","ended","maxBufferHole","resetLoadingState","tolerance","fragStartOffset","fragEndOffset","pastFragment","loadFragment","targetBufferTime","_loadFragForPlayback","_doFragLoad","fragContextChanged","_handleFragmentLoadProgress","_handleFragmentLoadComplete","resetFragmentLoading","clearTrackerIfNeeded","_this$mediaBuffer","getFwdBufferInfo","minForwardBufferLength","maxBufferLength","reduceMaxBufferLength","checkLiveUpdate","flushMainBuffer","flushScope","_loadInitSegment","decryptData","decryptedData","FRAG_DECRYPTED","tstart","tdecrypt","fragBufferedComplete","_frag$startPTS","_frag$endPTS","_this$fragCurrent","_this$fragPrevious","NaN","seekToStartPos","fragLoadedEndData","partsLoaded","complete","fragLoaded","chunkMeta","progressCallback","keyLoadingPromise","KEY_LOADED","KEY_LOADING","getNextPart","doFragPartsLoad","handleFragLoadError","FRAG_LOADING","loadedEndOfParts","dataOnProgress","progressive","all","fragLoadedData","fromPart","_this5","initialPartList","loadedPart","nextPart","handleFragLoadAborted","_handleTransmuxerFlush","getCurrentContext","updateLevelTiming","getFragmentWithSN","bufferFragmentData","noBacktracking","_buffer","BUFFER_APPENDING","dropped","flushBufferGap","fragDuration","segmentFraction","bufferable","getLoadPosition","getFwdBufferInfoAtPos","bufferedFragAtPos","getMaxBufferLength","levelBitrate","maxBufLen","maxBufferSize","maxMaxBufferLength","threshold","minLength","fragOrPart","getNextFragment","fragLen","initialLiveManifestSize","getInitialLiveFragment","liveSyncPosition","getFragmentAtPosition","mapToInitFragWhenRequired","isLoopLoading","trackerState","getNextFragmentLoopLoading","gapStart","nextFragment","nextbufferInfo","contiguous","independentAttrOmitted","PDTValue","isArray","seg","findFragmentByPDT","targetSN","findFragWithCC","liveStart","loadingParts","curSNIdx","fragState","nextFrag","synchronizeToLiveEdge","withinSlidingWindow","readyState","alignPlaylists","slidingStart","firstLevelLoad","aligned","alignedSlidingStart","waitForCdnTuneIn","setStartPosition","offsetInMultivariantPlaylist","onFragmentOrKeyLoadError","filterType","_this$fragCurrent2","gapTagEncountered","_ref2$retryCount","_this$levelLastLoaded","resetStartWhenNotLoaded","resetFragmentErrors","reduceLengthAndFlushBuffer","flushBuffer","afterBufferFlushed","bufferType","bufferedTimeRanges","resetWhenMissingContext","_this$levelLastLoaded2","removeUnbufferedFrags","_this$transmuxer","_this6","parsedDuration","LEVEL_PTS_UPDATED","FRAG_PARSED","recoverWorkerError","_this$levelLastLoaded3","_this$fragCurrent3","nextState","previousState","getSourceBuffer","SourceBuffer","WebKitSourceBuffer","dummyTrack","inputTimeScale","pid","sequenceNumber","BaseAudioDemuxer","_audioTrack","_id3Track","frameIndex","cachedData","basePTS","lastPTS","resetInitSegment","trackDuration","resetTimeStamp","deaultTimestamp","resetContiguity","appendFrame","demux","lastDataIndex","initPTSFn","dts","sample","partialData","videoTrack","demuxSampleAes","isHeaderPattern","getHeaderLength","getFullFrameLength","probe","headerLength","frameLength","newOffset","initTrackConfig","observer","samplerate","adtsObjectType","adtsExtensionSamplingIndex","adtsChannelConfig","toLowerCase","manifestCodec","adtsSamplingRates","adtsSamplingIndex","channelCount","getAudioConfig","getFrameDuration","unit","stamp","header","parseFrameHeader","missing","AACDemuxer","_BaseAudioDemuxer","container","segmentCodec","ADTS","canGetFrameLength","emsgSchemePattern","MP4Demuxer","txtTrack","captionTrack","initData","_initData$video","_initData$audio","videoSamples","segmentedData","segmentedRange","valid","remainder","moofs","last","segmentValidRange","extractID3Track","emsgs","emsgInfo","schemeIdUri","timeScale","presentationTimeDelta","presentationTime","eventDuration","leftPresentationTime","rightPresentationTime","_isSafeInteger","parseEmsg","chromeVersion","BitratesMap","SamplingRateMap","SamplesCoefficients","BytesInSlot","parseHeader","samplesPerFrame","sampleRate","mpegVersion","mpegLayer","bitRateIndex","sampleRateIndex","paddingBit","channelMode","bitRate","sampleCoefficient","bytesInSlot","ExpGolomb","bytesAvailable","bitsAvailable","loadWord","workingBytes","availableBytes","skipBits","count","skipBytes","readBits","bits","valu","skipLZ","leadingZeroCount","skipUEG","skipEG","readUEG","clz","readEG","readBoolean","readUByte","readUShort","readUInt","skipScalingList","lastScale","nextScale","readSPS","numRefFramesInPicOrderCntCycle","scalingListCount","frameCropLeftOffset","frameCropRightOffset","frameCropTopOffset","frameCropBottomOffset","profileIdc","chromaFormatIdc","picOrderCntType","picWidthInMbsMinus1","picHeightInMapUnitsMinus1","frameMbsOnlyFlag","pixelRatio","ceil","readSliceType","SampleAesDecrypter","decryptBuffer","encryptedData","decryptAacSample","sampleIndex","callback","curUnit","encryptedBuffer","decryptedBuffer","decryptAacSamples","getAvcEncryptedData","decodedData","encryptedDataLen","Int8Array","outputPos","inputPos","getAvcDecryptedUnit","uint8DecryptedData","decryptAvcSample","unitIndex","decryptAvcSamples","curUnits","units","PACKET_LENGTH","TSDemuxer","typeSupported","sampleAes","pmtParsed","_duration","_pmtId","_avcTrack","_txtTrack","aacOverFlow","avcSample","syncOffset","scanwindow","foundPat","packetStart","tsPackets","parsePID","pesData","isSampleAes","pes","avcId","avcData","audioId","id3Id","audioData","unknownPID","pmtId","tsPacketErrors","stt","parsePES","parseAVCPES","parseAACPES","parseMPEGPES","parseID3PES","parsePAT","parsedPIDs","parsePMT","avc","emit","demuxResult","extractRemainingSamples","parseAVCNALu","spsfound","audFound","pushAccessUnit","createAVCSample","_avcSample2","iskey","_avcSample","sliceType","sps","codecarray","codecstring","pps","getLastNalUnit","_avcSample3","lastUnit","overflow","naluState","lastState","lastUnitStart","lastUnitType","tmp","frameMissingBytes","sampleLength","frameOverflowBytes","recoverable","frameDuration","MpegAudio","id3Sample","tableEnd","mpeg","mp3","stream","pesLen","pesHdrLen","pesPts","pesDts","pesFlags","payloadStartOffset","dataLen","avcTrack","nbSamples","lastSample","MP3Demuxer","AAC","getSilentFrame","MP4","types","avcC","btrt","dinf","dref","esds","ftyp","mdat","mdia","mfhd","minf","moov","mvex","mvhd","pasp","sdtp","stbl","stco","stsc","stsz","stts","vmhd","smhd","videoHdlr","audioHdlr","HDLR_TYPES","STTS","STSC","STCO","STSZ","VMHD","SMHD","STSD","majorBrand","avc1Brand","minorVersion","FTYP","box","DINF","upperWordDuration","lowerWordDuration","baseMediaDecodeTime","boxes","dependsOn","isDependedOn","hasRedundancy","avcc","hSpacing","vSpacing","configlen","sampleDependencyTable","upperWordBaseMediaDecodeTime","lowerWordBaseMediaDecodeTime","cts","arraylen","isLeading","paddingValue","isNonSync","degradPrio","movie","toTimescaleFromBase","destScale","srcBase","toMsFromMpegTsClock","safariWebkitVersion","MP4Remuxer","vendor","ISGenerated","_initPTS","_initDTS","nextAvcDts","nextAudioPts","videoSampleDuration","isAudioContiguous","isVideoContiguous","defaultTimeStamp","resetNextTimestamp","getVideoStartPts","rolloverDetected","minPTS","normalizePts","remux","accurateTimeOffset","audioTimeOffset","videoTimeOffset","hasAudio","hasVideo","enoughAudioSamples","enoughVideoSamples","generateIS","firstKeyFramePTS","firstKeyFrameIndex","findKeyframeIndex","forceKeyFrameOnDiscontinuity","audiovideoTimestampDelta","remuxAudio","audioTrackLength","remuxVideo","firstKeyFrame","flushTextTrackMetadataCueSamples","flushTextTrackUserdataCueSamples","initDTS","audioSamples","computePTSDTS","metadata","firstDTS","lastDTS","inputSamples","outputSamples","mp4SampleDuration","maxPTS","NEGATIVE_INFINITY","sortSamples","initTime","deltadts","deltapts","inputDuration","averageSampleDuration","foundHole","foundOverlap","firstPTS","nbNalu","naluLen","nbUnits","sampleLen","mdatSize","MUX_ERROR","stretchedLastFrame","minDtsDelta","minPtsDelta","maxDtsDelta","maxPtsDelta","avcSampleUnits","mp4SampleLength","unitData","unitDataLen","ptsDelta","lastFrameDuration","stretchShortVideoTrack","gapTolerance","deltaToFrameEnd","compositionTimeOffset","Mp4Sample","nextDts","nextPts","nb","scaleFactor","inputSampleDuration","rawMPEG","alignedWithVideo","timeOffsetMpegTS","maxAudioFramesDrift","newStamp","fillFrame","audioSample","unitLen","remuxEmptyAudio","init90kHz","silentFrame","reference","isKeyframe","Mp4SampleFlags","PassThroughRemuxer","emitInitSegment","initTracks","lastEndTime","defaultInitPTS","generateInitSegment","sampleEntries","encBoxes","isAudio","enc","tenc","tencKeyId","patchEncyptionData","getParsedTrackCodec","_initData","_initData2","rawDuration","videoDuration","audioDuration","trafs","trackDefault","truns","sidxDuration","sidxs","dur","ref","getDuration","fmp4","getStartDTS","decodeTime","minDuration","isInvalidInitPts","upper","lower","offsetStartDTS","parsedCodec","muxConfig","Transmuxer","async","demuxer","remuxer","decryptionPromise","transmuxConfig","currentTransmuxState","configure","uintData","discontinuity","trackSwitch","initSegmentChange","defaultInitPts","initSegmentData","encryptionType","getEncryptionType","getDecrypter","emptyResult","resetMuxers","needsProbing","configureTransmuxer","resetInitialTimestamp","transmux","currentState","transmuxResults","demuxResultOrPromise","isPromise","flushRemux","_this$currentTransmux","remuxResult","transmuxSampleAes","transmuxUnencrypted","_demux","mux","Remuxer","Demuxer","p","Function","TransmuxConfig","TransmuxState","prefix","EE","fn","once","addListener","emitter","TypeError","listener","evt","_events","_eventsCount","clearEvent","EventEmitter","__proto__","eventNames","events","names","getOwnPropertySymbols","listeners","handlers","l","ee","listenerCount","a1","a2","a3","a4","a5","args","removeListener","removeAllListeners","prefixed","emitTransmuxComplete","transmuxResult","transferable","_transmuxResult$remux","addToTransferable","postMessage","handleFlushResult","__IN_WORKER__","forwardMessage","ev","forwardWorkerLogs","logFn","logType","cmd","startWorker","TransmuxerInterface","onTransmuxComplete","onFlush","useWorker","workerContext","onwmsg","enableWorker","blob","objectURL","scriptURL","mp4","Worker","workerPath","location","worker","Blob","__HLS_WORKER_BUNDLE__","createObjectURL","onWorkerMessage","onerror","filename","lineno","resetWorker","_this$workerContext","revokeObjectURL","terminate","_frag$initSegment","_lastFrag$initSegment","snDiff","partDiff","ArrayBuffer","handleTransmuxComplete","transmuxerError","_this$workerContext2","GapController","nudgeRetry","stallReported","stalled","moved","seeking","poll","activeFrag","seeked","beginSeek","paused","hasEnoughBuffer","noBufferGap","startJump","maxStartGapJump","partialOrGap","_trySkipBufferHole","tnow","stalledDuration","_reportStall","bufferedWithHoles","_tryFixBufferStall","stalledDurationMs","highBufferWatchdogPeriod","_tryNudgeBuffer","bufferStarved","waiting","gapLength","startGap","startFrag","startProvisioned","moreToLoad","provisioned","targetTime","nudgeMaxRetry","nudgeOffset","StreamController","_BaseStreamController","audioCodecSwap","gapController","_forceStartLoad","fragPlaying","onvplaying","onvseeked","fragLastKbps","couldBacktrack","backtrackFragment","audioCodecSwitch","videoBuffer","onManifestParsed","FRAG_LOAD_EMERGENCY_ABORTED","onFragLoadEmergencyAborted","AUDIO_TRACK_SWITCHING","onAudioTrackSwitching","BUFFER_CREATED","onBufferCreated","BUFFER_FLUSHED","onBufferFlushed","testBandwidth","_levels$level","_this$media","doTickIdle","checkBuffer","checkFragmentChanged","startFragPrefetch","levelInfo","getMainFwdBufferInfo","BUFFER_EOS","manualLevel","_this$backtrackFragme","backtrackFrag","_loadBitrateTestFrag","followingBufferedFrag","immediateLevelSwitch","abortCurrentFrag","nextLevelSwitch","fetchdelay","fragPlayingCurrent","bufferedFrag","nextBufferedFrag","maxStart","startPts","onMediaPlaying","onMediaSeeked","BUFFER_RESET","_sourceBuffer$prototy","sourceBuffer","aac","heaac","changeType","_curLevel$details","newLevelId","_getAudioCodec","_handleTransmuxComplete","fromAltAudio","mediaTrack","alternate","swapAudioCodec","defaultAudioCodec","_id3$samples","mapFragment","_bufferInitSegment","FRAG_PARSING_INIT_SEGMENT","INIT_PTS_FOUND","isFirstFragment","isFirstInDiscontinuity","backtrack","emittedID3","emittedText","FRAG_PARSING_USERDATA","ua","levelCodec","BUFFER_CODECS","trackName","fragCurrentLevel","FRAG_CHANGED","LEVEL_SWITCHED","epocMs","EWMA","halfLife","estimate","weight","alpha_","estimate_","totalWeight_","adjAlpha","getTotalWeight","getEstimate","zeroFactor","EwmaBandWidthEstimator","slow","fast","defaultEstimate","defaultTTFB","defaultEstimate_","minWeight_","minDelayMs_","slow_","fast_","defaultTTFB_","ttfb_","update","durationMs","numBytes","durationS","bandwidthInBps","sampleTTFB","ttfb","seconds","sqrt","canEstimate","getEstimateTTFB","AbrController","lastLevelLoadSec","lastLoadedFragLevel","_nextAutoLevel","onCheck","_abandonRulesCheck","partCurrent","bitrateTestDelay","bwEstimator","abrEwmaSlowVoD","abrEwmaFastVoD","abrEwmaDefaultEstimate","onFragLoading","onLevelSwitching","_data$part","ignoreFragment","getTimeToLoadFrag","timeToFirstByteSec","bandwidth","fragSizeBits","isSwitch","_data$stats","abrEwmaSlowLive","abrEwmaFastLive","timeLoading","ttfbEstimate","bufferStarvationDelay","loadedFirstByte","expectedLen","timeStreaming","loadRate","fragLoadedDelay","bwe","fragLevelNextLoadedDelay","levelNextBitrate","abrMaxWithRealBitrate","loadedBytes","loadedDuration","fragBufferedData","processingMs","getNextABRAutoLevel","currentFragDuration","avgbw","bestLevel","findBestLevel","abrBandWidthFactor","abrBandWidthUpFactor","maxStarvationDelay","bwFactor","bwUpFactor","maxLoadingDelay","currentBw","maxFetchDuration","currentCodecSet","ttfbEstimateSec","levelSkippedMin","levelSkippedMax","avgDuration","adjustedbw","fetchDuration","forcedAutoLevel","nextABRAutoLevel","ChunkCache","chunks","dataLength","chunk","concatUint8Arrays","AudioStreamController","videoTrackCC","waitingVideoCC","bufferedTrack","switchingTrack","waitingData","mainDetails","bufferFlushed","cachedTrackLoadedData","AUDIO_TRACKS_UPDATED","onAudioTracksUpdated","onAudioTrackLoaded","onBufferReset","onInitPtsFound","_levels$trackId","cache","clearWaitingFragment","trackDetails","mainBufferInfo","atGap","atBufferSyncLimit","mainFrag","mainBufferLength","maxConfigBuffer","mediaPlaylist","_track$details","completeAudioSwitch","_track$details2","bufferedAttributes","switchAttributes","CHANNELS","AudioTrackController","tracksInGroup","currentTrack","selectDefaultTrack","trackInActiveGroup","audioTracksUpdated","selectInitialTrack","setAudioTrack","newId","lastTrack","findTrackId","subtitleOptionsIdentical","trackList1","trackList2","subtitleAttributesIdentical","attrs1","attrs2","stableRenditionId","subtitleAttribute","SubtitleStreamController","currentTrackId","tracksBuffered","SUBTITLE_TRACKS_UPDATED","onSubtitleTracksUpdated","SUBTITLE_TRACK_SWITCH","onSubtitleTrackSwitch","onSubtitleTrackLoaded","SUBTITLE_FRAG_PROCESSED","onSubtitleFragProcessed","success","fragStart","fragEnd","endOffsetSubtitles","mediaBufferTimeRanges","mainSlidingStartFragment","levelTargetDuration","foundFrag","lookupTolerance","BufferableInstance","timeranges","getRange","DOMException","SubtitleTrackController","queuedDefaultTrack","trackChangeListener","onTextTracksChanged","asyncPollTrackChange","pollTrackChange","useTextTrackPolling","subtitlePollingInterval","_subtitleDisplay","subtitleTrack","filterSubtitleTracks","initialTrackId","subtitleTracksUpdated","setSubtitleTrack","toggleTrackModes","groupTracks","oldTrack","nextTrack","subtitleDisplay","_tracks$newId","_track$groupId","renderTextTracksNatively","textTrackList","BufferOperationQueue","sourceBufferReference","buffers","queues","append","operation","queue","executeNext","insertAbort","appendBlocker","execute","promise","onStart","onComplete","sb","updating","shiftAndExecuteNext","current","VIDEO_CODEC_PROFILE_REPACE","BufferController","_objectUrl","operationQueue","bufferCodecEventsExpected","_bufferCodecEventsTotal","mediaSource","lastMpegAudioChunk","appendError","pendingTracks","_onMediaSourceOpen","_onMediaEmptied","updateMediaElementDuration","checkPendingTracks","_onMediaSourceClose","_onMediaSourceEnded","src","_initSourceBuffer","hasSourceTypes","getSourceBufferTypes","MEDIA_ATTACHING","onMediaAttaching","onBufferAppending","onBufferCodecs","onBufferEos","onFragParsed","onFragChanged","codecEvents","ms","endOfStream","removeAttribute","MEDIA_DETACHED","removeBufferListeners","removeSourceBuffer","sourceBufferCount","_data$trackName","currentCodec","nextCodec","mimeType","appendChangeType","eventData","chunkStats","bufferAppendingStart","fragBuffering","partBuffering","checkTimestampOffset","timestampOffset","appendExecutor","QUOTA_EXCEEDED_ERR","appendErrorMaxRetry","flushOperation","removeExecutor","_this7","buffersAppendedTo","blockBuffers","flushBackBuffer","_this8","ending","sourceBufferTypes","backBufferLength","liveBackBufferLength","maxBackBufferLength","targetBackBufferPosition","BACK_BUFFER_REACHED","LIVE_BACK_BUFFER_REACHED","levelDuration","mediaDuration","msDuration","liveDurationInfinity","updateSeekableRange","setLiveSeekableRange","pendingTracksCount","createSourceBuffers","BUFFER_INCOMPATIBLE_CODECS_ERROR","addSourceBuffer","sbName","addBufferListener","_onSBUpdateStart","_onSBUpdateEnd","_onSBUpdateError","removeStart","removeEnd","remove","appendBuffer","onUnblocked","_this9","blockingOperations","specialCea608CharsCodes","getCharForByte","byte","charCode","NR_ROWS","NR_COLS","rowsLowCh1","rowsHighCh1","rowsLowCh2","rowsHighCh2","backgroundColors","CaptionsLogger","verboseLevel","severity","m","numArrayToHexArray","numArray","hexArray","PenState","foreground","underline","italics","background","flash","setStyles","styles","attribs","style","isDefault","equals","other","copy","newPenState","StyledUnicodeChar","uchar","penState","_proto3","setChar","setPenState","newChar","isEmpty","Row","chars","currPenState","cueStartTime","_proto4","equal","empty","setCursor","absPos","moveCursor","relPos","newPos","backSpace","insertChar","char","clearFromPos","startPos","clear","clearToEndOfRow","getTextString","setPenStyles","CaptionScreen","rows","currRow","nrRollUpRows","lastOutputScreen","_proto5","setPen","setPAC","pacData","newRow","row","topRowIndex","prevLineTime","indent","prevPos","color","setBkgData","bkgData","setRollUpRows","nrRows","rollUp","getDisplayText","topRow","asOneRow","displayText","rowNr","rowText","getTextAndFormat","Cea608Channel","channelNumber","outputFilter","chNr","verbose","displayedMemory","nonDisplayedMemory","currRollUpRow","writeScreen","_proto6","getHandler","setHandler","newHandler","setMode","newMode","insertChars","screen","outputDataUpdate","ccRCL","ccBS","ccAOF","ccAON","ccDER","ccRU","ccFON","ccRDC","ccTR","ccRTD","ccEDM","ccCR","ccENM","ccEOC","ccTO","nrCols","ccMIDROW","secondByte","colorIndex","dispatch","newCue","dispatchCue","cueSplitAtTime","Cea608Parser","field","out1","out2","channels","currentChannel","cmdHistory","_proto7","channel","addData","byteList","cmdFound","charsFound","parseCmd","parseMidrow","parsePAC","parseBackgroundAttributes","parseChars","currChNr","hasCmdRepeated","setLastCmd","interpretPAC","pacIndex","channelNr","oneCode","charCodes","charCode1","hexCodes","OutputFilter","timelineController","cueRanges","addCues","createCaptionsTrack","AllowedDirections","AllowedAlignments","isAllowedValue","allowed","lcValue","findAlignSetting","extend","obj","rest","cobj","baseObj","enumerable","hasBeenReset","_id","_pauseOnExit","_startTime","_endTime","_text","_region","_vertical","_snapToLines","_line","_lineAlign","_position","_positionAlign","_size","_align","defineProperty","setting","findDirectionSetting","SyntaxError","displayState","getCueAsHTML","WebVTT","convertCueToDOMTree","StringDecoder","options","decodeURIComponent","parseTimeStamp","computeSeconds","s","f","Settings","values","dflt","defaultKey","alt","n","integer","percent","parseOptions","keyValueDelim","groupDelim","kv","defaults","center","align","parseCue","regionList","oInput","consumeTimeStamp","ts","skipWhitespace","settings","vals","region","vertical","line","lineAlign","snapToLines","consumeCueSettings","fixLineBreaks","VTTParser","oncue","onparsingerror","onflush","collectNextLine","alreadyCollectedLine","hasSubstring","LINEBREAKS","inputString","searchString","hash","generateCueId","parseWebVTT","vttByteArray","vttCCs","callBack","errorCallBack","srcScale","parsingError","parser","vttLines","cueTime","timestampMapMPEGTS","timestampMapLOCAL","inHeader","currCC","cueOffset","webVttMpegTsMapOffset","new","prevCC","presentationOffset","_prevCC","calculateOffset","timeString","secs","mins","hours","cueString2millis","IMSC1_CODEC","HMSF_REGEX","TIME_UNIT_REGEX","textAlignToLineAlign","parseIMSC1","ttmlList","syncTime","ttml","tt","defaultRateInfo","frameRate","subFrameRate","frameRateMultiplier","tickRate","rateInfo","styleElements","collectionToDictionary","getElementCollection","regionElements","cueElements","cueElement","cueText","getTextContent","hasAttribute","parseTtmlTime","timestampParsingError","ttsNs","regionStyle","styleAttributes","regionStyleName","getAttributeNS","getTtmlStyles","textAlign","parseTTML","fromElement","parentName","childName","querySelectorAll","elementsWithId","dict","element","node","_node$childNodes","nodeName","textContent","ns","hasAttributeNS","timeAttributeValue","parseHoursMinutesSecondsFrames","parseTimeUnits","TimelineController","Cues","unparsedVttFrags","captionsTracks","nonNativeCaptionsTracks","cea608Parser1","cea608Parser2","captionsProperties","cueHandler","textTrack1","captionsTextTrack1Label","languageCode","captionsTextTrack1LanguageCode","textTrack2","captionsTextTrack2Label","captionsTextTrack2LanguageCode","textTrack3","captionsTextTrack3Label","captionsTextTrack3LanguageCode","textTrack4","captionsTextTrack4Label","captionsTextTrack4LanguageCode","enableCEA708Captions","channel1","channel2","channel3","channel4","onFragParsingUserdata","onFragDecrypted","SUBTITLE_TRACKS_CLEARED","onSubtitleTracksCleared","x1","y1","y2","merged","cueRange","overlap","CUES_PARSED","getExistingTrack","createNativeTrack","createNonNativeTrack","_captionsProperties$t","existingTrack","createTextTrack","trackProperties","closedCaptions","NON_NATIVE_TEXT_TRACKS_FOUND","_cleanTracks","hasIMSC1","enableWebVTT","enableIMSC1","inUseTracks","inUseTrack","canReuseVttTextTrack","textTrackKind","_captionsOrSubtitlesFromCharacteristics","tracksList","CHARACTERISTICS","transcribesSpokenDialog","describesMusicAndSound","captionsTrack","instreamIdMatch","closedCaptionsForLevel","_data$part$index","decrypted","trackPlaylistMedia","_parseIMSC1","_parseVTTs","_appendCues","maxAvCC","missingInitPTS","_fallbackToIMSC1","fragLevel","ccBytes","ccdatas","extractCea608Data","actualCCBytes","tmpByte","ccbyte1","ccbyte2","ccType","manifestTrack","CapLevelController","autoLevelCapping","restrictedLevels","clientRect","streamController","setStreamController","unregisterListener","capLevelToPlayerSize","stopCapping","FPS_DROP_LEVEL_CAPPING","onFpsDropLevelCapping","droppedLevel","isLevelAllowed","HTMLVideoElement","startCapping","detectPlayerSize","mediaHeight","mediaWidth","getMaxLevel","capLevelIndex","validLevels","getMaxLevelByMediaSize","getDimensions","boundsRect","getBoundingClientRect","bottom","top","restrictedLevel","maxLevelIndex","contentScaleFactor","ignoreDevicePixelRatio","devicePixelRatio","FPSController","isVideoPlaybackQualityAvailable","lastTime","lastDroppedFrames","lastDecodedFrames","capLevelOnFPSDrop","getVideoPlaybackQuality","checkFPSInterval","fpsDroppedMonitoringPeriod","checkFPS","decodedFrames","droppedFrames","currentPeriod","currentDropped","currentDecoded","droppedFPS","FPS_DROP","totalDroppedFrames","fpsDroppedMonitoringThreshold","videoPlaybackQuality","totalVideoFrames","droppedVideoFrames","webkitDecodedFrameCount","webkitDroppedFrameCount","LOGGER_PREFIX","EMEController","keyFormatPromise","keySystemAccessPromises","_requestLicenseFailureCount","mediaKeySessions","keyIdToKeySessionPromise","setMediaKeysQueue","CDMCleanupPromise","onMediaEncrypted","_onMediaEncrypted","onWaitingForKey","_onWaitingForKey","onMediaDetached","requestMediaKeySystemAccessFunc","licenseXhrSetup","licenseResponseCallback","drmSystemOptions","getLicenseServerUrl","keySystemConfiguration","licenseUrl","getServerCertificateUrl","serverCertificateUrl","attemptKeySystemAccess","uniqueCodec","audioCodecs","videoCodecs","attempt","keySystems","getMediaKeysPromise","mediaKeys","EMEKeyError","KEY_SYSTEM_NO_ACCESS","supportedConfigurations","errMessage","protocol","mediaKeySystemConfigs","initDataTypes","persistentState","distinctiveIdentifier","sessionTypes","sessionType","audioCapabilities","contentType","robustness","audioRobustness","encryptionScheme","audioEncryptionScheme","videoCapabilities","videoRobustness","videoEncryptionScheme","createMediaKeySystemConfigurations","getSupportedMediaKeySystemConfigurations","keySystemAccess","mediaKeySystemAccess","certificateRequest","fetchServerCertificate","createMediaKeys","certificate","setMediaKeysServerCertificate","createMediaKeySessionContext","mediaKeysSession","createSession","renewKeySession","getKeyIdString","generateRequestWithPreferredKeySession","removeSession","updateKeySession","_mediaKeySessionConte","keySession","sessionId","getKeyFormatPromise","keySystemsInConfig","getKeySystemSelectionPromise","keySystemToKeySystemFormat","keyDetails","getKeySystemForKeyPromise","throwIfDestroyed","attemptSetMediaKeys","handleError","KEY_SYSTEM_NO_KEYS","KEY_SYSTEM_NO_CONFIGURED_LICENSE","initDataType","keySystemDomain","json","psshInfo","boxSize","dataSizeOrKidCount","parsePssh","keySystemIdToKeySystemDomain","keyIdHex","keyContext","oldKeyIdHex","_keySystemToKeySystem","setMediaKeysPromise","setMediaKeys","_this$config$drmSyste","_this$config$drmSyste2","generateRequestFilter","generateRequest","mappedInitData","_this$hls","licenseStatus","onmessage","messageType","renewLicense","onkeystatuseschange","onKeyStatusChange","keyUsablePromise","KEY_SYSTEM_STATUS_INTERNAL_ERROR","_context$mediaKeysSes","KEY_SYSTEM_NO_SESSION","keyStatuses","status","certLoader","certLoadPolicy","contex","KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED","cert","setServerCertificate","KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED","keyMessage","_this10","requestLicense","KEY_SYSTEM_SESSION_UPDATE_FAILED","setupLicenseXHR","xhr","keysListItem","licenseChallenge","_this11","open","licenseXhrSetupResult","_this12","XMLHttpRequest","onreadystatechange","KEY_SYSTEM_LICENSE_REQUEST_FAILED","statusText","attemptsLeft","licenseXhr","DONE","_ref5","send","_this13","mediaKeysList","keySessionCount","_ref6","formats","_this14","close","_this15","CMCDObjectType","CMCDController","sid","cid","useHeaders","initialized","starved","audioBuffer","onWaiting","onPlaying","applyPlaylistData","ot","su","applyFragmentData","getObjectType","br","tb","getTopBandwidth","bl","getBufferLength","cmcd","createPlaylistLoader","createFragmentLoader","contentId","_data$tracks$audio","_data$tracks$video","createData","sf","pr","mtp","bandwidthEstimate","isVideo","bs","toHeaders","toQuery","appendQueryToUri","_step","_iterator","_createForOfIteratorHelperLoose","done","Ctor","CmcdPlaylistLoader","callbacks","CmcdFragmentLoader","serialize","_step2","toRounded","toHundred","formatters","dl","nor","rtp","_iterator2","formatter","headerNames","headerGroups","headerMap","nrr","st","_i","_keys","separator","ContentSteeringController","pathwayPriority","timeToLoad","reloadTimer","started","penalizedPathways","ttl","scheduleRefresh","loadSteeringManifest","levelToRemove","pathways","updatePathwayPriority","pathwayLevels","getLevelsForPathway","selectedIndex","selectedLevel","levelAfterChange","clonePathways","pathwayClones","audioGroupCloneMap","subtitleGroupCloneMap","pathwayClone","cloneId","baseId","uriReplacement","clonedVariants","baseLevel","performUriReplacement","clonedAudioGroupId","clonedSubtitleGroupId","clonedLevel","cloneRenditionGroups","throughput","steeringManifestLoadPolicy","steeringData","VERSION","TTL","reloadUri","getResponseHeader","retryAfter","ttlMs","groupCloneMap","clonedTracks","clonedTrack","stableId","perOptionKey","perVariantUri","host","HOST","PARAMS","perOptionUris","AGE_HEADER_LINE_REGEX","XhrLoader","xhrSetup","requestTimeout","retryTimeout","abortInternal","onprogress","_this$callbacks","openAndSendXhr","_config$loadPolicy","setRequestHeader","readystatechange","loadprogress","loadtimeout","useResponse","responseText","responseURL","lengthComputable","getAllResponseHeaders","FetchLoader","fetchSetup","request","controller","getRequest","AbortController","ok","initParams","signal","credentials","Headers","getRequestParameters","isArrayBuffer","LENGTH","fetch","FetchError","contentRange","byteRangeLength","byteRangeHeader","getByteRangeLength","contentLength","getContentLength","loadProgressively","responseData","loaderResponse","chunkCache","reader","getReader","pump","read","Request","WHITESPACE_CHAR","hlsDefaultConfig","abrController","bufferController","capLevelController","errorController","fpsController","minAutoBitrate","manifestLoadingTimeOut","manifestLoadingMaxRetry","manifestLoadingRetryDelay","manifestLoadingMaxRetryTimeout","levelLoadingTimeOut","levelLoadingMaxRetry","levelLoadingRetryDelay","levelLoadingMaxRetryTimeout","fragLoadingTimeOut","fragLoadingMaxRetry","fragLoadingRetryDelay","fragLoadingMaxRetryTimeout","captionScreen","indenting","_track$cues","cueA","cueB","subtitleStreamController","subtitleTrackController","audioStreamController","audioTrackController","cmcdController","deepCpy","enableStreamingMode","currentLoader","ReadableStream","fetchSupported","Hls","coreComponents","networkControllers","_emitter","_autoLevelCapping","_maxHdcpLevel","latencyController","levelController","_media","defaultConfig","defaultsCopy","deprecatedSettings","policyName","policyNotSet","report","deprecatedSetting","mergeConfig","DefaultConfig","ConfigAbrController","ConfigBufferController","ConfigCapLevelController","ConfigErrorController","ConfigFpsController","playListLoader","id3TrackController","ConfigContentSteeringController","createController","AudioStreamControllerClass","SubtitleStreamControllerClass","sourceBufferValidAPI","ControllerClass","components","controllerInstance","eventObject","DESTROYING","detachMedia","component","attachMedia","loadSource","loadedSource","loadingSource","recoverMediaError","shouldStartCapping","newCapLevelToPlayerSize","currentProgramDateTime","audioTrackId","subtitleTrackId"],"mappings":"swHAEA,IACMA,EAEAC,EACAC,EACAC,EAEAC,EANAJ,EACF,iIACEC,EAAsB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IAAInmB,EACJ,IAAKA,KAxCLi3D,EAAIC,MAAQ,CACV/3C,KAAM,GACNg4C,KAAM,GACNC,KAAM,GACNC,KAAM,GACNC,KAAM,GACNC,KAAM,GACNC,KAAM,GACNlkD,KAAM,GACNmkD,KAAM,GACNpkD,KAAM,GACNqkD,KAAM,GACNC,KAAM,GACNC,KAAM,GACN3iD,KAAM,GACN4iD,KAAM,GACNr5C,KAAM,GACN,OAAQ,GACRs5C,KAAM,GACNC,KAAM,GACNC,KAAM,GACNC,KAAM,GACNC,KAAM,GACNC,KAAM,GACNC,KAAM,GACN1kD,KAAM,GACN2kD,KAAM,GACNC,KAAM,GACNhjD,KAAM,GACNE,KAAM,GACNJ,KAAM,GACNlC,KAAM,GACNkB,KAAM,GACNR,KAAM,GACNT,KAAM,GACNolD,KAAM,GACNC,KAAM,IAIEvB,EAAIC,MACRD,EAAIC,MAAMj4D,eAAee,KAC3Bi3D,EAAIC,MAAMl3D,GAAK,CACbA,EAAEgM,WAAW,GACbhM,EAAEgM,WAAW,GACbhM,EAAEgM,WAAW,GACbhM,EAAEgM,WAAW,KAKnB,IAAMysD,EAAY,IAAI14D,WAAW,CAC/B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IACA,IACA,IACA,IACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,IACA,IACA,IACA,GACA,GACA,IACA,IACA,IACA,IACA,IACA,IAGI24D,EAAY,IAAI34D,WAAW,CAC/B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IACA,IACA,IACA,IACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,IACA,IACA,IACA,GACA,GACA,IACA,IACA,IACA,IACA,IACA,IAGFk3D,EAAI0B,WAAa,CACf7wD,MAAO2wD,EACP5wD,MAAO6wD,GAGT,IAAMpB,EAAO,IAAIv3D,WAAW,CAC1B,EACA,EACA,EACA,EACA,EAC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,IAAI7nD,MAAM,KAAOulD,CAAAA,EAAIC,MAAMY,MAAIt9B,OAAKo/B,KAChD3C,EAEMc,KAAP,SAAYxlD,EAAWnQ,GACrBA,GAAYmQ,EACZ,IAAMknD,EAAoB/8D,KAAKwO,MAAM9I,GAAYiP,GAAa,IACxDqoD,EAAoBh9D,KAAKwO,MAAM9I,GAAYiP,GAAa,IACxDiH,EAAQ,IAAIvY,WAAW,CAC3B,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACCwS,GAAa,GAAM,IACnBA,GAAa,GAAM,IACnBA,GAAa,EAAK,IACP,IAAZA,EACAknD,GAAqB,GACpBA,GAAqB,GAAM,IAC3BA,GAAqB,EAAK,IACP,IAApBA,EACAC,GAAqB,GACpBA,GAAqB,GAAM,IAC3BA,GAAqB,EAAK,IACP,IAApBA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,IACA,IACA,IACA,MAEF,OAAOzC,EAAIsC,IAAItC,EAAIC,MAAMa,KAAMz/C,IAChC2+C,EAEMgB,KAAP,SAAYpkD,GACV,IAEI7T,EACA+T,EAHEe,EAAUjB,EAAMiB,SAAW,GAC3BwD,EAAQ,IAAIvY,WAAW,EAAI+U,EAAQ5Y,QAKzC,IAAK8D,EAAI,EAAGA,EAAI8U,EAAQ5Y,OAAQ8D,IAC9B+T,EAAQe,EAAQ9U,GAAG+T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AI14D,QAEhBs+B,OAAOo6B,GACPp6B,OAAO,CACN3mB,EAAMkhD,IAAI74D,SAEXs+B,OAAOu6B,KAGRr0D,EAAQmT,EAAMnT,MACdC,EAASkT,EAAMlT,OACfs5D,EAAWpmD,EAAMm8C,WAAW,GAC5BkK,EAAWrmD,EAAMm8C,WAAW,GAElC,OAAOiH,EAAIsC,IACTtC,EAAIC,MAAM/3C,KACV,IAAIpf,WAAW,CACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACCW,GAAS,EAAK,IACP,IAARA,EACCC,GAAU,EAAK,IACP,IAATA,EACA,EACA,GACA,EACA,EACA,EACA,GACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,IACA,GACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,IACA,GACA,IACA,IACA,IACA,GACA,IACA,IACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,GACA,KAEFq5D,EACA/C,EAAIsC,IACFtC,EAAIC,MAAME,KACV,IAAIr3D,WAAW,CACb,EACA,GACA,IACA,IACA,EACA,GACA,IACA,IACA,EACA,GACA,IACA,OAGJk3D,EAAIsC,IACFtC,EAAIC,MAAMc,KACV,IAAIj4D,WAAW,CACbk6D,GAAY,GACXA,GAAY,GAAM,IAClBA,GAAY,EAAK,IACP,IAAXA,EACAC,GAAY,GACXA,GAAY,GAAM,IAClBA,GAAY,EAAK,IACP,IAAXA,OAIPjD,EAEMM,KAAP,SAAY1jD,GACV,IAAMsmD,EAAYtmD,EAAMjG,OAAO1R,OAC/B,OAAO,IAAI6D,WACT,CACE,EACA,EACA,EACA,EAEA,EACA,GAAOo6D,EACP,EACA,EACA,EAEA,EACA,GAAOA,EACP,GACA,GACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EAEA,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T,EAAMlT,OACf84D,EAAoB/8D,KAAKwO,MAAM9I,GAAYiP,GAAa,IACxDqoD,EAAoBh9D,KAAKwO,MAAM9I,GAAYiP,GAAa,IAC9D,OAAO4lD,EAAIsC,IACTtC,EAAIC,MAAM/jD,KACV,IAAIpT,WAAW,CACb,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACC9B,GAAM,GAAM,IACZA,GAAM,GAAM,IACZA,GAAM,EAAK,IACP,IAALA,EACA,EACA,EACA,EACA,EACAw7D,GAAqB,GACpBA,GAAqB,GAAM,IAC3BA,GAAqB,EAAK,IACP,IAApBA,EACAC,GAAqB,GACpBA,GAAqB,GAAM,IAC3BA,GAAqB,EAAK,IACP,IAApBA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,EACA,GACA,EACA,EACA,EACCh5D,GAAS,EAAK,IACP,IAARA,EACA,EACA,EACCC,GAAU,EAAK,IACP,IAATA,EACA,EACA,MAGLs2D,EAEM7hD,KAAP,SAAYvB,EAAO8lD,GACjB,IAAMS,EAAwBnD,EAAIgB,KAAKpkD,GACjC5V,EAAK4V,EAAM5V,GACXo8D,EAA+B39D,KAAKwO,MACxCyuD,GAAuBtoD,GAAa,IAEhCipD,EAA+B59D,KAAKwO,MACxCyuD,GAAuBtoD,GAAa,IAEtC,OAAO4lD,EAAIsC,IACTtC,EAAIC,MAAM9hD,KACV6hD,EAAIsC,IACFtC,EAAIC,MAAM1hD,KACV,IAAIzV,WAAW,CACb,EACA,EACA,EACA,EACA9B,GAAM,GACLA,GAAM,GAAM,IACZA,GAAM,EAAK,IACP,IAAL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A,CAAA10B,IAAA,aAAAU,IAKA,WACE,OAAOhD,KAAKo5G,kBAAkB5hF,UAChC,GAEA,CAAAl1B,IAAA,gBAAAU,IAGA,WACE,OAAOhD,KAAKo5G,kBAAkB/hF,aAChC,GAEA,CAAA/0B,IAAA,QAAAU,IAGA,WACE,OAAOhD,KAAKo5G,kBAAkB1gF,KAChC,GAEA,CAAAp2B,IAAA,iBAAAU,IAGA,WACE,OAAOhD,KAAK8/F,iBAAiBz2D,cAC/B,IAAC,CAAA,CAAA/mC,IAAA,UAAAU,IAzxBD,WACE,MAAO,QACT,GAAC,CAAAV,IAAA,SAAAU,IASD,WACE,OAAOrF,CACT,GAAC,CAAA2E,IAAA,aAAAU,IAED,WACE,OAAOpF,CACT,GAAC,CAAA0E,IAAA,eAAAU,IAED,WACE,OAAOnF,CACT,GAEA,CAAAyE,IAAA,gBAAAU,IAGA,WACE,OAAK81G,EAAIS,cAIFT,EAAIS,cAHF3C,EAIX,EAEA3xG,IAGA,SAAyBs0G,GACvBT,EAAIS,cAAgBA,CACtB,KAACT,CAAA,CAzEqB,UAAHA,GACJS,mBAAa","x_google_ignoreList":[0,66]} \ No newline at end of file diff --git a/trunk/research/players/srs_player.html b/trunk/research/players/srs_player.html index 74579491e9..b659f16c0b 100755 --- a/trunk/research/players/srs_player.html +++ b/trunk/research/players/srs_player.html @@ -103,7 +103,7 @@ <script type="text/javascript" src="js/jquery-1.12.2.min.js"></script> <script type="text/javascript" src="js/bootstrap.min.js"></script> <script type="text/javascript" src="js/mpegts-1.7.3.min.js"></script> -<script type="text/javascript" src="js/hls-0.14.17.min.js"></script> +<script type="text/javascript" src="js/hls-1.4.14.min.js"></script> <script type="text/javascript" src="js/dash-v4.5.1.all.min.js"></script> <script type="text/javascript" src="js/json2.js"></script> <script type="text/javascript" src="js/srs.page.js"></script> @@ -196,6 +196,8 @@ stopPlayers(); if (!r) return; + const video = document.getElementById('video_player'); + // Use H5 native to play aac/mp3. if (r.stream.indexOf('.mp3') > 0 || r.stream.indexOf('.aac') > 0) { $('#audio_player').attr('src', r.url).show(); @@ -220,7 +222,7 @@ show_for_video_ok(); tsPlayer = mpegts.createPlayer({type: 'mpegts', url: r.url, isLive: true, enableStashBuffer: false}); - tsPlayer.attachMediaElement(document.getElementById('video_player')); + tsPlayer.attachMediaElement(video); tsPlayer.load(); tsPlayer.play(); return; @@ -235,9 +237,21 @@ show_for_video_ok(); - hlsPlayer = new Hls(); + // See https://github.com/video-dev/hls.js/blob/master/docs/API.md#maxlivesyncplaybackrate + // See https://github.com/video-dev/hls.js/issues/3077#issuecomment-705152394 + hlsPlayer = new Hls({ + enableWorker: true, // Improve performance and avoid lag/frame drops. + lowLatencyMode: true, // Enable Low-Latency HLS part playlist and segment loading. + liveSyncDurationCount: 0, // Start from the last segment. + liveMaxLatencyDurationCount: 4, // Maximum delay allowed from edge of live. + maxBufferLength: 5, // Maximum buffer length in seconds. + maxMaxBufferLength: 8, // The max Maximum buffer length in seconds. + maxLiveSyncPlaybackRate: 2, // Catch up if the latency is large. + liveDurationInfinity: true // Override current Media Source duration to Infinity for a live broadcast. + }); hlsPlayer.loadSource(r.url); - hlsPlayer.attachMedia(document.getElementById('video_player')); + hlsPlayer.attachMedia(video); + video.play(); return; } @@ -264,16 +278,23 @@ show_for_video_ok(); - flvPlayer = mpegts.createPlayer({type: 'flv', url: r.url, isLive: true, enableStashBuffer: false}); - flvPlayer.attachMediaElement(document.getElementById('video_player')); + // See https://github.com/xqq/mpegts.js/blob/master/src/config.js#L32 + // See https://github.com/xqq/mpegts.js/blob/master/docs/api.md + flvPlayer = mpegts.createPlayer({ + type: 'flv', url: r.url, + isLive: true, enableStashBuffer: false, liveSync: true + }); + flvPlayer.attachMediaElement(video); flvPlayer.load(); flvPlayer.play(); return; } - console.error('不支持的URL', r.url, r); $('#video_player').hide(); - $('#audio_player').hide(); + + const msg = `Not supported URL ${r.url} ${JSON.stringify(r)}`; + console.error(msg); + alert(msg); }; $("#txt_url").change(function(){ diff --git a/trunk/research/srt-proxy/.gitignore b/trunk/research/srt-proxy/.gitignore new file mode 100644 index 0000000000..5281c15ee4 --- /dev/null +++ b/trunk/research/srt-proxy/.gitignore @@ -0,0 +1,2 @@ +.idea +gosrt \ No newline at end of file diff --git a/trunk/research/srt-proxy/go.mod b/trunk/research/srt-proxy/go.mod new file mode 100644 index 0000000000..fa94f6a67f --- /dev/null +++ b/trunk/research/srt-proxy/go.mod @@ -0,0 +1,3 @@ +module srt-proxy + +go 1.18 diff --git a/trunk/research/srt-proxy/main.go b/trunk/research/srt-proxy/main.go new file mode 100644 index 0000000000..5aff5d0a89 --- /dev/null +++ b/trunk/research/srt-proxy/main.go @@ -0,0 +1,400 @@ +package main + +import ( + "context" + "encoding/binary" + "fmt" + "net" + "os" + "time" +) + +// Use FFmpeg to push stream to this proxy: +// ffmpeg -re -i ~/git/srs/trunk/doc/source.flv -c copy -pes_payload_size 0 -f mpegts 'srt://localhost:10081?streamid=#!::r=live/livestream?m=publish' +// Play by SRT from this proxy: +// ffplay 'srt://localhost:10081?streamid=#!::r=live/livestream,latency=20,m=request' +var listenAddress = "127.0.0.1:10081" + +// Proxy to backend SRS Server. +// Play by HTTP-FLV from SRS: +// ffplay http://localhost:8080/live/livestream.flv +// Play by SRT from SRS: +// ffplay 'srt://localhost:10080?streamid=#!::r=live/livestream,latency=20,m=request' +var backendAddress = "127.0.0.1:10080" + +func main() { + fmt.Println("Hello, SRT!") + if err := doMain(context.Background()); err != nil { + fmt.Println(fmt.Sprintf("err %+v", err)) + os.Exit(1) + } +} + +func doMain(ctx context.Context) error { + serverAddr, err := net.ResolveUDPAddr("udp", listenAddress) + if err != nil { + return err + } + + server, err := net.ListenUDP("udp", serverAddr) + if err != nil { + return err + } + defer server.Close() + fmt.Println("UDP server listening on", server.LocalAddr().String()) + + start := time.Now() + + buf := make([]byte, 4096) + connections := make(map[string]*SRTConnection) + for { + n, clientAddr, err := server.ReadFromUDP(buf) + if err != nil { + return err + } + + connection, ok := connections[clientAddr.String()] + if !ok { + connection = &SRTConnection{ + start: start, + server: server, + serverAddr: serverAddr, + clientAddr: clientAddr, + } + connections[clientAddr.String()] = connection + fmt.Println("New connection from", clientAddr.String()) + } + + if err := connection.Consume(buf[:n]); err != nil { + return err + } + + fmt.Println(fmt.Sprintf("Received %v bytes from %s", n, clientAddr.String())) + } + + return nil +} + +type SRTConnection struct { + // Listener start time. + start time.Time + // Local UDP server connection. + server *net.UDPConn + // Local UDP server listen address. + serverAddr *net.UDPAddr + // Client remote address. + clientAddr *net.UDPAddr + // Backend server connection. + backend *net.UDPConn + + // Handshake packets with client. + handshake0 *SRTHandshakePacket + handshake1 *SRTHandshakePacket + handshake2 *SRTHandshakePacket + handshake3 *SRTHandshakePacket +} + +func (v *SRTConnection) Close() error { + if v.backend != nil { + return v.backend.Close() + } + return nil +} + +func (v *SRTConnection) Consume(b []byte) error { + pkt := &SRTHandshakePacket{} + if err := pkt.UnmarshalBinary(b); err != nil { + return err + } + + // Handle handshake messages. + if pkt.IsHandshake() { + if pkt.SynCookie == 0 { + // Save handshake packet. + v.handshake0 = pkt + fmt.Println(fmt.Sprintf("Handshake 0: %v", v.handshake0.String())) + + // Response handshake 1. + v.handshake1 = &SRTHandshakePacket{ + ControlFlag: pkt.ControlFlag, + ControlType: 0, + SubType: 0, + AdditionalInfo: 0, + Timestamp: uint32(time.Since(v.start).Microseconds()), + SocketID: pkt.SRTSocketID, + Version: 5, + EncryptionField: 0, + ExtensionField: 0x4A17, + InitSequence: pkt.InitSequence, + MTU: pkt.MTU, + FlowWindow: pkt.FlowWindow, + HandshakeType: 1, + SRTSocketID: pkt.SRTSocketID, + SynCookie: 0x418d5e4e, + PeerIP: v.serverAddr.IP, + } + fmt.Println(fmt.Sprintf("Handshake 1: %v", v.handshake1.String())) + + if b, err := v.handshake1.MarshalBinary(); err != nil { + return err + } else if _, err = v.server.WriteToUDP(b, v.clientAddr); err != nil { + return err + } + + return nil + } else { + // Save handshake packet. + v.handshake2 = pkt + fmt.Println(fmt.Sprintf("Handshake 2: %v", v.handshake2.String())) + + // Ignore if already connected. + if v.backend == nil { + remoteAddress, err := net.ResolveUDPAddr("udp", backendAddress) + if err != nil { + return err + } + + if v.backend, err = net.DialUDP("udp", nil, remoteAddress); err != nil { + return err + } + } + + // Proxy handshake 0 to backend server. + if b, err := v.handshake0.MarshalBinary(); err != nil { + return err + } else if _, err = v.backend.Write(b); err != nil { + return err + } + fmt.Println(fmt.Sprintf("Proxy send handshake 0: %v", v.handshake0.String())) + + // Read handshake 1 from backend server. + b := make([]byte, 4096) + handshake1p := &SRTHandshakePacket{} + if nn, err := v.backend.Read(b); err != nil { + return err + } else if err := handshake1p.UnmarshalBinary(b[:nn]); err != nil { + return err + } + fmt.Println(fmt.Sprintf("Proxy got handshake 1: %v", handshake1p.String())) + + // Proxy handshake 2 to backend server. + handshake2p := *v.handshake2 + handshake2p.SynCookie = handshake1p.SynCookie + if b, err := handshake2p.MarshalBinary(); err != nil { + return err + } else if _, err = v.backend.Write(b); err != nil { + return err + } + fmt.Println(fmt.Sprintf("Proxy send handshake 2: %v", handshake2p.String())) + + // Read handshake 3 from backend server. + handshake3p := &SRTHandshakePacket{} + if nn, err := v.backend.Read(b); err != nil { + return err + } else if err := handshake3p.UnmarshalBinary(b[:nn]); err != nil { + return err + } + fmt.Println(fmt.Sprintf("Proxy got handshake 3: %v", handshake3p.String())) + + // Response handshake 3 to client. + v.handshake3 = &*handshake3p + v.handshake3.SynCookie = v.handshake1.SynCookie + fmt.Println(fmt.Sprintf("Handshake 3: %v", v.handshake3.String())) + + if b, err := v.handshake3.MarshalBinary(); err != nil { + return err + } else if _, err = v.server.WriteToUDP(b, v.clientAddr); err != nil { + return err + } + + // Start a goroutine to proxy message from backend to client. + go func() { + for { + nn, err := v.backend.Read(b) + if err != nil { + return + } else if _, err = v.server.WriteToUDP(b[:nn], v.clientAddr); err != nil { + return + } + fmt.Println(fmt.Sprintf("Proxy got %d bytes from backend server.", nn)) + } + }() + return nil + } + } + + // Proxy all other messages to backend server. + if _, err := v.backend.Write(b); err != nil { + return err + } + + fmt.Println(fmt.Sprintf("Packet: %v", pkt)) + return nil +} + +// See https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-3.2 +// See https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-3.2.1 +type SRTHandshakePacket struct { + // F: 1 bit. Packet Type Flag. The control packet has this flag set to + // "1". The data packet has this flag set to "0". + ControlFlag uint8 + // Control Type: 15 bits. Control Packet Type. The use of these bits + // is determined by the control packet type definition. + // Handshake control packets (Control Type = 0x0000) are used to + // exchange peer configurations, to agree on connection parameters, and + // to establish a connection. + ControlType uint16 + // Subtype: 16 bits. This field specifies an additional subtype for + // specific packets. + SubType uint16 + // Type-specific Information: 32 bits. The use of this field depends on + // the particular control packet type. Handshake packets do not use + // this field. + AdditionalInfo uint32 + // Timestamp: 32 bits. + Timestamp uint32 + // Destination Socket ID: 32 bits. + SocketID uint32 + + // Version: 32 bits. A base protocol version number. Currently used + // values are 4 and 5. Values greater than 5 are reserved for future + // use. + Version uint32 + // Encryption Field: 16 bits. Block cipher family and key size. The + // values of this field are described in Table 2. The default value + // is AES-128. + // 0 | No Encryption Advertised + // 2 | AES-128 + // 3 | AES-192 + // 4 | AES-256 + EncryptionField uint16 + // Extension Field: 16 bits. This field is message specific extension + // related to Handshake Type field. The value MUST be set to 0 + // except for the following cases. (1) If the handshake control + // packet is the INDUCTION message, this field is sent back by the + // Listener. (2) In the case of a CONCLUSION message, this field + // value should contain a combination of Extension Type values. + // 0x00000001 | HSREQ + // 0x00000002 | KMREQ + // 0x00000004 | CONFIG + // 0x4A17 if HandshakeType is INDUCTION, see https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-4.3.1.1 + ExtensionField uint16 + // Initial Packet Sequence Number: 32 bits. The sequence number of the + // very first data packet to be sent. + InitSequence uint32 + // Maximum Transmission Unit Size: 32 bits. This value is typically set + // to 1500, which is the default Maximum Transmission Unit (MTU) size + // for Ethernet, but can be less. + MTU uint32 + // Maximum Flow Window Size: 32 bits. The value of this field is the + // maximum number of data packets allowed to be "in flight" (i.e. the + // number of sent packets for which an ACK control packet has not yet + // been received). + FlowWindow uint32 + // Handshake Type: 32 bits. This field indicates the handshake packet + // type. + // 0xFFFFFFFD | DONE + // 0xFFFFFFFE | AGREEMENT + // 0xFFFFFFFF | CONCLUSION + // 0x00000000 | WAVEHAND + // 0x00000001 | INDUCTION + HandshakeType uint32 + // SRT Socket ID: 32 bits. This field holds the ID of the source SRT + // socket from which a handshake packet is issued. + SRTSocketID uint32 + // SYN Cookie: 32 bits. Randomized value for processing a handshake. + // The value of this field is specified by the handshake message + // type. + SynCookie uint32 + // Peer IP Address: 128 bits. IPv4 or IPv6 address of the packet's + // sender. The value consists of four 32-bit fields. + PeerIP net.IP + // Extensions. + // Extension Type: 16 bits. The value of this field is used to process + // an integrated handshake. Each extension can have a pair of + // request and response types. + // Extension Length: 16 bits. The length of the Extension Contents + // field in four-byte blocks. + // Extension Contents: variable length. The payload of the extension. + ExtraData []byte +} + +func (v *SRTHandshakePacket) IsControl() bool { + return v.ControlFlag == 0x80 +} + +func (v *SRTHandshakePacket) IsHandshake() bool { + return v.IsControl() && v.ControlType == 0x00 && v.SubType == 0x00 +} + +func (v *SRTHandshakePacket) String() string { + return fmt.Sprintf("Control=%v, CType=%v, SType=%v, Timestamp=%v, SocketID=%v, Version=%v, Encrypt=%v, Extension=%v, InitSequence=%v, MTU=%v, FlowWnd=%v, HSType=%v, SRTSocketID=%v, Cookie=%v, Peer=%vB, Extra=%vB", + v.IsControl(), v.ControlType, v.SubType, v.Timestamp, v.SocketID, v.Version, v.EncryptionField, v.ExtensionField, v.InitSequence, v.MTU, v.FlowWindow, v.HandshakeType, v.SRTSocketID, v.SynCookie, len(v.PeerIP), len(v.ExtraData)) +} + +func (v *SRTHandshakePacket) UnmarshalBinary(b []byte) error { + if len(b) < 4 { + return fmt.Errorf("Invalid packet length %v", len(b)) + } + v.ControlFlag = b[0] & 0x80 + v.ControlType = binary.BigEndian.Uint16(b[0:2]) & 0x7fff + v.SubType = binary.BigEndian.Uint16(b[2:4]) + + if !v.IsHandshake() { + return nil + } + + if len(b) < 64 { + return fmt.Errorf("Invalid packet length %v", len(b)) + } + v.AdditionalInfo = binary.BigEndian.Uint32(b[4:]) + v.Timestamp = binary.BigEndian.Uint32(b[8:]) + v.SocketID = binary.BigEndian.Uint32(b[12:]) + v.Version = binary.BigEndian.Uint32(b[16:]) + v.EncryptionField = binary.BigEndian.Uint16(b[20:]) + v.ExtensionField = binary.BigEndian.Uint16(b[22:]) + v.InitSequence = binary.BigEndian.Uint32(b[24:]) + v.MTU = binary.BigEndian.Uint32(b[28:]) + v.FlowWindow = binary.BigEndian.Uint32(b[32:]) + v.HandshakeType = binary.BigEndian.Uint32(b[36:]) + v.SRTSocketID = binary.BigEndian.Uint32(b[40:]) + v.SynCookie = binary.BigEndian.Uint32(b[44:]) + + // Only support IPv4. + v.PeerIP = net.IPv4(b[51], b[50], b[49], b[48]) + + v.ExtraData = b[64:] + + return nil +} + +func (v *SRTHandshakePacket) MarshalBinary() ([]byte, error) { + b := make([]byte, 64+len(v.ExtraData)) + binary.BigEndian.PutUint16(b, uint16(v.ControlFlag)<<8|v.ControlType) + binary.BigEndian.PutUint16(b[2:], v.SubType) + binary.BigEndian.PutUint32(b[4:], v.AdditionalInfo) + binary.BigEndian.PutUint32(b[8:], v.Timestamp) + binary.BigEndian.PutUint32(b[12:], v.SocketID) + binary.BigEndian.PutUint32(b[16:], v.Version) + binary.BigEndian.PutUint16(b[20:], v.EncryptionField) + binary.BigEndian.PutUint16(b[22:], v.ExtensionField) + binary.BigEndian.PutUint32(b[24:], v.InitSequence) + binary.BigEndian.PutUint32(b[28:], v.MTU) + binary.BigEndian.PutUint32(b[32:], v.FlowWindow) + binary.BigEndian.PutUint32(b[36:], v.HandshakeType) + binary.BigEndian.PutUint32(b[40:], v.SRTSocketID) + binary.BigEndian.PutUint32(b[44:], v.SynCookie) + + // Only support IPv4. + ip := v.PeerIP.To4() + b[48] = ip[3] + b[49] = ip[2] + b[50] = ip[1] + b[51] = ip[0] + + if len(v.ExtraData) > 0 { + copy(b[64:], v.ExtraData) + } + + return b, nil +} diff --git a/trunk/src/app/srs_app_async_call.cpp b/trunk/src/app/srs_app_async_call.cpp index 7fded0aaa8..9209ce4fa4 100644 --- a/trunk/src/app/srs_app_async_call.cpp +++ b/trunk/src/app/srs_app_async_call.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_async_call.hpp b/trunk/src/app/srs_app_async_call.hpp index ca38249623..354e816c23 100644 --- a/trunk/src/app/srs_app_async_call.hpp +++ b/trunk/src/app/srs_app_async_call.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_caster_flv.cpp b/trunk/src/app/srs_app_caster_flv.cpp index 81037c7295..758bfaf7d7 100644 --- a/trunk/src/app/srs_app_caster_flv.cpp +++ b/trunk/src/app/srs_app_caster_flv.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_caster_flv.hpp b/trunk/src/app/srs_app_caster_flv.hpp index 4532c46995..cb6801aacb 100644 --- a/trunk/src/app/srs_app_caster_flv.hpp +++ b/trunk/src/app/srs_app_caster_flv.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_config.cpp b/trunk/src/app/srs_app_config.cpp index 2179ff140b..258a510120 100644 --- a/trunk/src/app/srs_app_config.cpp +++ b/trunk/src/app/srs_app_config.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_config.hpp b/trunk/src/app/srs_app_config.hpp index 4a83460bc6..1666252ca5 100644 --- a/trunk/src/app/srs_app_config.hpp +++ b/trunk/src/app/srs_app_config.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_conn.cpp b/trunk/src/app/srs_app_conn.cpp index 4aa0173259..c407aaed45 100644 --- a/trunk/src/app/srs_app_conn.cpp +++ b/trunk/src/app/srs_app_conn.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_conn.hpp b/trunk/src/app/srs_app_conn.hpp index 955f5b6bc8..b5aeb48da0 100644 --- a/trunk/src/app/srs_app_conn.hpp +++ b/trunk/src/app/srs_app_conn.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_coworkers.cpp b/trunk/src/app/srs_app_coworkers.cpp index 0c30c92174..114ec0a703 100644 --- a/trunk/src/app/srs_app_coworkers.cpp +++ b/trunk/src/app/srs_app_coworkers.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_coworkers.hpp b/trunk/src/app/srs_app_coworkers.hpp index 89dd8492cb..ce0322e6e8 100644 --- a/trunk/src/app/srs_app_coworkers.hpp +++ b/trunk/src/app/srs_app_coworkers.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_dash.cpp b/trunk/src/app/srs_app_dash.cpp index 4d647a336c..7c350dd9ac 100644 --- a/trunk/src/app/srs_app_dash.cpp +++ b/trunk/src/app/srs_app_dash.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_dash.hpp b/trunk/src/app/srs_app_dash.hpp index 0bc26a0d5d..b74c46fcc1 100644 --- a/trunk/src/app/srs_app_dash.hpp +++ b/trunk/src/app/srs_app_dash.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_dvr.cpp b/trunk/src/app/srs_app_dvr.cpp index 83fe49dfef..492c6f12fb 100644 --- a/trunk/src/app/srs_app_dvr.cpp +++ b/trunk/src/app/srs_app_dvr.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_dvr.hpp b/trunk/src/app/srs_app_dvr.hpp index daf6140239..b8396e97d4 100644 --- a/trunk/src/app/srs_app_dvr.hpp +++ b/trunk/src/app/srs_app_dvr.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_edge.cpp b/trunk/src/app/srs_app_edge.cpp index 9b706000a1..f4a52115c3 100644 --- a/trunk/src/app/srs_app_edge.cpp +++ b/trunk/src/app/srs_app_edge.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_edge.hpp b/trunk/src/app/srs_app_edge.hpp index c9a7fae4a4..efb5705204 100644 --- a/trunk/src/app/srs_app_edge.hpp +++ b/trunk/src/app/srs_app_edge.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_empty.cpp b/trunk/src/app/srs_app_empty.cpp index cb4342a12e..624d501b8f 100644 --- a/trunk/src/app/srs_app_empty.cpp +++ b/trunk/src/app/srs_app_empty.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_empty.hpp b/trunk/src/app/srs_app_empty.hpp index d3aae5d9fb..b27ddd8651 100644 --- a/trunk/src/app/srs_app_empty.hpp +++ b/trunk/src/app/srs_app_empty.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_encoder.cpp b/trunk/src/app/srs_app_encoder.cpp index 432fdb3380..eac6b23198 100644 --- a/trunk/src/app/srs_app_encoder.cpp +++ b/trunk/src/app/srs_app_encoder.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_encoder.hpp b/trunk/src/app/srs_app_encoder.hpp index f78851cc9f..68daf1ab90 100644 --- a/trunk/src/app/srs_app_encoder.hpp +++ b/trunk/src/app/srs_app_encoder.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_ffmpeg.cpp b/trunk/src/app/srs_app_ffmpeg.cpp index d77336d7f3..f3ee57a304 100644 --- a/trunk/src/app/srs_app_ffmpeg.cpp +++ b/trunk/src/app/srs_app_ffmpeg.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_ffmpeg.hpp b/trunk/src/app/srs_app_ffmpeg.hpp index e4c006c583..d3ba5bd700 100644 --- a/trunk/src/app/srs_app_ffmpeg.hpp +++ b/trunk/src/app/srs_app_ffmpeg.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_forward.cpp b/trunk/src/app/srs_app_forward.cpp index 7fcaa354ca..bfc9911e9f 100755 --- a/trunk/src/app/srs_app_forward.cpp +++ b/trunk/src/app/srs_app_forward.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -97,7 +97,7 @@ srs_error_t SrsForwarder::on_publish() void SrsForwarder::on_unpublish() { trd->stop(); - sdk->close(); + if (sdk) sdk->close(); } srs_error_t SrsForwarder::on_meta_data(SrsSharedPtrMessage* shared_metadata) diff --git a/trunk/src/app/srs_app_forward.hpp b/trunk/src/app/srs_app_forward.hpp index c55234b322..dfe51fd28b 100644 --- a/trunk/src/app/srs_app_forward.hpp +++ b/trunk/src/app/srs_app_forward.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_fragment.cpp b/trunk/src/app/srs_app_fragment.cpp index c5380a27c0..4da9a370b6 100644 --- a/trunk/src/app/srs_app_fragment.cpp +++ b/trunk/src/app/srs_app_fragment.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_fragment.hpp b/trunk/src/app/srs_app_fragment.hpp index e72e0de7fe..36a8d850b6 100644 --- a/trunk/src/app/srs_app_fragment.hpp +++ b/trunk/src/app/srs_app_fragment.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_gb28181.cpp b/trunk/src/app/srs_app_gb28181.cpp index 420fd6c146..99c9dbf0cd 100644 --- a/trunk/src/app/srs_app_gb28181.cpp +++ b/trunk/src/app/srs_app_gb28181.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_gb28181.hpp b/trunk/src/app/srs_app_gb28181.hpp index a8eda1f24a..783842505f 100644 --- a/trunk/src/app/srs_app_gb28181.hpp +++ b/trunk/src/app/srs_app_gb28181.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_hds.cpp b/trunk/src/app/srs_app_hds.cpp index 1cbad15fc4..bb749344fa 100644 --- a/trunk/src/app/srs_app_hds.cpp +++ b/trunk/src/app/srs_app_hds.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_hds.hpp b/trunk/src/app/srs_app_hds.hpp index 4dcaddca79..26e632eaa6 100644 --- a/trunk/src/app/srs_app_hds.hpp +++ b/trunk/src/app/srs_app_hds.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_heartbeat.cpp b/trunk/src/app/srs_app_heartbeat.cpp index 692472e667..873ecdce40 100644 --- a/trunk/src/app/srs_app_heartbeat.cpp +++ b/trunk/src/app/srs_app_heartbeat.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_heartbeat.hpp b/trunk/src/app/srs_app_heartbeat.hpp index d8ea8c1a4e..eeb73c5dfb 100644 --- a/trunk/src/app/srs_app_heartbeat.hpp +++ b/trunk/src/app/srs_app_heartbeat.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_hls.cpp b/trunk/src/app/srs_app_hls.cpp index 2d33688a03..21d163a163 100644 --- a/trunk/src/app/srs_app_hls.cpp +++ b/trunk/src/app/srs_app_hls.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_hls.hpp b/trunk/src/app/srs_app_hls.hpp index ff45cbb126..77187d6823 100644 --- a/trunk/src/app/srs_app_hls.hpp +++ b/trunk/src/app/srs_app_hls.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_hourglass.cpp b/trunk/src/app/srs_app_hourglass.cpp index b44a635a6f..56593602f6 100644 --- a/trunk/src/app/srs_app_hourglass.cpp +++ b/trunk/src/app/srs_app_hourglass.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_hourglass.hpp b/trunk/src/app/srs_app_hourglass.hpp index 8f35edd9d7..552f91e12a 100644 --- a/trunk/src/app/srs_app_hourglass.hpp +++ b/trunk/src/app/srs_app_hourglass.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_api.cpp b/trunk/src/app/srs_app_http_api.cpp index e33b0c8361..af1b986b25 100644 --- a/trunk/src/app/srs_app_http_api.cpp +++ b/trunk/src/app/srs_app_http_api.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_api.hpp b/trunk/src/app/srs_app_http_api.hpp index 23bddbe5a0..8bcb30e503 100644 --- a/trunk/src/app/srs_app_http_api.hpp +++ b/trunk/src/app/srs_app_http_api.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_client.cpp b/trunk/src/app/srs_app_http_client.cpp index de1ad15230..88967f50c3 100644 --- a/trunk/src/app/srs_app_http_client.cpp +++ b/trunk/src/app/srs_app_http_client.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_client.hpp b/trunk/src/app/srs_app_http_client.hpp index 3628645d6d..bcd3ea6d43 100644 --- a/trunk/src/app/srs_app_http_client.hpp +++ b/trunk/src/app/srs_app_http_client.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_conn.cpp b/trunk/src/app/srs_app_http_conn.cpp index e4e5e11d1e..721f038a67 100644 --- a/trunk/src/app/srs_app_http_conn.cpp +++ b/trunk/src/app/srs_app_http_conn.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_conn.hpp b/trunk/src/app/srs_app_http_conn.hpp index e87fa3ddbe..7952b40a37 100644 --- a/trunk/src/app/srs_app_http_conn.hpp +++ b/trunk/src/app/srs_app_http_conn.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_hooks.cpp b/trunk/src/app/srs_app_http_hooks.cpp index cd976c5240..d8dd85d952 100644 --- a/trunk/src/app/srs_app_http_hooks.cpp +++ b/trunk/src/app/srs_app_http_hooks.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_hooks.hpp b/trunk/src/app/srs_app_http_hooks.hpp index 1bae00fec7..4600c1ada0 100644 --- a/trunk/src/app/srs_app_http_hooks.hpp +++ b/trunk/src/app/srs_app_http_hooks.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_http_static.cpp b/trunk/src/app/srs_app_http_static.cpp index a1e7b93c89..a126853db6 100644 --- a/trunk/src/app/srs_app_http_static.cpp +++ b/trunk/src/app/srs_app_http_static.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -64,6 +64,7 @@ void SrsHlsVirtualConn::expire() SrsHlsStream::SrsHlsStream() { _srs_hybrid->timer5s()->subscribe(this); + security_ = new SrsSecurity(); } SrsHlsStream::~SrsHlsStream() @@ -76,6 +77,7 @@ SrsHlsStream::~SrsHlsStream() srs_freep(info); } map_ctx_info_.clear(); + srs_freep(security_); } srs_error_t SrsHlsStream::serve_m3u8_ctx(ISrsHttpResponseWriter* w, ISrsHttpMessage* r, ISrsFileReaderFactory* factory, string fullpath, SrsRequest* req, bool* served) @@ -167,6 +169,10 @@ srs_error_t SrsHlsStream::serve_new_session(ISrsHttpResponseWriter* w, ISrsHttpM return srs_error_wrap(err, "stat on client"); } + if ((err = security_->check(SrsHlsPlay, req->ip, req)) != srs_success) { + return srs_error_wrap(err, "HLS: security check"); + } + // We must do hook after stat, because depends on it. if ((err = http_hooks_on_play(req)) != srs_success) { return srs_error_wrap(err, "HLS: http_hooks_on_play"); diff --git a/trunk/src/app/srs_app_http_static.hpp b/trunk/src/app/srs_app_http_static.hpp index 4d9da18537..d4682370d8 100644 --- a/trunk/src/app/srs_app_http_static.hpp +++ b/trunk/src/app/srs_app_http_static.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -8,7 +8,7 @@ #define SRS_APP_HTTP_STATIC_HPP #include <srs_core.hpp> - +#include <srs_app_security.hpp> #include <srs_app_http_conn.hpp> class ISrsFileReaderFactory; @@ -52,6 +52,8 @@ class SrsHlsStream : public ISrsFastTimer // interface ISrsFastTimer private: srs_error_t on_timer(srs_utime_t interval); +private: + SrsSecurity* security_; }; // The Vod streaming, like FLV, MP4 or HLS streaming. diff --git a/trunk/src/app/srs_app_http_stream.cpp b/trunk/src/app/srs_app_http_stream.cpp index eaa1984f3f..181ee14c09 100755 --- a/trunk/src/app/srs_app_http_stream.cpp +++ b/trunk/src/app/srs_app_http_stream.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -558,11 +558,13 @@ SrsLiveStream::SrsLiveStream(SrsLiveSource* s, SrsRequest* r, SrsBufferCache* c) source = s; cache = c; req = r->copy()->as_http(); + security_ = new SrsSecurity(); } SrsLiveStream::~SrsLiveStream() { srs_freep(req); + srs_freep(security_); } srs_error_t SrsLiveStream::update_auth(SrsLiveSource* s, SrsRequest* r) @@ -600,6 +602,10 @@ srs_error_t SrsLiveStream::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessage return srs_error_wrap(err, "stat on client"); } + if ((err = security_->check(SrsFlvPlay, req->ip, req)) != srs_success) { + return srs_error_wrap(err, "flv: security check"); + } + // We must do hook after stat, because depends on it. if ((err = http_hooks_on_play(r)) != srs_success) { return srs_error_wrap(err, "http hook"); diff --git a/trunk/src/app/srs_app_http_stream.hpp b/trunk/src/app/srs_app_http_stream.hpp index 0264f60698..138eb003c4 100755 --- a/trunk/src/app/srs_app_http_stream.hpp +++ b/trunk/src/app/srs_app_http_stream.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -8,7 +8,7 @@ #define SRS_APP_HTTP_STREAM_HPP #include <srs_core.hpp> - +#include <srs_app_security.hpp> #include <srs_app_http_conn.hpp> class SrsAacTransmuxer; @@ -180,6 +180,7 @@ class SrsLiveStream : public ISrsHttpHandler SrsRequest* req; SrsLiveSource* source; SrsBufferCache* cache; + SrsSecurity* security_; public: SrsLiveStream(SrsLiveSource* s, SrsRequest* r, SrsBufferCache* c); virtual ~SrsLiveStream(); diff --git a/trunk/src/app/srs_app_hybrid.cpp b/trunk/src/app/srs_app_hybrid.cpp index b1fa4133ad..c623782953 100644 --- a/trunk/src/app/srs_app_hybrid.cpp +++ b/trunk/src/app/srs_app_hybrid.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_hybrid.hpp b/trunk/src/app/srs_app_hybrid.hpp index b8ef9a69ee..c4bf050cc7 100644 --- a/trunk/src/app/srs_app_hybrid.hpp +++ b/trunk/src/app/srs_app_hybrid.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_ingest.cpp b/trunk/src/app/srs_app_ingest.cpp index df89b900c0..707aa730d1 100644 --- a/trunk/src/app/srs_app_ingest.cpp +++ b/trunk/src/app/srs_app_ingest.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_ingest.hpp b/trunk/src/app/srs_app_ingest.hpp index 741990d261..db4a2ed45c 100644 --- a/trunk/src/app/srs_app_ingest.hpp +++ b/trunk/src/app/srs_app_ingest.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_latest_version.cpp b/trunk/src/app/srs_app_latest_version.cpp index 2e4eda7b83..7220862d99 100644 --- a/trunk/src/app/srs_app_latest_version.cpp +++ b/trunk/src/app/srs_app_latest_version.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_latest_version.hpp b/trunk/src/app/srs_app_latest_version.hpp index da4cc775c2..aa365188e7 100644 --- a/trunk/src/app/srs_app_latest_version.hpp +++ b/trunk/src/app/srs_app_latest_version.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_listener.cpp b/trunk/src/app/srs_app_listener.cpp index ff66258dad..8216352d43 100755 --- a/trunk/src/app/srs_app_listener.cpp +++ b/trunk/src/app/srs_app_listener.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_listener.hpp b/trunk/src/app/srs_app_listener.hpp index 6dea65e239..b30461454b 100644 --- a/trunk/src/app/srs_app_listener.hpp +++ b/trunk/src/app/srs_app_listener.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_log.cpp b/trunk/src/app/srs_app_log.cpp index ba38e8d8fc..3db0c95794 100644 --- a/trunk/src/app/srs_app_log.cpp +++ b/trunk/src/app/srs_app_log.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_log.hpp b/trunk/src/app/srs_app_log.hpp index 4a425f6a87..cd284fa26b 100644 --- a/trunk/src/app/srs_app_log.hpp +++ b/trunk/src/app/srs_app_log.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_mpegts_udp.cpp b/trunk/src/app/srs_app_mpegts_udp.cpp index 2cacd22783..1b5adc73dd 100644 --- a/trunk/src/app/srs_app_mpegts_udp.cpp +++ b/trunk/src/app/srs_app_mpegts_udp.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_mpegts_udp.hpp b/trunk/src/app/srs_app_mpegts_udp.hpp index 0a234a762b..46b112ab62 100644 --- a/trunk/src/app/srs_app_mpegts_udp.hpp +++ b/trunk/src/app/srs_app_mpegts_udp.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_ng_exec.cpp b/trunk/src/app/srs_app_ng_exec.cpp index 827012d54b..d1a8590bae 100644 --- a/trunk/src/app/srs_app_ng_exec.cpp +++ b/trunk/src/app/srs_app_ng_exec.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_ng_exec.hpp b/trunk/src/app/srs_app_ng_exec.hpp index a33496ec9c..f29d914d47 100644 --- a/trunk/src/app/srs_app_ng_exec.hpp +++ b/trunk/src/app/srs_app_ng_exec.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_pithy_print.cpp b/trunk/src/app/srs_app_pithy_print.cpp index 3f6ebf8637..08a26d8f83 100644 --- a/trunk/src/app/srs_app_pithy_print.cpp +++ b/trunk/src/app/srs_app_pithy_print.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_pithy_print.hpp b/trunk/src/app/srs_app_pithy_print.hpp index 55ab8fd65a..707ca576a8 100644 --- a/trunk/src/app/srs_app_pithy_print.hpp +++ b/trunk/src/app/srs_app_pithy_print.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_process.cpp b/trunk/src/app/srs_app_process.cpp index ed50821ef9..fceb4ee5c3 100644 --- a/trunk/src/app/srs_app_process.cpp +++ b/trunk/src/app/srs_app_process.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_process.hpp b/trunk/src/app/srs_app_process.hpp index 02a6e97598..1a736b110c 100644 --- a/trunk/src/app/srs_app_process.hpp +++ b/trunk/src/app/srs_app_process.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_recv_thread.cpp b/trunk/src/app/srs_app_recv_thread.cpp index 976b09eed0..5e77245fac 100644 --- a/trunk/src/app/srs_app_recv_thread.cpp +++ b/trunk/src/app/srs_app_recv_thread.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_recv_thread.hpp b/trunk/src/app/srs_app_recv_thread.hpp index 305e878f76..fdef672702 100644 --- a/trunk/src/app/srs_app_recv_thread.hpp +++ b/trunk/src/app/srs_app_recv_thread.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_refer.cpp b/trunk/src/app/srs_app_refer.cpp index 9540b895dd..aa841c6272 100644 --- a/trunk/src/app/srs_app_refer.cpp +++ b/trunk/src/app/srs_app_refer.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_refer.hpp b/trunk/src/app/srs_app_refer.hpp index c313faf585..3392b3808f 100644 --- a/trunk/src/app/srs_app_refer.hpp +++ b/trunk/src/app/srs_app_refer.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_reload.cpp b/trunk/src/app/srs_app_reload.cpp index 267cfadd9c..a2849c9e8a 100644 --- a/trunk/src/app/srs_app_reload.cpp +++ b/trunk/src/app/srs_app_reload.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_reload.hpp b/trunk/src/app/srs_app_reload.hpp index f3f5dfdc10..1b457e910a 100644 --- a/trunk/src/app/srs_app_reload.hpp +++ b/trunk/src/app/srs_app_reload.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_api.cpp b/trunk/src/app/srs_app_rtc_api.cpp index b0d695c4a3..46512d8517 100644 --- a/trunk/src/app/srs_app_rtc_api.cpp +++ b/trunk/src/app/srs_app_rtc_api.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -31,10 +31,12 @@ using namespace std; SrsGoApiRtcPlay::SrsGoApiRtcPlay(SrsRtcServer* server) { server_ = server; + security_ = new SrsSecurity(); } SrsGoApiRtcPlay::~SrsGoApiRtcPlay() { + srs_freep(security_); } @@ -228,6 +230,10 @@ srs_error_t SrsGoApiRtcPlay::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMessa } } + if ((err = security_->check(SrsRtcConnPlay, ruc->req_->ip, ruc->req_)) != srs_success) { + return srs_error_wrap(err, "RTC: security check"); + } + if ((err = http_hooks_on_play(ruc->req_)) != srs_success) { return srs_error_wrap(err, "RTC: http_hooks_on_play"); } @@ -324,10 +330,12 @@ srs_error_t SrsGoApiRtcPlay::http_hooks_on_play(SrsRequest* req) SrsGoApiRtcPublish::SrsGoApiRtcPublish(SrsRtcServer* server) { server_ = server; + security_ = new SrsSecurity(); } SrsGoApiRtcPublish::~SrsGoApiRtcPublish() { + srs_freep(security_); } // Request: @@ -503,6 +511,10 @@ srs_error_t SrsGoApiRtcPublish::serve_http(ISrsHttpResponseWriter* w, ISrsHttpMe return srs_error_wrap(err, "create session"); } + if ((err = security_->check(SrsRtcConnPublish, ruc->req_->ip, ruc->req_)) != srs_success) { + return srs_error_wrap(err, "RTC: security check"); + } + // We must do hook after stat, because depends on it. if ((err = http_hooks_on_publish(ruc->req_)) != srs_success) { return srs_error_wrap(err, "RTC: http_hooks_on_publish"); diff --git a/trunk/src/app/srs_app_rtc_api.hpp b/trunk/src/app/srs_app_rtc_api.hpp index a4797f7a9c..a251831482 100644 --- a/trunk/src/app/srs_app_rtc_api.hpp +++ b/trunk/src/app/srs_app_rtc_api.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -8,7 +8,7 @@ #define SRS_APP_RTC_API_HPP #include <srs_core.hpp> - +#include <srs_app_security.hpp> #include <srs_protocol_http_stack.hpp> class SrsRtcServer; @@ -20,6 +20,7 @@ class SrsGoApiRtcPlay : public ISrsHttpHandler { private: SrsRtcServer* server_; + SrsSecurity* security_; public: SrsGoApiRtcPlay(SrsRtcServer* server); virtual ~SrsGoApiRtcPlay(); @@ -39,6 +40,7 @@ class SrsGoApiRtcPublish : public ISrsHttpHandler { private: SrsRtcServer* server_; + SrsSecurity* security_; public: SrsGoApiRtcPublish(SrsRtcServer* server); virtual ~SrsGoApiRtcPublish(); diff --git a/trunk/src/app/srs_app_rtc_codec.cpp b/trunk/src/app/srs_app_rtc_codec.cpp index a73b6f2bc7..1047d661df 100644 --- a/trunk/src/app/srs_app_rtc_codec.cpp +++ b/trunk/src/app/srs_app_rtc_codec.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -249,7 +249,7 @@ srs_error_t SrsAudioTranscoder::init_enc(SrsAudioCodecId dst_codec, int dst_chan enc_->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; #ifdef SRS_FFMPEG_OPUS - av_opt_set(enc_->priv_data, "opus_delay", "2.5", 0); + av_opt_set(enc_->priv_data, "opus_delay", "25", 0); #endif } else if (dst_codec == SrsAudioCodecIdAAC) { enc_->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL; diff --git a/trunk/src/app/srs_app_rtc_codec.hpp b/trunk/src/app/srs_app_rtc_codec.hpp index 15b2203889..87abd934c0 100644 --- a/trunk/src/app/srs_app_rtc_codec.hpp +++ b/trunk/src/app/srs_app_rtc_codec.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_conn.cpp b/trunk/src/app/srs_app_rtc_conn.cpp index dba934a483..b243c75f85 100644 --- a/trunk/src/app/srs_app_rtc_conn.cpp +++ b/trunk/src/app/srs_app_rtc_conn.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -534,6 +534,15 @@ void SrsRtcPlayStream::on_stream_change(SrsRtcSourceDescription* desc) uint32_t ssrc = desc->audio_track_desc_->ssrc_; SrsRtcAudioSendTrack* track = audio_tracks_.begin()->second; + if (track->track_desc_->media_->pt_of_publisher_ != desc->audio_track_desc_->media_->pt_) { + track->track_desc_->media_->pt_of_publisher_ = desc->audio_track_desc_->media_->pt_; + } + + if (desc->audio_track_desc_->red_ && track->track_desc_->red_ && + track->track_desc_->red_->pt_of_publisher_ != desc->audio_track_desc_->red_->pt_) { + track->track_desc_->red_->pt_of_publisher_ = desc->audio_track_desc_->red_->pt_; + } + audio_tracks_.clear(); audio_tracks_.insert(make_pair(ssrc, track)); } @@ -547,6 +556,15 @@ void SrsRtcPlayStream::on_stream_change(SrsRtcSourceDescription* desc) uint32_t ssrc = vdesc->ssrc_; SrsRtcVideoSendTrack* track = video_tracks_.begin()->second; + if (track->track_desc_->media_->pt_of_publisher_ != vdesc->media_->pt_) { + track->track_desc_->media_->pt_of_publisher_ = vdesc->media_->pt_; + } + + if (vdesc->red_ && track->track_desc_->red_ && + track->track_desc_->red_->pt_of_publisher_ != vdesc->red_->pt_) { + track->track_desc_->red_->pt_of_publisher_ = vdesc->red_->pt_; + } + video_tracks_.clear(); video_tracks_.insert(make_pair(ssrc, track)); } diff --git a/trunk/src/app/srs_app_rtc_conn.hpp b/trunk/src/app/srs_app_rtc_conn.hpp index 7866d63eed..815547d2c9 100644 --- a/trunk/src/app/srs_app_rtc_conn.hpp +++ b/trunk/src/app/srs_app_rtc_conn.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_dtls.cpp b/trunk/src/app/srs_app_rtc_dtls.cpp index 90fc006966..c83b5c29f0 100644 --- a/trunk/src/app/srs_app_rtc_dtls.cpp +++ b/trunk/src/app/srs_app_rtc_dtls.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_dtls.hpp b/trunk/src/app/srs_app_rtc_dtls.hpp index d6c053f5f0..8fec6d00e3 100644 --- a/trunk/src/app/srs_app_rtc_dtls.hpp +++ b/trunk/src/app/srs_app_rtc_dtls.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_network.cpp b/trunk/src/app/srs_app_rtc_network.cpp index dabcf3bfea..d0554999ee 100644 --- a/trunk/src/app/srs_app_rtc_network.cpp +++ b/trunk/src/app/srs_app_rtc_network.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_network.hpp b/trunk/src/app/srs_app_rtc_network.hpp index 44eb15395e..309dba4b48 100644 --- a/trunk/src/app/srs_app_rtc_network.hpp +++ b/trunk/src/app/srs_app_rtc_network.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_queue.cpp b/trunk/src/app/srs_app_rtc_queue.cpp index 4dd7703b71..e02ac12253 100644 --- a/trunk/src/app/srs_app_rtc_queue.cpp +++ b/trunk/src/app/srs_app_rtc_queue.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_queue.hpp b/trunk/src/app/srs_app_rtc_queue.hpp index bd3a512486..bb94840434 100644 --- a/trunk/src/app/srs_app_rtc_queue.hpp +++ b/trunk/src/app/srs_app_rtc_queue.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_sdp.cpp b/trunk/src/app/srs_app_rtc_sdp.cpp index 3afe3ff1df..901d4bffee 100644 --- a/trunk/src/app/srs_app_rtc_sdp.cpp +++ b/trunk/src/app/srs_app_rtc_sdp.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_sdp.hpp b/trunk/src/app/srs_app_rtc_sdp.hpp index d9f9b4f1af..d8fb5f18cd 100644 --- a/trunk/src/app/srs_app_rtc_sdp.hpp +++ b/trunk/src/app/srs_app_rtc_sdp.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_server.cpp b/trunk/src/app/srs_app_rtc_server.cpp index 31ff691194..37f018be60 100644 --- a/trunk/src/app/srs_app_rtc_server.cpp +++ b/trunk/src/app/srs_app_rtc_server.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_server.hpp b/trunk/src/app/srs_app_rtc_server.hpp index 68de69ee4c..32e59e9fe7 100644 --- a/trunk/src/app/srs_app_rtc_server.hpp +++ b/trunk/src/app/srs_app_rtc_server.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtc_source.cpp b/trunk/src/app/srs_app_rtc_source.cpp index 40bbc48dc0..c74b59e9e4 100644 --- a/trunk/src/app/srs_app_rtc_source.cpp +++ b/trunk/src/app/srs_app_rtc_source.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -1318,12 +1318,16 @@ SrsRtcFrameBuilder::SrsRtcFrameBuilder(ISrsStreamBridge* bridge) header_sn_ = 0; memset(cache_video_pkts_, 0, sizeof(cache_video_pkts_)); rtp_key_frame_ts_ = -1; + sync_state_ = -1; + obs_whip_sps_ = obs_whip_pps_ = NULL; } SrsRtcFrameBuilder::~SrsRtcFrameBuilder() { srs_freep(codec_); clear_cached_video(); + srs_freep(obs_whip_sps_); + srs_freep(obs_whip_pps_); } srs_error_t SrsRtcFrameBuilder::initialize(SrsRequest* r) @@ -1366,8 +1370,18 @@ srs_error_t SrsRtcFrameBuilder::on_rtp(SrsRtpPacket *pkt) // Have no received any sender report, can't calculate avsync_time, // discard it to avoid timestamp problem in live source + const SrsRtpHeader& h = pkt->header; if (pkt->get_avsync_time() <= 0) { + if (sync_state_ < 0) { + srs_trace("RTC: Discard no-sync %s, ssrc=%u, seq=%u, ts=%u, state=%d", pkt->is_audio() ? "Audio" : "Video", + h.get_ssrc(), h.get_sequence(), h.get_timestamp(), sync_state_); + sync_state_ = 0; + } return err; + } else if (sync_state_ < 1) { + srs_trace("RTC: Accept sync %s, ssrc=%u, seq=%u, ts=%u, state=%d", pkt->is_audio() ? "Audio" : "Video", + h.get_ssrc(), h.get_sequence(), h.get_timestamp(), sync_state_); + sync_state_ = 2; } if (pkt->is_audio()) { @@ -1499,46 +1513,75 @@ srs_error_t SrsRtcFrameBuilder::packet_video_key_frame(SrsRtpPacket* pkt) { srs_error_t err = srs_success; - // TODO: handle sps and pps in 2 rtp packets + // For OBS WHIP, it uses RTP Raw packet with SPS/PPS/IDR frame. Note that not all + // raw payload is SPS/PPS. + bool has_sps_pps_in_raw_payload = false; + SrsRtpRawPayload* raw_payload = dynamic_cast<SrsRtpRawPayload*>(pkt->payload()); + if (raw_payload) { + if (pkt->nalu_type == SrsAvcNaluTypeSPS) { + has_sps_pps_in_raw_payload = true; + srs_freep(obs_whip_sps_); + obs_whip_sps_ = pkt->copy(); + } else if (pkt->nalu_type == SrsAvcNaluTypePPS) { + has_sps_pps_in_raw_payload = true; + srs_freep(obs_whip_pps_); + obs_whip_pps_ = pkt->copy(); + } + // Ignore if one of OBS WHIP SPS/PPS is not ready. + if (has_sps_pps_in_raw_payload && (!obs_whip_sps_ || !obs_whip_pps_)) { + return err; + } + } + + // Generally, there will be SPS+PPS+IDR in a STAP-A packet. SrsRtpSTAPPayload* stap_payload = dynamic_cast<SrsRtpSTAPPayload*>(pkt->payload()); - if (stap_payload) { - SrsSample* sps = stap_payload->get_sps(); - SrsSample* pps = stap_payload->get_pps(); - if (NULL == sps || NULL == pps) { + + // Handle SPS/PPS in cache or STAP-A packet. + if (stap_payload || has_sps_pps_in_raw_payload) { + // Get the SPS/PPS from cache or STAP-A packet. + SrsSample* sps = stap_payload ? stap_payload->get_sps() : NULL; + if (!sps && obs_whip_sps_) sps = dynamic_cast<SrsRtpRawPayload*>(obs_whip_sps_->payload())->sample_; + SrsSample* pps = stap_payload ? stap_payload->get_pps() : NULL; + if (!pps && obs_whip_pps_) pps = dynamic_cast<SrsRtpRawPayload*>(obs_whip_pps_->payload())->sample_; + if (!sps || !pps) { return srs_error_new(ERROR_RTC_RTP_MUXER, "no sps or pps in stap-a rtp. sps: %p, pps:%p", sps, pps); - } else { - // h264 raw to h264 packet. - std::string sh; - SrsRawH264Stream* avc = new SrsRawH264Stream(); - SrsAutoFree(SrsRawH264Stream, avc); + } - if ((err = avc->mux_sequence_header(string(sps->bytes, sps->size), string(pps->bytes, pps->size), sh)) != srs_success) { - return srs_error_wrap(err, "mux sequence header"); - } + // Reset SPS/PPS cache, ensuring that the next SPS/PPS will be handled when both are received. + SrsAutoFree(SrsRtpPacket, obs_whip_sps_); + SrsAutoFree(SrsRtpPacket, obs_whip_pps_); - // h264 packet to flv packet. - char* flv = NULL; - int nb_flv = 0; - if ((err = avc->mux_avc2flv(sh, SrsVideoAvcFrameTypeKeyFrame, SrsVideoAvcFrameTraitSequenceHeader, pkt->get_avsync_time(), - pkt->get_avsync_time(), &flv, &nb_flv)) != srs_success) { - return srs_error_wrap(err, "avc to flv"); - } + // h264 raw to h264 packet. + std::string sh; + SrsRawH264Stream* avc = new SrsRawH264Stream(); + SrsAutoFree(SrsRawH264Stream, avc); - SrsMessageHeader header; - header.initialize_video(nb_flv, pkt->get_avsync_time(), 1); - SrsCommonMessage rtmp; - if ((err = rtmp.create(&header, flv, nb_flv)) != srs_success) { - return srs_error_wrap(err, "create rtmp"); - } + if ((err = avc->mux_sequence_header(string(sps->bytes, sps->size), string(pps->bytes, pps->size), sh)) != srs_success) { + return srs_error_wrap(err, "mux sequence header"); + } - SrsSharedPtrMessage msg; - if ((err = msg.create(&rtmp)) != srs_success) { - return srs_error_wrap(err, "create message"); - } + // h264 packet to flv packet. + char* flv = NULL; + int nb_flv = 0; + if ((err = avc->mux_avc2flv(sh, SrsVideoAvcFrameTypeKeyFrame, SrsVideoAvcFrameTraitSequenceHeader, pkt->get_avsync_time(), + pkt->get_avsync_time(), &flv, &nb_flv)) != srs_success) { + return srs_error_wrap(err, "avc to flv"); + } - if ((err = bridge_->on_frame(&msg)) != srs_success) { - return err; - } + SrsMessageHeader header; + header.initialize_video(nb_flv, pkt->get_avsync_time(), 1); + SrsCommonMessage rtmp; + if ((err = rtmp.create(&header, flv, nb_flv)) != srs_success) { + return srs_error_wrap(err, "create rtmp"); + } + + SrsSharedPtrMessage msg; + if ((err = msg.create(&rtmp)) != srs_success) { + return srs_error_wrap(err, "create message"); + } + + if ((err = bridge_->on_frame(&msg)) != srs_success) { + return err; } } @@ -1583,7 +1626,7 @@ srs_error_t SrsRtcFrameBuilder::packet_video_key_frame(SrsRtpPacket* pkt) if (-1 == sn) { if (check_frame_complete(header_sn_, tail_sn)) { if ((err = packet_video_rtmp(header_sn_, tail_sn)) != srs_success) { - err = srs_error_wrap(err, "fail to packet key frame"); + err = srs_error_wrap(err, "fail to packet frame"); } } } else if (-2 == sn) { @@ -1968,6 +2011,7 @@ SrsAudioPayload::SrsAudioPayload(uint8_t pt, std::string encode_name, int sample channel_ = channel; opus_param_.minptime = 0; opus_param_.use_inband_fec = false; + opus_param_.stereo = false; opus_param_.usedtx = false; } @@ -2009,6 +2053,9 @@ SrsMediaPayloadType SrsAudioPayload::generate_media_payload_type() if (opus_param_.use_inband_fec) { format_specific_param << ";useinbandfec=1"; } + if (opus_param_.stereo) { + format_specific_param << ";stereo=1"; + } if (opus_param_.usedtx) { format_specific_param << ";usedtx=1"; } @@ -2028,6 +2075,8 @@ srs_error_t SrsAudioPayload::set_opus_param_desc(std::string fmtp) opus_param_.minptime = (int)::atol(kv[1].c_str()); } else if (kv[0] == "useinbandfec") { opus_param_.use_inband_fec = (kv[1] == "1") ? true : false; + } else if (kv[0] == "stereo") { + opus_param_.stereo = (kv[1] == "1") ? true : false; } else if (kv[0] == "usedtx") { opus_param_.usedtx = (kv[1] == "1") ? true : false; } diff --git a/trunk/src/app/srs_app_rtc_source.hpp b/trunk/src/app/srs_app_rtc_source.hpp index 191e7d7ec4..02e786cf28 100644 --- a/trunk/src/app/srs_app_rtc_source.hpp +++ b/trunk/src/app/srs_app_rtc_source.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -318,6 +318,13 @@ class SrsRtcFrameBuilder uint16_t header_sn_; uint16_t lost_sn_; int64_t rtp_key_frame_ts_; +private: + // The state for timestamp sync state. -1 for init. 0 not sync. 1 sync. + int sync_state_; +private: + // For OBS WHIP, send SPS/PPS in dedicated RTP packet. + SrsRtpPacket* obs_whip_sps_; + SrsRtpPacket* obs_whip_pps_; public: SrsRtcFrameBuilder(ISrsStreamBridge* bridge); virtual ~SrsRtcFrameBuilder(); @@ -389,11 +396,13 @@ class SrsAudioPayload : public SrsCodecPayload { int minptime; bool use_inband_fec; + bool stereo; bool usedtx; SrsOpusParameter() { minptime = 0; use_inband_fec = false; + stereo = false; usedtx = false; } }; diff --git a/trunk/src/app/srs_app_rtmp_conn.cpp b/trunk/src/app/srs_app_rtmp_conn.cpp index 119a0ba913..dc0989632f 100644 --- a/trunk/src/app/srs_app_rtmp_conn.cpp +++ b/trunk/src/app/srs_app_rtmp_conn.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_rtmp_conn.hpp b/trunk/src/app/srs_app_rtmp_conn.hpp index 84599f2992..c0704be5f9 100644 --- a/trunk/src/app/srs_app_rtmp_conn.hpp +++ b/trunk/src/app/srs_app_rtmp_conn.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_security.cpp b/trunk/src/app/srs_app_security.cpp index af4d6bec71..0c9fa2ddb4 100644 --- a/trunk/src/app/srs_app_security.cpp +++ b/trunk/src/app/srs_app_security.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -75,7 +75,10 @@ srs_error_t SrsSecurity::allow_check(SrsConfDirective* rules, SrsRtmpConnType ty switch (type) { case SrsRtmpConnPlay: - case SrsRtcConnPlay: + case SrsHlsPlay: + case SrsFlvPlay: + case SrsRtcConnPlay: + case SrsSrtConnPlay: if (rule->arg0() != "play") { break; } @@ -90,6 +93,7 @@ srs_error_t SrsSecurity::allow_check(SrsConfDirective* rules, SrsRtmpConnType ty case SrsRtmpConnFlashPublish: case SrsRtmpConnHaivisionPublish: case SrsRtcConnPublish: + case SrsSrtConnPublish: if (rule->arg0() != "publish") { break; } @@ -126,7 +130,10 @@ srs_error_t SrsSecurity::deny_check(SrsConfDirective* rules, SrsRtmpConnType typ switch (type) { case SrsRtmpConnPlay: - case SrsRtcConnPlay: + case SrsHlsPlay: + case SrsFlvPlay: + case SrsRtcConnPlay: + case SrsSrtConnPlay: if (rule->arg0() != "play") { break; } @@ -141,6 +148,7 @@ srs_error_t SrsSecurity::deny_check(SrsConfDirective* rules, SrsRtmpConnType typ case SrsRtmpConnFlashPublish: case SrsRtmpConnHaivisionPublish: case SrsRtcConnPublish: + case SrsSrtConnPublish: if (rule->arg0() != "publish") { break; } diff --git a/trunk/src/app/srs_app_security.hpp b/trunk/src/app/srs_app_security.hpp index cab7cafc1e..1502027cb5 100644 --- a/trunk/src/app/srs_app_security.hpp +++ b/trunk/src/app/srs_app_security.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_server.cpp b/trunk/src/app/srs_app_server.cpp index c22b47db90..9c36bc2849 100644 --- a/trunk/src/app/srs_app_server.cpp +++ b/trunk/src/app/srs_app_server.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -604,7 +604,7 @@ srs_error_t SrsServer::listen() // Create HTTPS API listener. if (_srs_config->get_https_api_enabled()) { if (reuse_api_over_server_) { - srs_trace("HTTPS-API: Reuse listen to http server %s", _srs_config->get_http_stream_listen().c_str()); + srs_trace("HTTPS-API: Reuse listen to http server %s", _srs_config->get_https_stream_listen().c_str()); } else { apis_listener_->set_endpoint(_srs_config->get_https_api_listen())->set_label("HTTPS-API"); if ((err = apis_listener_->listen()) != srs_success) { diff --git a/trunk/src/app/srs_app_server.hpp b/trunk/src/app/srs_app_server.hpp index 505d8d29f9..bc5575c34c 100644 --- a/trunk/src/app/srs_app_server.hpp +++ b/trunk/src/app/srs_app_server.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_source.cpp b/trunk/src/app/srs_app_source.cpp index 49f3ad57f2..ecd61fd692 100755 --- a/trunk/src/app/srs_app_source.cpp +++ b/trunk/src/app/srs_app_source.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_source.hpp b/trunk/src/app/srs_app_source.hpp index 59a97fa52f..75a0b6a765 100644 --- a/trunk/src/app/srs_app_source.hpp +++ b/trunk/src/app/srs_app_source.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_srt_conn.cpp b/trunk/src/app/srs_app_srt_conn.cpp index 427f567f4d..8306bc34af 100644 --- a/trunk/src/app/srs_app_srt_conn.cpp +++ b/trunk/src/app/srs_app_srt_conn.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -174,6 +174,8 @@ SrsMpegtsSrtConn::SrsMpegtsSrtConn(SrsSrtServer* srt_server, srs_srt_t srt_fd, s srt_source_ = NULL; req_ = new SrsRequest(); req_->ip = ip; + + security_ = new SrsSecurity(); } SrsMpegtsSrtConn::~SrsMpegtsSrtConn() @@ -184,6 +186,7 @@ SrsMpegtsSrtConn::~SrsMpegtsSrtConn() srs_freep(delta_); srs_freep(srt_conn_); srs_freep(req_); + srs_freep(security_); } std::string SrsMpegtsSrtConn::desc() @@ -260,7 +263,7 @@ srs_error_t SrsMpegtsSrtConn::do_cycle() // If streamid empty, using default streamid instead. if (streamid.empty()) { streamid = "#!::r=live/livestream,m=publish"; - srs_warn("srt get empty streamid, using default steramid %s instead", streamid.c_str()); + srs_warn("srt get empty streamid, using default streamid %s instead", streamid.c_str()); } // Detect streamid of srt to request. @@ -311,6 +314,10 @@ srs_error_t SrsMpegtsSrtConn::publishing() return srs_error_wrap(err, "srt: stat client"); } + if ((err = security_->check(SrsSrtConnPublish, ip_, req_)) != srs_success) { + return srs_error_wrap(err, "srt: security check"); + } + // We must do hook after stat, because depends on it. if ((err = http_hooks_on_publish()) != srs_success) { return srs_error_wrap(err, "srt: callback on publish"); @@ -333,12 +340,16 @@ srs_error_t SrsMpegtsSrtConn::playing() // We must do stat the client before hooks, because hooks depends on it. SrsStatistic* stat = SrsStatistic::instance(); if ((err = stat->on_client(_srs_context->get_id().c_str(), req_, this, SrsSrtConnPlay)) != srs_success) { - return srs_error_wrap(err, "rtmp: stat client"); + return srs_error_wrap(err, "srt: stat client"); + } + + if ((err = security_->check(SrsSrtConnPlay, ip_, req_)) != srs_success) { + return srs_error_wrap(err, "srt: security check"); } // We must do hook after stat, because depends on it. if ((err = http_hooks_on_play()) != srs_success) { - return srs_error_wrap(err, "rtmp: callback on play"); + return srs_error_wrap(err, "srt: callback on play"); } err = do_playing(); diff --git a/trunk/src/app/srs_app_srt_conn.hpp b/trunk/src/app/srs_app_srt_conn.hpp index 0b9f04884a..71833985f1 100644 --- a/trunk/src/app/srs_app_srt_conn.hpp +++ b/trunk/src/app/srs_app_srt_conn.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -16,6 +16,7 @@ #include <srs_app_st.hpp> #include <srs_app_conn.hpp> #include <srs_app_srt_utility.hpp> +#include <srs_app_security.hpp> class SrsBuffer; class SrsLiveSource; @@ -123,6 +124,7 @@ class SrsMpegtsSrtConn : public ISrsConnection, public ISrsStartable, public ISr SrsRequest* req_; SrsSrtSource* srt_source_; + SrsSecurity* security_; }; #endif diff --git a/trunk/src/app/srs_app_srt_listener.cpp b/trunk/src/app/srs_app_srt_listener.cpp index 6bf4403f00..75b37baf6d 100644 --- a/trunk/src/app/srs_app_srt_listener.cpp +++ b/trunk/src/app/srs_app_srt_listener.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_srt_listener.hpp b/trunk/src/app/srs_app_srt_listener.hpp index e37279f599..31fc41632e 100644 --- a/trunk/src/app/srs_app_srt_listener.hpp +++ b/trunk/src/app/srs_app_srt_listener.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_srt_server.cpp b/trunk/src/app/srs_app_srt_server.cpp index 5811f817c7..aea7f59fcb 100644 --- a/trunk/src/app/srs_app_srt_server.cpp +++ b/trunk/src/app/srs_app_srt_server.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_srt_server.hpp b/trunk/src/app/srs_app_srt_server.hpp index 0ec2857131..7ede58b4bd 100644 --- a/trunk/src/app/srs_app_srt_server.hpp +++ b/trunk/src/app/srs_app_srt_server.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_srt_source.cpp b/trunk/src/app/srs_app_srt_source.cpp index 722e783927..032bda5cc9 100644 --- a/trunk/src/app/srs_app_srt_source.cpp +++ b/trunk/src/app/srs_app_srt_source.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_srt_source.hpp b/trunk/src/app/srs_app_srt_source.hpp index 8051edbe31..80ea4b10f0 100644 --- a/trunk/src/app/srs_app_srt_source.hpp +++ b/trunk/src/app/srs_app_srt_source.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -111,13 +111,13 @@ class SrsSrtFrameBuilder : public ISrsTsHandler srs_error_t on_ts_video_avc(SrsTsMessage* msg, SrsBuffer* avs); srs_error_t on_ts_audio(SrsTsMessage* msg, SrsBuffer* avs); srs_error_t check_sps_pps_change(SrsTsMessage* msg); - srs_error_t on_h264_frame(SrsTsMessage* msg, std::vector<std::pair<char*, int> >& ipb_frames); + srs_error_t on_h264_frame(SrsTsMessage* msg, std::vector< std::pair<char*, int> >& ipb_frames); srs_error_t check_audio_sh_change(SrsTsMessage* msg, uint32_t pts); srs_error_t on_aac_frame(SrsTsMessage* msg, uint32_t pts, char* frame, int frame_size); #ifdef SRS_H265 srs_error_t on_ts_video_hevc(SrsTsMessage *msg, SrsBuffer *avs); srs_error_t check_vps_sps_pps_change(SrsTsMessage *msg); - srs_error_t on_hevc_frame(SrsTsMessage *msg, std::vector<std::pair<char *, int>> &ipb_frames); + srs_error_t on_hevc_frame(SrsTsMessage *msg, std::vector< std::pair<char *, int> > &ipb_frames); #endif private: ISrsStreamBridge* bridge_; diff --git a/trunk/src/app/srs_app_srt_utility.cpp b/trunk/src/app/srs_app_srt_utility.cpp index 0fa7fb51c8..360bab38cd 100644 --- a/trunk/src/app/srs_app_srt_utility.cpp +++ b/trunk/src/app/srs_app_srt_utility.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_srt_utility.hpp b/trunk/src/app/srs_app_srt_utility.hpp index 06cd74dcc8..366493e425 100644 --- a/trunk/src/app/srs_app_srt_utility.hpp +++ b/trunk/src/app/srs_app_srt_utility.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_st.cpp b/trunk/src/app/srs_app_st.cpp index 0d4c49ed5f..77f581a640 100755 --- a/trunk/src/app/srs_app_st.cpp +++ b/trunk/src/app/srs_app_st.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_st.hpp b/trunk/src/app/srs_app_st.hpp index 6ec5c882c9..2f221f6e88 100644 --- a/trunk/src/app/srs_app_st.hpp +++ b/trunk/src/app/srs_app_st.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_statistic.cpp b/trunk/src/app/srs_app_statistic.cpp index 82743b4dc2..986e74c0e9 100644 --- a/trunk/src/app/srs_app_statistic.cpp +++ b/trunk/src/app/srs_app_statistic.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_statistic.hpp b/trunk/src/app/srs_app_statistic.hpp index 3777ffa926..f3bfd83117 100644 --- a/trunk/src/app/srs_app_statistic.hpp +++ b/trunk/src/app/srs_app_statistic.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_stream_bridge.cpp b/trunk/src/app/srs_app_stream_bridge.cpp index 34ea1ba0ee..1c391dd83e 100644 --- a/trunk/src/app/srs_app_stream_bridge.cpp +++ b/trunk/src/app/srs_app_stream_bridge.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_stream_bridge.hpp b/trunk/src/app/srs_app_stream_bridge.hpp index 50a13bdae9..6b85bb7a55 100644 --- a/trunk/src/app/srs_app_stream_bridge.hpp +++ b/trunk/src/app/srs_app_stream_bridge.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_tencentcloud.cpp b/trunk/src/app/srs_app_tencentcloud.cpp index e980e6fbab..68a2f4ae34 100644 --- a/trunk/src/app/srs_app_tencentcloud.cpp +++ b/trunk/src/app/srs_app_tencentcloud.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_tencentcloud.hpp b/trunk/src/app/srs_app_tencentcloud.hpp index 19109884e4..a3aac3e5ab 100644 --- a/trunk/src/app/srs_app_tencentcloud.hpp +++ b/trunk/src/app/srs_app_tencentcloud.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_threads.cpp b/trunk/src/app/srs_app_threads.cpp index 78d540b5c9..b42a163be1 100644 --- a/trunk/src/app/srs_app_threads.cpp +++ b/trunk/src/app/srs_app_threads.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_threads.hpp b/trunk/src/app/srs_app_threads.hpp index 9e1c6f1a3f..3192f500c4 100644 --- a/trunk/src/app/srs_app_threads.hpp +++ b/trunk/src/app/srs_app_threads.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_utility.cpp b/trunk/src/app/srs_app_utility.cpp index 5d9aa91861..9206eb2991 100644 --- a/trunk/src/app/srs_app_utility.cpp +++ b/trunk/src/app/srs_app_utility.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/app/srs_app_utility.hpp b/trunk/src/app/srs_app_utility.hpp index 3376f0974d..347cb54bfe 100644 --- a/trunk/src/app/srs_app_utility.hpp +++ b/trunk/src/app/srs_app_utility.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core.cpp b/trunk/src/core/srs_core.cpp index f7f72f285b..8bd4a9b5f9 100644 --- a/trunk/src/core/srs_core.cpp +++ b/trunk/src/core/srs_core.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core.hpp b/trunk/src/core/srs_core.hpp index 5262ca641e..aee49c567b 100644 --- a/trunk/src/core/srs_core.hpp +++ b/trunk/src/core/srs_core.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_autofree.cpp b/trunk/src/core/srs_core_autofree.cpp index efc7ef0690..2c5f8f14df 100644 --- a/trunk/src/core/srs_core_autofree.cpp +++ b/trunk/src/core/srs_core_autofree.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_autofree.hpp b/trunk/src/core/srs_core_autofree.hpp index 1a6a95c78c..e8f281519e 100644 --- a/trunk/src/core/srs_core_autofree.hpp +++ b/trunk/src/core/srs_core_autofree.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_performance.cpp b/trunk/src/core/srs_core_performance.cpp index dbfdaff12c..d5eac676d6 100644 --- a/trunk/src/core/srs_core_performance.cpp +++ b/trunk/src/core/srs_core_performance.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_performance.hpp b/trunk/src/core/srs_core_performance.hpp index 7e7dde340e..0d72d49bc7 100644 --- a/trunk/src/core/srs_core_performance.hpp +++ b/trunk/src/core/srs_core_performance.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_platform.cpp b/trunk/src/core/srs_core_platform.cpp index daa790bfbf..e5b3e2675c 100644 --- a/trunk/src/core/srs_core_platform.cpp +++ b/trunk/src/core/srs_core_platform.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_platform.hpp b/trunk/src/core/srs_core_platform.hpp index e743438fe2..8ff5001976 100644 --- a/trunk/src/core/srs_core_platform.hpp +++ b/trunk/src/core/srs_core_platform.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_time.cpp b/trunk/src/core/srs_core_time.cpp index 610064f43f..9a401b46de 100644 --- a/trunk/src/core/srs_core_time.cpp +++ b/trunk/src/core/srs_core_time.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_time.hpp b/trunk/src/core/srs_core_time.hpp index 2f9aff98d2..c10c7c9b1b 100644 --- a/trunk/src/core/srs_core_time.hpp +++ b/trunk/src/core/srs_core_time.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version.cpp b/trunk/src/core/srs_core_version.cpp index 6d4df13350..c9d0d5b789 100644 --- a/trunk/src/core/srs_core_version.cpp +++ b/trunk/src/core/srs_core_version.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version.hpp b/trunk/src/core/srs_core_version.hpp index 0f7ef84c15..cb535d6242 100644 --- a/trunk/src/core/srs_core_version.hpp +++ b/trunk/src/core/srs_core_version.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version3.cpp b/trunk/src/core/srs_core_version3.cpp index 03386ab1ad..80103d013d 100644 --- a/trunk/src/core/srs_core_version3.cpp +++ b/trunk/src/core/srs_core_version3.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version3.hpp b/trunk/src/core/srs_core_version3.hpp index d7f0eb155c..230152de83 100644 --- a/trunk/src/core/srs_core_version3.hpp +++ b/trunk/src/core/srs_core_version3.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version4.cpp b/trunk/src/core/srs_core_version4.cpp index 9cedbcc826..92231cca0a 100644 --- a/trunk/src/core/srs_core_version4.cpp +++ b/trunk/src/core/srs_core_version4.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version4.hpp b/trunk/src/core/srs_core_version4.hpp index 4c217cb9ff..8f8537799a 100644 --- a/trunk/src/core/srs_core_version4.hpp +++ b/trunk/src/core/srs_core_version4.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version5.cpp b/trunk/src/core/srs_core_version5.cpp index ec80c677a7..36e735316a 100644 --- a/trunk/src/core/srs_core_version5.cpp +++ b/trunk/src/core/srs_core_version5.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version5.hpp b/trunk/src/core/srs_core_version5.hpp index 4f782697da..1e9a74079e 100644 --- a/trunk/src/core/srs_core_version5.hpp +++ b/trunk/src/core/srs_core_version5.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -9,6 +9,6 @@ #define VERSION_MAJOR 5 #define VERSION_MINOR 0 -#define VERSION_REVISION 200 +#define VERSION_REVISION 208 #endif diff --git a/trunk/src/core/srs_core_version6.cpp b/trunk/src/core/srs_core_version6.cpp index dbc9c0bcc7..96b1389928 100644 --- a/trunk/src/core/srs_core_version6.cpp +++ b/trunk/src/core/srs_core_version6.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/core/srs_core_version6.hpp b/trunk/src/core/srs_core_version6.hpp index d1ce3f3583..d19e4628a1 100644 --- a/trunk/src/core/srs_core_version6.hpp +++ b/trunk/src/core/srs_core_version6.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -9,6 +9,6 @@ #define VERSION_MAJOR 6 #define VERSION_MINOR 0 -#define VERSION_REVISION 101 +#define VERSION_REVISION 113 #endif diff --git a/trunk/src/kernel/srs_kernel_aac.cpp b/trunk/src/kernel/srs_kernel_aac.cpp index 90a00b47ac..a3dad0c006 100644 --- a/trunk/src/kernel/srs_kernel_aac.cpp +++ b/trunk/src/kernel/srs_kernel_aac.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_aac.hpp b/trunk/src/kernel/srs_kernel_aac.hpp index 3a55726de0..0d91fef25f 100644 --- a/trunk/src/kernel/srs_kernel_aac.hpp +++ b/trunk/src/kernel/srs_kernel_aac.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_balance.cpp b/trunk/src/kernel/srs_kernel_balance.cpp index 3627f640d1..eca9aaf692 100644 --- a/trunk/src/kernel/srs_kernel_balance.cpp +++ b/trunk/src/kernel/srs_kernel_balance.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_balance.hpp b/trunk/src/kernel/srs_kernel_balance.hpp index 41fb28b03f..8fcfaee6be 100644 --- a/trunk/src/kernel/srs_kernel_balance.hpp +++ b/trunk/src/kernel/srs_kernel_balance.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_buffer.cpp b/trunk/src/kernel/srs_kernel_buffer.cpp index d37abf8caf..8f0bc8aad2 100644 --- a/trunk/src/kernel/srs_kernel_buffer.cpp +++ b/trunk/src/kernel/srs_kernel_buffer.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_buffer.hpp b/trunk/src/kernel/srs_kernel_buffer.hpp index b093e97248..9233c256b2 100644 --- a/trunk/src/kernel/srs_kernel_buffer.hpp +++ b/trunk/src/kernel/srs_kernel_buffer.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_codec.cpp b/trunk/src/kernel/srs_kernel_codec.cpp index d232aabc35..9afe07867e 100644 --- a/trunk/src/kernel/srs_kernel_codec.cpp +++ b/trunk/src/kernel/srs_kernel_codec.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_codec.hpp b/trunk/src/kernel/srs_kernel_codec.hpp index ecb188ebc5..5f8fc934af 100644 --- a/trunk/src/kernel/srs_kernel_codec.hpp +++ b/trunk/src/kernel/srs_kernel_codec.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -778,7 +778,7 @@ struct SrsHevcRbspVps uint32_t vps_max_latency_increase_plus1[8]; uint8_t vps_max_layer_id; uint32_t vps_num_layer_sets_minus1; - std::vector<std::vector<uint8_t>> layer_id_included_flag; + std::vector< std::vector<uint8_t> > layer_id_included_flag; uint8_t vps_timing_info_present_flag; uint32_t vps_num_units_in_tick; uint32_t vps_time_scale; diff --git a/trunk/src/kernel/srs_kernel_consts.cpp b/trunk/src/kernel/srs_kernel_consts.cpp index e0d9669ff0..b8472f555b 100644 --- a/trunk/src/kernel/srs_kernel_consts.cpp +++ b/trunk/src/kernel/srs_kernel_consts.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_consts.hpp b/trunk/src/kernel/srs_kernel_consts.hpp index 6b46c78df4..cec4260abe 100644 --- a/trunk/src/kernel/srs_kernel_consts.hpp +++ b/trunk/src/kernel/srs_kernel_consts.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_error.cpp b/trunk/src/kernel/srs_kernel_error.cpp index f8fac3c81f..886f8f9513 100644 --- a/trunk/src/kernel/srs_kernel_error.cpp +++ b/trunk/src/kernel/srs_kernel_error.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_error.hpp b/trunk/src/kernel/srs_kernel_error.hpp index b20bf908ce..c444e2f58a 100644 --- a/trunk/src/kernel/srs_kernel_error.hpp +++ b/trunk/src/kernel/srs_kernel_error.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_file.cpp b/trunk/src/kernel/srs_kernel_file.cpp index d14c020b09..94620dddae 100644 --- a/trunk/src/kernel/srs_kernel_file.cpp +++ b/trunk/src/kernel/srs_kernel_file.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_file.hpp b/trunk/src/kernel/srs_kernel_file.hpp index 0a69a1d93a..f7dfad5bc8 100644 --- a/trunk/src/kernel/srs_kernel_file.hpp +++ b/trunk/src/kernel/srs_kernel_file.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_flv.cpp b/trunk/src/kernel/srs_kernel_flv.cpp index 9503553c3b..20111e8396 100644 --- a/trunk/src/kernel/srs_kernel_flv.cpp +++ b/trunk/src/kernel/srs_kernel_flv.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_flv.hpp b/trunk/src/kernel/srs_kernel_flv.hpp index a218aa411c..349c4c5795 100644 --- a/trunk/src/kernel/srs_kernel_flv.hpp +++ b/trunk/src/kernel/srs_kernel_flv.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_io.cpp b/trunk/src/kernel/srs_kernel_io.cpp index 10c93f4a25..8e61784500 100644 --- a/trunk/src/kernel/srs_kernel_io.cpp +++ b/trunk/src/kernel/srs_kernel_io.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_io.hpp b/trunk/src/kernel/srs_kernel_io.hpp index 7798f5a870..1236d0757d 100644 --- a/trunk/src/kernel/srs_kernel_io.hpp +++ b/trunk/src/kernel/srs_kernel_io.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_kbps.cpp b/trunk/src/kernel/srs_kernel_kbps.cpp index 59b5bcdbd0..147b92b335 100644 --- a/trunk/src/kernel/srs_kernel_kbps.cpp +++ b/trunk/src/kernel/srs_kernel_kbps.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_kbps.hpp b/trunk/src/kernel/srs_kernel_kbps.hpp index fd69e8d385..b97a4a94bb 100644 --- a/trunk/src/kernel/srs_kernel_kbps.hpp +++ b/trunk/src/kernel/srs_kernel_kbps.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_log.cpp b/trunk/src/kernel/srs_kernel_log.cpp index 994ecc6302..eeb527e7c8 100644 --- a/trunk/src/kernel/srs_kernel_log.cpp +++ b/trunk/src/kernel/srs_kernel_log.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_log.hpp b/trunk/src/kernel/srs_kernel_log.hpp index 84b1988d3d..ec64c25989 100644 --- a/trunk/src/kernel/srs_kernel_log.hpp +++ b/trunk/src/kernel/srs_kernel_log.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_mp3.cpp b/trunk/src/kernel/srs_kernel_mp3.cpp index 8bd322d86b..c18a28beee 100644 --- a/trunk/src/kernel/srs_kernel_mp3.cpp +++ b/trunk/src/kernel/srs_kernel_mp3.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_mp3.hpp b/trunk/src/kernel/srs_kernel_mp3.hpp index 55c4a69def..5aed6affd6 100644 --- a/trunk/src/kernel/srs_kernel_mp3.hpp +++ b/trunk/src/kernel/srs_kernel_mp3.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_mp4.cpp b/trunk/src/kernel/srs_kernel_mp4.cpp index a673137fda..f0ce4c1f93 100644 --- a/trunk/src/kernel/srs_kernel_mp4.cpp +++ b/trunk/src/kernel/srs_kernel_mp4.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_mp4.hpp b/trunk/src/kernel/srs_kernel_mp4.hpp index b5b8910cee..23805773e6 100644 --- a/trunk/src/kernel/srs_kernel_mp4.hpp +++ b/trunk/src/kernel/srs_kernel_mp4.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_ps.cpp b/trunk/src/kernel/srs_kernel_ps.cpp index f4c1b10569..6207a446b8 100644 --- a/trunk/src/kernel/srs_kernel_ps.cpp +++ b/trunk/src/kernel/srs_kernel_ps.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_ps.hpp b/trunk/src/kernel/srs_kernel_ps.hpp index 6c0b375f84..8d64ad3ae0 100644 --- a/trunk/src/kernel/srs_kernel_ps.hpp +++ b/trunk/src/kernel/srs_kernel_ps.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_rtc_rtcp.cpp b/trunk/src/kernel/srs_kernel_rtc_rtcp.cpp index 18fa7848d5..847b85e28f 100644 --- a/trunk/src/kernel/srs_kernel_rtc_rtcp.cpp +++ b/trunk/src/kernel/srs_kernel_rtc_rtcp.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_rtc_rtcp.hpp b/trunk/src/kernel/srs_kernel_rtc_rtcp.hpp index 47c57858a7..57efb6a9ce 100644 --- a/trunk/src/kernel/srs_kernel_rtc_rtcp.hpp +++ b/trunk/src/kernel/srs_kernel_rtc_rtcp.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_rtc_rtp.cpp b/trunk/src/kernel/srs_kernel_rtc_rtp.cpp index 4c9a99bdcb..761223f8be 100644 --- a/trunk/src/kernel/srs_kernel_rtc_rtp.cpp +++ b/trunk/src/kernel/srs_kernel_rtc_rtp.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -970,12 +970,14 @@ SrsRtpRawPayload::SrsRtpRawPayload() { payload = NULL; nn_payload = 0; + sample_ = new SrsSample(); ++_srs_pps_objs_rraw->sugar; } SrsRtpRawPayload::~SrsRtpRawPayload() { + srs_freep(sample_); } uint64_t SrsRtpRawPayload::nb_bytes() @@ -1007,6 +1009,9 @@ srs_error_t SrsRtpRawPayload::decode(SrsBuffer* buf) payload = buf->head(); nn_payload = buf->left(); + sample_->bytes = payload; + sample_->size = nn_payload; + return srs_success; } @@ -1016,6 +1021,7 @@ ISrsRtpPayloader* SrsRtpRawPayload::copy() cp->payload = payload; cp->nn_payload = nn_payload; + cp->sample_ = sample_->copy(); return cp; } diff --git a/trunk/src/kernel/srs_kernel_rtc_rtp.hpp b/trunk/src/kernel/srs_kernel_rtc_rtp.hpp index db5c8e0500..9aca86e660 100644 --- a/trunk/src/kernel/srs_kernel_rtc_rtp.hpp +++ b/trunk/src/kernel/srs_kernel_rtc_rtp.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -348,6 +348,9 @@ class SrsRtpRawPayload : public ISrsRtpPayloader // @remark We only refer to the memory, user must free its bytes. char* payload; int nn_payload; +public: + // Use the whole RAW RTP payload as a sample. + SrsSample* sample_; public: SrsRtpRawPayload(); virtual ~SrsRtpRawPayload(); diff --git a/trunk/src/kernel/srs_kernel_stream.cpp b/trunk/src/kernel/srs_kernel_stream.cpp index c1d75b2e42..ce75719874 100755 --- a/trunk/src/kernel/srs_kernel_stream.cpp +++ b/trunk/src/kernel/srs_kernel_stream.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_stream.hpp b/trunk/src/kernel/srs_kernel_stream.hpp index 4dc3fced46..cb0bcf6463 100644 --- a/trunk/src/kernel/srs_kernel_stream.hpp +++ b/trunk/src/kernel/srs_kernel_stream.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_ts.cpp b/trunk/src/kernel/srs_kernel_ts.cpp index 5fd6585c89..a2fca00eab 100644 --- a/trunk/src/kernel/srs_kernel_ts.cpp +++ b/trunk/src/kernel/srs_kernel_ts.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_ts.hpp b/trunk/src/kernel/srs_kernel_ts.hpp index 8ded422202..e79f07f9ef 100644 --- a/trunk/src/kernel/srs_kernel_ts.hpp +++ b/trunk/src/kernel/srs_kernel_ts.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_utility.cpp b/trunk/src/kernel/srs_kernel_utility.cpp index ed5125f957..204b8f1459 100644 --- a/trunk/src/kernel/srs_kernel_utility.cpp +++ b/trunk/src/kernel/srs_kernel_utility.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/kernel/srs_kernel_utility.hpp b/trunk/src/kernel/srs_kernel_utility.hpp index f81184495a..603f4d2f69 100644 --- a/trunk/src/kernel/srs_kernel_utility.hpp +++ b/trunk/src/kernel/srs_kernel_utility.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/main/srs_main_ingest_hls.cpp b/trunk/src/main/srs_main_ingest_hls.cpp index d2bb944ac7..c2038568d1 100644 --- a/trunk/src/main/srs_main_ingest_hls.cpp +++ b/trunk/src/main/srs_main_ingest_hls.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/main/srs_main_mp4_parser.cpp b/trunk/src/main/srs_main_mp4_parser.cpp index 84f0c564f3..e9137c8374 100644 --- a/trunk/src/main/srs_main_mp4_parser.cpp +++ b/trunk/src/main/srs_main_mp4_parser.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/main/srs_main_server.cpp b/trunk/src/main/srs_main_server.cpp index f30d18d61d..c101d1a9df 100644 --- a/trunk/src/main/srs_main_server.cpp +++ b/trunk/src/main/srs_main_server.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_amf0.cpp b/trunk/src/protocol/srs_protocol_amf0.cpp index ddd5d6899f..b24b96e5ba 100644 --- a/trunk/src/protocol/srs_protocol_amf0.cpp +++ b/trunk/src/protocol/srs_protocol_amf0.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_amf0.hpp b/trunk/src/protocol/srs_protocol_amf0.hpp index f221ffc5d6..a69e4b5cd4 100644 --- a/trunk/src/protocol/srs_protocol_amf0.hpp +++ b/trunk/src/protocol/srs_protocol_amf0.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_conn.cpp b/trunk/src/protocol/srs_protocol_conn.cpp index aac5f133a4..0c988b9b60 100644 --- a/trunk/src/protocol/srs_protocol_conn.cpp +++ b/trunk/src/protocol/srs_protocol_conn.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_conn.hpp b/trunk/src/protocol/srs_protocol_conn.hpp index a884c8d310..b136716adf 100644 --- a/trunk/src/protocol/srs_protocol_conn.hpp +++ b/trunk/src/protocol/srs_protocol_conn.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_format.cpp b/trunk/src/protocol/srs_protocol_format.cpp index 20fe4433b9..88c85cbdad 100644 --- a/trunk/src/protocol/srs_protocol_format.cpp +++ b/trunk/src/protocol/srs_protocol_format.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_format.hpp b/trunk/src/protocol/srs_protocol_format.hpp index cc187d6489..668029cbd7 100644 --- a/trunk/src/protocol/srs_protocol_format.hpp +++ b/trunk/src/protocol/srs_protocol_format.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_http_client.cpp b/trunk/src/protocol/srs_protocol_http_client.cpp index 0362ded0b3..99379b3823 100644 --- a/trunk/src/protocol/srs_protocol_http_client.cpp +++ b/trunk/src/protocol/srs_protocol_http_client.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_http_client.hpp b/trunk/src/protocol/srs_protocol_http_client.hpp index 6f03f7acf4..f6ac9633fc 100644 --- a/trunk/src/protocol/srs_protocol_http_client.hpp +++ b/trunk/src/protocol/srs_protocol_http_client.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_http_conn.cpp b/trunk/src/protocol/srs_protocol_http_conn.cpp index 2b29c2b323..7b91b8afb4 100644 --- a/trunk/src/protocol/srs_protocol_http_conn.cpp +++ b/trunk/src/protocol/srs_protocol_http_conn.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_http_conn.hpp b/trunk/src/protocol/srs_protocol_http_conn.hpp index 07e4c96e08..92804e3437 100644 --- a/trunk/src/protocol/srs_protocol_http_conn.hpp +++ b/trunk/src/protocol/srs_protocol_http_conn.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_http_stack.cpp b/trunk/src/protocol/srs_protocol_http_stack.cpp index b89d87c6bf..8b02a3175a 100644 --- a/trunk/src/protocol/srs_protocol_http_stack.cpp +++ b/trunk/src/protocol/srs_protocol_http_stack.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_http_stack.hpp b/trunk/src/protocol/srs_protocol_http_stack.hpp index 3088dc5ad1..9cafb1ba91 100644 --- a/trunk/src/protocol/srs_protocol_http_stack.hpp +++ b/trunk/src/protocol/srs_protocol_http_stack.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_io.cpp b/trunk/src/protocol/srs_protocol_io.cpp index b55367317c..d16dfeedad 100644 --- a/trunk/src/protocol/srs_protocol_io.cpp +++ b/trunk/src/protocol/srs_protocol_io.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_io.hpp b/trunk/src/protocol/srs_protocol_io.hpp index f22a63acf8..5f1c4fe792 100644 --- a/trunk/src/protocol/srs_protocol_io.hpp +++ b/trunk/src/protocol/srs_protocol_io.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_json.cpp b/trunk/src/protocol/srs_protocol_json.cpp index 9248139101..4692b3d5ec 100644 --- a/trunk/src/protocol/srs_protocol_json.cpp +++ b/trunk/src/protocol/srs_protocol_json.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // @@ -1314,7 +1314,7 @@ void json_value_free (json_value * value) // LCOV_EXCL_STOP // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_json.hpp b/trunk/src/protocol/srs_protocol_json.hpp index 58558296ab..c316f696dc 100644 --- a/trunk/src/protocol/srs_protocol_json.hpp +++ b/trunk/src/protocol/srs_protocol_json.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_kbps.cpp b/trunk/src/protocol/srs_protocol_kbps.cpp index 451f0d2663..4b46f76815 100644 --- a/trunk/src/protocol/srs_protocol_kbps.cpp +++ b/trunk/src/protocol/srs_protocol_kbps.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_kbps.hpp b/trunk/src/protocol/srs_protocol_kbps.hpp index 445dcb94c2..56e5852607 100644 --- a/trunk/src/protocol/srs_protocol_kbps.hpp +++ b/trunk/src/protocol/srs_protocol_kbps.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_log.cpp b/trunk/src/protocol/srs_protocol_log.cpp index 7e58c6199f..49a863f5cf 100644 --- a/trunk/src/protocol/srs_protocol_log.cpp +++ b/trunk/src/protocol/srs_protocol_log.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_log.hpp b/trunk/src/protocol/srs_protocol_log.hpp index a8a60fedb0..66d529f6f7 100644 --- a/trunk/src/protocol/srs_protocol_log.hpp +++ b/trunk/src/protocol/srs_protocol_log.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_protobuf.cpp b/trunk/src/protocol/srs_protocol_protobuf.cpp index 08011f44d5..0035861659 100644 --- a/trunk/src/protocol/srs_protocol_protobuf.cpp +++ b/trunk/src/protocol/srs_protocol_protobuf.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_protobuf.hpp b/trunk/src/protocol/srs_protocol_protobuf.hpp index 04dcfd2389..57f08b5816 100644 --- a/trunk/src/protocol/srs_protocol_protobuf.hpp +++ b/trunk/src/protocol/srs_protocol_protobuf.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_raw_avc.cpp b/trunk/src/protocol/srs_protocol_raw_avc.cpp index 9a02d2f814..2e1ea9f77b 100644 --- a/trunk/src/protocol/srs_protocol_raw_avc.cpp +++ b/trunk/src/protocol/srs_protocol_raw_avc.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_raw_avc.hpp b/trunk/src/protocol/srs_protocol_raw_avc.hpp index 246b52a029..fabac788e2 100644 --- a/trunk/src/protocol/srs_protocol_raw_avc.hpp +++ b/trunk/src/protocol/srs_protocol_raw_avc.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtc_stun.cpp b/trunk/src/protocol/srs_protocol_rtc_stun.cpp index 9c259cb546..e52e7002c6 100644 --- a/trunk/src/protocol/srs_protocol_rtc_stun.cpp +++ b/trunk/src/protocol/srs_protocol_rtc_stun.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtc_stun.hpp b/trunk/src/protocol/srs_protocol_rtc_stun.hpp index 05abd75029..5387205837 100644 --- a/trunk/src/protocol/srs_protocol_rtc_stun.hpp +++ b/trunk/src/protocol/srs_protocol_rtc_stun.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtmp_conn.cpp b/trunk/src/protocol/srs_protocol_rtmp_conn.cpp index 5be371174c..f489d16e68 100644 --- a/trunk/src/protocol/srs_protocol_rtmp_conn.cpp +++ b/trunk/src/protocol/srs_protocol_rtmp_conn.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtmp_conn.hpp b/trunk/src/protocol/srs_protocol_rtmp_conn.hpp index dc2db1270a..ea3177937c 100644 --- a/trunk/src/protocol/srs_protocol_rtmp_conn.hpp +++ b/trunk/src/protocol/srs_protocol_rtmp_conn.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtmp_handshake.cpp b/trunk/src/protocol/srs_protocol_rtmp_handshake.cpp index 751294de9f..0e8c9f097e 100644 --- a/trunk/src/protocol/srs_protocol_rtmp_handshake.cpp +++ b/trunk/src/protocol/srs_protocol_rtmp_handshake.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtmp_handshake.hpp b/trunk/src/protocol/srs_protocol_rtmp_handshake.hpp index 3f2c5f1d18..fb4cd83e7d 100644 --- a/trunk/src/protocol/srs_protocol_rtmp_handshake.hpp +++ b/trunk/src/protocol/srs_protocol_rtmp_handshake.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtmp_msg_array.cpp b/trunk/src/protocol/srs_protocol_rtmp_msg_array.cpp index d809f2f834..eb173e00d6 100644 --- a/trunk/src/protocol/srs_protocol_rtmp_msg_array.cpp +++ b/trunk/src/protocol/srs_protocol_rtmp_msg_array.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtmp_msg_array.hpp b/trunk/src/protocol/srs_protocol_rtmp_msg_array.hpp index 6346dd2fb5..de03e3cc75 100644 --- a/trunk/src/protocol/srs_protocol_rtmp_msg_array.hpp +++ b/trunk/src/protocol/srs_protocol_rtmp_msg_array.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtmp_stack.cpp b/trunk/src/protocol/srs_protocol_rtmp_stack.cpp index 4bc5c0e28d..ac15baa6c6 100644 --- a/trunk/src/protocol/srs_protocol_rtmp_stack.cpp +++ b/trunk/src/protocol/srs_protocol_rtmp_stack.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_rtmp_stack.hpp b/trunk/src/protocol/srs_protocol_rtmp_stack.hpp index eeb244a37e..8eba0c1a6d 100644 --- a/trunk/src/protocol/srs_protocol_rtmp_stack.hpp +++ b/trunk/src/protocol/srs_protocol_rtmp_stack.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_srt.cpp b/trunk/src/protocol/srs_protocol_srt.cpp index 9587909e92..efad018e85 100644 --- a/trunk/src/protocol/srs_protocol_srt.cpp +++ b/trunk/src/protocol/srs_protocol_srt.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_srt.hpp b/trunk/src/protocol/srs_protocol_srt.hpp index 68c166c650..3412cf95b6 100644 --- a/trunk/src/protocol/srs_protocol_srt.hpp +++ b/trunk/src/protocol/srs_protocol_srt.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_st.cpp b/trunk/src/protocol/srs_protocol_st.cpp index 37e9ec695c..e6127691f6 100644 --- a/trunk/src/protocol/srs_protocol_st.cpp +++ b/trunk/src/protocol/srs_protocol_st.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_st.hpp b/trunk/src/protocol/srs_protocol_st.hpp index d9cb6a0c1b..c893db0777 100644 --- a/trunk/src/protocol/srs_protocol_st.hpp +++ b/trunk/src/protocol/srs_protocol_st.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_stream.cpp b/trunk/src/protocol/srs_protocol_stream.cpp index 381bcdff90..63a8b9a473 100755 --- a/trunk/src/protocol/srs_protocol_stream.cpp +++ b/trunk/src/protocol/srs_protocol_stream.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_stream.hpp b/trunk/src/protocol/srs_protocol_stream.hpp index 39012506e4..44478bc114 100644 --- a/trunk/src/protocol/srs_protocol_stream.hpp +++ b/trunk/src/protocol/srs_protocol_stream.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_utility.cpp b/trunk/src/protocol/srs_protocol_utility.cpp index e6dca59f9d..4a2e599e24 100644 --- a/trunk/src/protocol/srs_protocol_utility.cpp +++ b/trunk/src/protocol/srs_protocol_utility.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/protocol/srs_protocol_utility.hpp b/trunk/src/protocol/srs_protocol_utility.hpp index d1656f71e3..965d3e0758 100644 --- a/trunk/src/protocol/srs_protocol_utility.hpp +++ b/trunk/src/protocol/srs_protocol_utility.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest.cpp b/trunk/src/utest/srs_utest.cpp index b98bd55187..d8ca03562c 100644 --- a/trunk/src/utest/srs_utest.cpp +++ b/trunk/src/utest/srs_utest.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest.hpp b/trunk/src/utest/srs_utest.hpp index c9b2641ede..cd81614d2a 100644 --- a/trunk/src/utest/srs_utest.hpp +++ b/trunk/src/utest/srs_utest.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_amf0.cpp b/trunk/src/utest/srs_utest_amf0.cpp index b2d1bd2f76..e8c446f4f5 100644 --- a/trunk/src/utest/srs_utest_amf0.cpp +++ b/trunk/src/utest/srs_utest_amf0.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_amf0.hpp b/trunk/src/utest/srs_utest_amf0.hpp index a8cf142eb3..4ca9af5aa5 100644 --- a/trunk/src/utest/srs_utest_amf0.hpp +++ b/trunk/src/utest/srs_utest_amf0.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_app.cpp b/trunk/src/utest/srs_utest_app.cpp index 856aaa2e28..0853a2b327 100644 --- a/trunk/src/utest/srs_utest_app.cpp +++ b/trunk/src/utest/srs_utest_app.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_app.hpp b/trunk/src/utest/srs_utest_app.hpp index 1bb25f3383..87ca3acb75 100644 --- a/trunk/src/utest/srs_utest_app.hpp +++ b/trunk/src/utest/srs_utest_app.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_avc.cpp b/trunk/src/utest/srs_utest_avc.cpp index 7fb7374e2e..384ede82b6 100644 --- a/trunk/src/utest/srs_utest_avc.cpp +++ b/trunk/src/utest/srs_utest_avc.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_avc.hpp b/trunk/src/utest/srs_utest_avc.hpp index 1289a7c111..5b5c7db385 100644 --- a/trunk/src/utest/srs_utest_avc.hpp +++ b/trunk/src/utest/srs_utest_avc.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_config.cpp b/trunk/src/utest/srs_utest_config.cpp index c4c495967d..640364ce37 100644 --- a/trunk/src/utest/srs_utest_config.cpp +++ b/trunk/src/utest/srs_utest_config.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_config.hpp b/trunk/src/utest/srs_utest_config.hpp index ca538707db..c253e04707 100644 --- a/trunk/src/utest/srs_utest_config.hpp +++ b/trunk/src/utest/srs_utest_config.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_config2.cpp b/trunk/src/utest/srs_utest_config2.cpp index d4e7df9079..3f9f9acd25 100644 --- a/trunk/src/utest/srs_utest_config2.cpp +++ b/trunk/src/utest/srs_utest_config2.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_config2.hpp b/trunk/src/utest/srs_utest_config2.hpp index 5871517432..efdee2e624 100644 --- a/trunk/src/utest/srs_utest_config2.hpp +++ b/trunk/src/utest/srs_utest_config2.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_core.cpp b/trunk/src/utest/srs_utest_core.cpp index 59f8bce1f8..1b399fd771 100644 --- a/trunk/src/utest/srs_utest_core.cpp +++ b/trunk/src/utest/srs_utest_core.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_core.hpp b/trunk/src/utest/srs_utest_core.hpp index 95baaaf4d9..1c7795b977 100644 --- a/trunk/src/utest/srs_utest_core.hpp +++ b/trunk/src/utest/srs_utest_core.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_gb28181.cpp b/trunk/src/utest/srs_utest_gb28181.cpp index 6b78d3a582..5961f10f61 100644 --- a/trunk/src/utest/srs_utest_gb28181.cpp +++ b/trunk/src/utest/srs_utest_gb28181.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_gb28181.hpp b/trunk/src/utest/srs_utest_gb28181.hpp index edebbf5a9c..5257484506 100644 --- a/trunk/src/utest/srs_utest_gb28181.hpp +++ b/trunk/src/utest/srs_utest_gb28181.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_http.cpp b/trunk/src/utest/srs_utest_http.cpp index 382f5dc3ec..c8a839f0fc 100644 --- a/trunk/src/utest/srs_utest_http.cpp +++ b/trunk/src/utest/srs_utest_http.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_http.hpp b/trunk/src/utest/srs_utest_http.hpp index 81e8d21153..0b328b3863 100644 --- a/trunk/src/utest/srs_utest_http.hpp +++ b/trunk/src/utest/srs_utest_http.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_kernel.cpp b/trunk/src/utest/srs_utest_kernel.cpp index 59f63a143e..9be30ef11f 100644 --- a/trunk/src/utest/srs_utest_kernel.cpp +++ b/trunk/src/utest/srs_utest_kernel.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_kernel.hpp b/trunk/src/utest/srs_utest_kernel.hpp index 9ea9cb8ebd..142d8a4594 100644 --- a/trunk/src/utest/srs_utest_kernel.hpp +++ b/trunk/src/utest/srs_utest_kernel.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_kernel2.cpp b/trunk/src/utest/srs_utest_kernel2.cpp index edf6cf4167..afaf045a00 100644 --- a/trunk/src/utest/srs_utest_kernel2.cpp +++ b/trunk/src/utest/srs_utest_kernel2.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_kernel2.hpp b/trunk/src/utest/srs_utest_kernel2.hpp index 293bc1a963..4f45b2a3ca 100644 --- a/trunk/src/utest/srs_utest_kernel2.hpp +++ b/trunk/src/utest/srs_utest_kernel2.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_mp4.cpp b/trunk/src/utest/srs_utest_mp4.cpp index e324522f79..77f9355fea 100644 --- a/trunk/src/utest/srs_utest_mp4.cpp +++ b/trunk/src/utest/srs_utest_mp4.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_mp4.hpp b/trunk/src/utest/srs_utest_mp4.hpp index 7df061f2f9..8aa1f1824b 100644 --- a/trunk/src/utest/srs_utest_mp4.hpp +++ b/trunk/src/utest/srs_utest_mp4.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_protocol.cpp b/trunk/src/utest/srs_utest_protocol.cpp index ce9326790f..8ac6a79d42 100644 --- a/trunk/src/utest/srs_utest_protocol.cpp +++ b/trunk/src/utest/srs_utest_protocol.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_protocol.hpp b/trunk/src/utest/srs_utest_protocol.hpp index b07080b0fa..131ef509ab 100644 --- a/trunk/src/utest/srs_utest_protocol.hpp +++ b/trunk/src/utest/srs_utest_protocol.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_protocol2.cpp b/trunk/src/utest/srs_utest_protocol2.cpp index 585cd4f6c1..e3444727e5 100644 --- a/trunk/src/utest/srs_utest_protocol2.cpp +++ b/trunk/src/utest/srs_utest_protocol2.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_protocol2.hpp b/trunk/src/utest/srs_utest_protocol2.hpp index b3fa60d6e4..aebbbe004e 100644 --- a/trunk/src/utest/srs_utest_protocol2.hpp +++ b/trunk/src/utest/srs_utest_protocol2.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_reload.cpp b/trunk/src/utest/srs_utest_reload.cpp index ba4ccd963f..85c0d29a04 100644 --- a/trunk/src/utest/srs_utest_reload.cpp +++ b/trunk/src/utest/srs_utest_reload.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_reload.hpp b/trunk/src/utest/srs_utest_reload.hpp index 3c774d2f61..d427766fec 100644 --- a/trunk/src/utest/srs_utest_reload.hpp +++ b/trunk/src/utest/srs_utest_reload.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_rtc.cpp b/trunk/src/utest/srs_utest_rtc.cpp index 728a09964c..e7e3dd1542 100644 --- a/trunk/src/utest/srs_utest_rtc.cpp +++ b/trunk/src/utest/srs_utest_rtc.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_rtc.hpp b/trunk/src/utest/srs_utest_rtc.hpp index 7c91131f29..3d7df99495 100644 --- a/trunk/src/utest/srs_utest_rtc.hpp +++ b/trunk/src/utest/srs_utest_rtc.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_rtmp.cpp b/trunk/src/utest/srs_utest_rtmp.cpp index 5e30be1119..9a44a5861d 100644 --- a/trunk/src/utest/srs_utest_rtmp.cpp +++ b/trunk/src/utest/srs_utest_rtmp.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_rtmp.hpp b/trunk/src/utest/srs_utest_rtmp.hpp index 566cb1ab65..7ecfe8d01e 100644 --- a/trunk/src/utest/srs_utest_rtmp.hpp +++ b/trunk/src/utest/srs_utest_rtmp.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_service.cpp b/trunk/src/utest/srs_utest_service.cpp index a44d26b609..06e529f20c 100644 --- a/trunk/src/utest/srs_utest_service.cpp +++ b/trunk/src/utest/srs_utest_service.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_service.hpp b/trunk/src/utest/srs_utest_service.hpp index f27e0d233e..5396d5ac25 100644 --- a/trunk/src/utest/srs_utest_service.hpp +++ b/trunk/src/utest/srs_utest_service.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 The SRS Authors +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_srt.cpp b/trunk/src/utest/srs_utest_srt.cpp index 371eba03fb..d8f458771c 100644 --- a/trunk/src/utest/srs_utest_srt.cpp +++ b/trunk/src/utest/srs_utest_srt.cpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 Winlin +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT // diff --git a/trunk/src/utest/srs_utest_srt.hpp b/trunk/src/utest/srs_utest_srt.hpp index 02c0d36cb4..0dab6ad269 100644 --- a/trunk/src/utest/srs_utest_srt.hpp +++ b/trunk/src/utest/srs_utest_srt.hpp @@ -1,5 +1,5 @@ // -// Copyright (c) 2013-2023 Winlin +// Copyright (c) 2013-2024 The SRS Authors // // SPDX-License-Identifier: MIT //