commit 9d7c20e4dbfa680857b54081d6b5e0180877b6aa Author: Codex Date: Sat Oct 3 16:12:25 2026 +0800 feat: local vision service with structured spaces and camera lens objects diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..58025cb --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +* text=auto eol=lf +web/vendor/* -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..64c2260 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +data/ +recordings/ +runtime/ +*.db* +*.log +*.key +*.env +__pycache__/ +.venv/ +mediamtx +mediamtx.exe +*.tar.gz + diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..60598a1 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 优创未来 + +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 the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..90f28ee --- /dev/null +++ b/README.md @@ -0,0 +1,64 @@ +# 赵府智家 · 视觉系统 + +运行在自有小电脑上的视频管理程序。Python 标准库负责对象、空间、配置与登录;MediaMTX 负责 RTSP 接入、HLS 实时预览、本机录像及回放;浏览器使用本地打包的 hls.js。 + +## 对象与空间 + +- **空间档案**:家庭 / 公司 / 其他,所属家庭或单位,省、市、区县、街道、小区或园区、楼栋、单元、楼层、门牌和详细地址。 +- **摄像头对象**:实体设备的稳定 ID、品牌、型号、序列号、镜头数、安装位置和空间引用。 +- **镜头通道**:每个物理镜头一个通道,关联摄像头对象,配置主、子码流。双镜头摄像头的主、子码流不能当作两个物理镜头。 +- **录像机**:独立的设备与凭据档案,通道可以引用录像机获取画面。也可以直接连接摄像头。 +- **录像来源**:明确区分录像机原有录像与小电脑新保存的录像。 + +## v0.1.0 功能与边界 + +源码包括空间 / 摄像头 / 录像机 / 镜头档案,局域网 RTSP 探测、同源 HLS 播放、本机可选持续录像、日期查询、录像时间轴、定位回放和片段下载、存储保护、管理员初始化与登录。 + +**录像机原有历史录像回放尚未实现。** 需要取得具体型号及合法设备账号,接入其录像检索和回放接口;实时 RTSP 地址不能代替录像检索接口。驱动选项目前仅表示路径模板与接入类型,不能视为某个品牌全系列已经兼容。实际通道号需要由设备确认,不能根据三台双镜头直接猜成通道 1–6。 + +本机录像默认关闭,用户逐通道开启。默认保留 7 天、容量 40 GB、磁盘预留 8 GB,界面可调整。保留期限到达后 MediaMTX 自动删除本机录像;配额达到后暂停录制,不删除录像机中的数据。配额每 20 秒观察一次,允许少量超出。文件路径及录像索引使用 UTC,界面按浏览器时区显示。 + +HLS 会有数秒延迟。此版本不转码,推荐 H.264;H.265 和不同音频编码的浏览器兼容性取决于浏览器及设备。设备状态基于 MediaMTX 实际码流状态;“正在录像”还要求观察到近期写入的本机录像文件。离线不会生成假画面或假录像。 + +## Ubuntu x86_64 部署 + +先将源文件提交、公开发布,再部署同一 Git 提交的归档。建议放在 `/opt/zhaovision/releases//`。Python 3.11 以上,无 pip 运行依赖。 + +```sh +sudo VISION_BIND=<本机的Tailscale-IPv4> bash deploy/install.sh +``` + +安装脚本校验并安装固定版本 MediaMTX v1.21.1,创建无登录权限的服务用户,数据写入 `/var/lib/zhaovision`,应用入口为 `http://:8790/`。视频服务的 HTTP、RTSP 与管理 API 全部仅监听回环地址,由应用进行登录鉴权并代理。 + +首次打开页面,读取服务器上的 `/var/lib/zhaovision/setup-code.txt`,输入初始化码,设置至少 10 位管理密码。初始化后码文件删除。摄像头与录像机密码在自己的界面填写。 + +```sh +systemctl status zhaovision zhaovision-media +journalctl -u zhaovision -u zhaovision-media --since '10 minutes ago' +``` + +程序不自动修改网络、防火墙、Tailscale 子网路由或设备密码。录像机仍按其原有设置运行。 + +## 开发 + +```sh +python3 app.py +# 在另一个终端运行 MediaMTX,使用首次启动生成的配置 +mediamtx ./data/mediamtx.yml +``` + +访问 `http://127.0.0.1:8790/`。后端配置变量:`VISION_BIND`、`VISION_PORT`、`VISION_DATA`、`VISION_RECORDINGS`,HTTPS 反向代理场景可设 `VISION_SECURE_COOKIE=1`。当前管理 API 是单管理员模型。 + +## 数据与恢复 + +数据库和生成的 MediaMTX 配置含设备连接凭据,存于权限受限的本机目录,不进入 Git。系统管理员可以读取这些凭据;当前版本未提供硬盘加密。备份时停止两个服务并一并备份整个 `/var/lib/zhaovision`。恢复到同一路径、修正服务用户所有权后启动服务。升级时保留数据目录,发布目录按提交留存,回滚 `current` 符号链接并重启服务;后续涉及数据库版本变更时需遵循对应迁移说明。 + +本仓库不包含真实家庭地址、设备凭据、视频文件或部署主机凭据。 + +## 第三方软件 + +- [MediaMTX](https://github.com/bluenviron/mediamtx) v1.21.1,MIT,部署时独立安装。 +- [hls.js](https://github.com/video-dev/hls.js) v1.7.3,Apache-2.0,浏览器构建与许可证位于 `web/vendor/`。 +- 官方接口参考:[录像](https://mediamtx.org/docs/features/record)、[回放](https://mediamtx.org/docs/features/playback)、[配置](https://mediamtx.org/docs/references/configuration-file)。 + +本项目源码以 MIT 许可证发布。v0.1.0 为初始版本,真实录像机的历史回放兼容性需完成型号适配后另行验证。 diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..6e8bf73 --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.1.0 diff --git a/app.py b/app.py new file mode 100644 index 0000000..6cd5912 --- /dev/null +++ b/app.py @@ -0,0 +1,674 @@ +"""Local video management. Python standard library + an external MediaMTX process.""" +import base64 +import concurrent.futures +import datetime as dt +import hashlib +import hmac +import http.client +import http.cookies +import ipaddress +import json +import math +import mimetypes +import os +from pathlib import Path +import re +import secrets +import shutil +import socket +import sqlite3 +import threading +import time +import urllib.error +import urllib.parse as url +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +ROOT = Path(__file__).resolve().parent +os.umask(0o077) +DATA = Path(os.environ.get('VISION_DATA', ROOT / 'data')).resolve() +DATA.mkdir(mode=0o700, parents=True, exist_ok=True) +RECORDINGS = Path(os.environ.get('VISION_RECORDINGS', DATA / 'recordings')).resolve() +RECORDINGS.mkdir(mode=0o700, parents=True, exist_ok=True) +CONFIG = DATA / 'mediamtx.yml' +LOCK = threading.RLock() +DB = sqlite3.connect(DATA / 'vision.db', check_same_thread=False) +DB.row_factory = sqlite3.Row +DB.executescript(''' +PRAGMA journal_mode=WAL; +PRAGMA foreign_keys=ON; +CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS sites (id TEXT PRIMARY KEY, body TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS cameras (id TEXT PRIMARY KEY, body TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS assets (id TEXT PRIMARY KEY, body TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS recorders (id TEXT PRIMARY KEY, body TEXT NOT NULL); +CREATE TABLE IF NOT EXISTS sessions (hash TEXT PRIMARY KEY, expires REAL NOT NULL); +CREATE TABLE IF NOT EXISTS audit (id INTEGER PRIMARY KEY, at TEXT, action TEXT, name TEXT); +''') +DB.commit() +os.chmod(DATA / 'vision.db', 0o600) +STARTED = time.time() +STORAGE = {'freeGB': None, 'usedGB': None, 'paused': False, 'reason': ''} +RECENT_RECORDS = {} +SCAN = {'running': False, 'items': [], 'error': '', 'network': '', 'at': None} +ATTEMPTS = {} +API_PORT, HLS_PORT, PLAYBACK_PORT = 19997, 18888, 19996 +MEDIA_AUTH = None + + +class Problem(Exception): + def __init__(self, message, status=400): + super().__init__(message) + self.status = status + + +def setting(key, default=None): + with LOCK: + row = DB.execute('SELECT value FROM settings WHERE key=?', (key,)).fetchone() + return json.loads(row[0]) if row else default + + +def set_setting(key, value): + with LOCK: + DB.execute('INSERT OR REPLACE INTO settings VALUES (?,?)', (key, json.dumps(value))) + DB.commit() + + +def objects(table): + with LOCK: + return [dict(json.loads(r['body']), id=r['id']) for r in DB.execute('SELECT * FROM ' + table)] + + +def get_object(table, key): + return next((o for o in objects(table) if o['id'] == key), None) + + +def audit(action, name=''): + with LOCK: + DB.execute('INSERT INTO audit (at,action,name) VALUES (?,?,?)', + (dt.datetime.now(dt.timezone.utc).isoformat(), action, name)) + DB.execute('DELETE FROM audit WHERE id NOT IN (SELECT id FROM audit ORDER BY id DESC LIMIT 500)') + DB.commit() + + +def save_object(table, body): + with LOCK: + DB.execute('INSERT OR REPLACE INTO ' + table + ' VALUES (?,?)', (body['id'], json.dumps(body))) + DB.commit() + + +def clean_text(value, limit=120, required=False): + if not isinstance(value, str) or len(value) > limit or any(ord(c) < 32 for c in value): + raise Problem('文本格式或长度不正确') + value = value.strip() + if required and not value: + raise Problem('请填写必填项') + return value + + +def integer(value, lo, hi): + if isinstance(value, bool) or not isinstance(value, int) or not lo <= value <= hi: + raise Problem('数值超出允许范围') + return value + + +def host_address(value): + try: + ip = ipaddress.ip_address(value) + if ip.version != 4 or ip.is_global or ip.is_loopback or ip.is_multicast or ip.is_unspecified or ip.is_reserved: + raise ValueError() + return str(ip) + except ValueError: + raise Problem('请填写局域网或 Tailscale IPv4 地址') + + +SITE_FIELDS = ('name', 'province', 'city', 'district', 'street', 'community', 'owner', + 'building', 'unit', 'floor', 'door', 'address', 'note') + + +def save_site(body): + key = body.get('id') or secrets.token_hex(8) + if not re.fullmatch('[a-f0-9]{16}', key): + raise Problem('空间编号不正确') + item = {k: clean_text(body.get(k, ''), 240 if k in ('address', 'note') else 100, + required=k == 'name') for k in SITE_FIELDS} + item.update(id=key, kind=body.get('kind', 'home')) + if item['kind'] not in ('home', 'company', 'other'): + raise Problem('请选择家庭、公司或其他用途') + save_object('sites', item) + audit('保存空间', item['name']) + return item + + +def save_camera(body): + key = body.get('id') or secrets.token_hex(8) + if not re.fullmatch('[a-f0-9]{16}', key): + raise Problem('设备编号不正确') + old = get_object('cameras', key) or {} + item = {k: clean_text(body.get(k, ''), 120, required=k == 'name') + for k in ('name', 'point', 'username', 'model')} + asset = get_object('assets', body.get('assetId')) + if not asset: + raise Problem('请先建立并选择摄像头对象') + siblings = [c for c in objects('cameras') if c.get('assetId') == asset['id'] and c['id'] != key] + if len(siblings) >= asset['lensCount']: + raise Problem('该摄像头的镜头通道数已达到档案中设置的镜头数') + site = asset['siteId'] + source_kind = body.get('sourceKind', 'direct') + recorder = get_object('recorders', body.get('recorderId')) if source_kind == 'recorder' else None + if source_kind not in ('direct', 'recorder') or (source_kind == 'recorder' and not recorder): + raise Problem('请选择录像机或直接接入') + item.update(assetId=asset['id'], sourceKind=source_kind, recorderId=recorder['id'] if recorder else '', + channelNumber=clean_text(body.get('channelNumber', ''), 30), + archiveSource=body.get('archiveSource', 'recorder' if recorder else 'local')) + if item['archiveSource'] not in ('local', 'recorder'): + raise Problem('录像存储来源不正确') + if item['archiveSource'] == 'recorder' and not recorder: + raise Problem('录像保存在录像机时,请先选择对应录像机') + item.update(id=key, siteId=site, host=host_address(recorder['host'] if recorder else body.get('host', '')), + port=integer(recorder['port'] if recorder else body.get('port', 554), 1, 65535)) + for k, default in [('mainPath', '/stream1'), ('subPath', '/stream2')]: + path = clean_text(body.get(k, default), 500, required=True) + if not path.startswith('/') or path.startswith('//') or '#' in path: + raise Problem('码流路径必须以一个 / 开头,不含 #') + item[k] = path + password = body.get('password', '') + if not isinstance(password, str) or len(password) > 256 or any(ord(c) < 32 for c in password): + raise Problem('设备密码格式不正确') + item['password'] = '' if recorder else password or old.get('password', '') + for k in ('enabled', 'record'): + if not isinstance(body.get(k, False), bool): + raise Problem('开关值不正确') + item[k] = body.get(k, False) + if not old and len(objects('cameras')) >= 32: + raise Problem('此版本最多配置 32 台设备') + save_object('cameras', item) + write_media_config() + audit('保存摄像头', item['name']) + return public_camera(item) + + +def save_asset(body): + key = body.get('id') or secrets.token_hex(8) + if not re.fullmatch('[a-f0-9]{16}', key): + raise Problem('对象编号不正确') + site = body.get('siteId') + if not get_object('sites', site): + raise Problem('请选择所属空间') + item = {k: clean_text(body.get(k, ''), 120, required=k == 'name') + for k in ('name', 'brand', 'model', 'serial', 'point', 'note')} + item.update(id=key, siteId=site, lensCount=integer(body.get('lensCount', 2), 1, 16)) + attached = [c for c in objects('cameras') if c.get('assetId') == key] + if len(attached) > item['lensCount']: + raise Problem('镜头数不能小于已经建立的通道数') + with LOCK: + save_object('assets', item) + for c in attached: + c['siteId'] = site + save_object('cameras', c) + audit('保存摄像头对象', item['name']) + return item + + +def save_recorder(body): + key = body.get('id') or secrets.token_hex(8) + if not re.fullmatch('[a-f0-9]{16}', key): + raise Problem('录像机编号不正确') + old = get_object('recorders', key) or {} + item = {k: clean_text(body.get(k, ''), 120, required=k == 'name') + for k in ('name', 'brand', 'model', 'username')} + site = body.get('siteId') + if not get_object('sites', site): + raise Problem('请选择录像机所属空间') + item.update(id=key, siteId=site, host=host_address(body.get('host', '')), + port=integer(body.get('port', 554), 1, 65535), driver=body.get('driver', 'generic-rtsp')) + if item['driver'] not in ('generic-rtsp', 'hikvision-rtsp', 'tplink-rtsp', 'dahua-rtsp'): + raise Problem('接入驱动不正确') + password = body.get('password', '') + if not isinstance(password, str) or len(password) > 256 or any(ord(c) < 32 for c in password): + raise Problem('密码格式不正确') + item['password'] = password or old.get('password', '') + save_object('recorders', item) + write_media_config() + audit('保存录像机', item['name']) + return public_camera(item) + + +def public_camera(c): + return {**{k: v for k, v in c.items() if k != 'password'}, 'passwordConfigured': bool(c['password'])} + + +def stream_name(c, quality='main'): + return 'cam_' + c['id'] + '_' + quality + + +def source(c, quality): + endpoint = get_object('recorders', c.get('recorderId')) if c.get('sourceKind') == 'recorder' else c + if not endpoint: + raise Problem('关联录像机不存在') + auth = (url.quote(endpoint['username'], safe='') + ':' + url.quote(endpoint['password'], safe='') + '@') if endpoint['username'] else '' + return 'rtsp://' + auth + endpoint['host'] + ':' + str(endpoint['port']) + c[quality + 'Path'] + + +def write_media_config(): + with LOCK: + paths = {} + policy = setting('storage', {'retentionDays': 7, 'maxGB': 40, 'reserveGB': 8}) + for c in objects('cameras'): + for quality in ('main', 'sub'): + paths[stream_name(c, quality)] = { + 'source': source(c, quality) if c['enabled'] else 'publisher', + 'rtspTransport': 'tcp', + 'sourceOnDemand': quality == 'sub' and c['enabled'], + 'record': bool(c['enabled'] and c['record'] and quality == 'main' and not STORAGE['paused']), + 'recordDeleteAfter': str(policy['retentionDays'] * 24) + 'h', + } + config = { + 'logLevel': 'warn', 'logDestinations': ['stdout'], + 'api': True, 'apiAddress': '127.0.0.1:' + str(API_PORT), + 'rtsp': True, 'rtspAddress': '127.0.0.1:18554', 'rtspTransports': ['tcp'], + 'rtmp': False, 'srt': False, 'webrtc': False, 'moq': False, + 'hls': True, 'hlsAddress': '127.0.0.1:' + str(HLS_PORT), 'hlsVariant': 'fmp4', + 'hlsSegmentDuration': '1s', 'hlsSegmentCount': 5, 'hlsAllowOrigins': [], + 'playback': True, 'playbackAddress': '127.0.0.1:' + str(PLAYBACK_PORT), + 'playbackAllowOrigins': [], + 'authMethod': 'internal', + 'authInternalUsers': [{'user': 'vision', 'pass': setting('mediaSecret'), + 'ips': ['127.0.0.1', '::1'], + 'permissions': [{'action': a} for a in ('read', 'api', 'playback')]}], + 'pathDefaults': {'recordFormat': 'fmp4', 'recordPath': str(RECORDINGS / '%path' / '%Y-%m-%d_%H-%M-%S-%f'), + 'recordSegmentDuration': '5m', 'recordPartDuration': '1s'}, + 'paths': paths, + } + raw = json.dumps(config, ensure_ascii=False, indent=2) + if CONFIG.exists() and CONFIG.read_text(encoding='utf8') == raw: + return + temp = DATA / 'mediamtx.tmp' + temp.write_text(raw, encoding='utf8') + os.chmod(temp, 0o600) + os.replace(temp, CONFIG) + + +def media_json(path, playback=False): + target = 'http://127.0.0.1:' + str(PLAYBACK_PORT if playback else API_PORT) + path + try: + req = urllib.request.Request(target, headers={'Authorization': MEDIA_AUTH}) + with urllib.request.urlopen(req, timeout=5) as r: + return json.load(r) + except Exception: + raise Problem('视频服务暂不可用,或该时段尚无可回放录像', 503) + + +def status(): + try: + data = media_json('/v3/paths/list?itemsPerPage=200') + ready = {p['name']: {'ready': bool(p.get('ready')), 'tracks': p.get('tracks', []), + 'bytesReceived': p.get('bytesReceived', 0)} for p in data.get('items', [])} + media = True + except Problem: + ready, media = {}, False + cameras = [] + for c in objects('cameras'): + if c.get('sourceKind') == 'recorder': + endpoint = get_object('recorders', c.get('recorderId')) + if endpoint: + c = dict(c, host=endpoint['host'], port=endpoint['port']) + main = ready.get(stream_name(c), {}) + cameras.append({**public_camera(c), 'ready': main.get('ready', False), 'tracks': main.get('tracks', []), + 'recordingRequested': c['enabled'] and c['record'] and not STORAGE['paused'], + 'recordingActive': bool(c['enabled'] and c['record'] and not STORAGE['paused'] and main.get('ready', False) + and time.time() - RECENT_RECORDS.get(stream_name(c), 0) < 45)}) + with LOCK: + storage = dict(STORAGE) + scan = dict(SCAN) + return {'cameras': cameras, 'assets': objects('assets'), 'recorders': [public_camera(r) for r in objects('recorders')], + 'sites': objects('sites'), 'mediaOnline': media, + 'storage': {**setting('storage'), **storage}, 'scan': scan, + 'version': (ROOT / 'VERSION').read_text().strip(), 'uptime': round(time.time() - STARTED)} + + +def storage_watch(): + while True: + try: + usage = shutil.disk_usage(RECORDINGS) + used, recent = 0, {} + for p in RECORDINGS.rglob('*.mp4'): + try: + info = p.stat() + used += info.st_size + recent[p.parent.name] = max(recent.get(p.parent.name, 0), info.st_mtime) + except FileNotFoundError: + pass + policy = setting('storage') + free_gb, used_gb = usage.free / 1e9, used / 1e9 + reason = '录像空间已达到配额' if used_gb >= policy['maxGB'] else ('磁盘可用空间不足' if free_gb < policy['reserveGB'] else '') + with LOCK: + changed = STORAGE['paused'] != bool(reason) + STORAGE.update(freeGB=round(free_gb, 2), usedGB=round(used_gb, 2), paused=bool(reason), reason=reason) + RECENT_RECORDS.clear() + RECENT_RECORDS.update(recent) + if changed: + write_media_config() + audit('录像空间保护', reason or '空间恢复,继续按设备配置录像') + except Exception: + with LOCK: + STORAGE.update(paused=True, reason='存储状态读取失败') + try: + write_media_config() + except Exception: + pass + time.sleep(20) + + +def discover(network): + def probe(ip): + try: + with socket.create_connection((str(ip), 554), timeout=0.7) as s: + s.settimeout(1) + s.sendall(('OPTIONS rtsp://' + str(ip) + '/ RTSP/1.0\r\nCSeq: 1\r\n\r\n').encode()) + response = s.recv(1024).decode(errors='replace').split('\r\n')[0] + if response.startswith('RTSP/'): + return {'host': str(ip), 'port': 554, 'response': response, 'authenticated': False} + except OSError: + return None + try: + with concurrent.futures.ThreadPoolExecutor(max_workers=24) as pool: + items = [p for p in pool.map(probe, network.hosts()) if p] + with LOCK: + SCAN.update(items=items, at=dt.datetime.now(dt.timezone.utc).isoformat()) + except Exception: + with LOCK: + SCAN['error'] = '探测未完成,请检查主机网络' + finally: + with LOCK: + SCAN['running'] = False + + +def parse_time(text): + try: + value = dt.datetime.fromisoformat(text.replace('Z', '+00:00')) + if value.tzinfo is None: + raise ValueError() + return value + except (ValueError, AttributeError): + raise Problem('时间必须包含时区') + + +class Handler(BaseHTTPRequestHandler): + server_version = 'ZhaoVision' + + def log_message(self, *_): + pass # Do not put camera credentials, cookies or playback queries into logs. + + def answer(self, value, code=200, cookie=None): + data = json.dumps(value, ensure_ascii=False).encode() + self.send_response(code) + self.send_header('Content-Type', 'application/json; charset=utf-8') + self.send_header('Content-Length', str(len(data))) + self.send_header('Cache-Control', 'no-store') + self.send_header('X-Content-Type-Options', 'nosniff') + if cookie: + self.send_header('Set-Cookie', cookie) + self.end_headers() + self.wfile.write(data) + + def token(self): + try: + c = http.cookies.SimpleCookie(self.headers.get('Cookie', '')) + return c['vision'].value if 'vision' in c else '' + except http.cookies.CookieError: + return '' + + def authenticated(self): + token = self.token() + if not re.fullmatch('[a-f0-9]{64}', token): + return False + with LOCK: + return bool(DB.execute('SELECT 1 FROM sessions WHERE hash=? AND expires>?', + (hashlib.sha256(token.encode()).hexdigest(), time.time())).fetchone()) + + def require_auth(self): + if not self.authenticated(): + raise Problem('请先登录', 401) + + def body(self): + if self.headers.get_content_type() != 'application/json': + raise Problem('请求需要 JSON 格式') + n = int(self.headers.get('Content-Length', '0')) + if not 0 < n <= 16384: + raise Problem('请求长度不正确') + try: + data = json.loads(self.rfile.read(n)) + if not isinstance(data, dict): + raise ValueError() + return data + except (ValueError, UnicodeError): + raise Problem('请求内容无法解析') + + def validate_origin(self): + origin = self.headers.get('Origin') + if origin and url.urlsplit(origin).netloc != self.headers.get('Host'): + raise Problem('请从系统页面提交操作', 403) + + def login(self, data, setup=False): + ip = self.client_address[0] + now = time.time() + with LOCK: + for k in list(ATTEMPTS): + if ATTEMPTS[k][1] < now: + del ATTEMPTS[k] + count, expiry = ATTEMPTS.get(ip, (0, now + 900)) + ATTEMPTS[ip] = (count + 1, expiry) + if count >= 12: + raise Problem('尝试次数过多,请 15 分钟后重试', 429) + account = setting('account') + password = data.get('password', '') + if not isinstance(password, str) or not 10 <= len(password) <= 128: + raise Problem('管理密码需要 10 至 128 个字符') + if setup: + if account: + raise Problem('管理员已经初始化', 409) + code = data.get('code', '') + expected = (DATA / 'setup-code.txt').read_text().strip() + if not isinstance(code, str) or not hmac.compare_digest(code, expected): + raise Problem('初始化码不正确', 403) + salt = secrets.token_hex(16) + derived = hashlib.scrypt(password.encode(), salt=salt.encode(), n=16384, r=8, p=1).hex() + set_setting('account', {'salt': salt, 'hash': derived}) + (DATA / 'setup-code.txt').unlink(missing_ok=True) + audit('初始化管理员') + else: + if not account: + raise Problem('请先初始化管理员', 409) + derived = hashlib.scrypt(password.encode(), salt=account['salt'].encode(), n=16384, r=8, p=1).hex() + if not hmac.compare_digest(derived, account['hash']): + raise Problem('密码不正确', 403) + token = secrets.token_hex(32) + DB.execute('DELETE FROM sessions WHERE expires 30: + raise ValueError() + host_address(str(network.network_address)) + except ValueError: + raise Problem('请输入最多 254 个地址的局域网网段,例如 192.168.1.0/24') + with LOCK: + if SCAN['running']: + raise Problem('探测正在进行', 409) + SCAN.update(running=True, items=[], error='', network=str(network)) + threading.Thread(target=discover, args=(network,), daemon=True).start() + self.answer({'ok': True}, 202) + else: + raise Problem('接口不存在', 404) + except Problem as e: + self.answer({'error': str(e)}, e.status) + except (BrokenPipeError, ConnectionResetError): + pass + except Exception: + self.answer({'error': '操作未完成,请检查输入或服务状态'}, 500) + + def proxy(self, port, path): + conn = http.client.HTTPConnection('127.0.0.1', port, timeout=25) + headers = {'Authorization': MEDIA_AUTH} + if self.headers.get('Range'): + headers['Range'] = self.headers['Range'] + started = False + try: + conn.request('GET', path, headers=headers) + r = conn.getresponse() + if r.status >= 400: + raise Problem('暂时没有可播放画面,请确认设备网络、账号、码流路径和录像时间', 503) + self.send_response(r.status) + for k in ('Content-Type', 'Content-Length', 'Content-Range', 'Accept-Ranges'): + if r.getheader(k): + self.send_header(k, r.getheader(k)) + self.send_header('Cache-Control', 'no-store') + self.send_header('X-Content-Type-Options', 'nosniff') + self.end_headers() + started = True + while True: + chunk = r.read(65536) + if not chunk: + break + self.wfile.write(chunk) + except (OSError, http.client.HTTPException): + if not started: + raise Problem('视频服务连接失败', 503) + finally: + conn.close() + + def do_GET(self): + try: + parsed = url.urlsplit(self.path) + path = parsed.path + query = {k: v[0] for k, v in url.parse_qs(parsed.query).items()} + if path == '/api/session': + self.answer({'authenticated': self.authenticated(), 'setupRequired': not bool(setting('account'))}) + return + if path == '/healthz': + self.answer({'status': 'running', 'version': (ROOT / 'VERSION').read_text().strip()}) + return + if path.startswith(('/api/', '/media/')): + self.require_auth() + if path == '/api/state': + self.answer(status()) + elif path == '/api/audit': + with LOCK: + rows = [dict(r) for r in DB.execute('SELECT * FROM audit ORDER BY id DESC LIMIT 50')] + self.answer(rows) + elif path == '/api/recordings': + c = get_object('cameras', query.get('camera')) + if not c: + raise Problem('请选择摄像头') + start, end = parse_time(query.get('start')), parse_time(query.get('end')) + if not 0 < (end - start).total_seconds() <= 172800: + raise Problem('每次查询最多两天') + q = url.urlencode({'path': stream_name(c), 'start': start.isoformat(), 'end': end.isoformat()}) + raw = media_json('/list?' + q, playback=True) + items = [{'start': r['start'], 'duration': r['duration']} for r in raw] + self.answer({'items': items}) + elif path.startswith('/media/live/'): + suffix = path[len('/media/live/'):] + if not re.fullmatch(r'cam_[a-f0-9]{16}_(main|sub)/[a-zA-Z0-9_.-]+', suffix): + raise Problem('视频路径不正确') + self.proxy(HLS_PORT, '/' + suffix + ('?' + parsed.query if parsed.query else '')) + elif path == '/media/playback': + c = get_object('cameras', query.get('camera')) + if not c: + raise Problem('摄像头不存在', 404) + start = parse_time(query.get('start')) + try: + duration = float(query.get('duration', '300')) + if not math.isfinite(duration) or not 0 < duration <= 3600: + raise ValueError() + except ValueError: + raise Problem('单次回放最多一小时') + q = url.urlencode({'path': stream_name(c), 'start': start.isoformat(), 'duration': duration, + 'format': 'mp4' if query.get('download') == '1' else 'fmp4'}) + self.proxy(PLAYBACK_PORT, '/get?' + q) + else: + raise Problem('接口不存在', 404) + else: + files = {'/': 'index.html', '/app.js': 'app.js', '/style.css': 'style.css', + '/vendor/hls.min.js': 'vendor/hls.min.js'} + if path not in files: + raise Problem('页面不存在', 404) + file = ROOT / 'web' / files[path] + raw = file.read_bytes() + self.send_response(200) + self.send_header('Content-Type', (mimetypes.guess_type(file.name)[0] or 'application/octet-stream') + '; charset=utf-8') + self.send_header('Content-Length', str(len(raw))) + self.send_header('X-Content-Type-Options', 'nosniff') + self.send_header('X-Frame-Options', 'DENY') + self.send_header('Referrer-Policy', 'same-origin') + self.send_header('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; media-src 'self' blob:; worker-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'") + self.send_header('Cache-Control', 'no-cache') + self.end_headers() + self.wfile.write(raw) + except Problem as e: + self.answer({'error': str(e)}, e.status) + except (BrokenPipeError, ConnectionResetError): + pass + except Exception: + self.answer({'error': '请求未完成'}, 500) + + +def initialize(): + global MEDIA_AUTH + if not setting('storage'): + set_setting('storage', {'retentionDays': 7, 'maxGB': 40, 'reserveGB': 8}) + if not setting('mediaSecret'): + set_setting('mediaSecret', secrets.token_hex(32)) + MEDIA_AUTH = 'Basic ' + base64.b64encode(('vision:' + setting('mediaSecret')).encode()).decode() + if not setting('account') and not (DATA / 'setup-code.txt').exists(): + (DATA / 'setup-code.txt').write_text(secrets.token_hex(12), encoding='utf8') + os.chmod(DATA / 'setup-code.txt', 0o600) + write_media_config() + + +if __name__ == '__main__': + initialize() + threading.Thread(target=storage_watch, daemon=True).start() + bind = os.environ.get('VISION_BIND', '127.0.0.1') + port = int(os.environ.get('VISION_PORT', '8790')) + server = ThreadingHTTPServer((bind, port), Handler) + server.daemon_threads = True + print('ZhaoVision listening on ' + bind + ':' + str(port), flush=True) + server.serve_forever() diff --git a/deploy/install.sh b/deploy/install.sh new file mode 100644 index 0000000..80d14db --- /dev/null +++ b/deploy/install.sh @@ -0,0 +1,49 @@ +#!/usr/bin/env bash +set -euo pipefail +# Run from a committed, published release checkout on an x86_64 Ubuntu host. +# VISION_BIND is the host's Tailscale IPv4; defaults to loopback. +# MEDIA_ARCHIVE optionally points to an already downloaded pinned release archive. +[[ $(id -u) == 0 ]] || { echo 'Run as root'; exit 1; } +[[ $(uname -m) == x86_64 ]] || { echo 'This installer targets x86_64'; exit 1; } +command -v python3 >/dev/null +release_dir=$(cd -- "$(dirname -- "$0")/.." && pwd) +bind_address=${VISION_BIND:-127.0.0.1} +python3 - "$bind_address" <<'PY' +import ipaddress,sys +ip=ipaddress.ip_address(sys.argv[1]) +assert ip.version==4 and (ip.is_loopback or ip in ipaddress.ip_network('100.64.0.0/10')), 'Use a Tailscale or loopback address' +PY +getent passwd zhaovision >/dev/null || useradd --system --home-dir /var/lib/zhaovision --shell /usr/sbin/nologin zhaovision +install -d -o zhaovision -g zhaovision -m 700 /var/lib/zhaovision /var/lib/zhaovision/recordings +install -d -m 755 /opt/zhaovision /usr/local/lib/zhaovision +archive=${MEDIA_ARCHIVE:-/tmp/mediamtx_v1.21.1_linux_amd64.tar.gz} +if [[ ! -f "$archive" ]]; then + curl -fL --retry 3 'https://github.com/bluenviron/mediamtx/releases/download/v1.21.1/mediamtx_v1.21.1_linux_amd64.tar.gz' -o "$archive" +fi +python3 - "$archive" <<'PY' +import hashlib,sys +expected='653abc672a3e693f8d3b2717752492fdcfb8072291ec108d03d3dd857411b0ee' +assert hashlib.file_digest(open(sys.argv[1],'rb'),'sha256').hexdigest()==expected, 'MediaMTX checksum mismatch' +PY +tar -xzf "$archive" -C /usr/local/lib/zhaovision mediamtx LICENSE +chmod 755 /usr/local/lib/zhaovision/mediamtx +if [[ -e /opt/zhaovision/current && ! -L /opt/zhaovision/current ]]; then + echo '/opt/zhaovision/current is not a symlink; refusing to replace it'; exit 1 +fi +ln -sfn "$release_dir" /opt/zhaovision/current +if [[ ! -f /etc/zhaovision.env ]]; then + umask 077 + printf 'VISION_BIND=%s\nVISION_PORT=8790\nVISION_DATA=/var/lib/zhaovision\nVISION_RECORDINGS=/var/lib/zhaovision/recordings\n' "$bind_address" > /etc/zhaovision.env +fi +install -m 644 "$release_dir/deploy/zhaovision.service" /etc/systemd/system/zhaovision.service +install -m 644 "$release_dir/deploy/zhaovision-media.service" /etc/systemd/system/zhaovision-media.service +systemctl daemon-reload +systemctl enable zhaovision.service zhaovision-media.service +systemctl restart zhaovision.service +for attempt in {1..20}; do + [[ -s /var/lib/zhaovision/mediamtx.yml ]] && break + sleep 1 +done +systemctl restart zhaovision-media.service +echo 'Services started. Initial setup code: /var/lib/zhaovision/setup-code.txt' +echo "Tailscale entry: http://${bind_address}:8790/" diff --git a/deploy/zhaovision-media.service b/deploy/zhaovision-media.service new file mode 100644 index 0000000..eb83d2a --- /dev/null +++ b/deploy/zhaovision-media.service @@ -0,0 +1,24 @@ +[Unit] +Description=ZhaoVision MediaMTX video and recording service +After=zhaovision.service +Requires=zhaovision.service + +[Service] +Type=simple +User=zhaovision +Group=zhaovision +WorkingDirectory=/var/lib/zhaovision +Environment=TZ=UTC +ExecStart=/usr/local/lib/zhaovision/mediamtx /var/lib/zhaovision/mediamtx.yml +Restart=always +RestartSec=4 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/var/lib/zhaovision +MemoryMax=1200M + +[Install] +WantedBy=multi-user.target diff --git a/deploy/zhaovision.service b/deploy/zhaovision.service new file mode 100644 index 0000000..e6efc38 --- /dev/null +++ b/deploy/zhaovision.service @@ -0,0 +1,27 @@ +[Unit] +Description=ZhaoVision local video management +After=network-online.target tailscaled.service +Wants=network-online.target + +[Service] +Type=simple +User=zhaovision +Group=zhaovision +WorkingDirectory=/opt/zhaovision/current +EnvironmentFile=/etc/zhaovision.env +Environment=PYTHONDONTWRITEBYTECODE=1 +Environment=PYTHONUNBUFFERED=1 +Environment=TZ=UTC +ExecStart=/usr/bin/python3 /opt/zhaovision/current/app.py +Restart=always +RestartSec=4 +UMask=0077 +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/var/lib/zhaovision +MemoryMax=512M + +[Install] +WantedBy=multi-user.target diff --git a/web/app.js b/web/app.js new file mode 100644 index 0000000..f21cc1e --- /dev/null +++ b/web/app.js @@ -0,0 +1,135 @@ +'use strict'; +const $ = (s) => document.querySelector(s); +const $$ = (s) => [...document.querySelectorAll(s)]; +const esc = (s) => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +const kind = (v) => ({home:'家庭',company:'公司',other:'其他'}[v] || '其他'); +let state = {cameras:[], assets:[], recorders:[], sites:[], storage:{}, scan:{}}, activePage = 'live', loggedIn = false, setup = false; +let players = [], liveKey = '', spans = [], queryStart = null, queryEnd = null, queryCamera = '', toastTimer; +const pageInfo = {live:['实时画面','从一个空间,看到每一个位置。'],playback:['录像回放','沿着时间,找回需要的画面。'],cameras:['镜头通道','为摄像头的每个镜头配置独立通道。'],objects:['摄像头对象','实体设备、镜头通道与空间,明确关联。'],recorders:['录像机','连接现有录像与各个现场通道。'],sites:['空间档案','地区、场所、楼栋与门牌,清楚关联每一个镜头。'],storage:['录像与存储','让记录持续,也让磁盘留有余地。']}; +async function api(path, data) { + const r = await fetch(path, {method:data === undefined ? 'GET' : 'POST', headers:data === undefined ? {} : {'Content-Type':'application/json'}, body:data === undefined ? undefined : JSON.stringify(data)}); + let result; try { result = await r.json(); } catch { throw Error('服务返回异常,请稍后重试'); } + if (!r.ok) { if (r.status === 401 && loggedIn) { loggedIn = false; stopPlayers(); auth(); } throw Error(result.error || '操作未完成'); } + return result; +} +function toast(text) { clearTimeout(toastTimer); $('#toast').textContent = text; $('#toast').hidden = false; toastTimer = setTimeout(() => $('#toast').hidden = true, 4000); } +function siteName(id) { return state.sites.find(s => s.id === id)?.name || '未关联空间'; } +function address(s) { return [s.province,s.city,s.district,s.street,s.community,s.building,s.unit,s.floor,s.door].filter(Boolean).join(' · ') || '地址待完善'; } +function filtered() { return state.cameras.filter(c => !$('#site-filter').value || c.siteId === $('#site-filter').value); } +function setOptions(select, html) { const old = select.value; select.innerHTML = html; if ([...select.options].some(o => o.value === old)) select.value = old; } +function stopPlayers() { players.forEach(p => p.destroy()); players = []; $$('#live-grid video').forEach(v => {v.pause();v.removeAttribute('src');v.load();}); liveKey = ''; } +function showPage(page) { + if (activePage !== page) stopPlayers(); + activePage = page; + $$('.page').forEach(el => el.hidden = el.id !== 'page-' + page); + $$('nav button').forEach(b => b.classList.toggle('active', b.dataset.page === page)); + $('#page-title').textContent = pageInfo[page][0]; $('#page-note').textContent = pageInfo[page][1]; + if (page !== 'playback') $('#play-video').pause(); + render(); + if (page === 'storage') loadAudit(); +} +function render() { + $('#metric-all').textContent = state.assets.length; + $('#metric-ready').textContent = state.cameras.filter(c=>c.ready).length; + $('#metric-sites').textContent = state.sites.length; + $('#metric-used').textContent = state.storage.usedGB == null ? '—' : state.storage.usedGB + ' GB'; + $('#service-status').textContent = state.mediaOnline ? '视频服务已连接' : '视频服务未连接'; + $('#service-status').classList.toggle('off', !state.mediaOnline); + $('#version').textContent = 'v' + state.version + ' / 数据存于本机'; + const warning = state.storage.paused ? state.storage.reason + ',已暂停录像。' : ''; + $('#banner').textContent = warning; $('#banner').hidden = !warning; + setOptions($('#site-filter'), '' + state.sites.map(s=>``).join('')); + if (activePage === 'live') renderLive(); + if (activePage === 'cameras') renderCameras(); + if (activePage === 'sites') renderSites(); + if (activePage === 'objects') renderAssets(); + if (activePage === 'recorders') renderRecorders(); + if (activePage === 'playback') { + setOptions($('#play-camera'), filtered().map(c=>``).join('')); + drawTimeline(); + } + if (activePage === 'storage') renderStorage(); +} +function empty(title, description, button) { return `

${esc(title)}

${esc(description)}

${button || ''}
`; } +function renderLive() { + const cameras = filtered(), quality = $('#quality').value; + const key = JSON.stringify(cameras.map(c=>[c.id,c.name,c.siteId,c.point,c.ready,c.enabled,c.record,c.recordingActive])) + quality; + if (key === liveKey) return; + stopPlayers(); liveKey = key; + $('#live-grid').innerHTML = cameras.length ? cameras.map(c=>`
◎${c.enabled ? '正在等待画面' : '设备连接已停用'}
${esc(c.name)}

${esc(siteName(c.siteId)+' · '+(c.point || '安装位置待填写'))}

${c.recordingActive ? '● 正在录像' : c.ready ? '码流已接通' : c.enabled ? '等待接通' : '已停用'}
`).join('') : empty('先接入一台摄像头','建立空间档案,再把设备添加到对应位置。',''); + for (const c of cameras.filter(c=>c.enabled)) { + const video = $(`video[data-camera="${c.id}"]`), panel = video.parentElement; + const src = `/media/live/cam_${c.id}_${quality}/index.m3u8`; + const error = text => {const el=panel.querySelector('.video-error');el.textContent=text;el.hidden=false;}; + video.onplaying=()=>{panel.querySelector('.video-empty').hidden=true;panel.querySelector('.video-error').hidden=true;}; + video.onerror=()=>error('浏览器无法解码此码流。可尝试切换清晰度,或将摄像头设为 H.264。'); + if (window.Hls?.isSupported()) { + const hls = new Hls({maxBufferLength:10,backBufferLength:5,liveSyncDurationCount:3,manifestLoadingMaxRetry:2,levelLoadingMaxRetry:2}); + hls.on(Hls.Events.ERROR,(_,data)=>{if(data.fatal){error('画面暂未接通,请检查设备账号、路径、网络或编码。点击刷新状态可重试。');hls.destroy();}}); + hls.on(Hls.Events.MANIFEST_PARSED,()=>video.play().catch(()=>{})); + hls.loadSource(src);hls.attachMedia(video);players.push(hls); + } else if (video.canPlayType('application/vnd.apple.mpegurl')) {video.src=src;video.play().catch(()=>{});} + else error('当前浏览器不支持 HLS 播放,请使用较新的浏览器。'); + } +} +function renderCameras() { + $('#scan-button').disabled=state.scan.running; $('#scan-button').textContent=state.scan.running?'正在探测…':'开始探测'; + $('#scan-result').innerHTML=(state.scan.items||[]).map(s=>`
${esc(s.host)} · RTSP 服务响应
`).join('') || (state.scan.at ? '

本次没有发现响应 RTSP 554 端口的设备。

' : ''); + const cameras=filtered(); + $('#camera-list').innerHTML=cameras.length?`
${cameras.map(c=>``).join('')}
设备 / 位置所属空间地址码流状态录像
${esc(c.name)}${esc(c.point||'位置待完善')}${esc(siteName(c.siteId))}${esc(c.host)}:${c.port}${c.ready?'已接通':c.enabled?'未接通':'停用'}${c.recordingActive?'正在录像':c.record?'已配置,等待写入':'未开启'}
`:empty('尚无摄像头','可以先扫描当前局域网,或手动填写设备地址。'); +} +function renderSites() { + $('#site-list').innerHTML=state.sites.length?state.sites.map(s=>`
${kind(s.kind)}

${esc(s.name)}

所属
${esc(s.owner||'待填写')}
地区
${esc([s.province,s.city,s.district,s.street].filter(Boolean).join(' / ')||'待填写')}
小区 / 园区
${esc(s.community||'待填写')}
楼栋门牌
${esc([s.building,s.unit,s.floor,s.door].filter(Boolean).join(' / ')||'待填写')}
摄像头
${state.cameras.filter(c=>c.siteId===s.id).length} 台
详细地址
${esc(s.address||'待填写')}
`).join(''):empty('建立第一个空间','填写地区、小区、用途、楼栋和门牌,让摄像头有明确的归属。',''); +} +function renderStorage() { + const s=state.storage; + if (!$('#storage-form').contains(document.activeElement)) for(const k of ['retentionDays','maxGB','reserveGB']) $('#storage-form').elements[k].value=s[k]??''; + $('#storage-status').innerHTML=[['录像占用',(s.usedGB??'—')+' GB'],['磁盘可用',(s.freeGB??'—')+' GB'],['视频服务',state.mediaOnline?'运行中':'未连接'],['空间保护',s.paused?s.reason:'未触发'],['录像方式','主码流持续录像 / 分段保存'],['系统运行',Math.floor(state.uptime/3600)+' 小时 '+Math.floor(state.uptime%3600/60)+' 分钟']].map(([k,v])=>`
${esc(k)}
${esc(v)}
`).join(''); +} +async function loadAudit() { try {const rows=await api('/api/audit');$('#audit-list').innerHTML=rows.slice(0,8).map(r=>`
${new Date(r.at).toLocaleString()}${esc(r.action)} ${esc(r.name)}
`).join('')||'

尚无操作记录

';}catch(e){toast(e.message);} } +async function refresh() {if(!loggedIn)return;try{state=await api('/api/state');render();}catch(e){$('#banner').textContent=e.message;$('#banner').hidden=false;}} +async function auth() {try{const s=await api('/api/session');loggedIn=s.authenticated;setup=s.setupRequired;$('#setup-code-label').hidden=!setup;$('#auth-title').textContent=setup?'建立你的视觉空间':'欢迎回来';$('#auth-note').textContent=setup?'使用部署时生成的初始化码,设置你自己的管理密码。':'输入管理密码,进入视觉工作空间。';if(!loggedIn&&!$('#auth-dialog').open)$('#auth-dialog').showModal();if(loggedIn){$('#auth-dialog').close();await refresh();}}catch(e){toast('无法连接管理服务:'+e.message);}} +function openSite(id) {const f=$('#site-form');f.reset();f.querySelector('.form-error').textContent='';const item=state.sites.find(s=>s.id===id);if(item)for(const [k,v]of Object.entries(item))if(f.elements[k])f.elements[k].value=v;$('#site-dialog').showModal();} +function openCamera(id, host='') {if(!state.assets.length){toast('请先建立摄像头对象,再配置镜头通道');openAsset();return;}if(!state.sites.length){toast('请先建立空间档案,再添加摄像头');openSite();return;}const f=$('#camera-form');f.reset();f.querySelector('.form-error').textContent='';f.elements.assetId.innerHTML=state.assets.map(a=>``).join('');f.elements.recorderId.innerHTML=''+state.recorders.map(r=>``).join('');f.elements.siteId.innerHTML=state.sites.map(s=>``).join('');const c=state.cameras.find(c=>c.id===id);if(c){for(const [k,v]of Object.entries(c)){const el=f.elements[k];if(!el)continue;if(el.type==='checkbox')el.checked=v;else el.value=v;}}else{f.elements.host.value=host;if($('#site-filter').value)f.elements.siteId.value=$('#site-filter').value;}$('#path-preset').value='custom';if(!c){if(state.recorders.length){f.elements.recorderId.value=state.recorders[0].id;}else{f.elements.sourceKind.value='direct';f.elements.archiveSource.value='local';}}syncEndpoint();$('#camera-dialog').showModal();} +function formValues(f) {return Object.fromEntries(new FormData(f).entries());} +function handleForm(id, endpoint, transform=x=>x, after=()=>{}) {$(`#${id}`).addEventListener('submit',async e=>{e.preventDefault();const f=e.currentTarget,b=f.querySelector('[type=submit]');b.disabled=true;f.querySelector('.form-error').textContent='';try{await api(endpoint,transform(formValues(f),f));f.closest('dialog')?.close();toast('已保存');await refresh();after();}catch(err){f.querySelector('.form-error').textContent=err.message;}finally{b.disabled=false;}});} +handleForm('site-form','/api/sites'); +handleForm('camera-form','/api/cameras',(d,f)=>({...d,port:Number(d.port),enabled:f.elements.enabled.checked,record:f.elements.record.checked})); +handleForm('storage-form','/api/storage',d=>Object.fromEntries(Object.entries(d).map(([k,v])=>[k,Number(v)])),loadAudit); +$('#auth-form').addEventListener('submit',async e=>{e.preventDefault();const f=e.currentTarget,b=f.querySelector('button');b.disabled=true;try{await api(setup?'/api/setup':'/api/login',formValues(f));f.reset();f.querySelector('.form-error').textContent='';await auth();}catch(err){f.querySelector('.form-error').textContent=err.message;}finally{b.disabled=false;}}); +$('#auth-dialog').addEventListener('cancel',e=>e.preventDefault()); +document.addEventListener('click',e=>{const b=e.target.closest('button');if(!b)return;if(b.dataset.page)showPage(b.dataset.page);if(b.dataset.close)$(`#${b.dataset.close}`).close();if(b.dataset.action==='new-camera')openCamera();if(b.dataset.action==='new-asset')openAsset();if(b.dataset.action==='new-recorder')openRecorder();if(b.dataset.editAsset)openAsset(b.dataset.editAsset);if(b.dataset.editRecorder)openRecorder(b.dataset.editRecorder);if(b.dataset.action==='new-site')openSite();if(b.dataset.editSite)openSite(b.dataset.editSite);if(b.dataset.editCamera)openCamera(b.dataset.editCamera);if(b.dataset.found)openCamera(null,b.dataset.found);if(b.dataset.playCamera){showPage('playback');$('#play-camera').value=b.dataset.playCamera;queryRecordings();}if(b.dataset.span)playAt(new Date(b.dataset.span));}); +$('#logout').onclick=async()=>{await api('/api/logout',{});loggedIn=false;stopPlayers();$('#play-video').pause();await auth();}; +$('#refresh').onclick=()=>{liveKey='';refresh();};$('#site-filter').onchange=()=>{stopPlayers();render();};$('#quality').onchange=()=>{stopPlayers();renderLive();}; +$('#scan-button').onclick=async()=>{try{await api('/api/discover',{network:$('#scan-network').value});await refresh();}catch(e){toast(e.message);}}; +$('#path-preset').onchange=e=>{const presets={tplink:['/stream1','/stream2'],hikvision:['/Streaming/Channels/101','/Streaming/Channels/102'],dahua:['/cam/realmonitor?channel=1&subtype=0','/cam/realmonitor?channel=1&subtype=1']};const v=presets[e.target.value];if(v){$('#camera-form').elements.mainPath.value=v[0];$('#camera-form').elements.subPath.value=v[1];}}; +function resetPlayback() {const v=$('#play-video');v.pause();v.removeAttribute('src');v.load();$('#play-empty').hidden=false;$('#download').hidden=true;spans=[];queryCamera='';drawTimeline();$('#recording-list').innerHTML='';} +async function queryRecordings() { + resetPlayback();const id=$('#play-camera').value,date=$('#play-date').value;if(!id||!date){toast('请选择摄像头和日期');return;} + const channel=state.cameras.find(c=>c.id===id);if($('#archive-source').value==='recorder'){$('#play-info').textContent='录像机历史回放接口待接入。请先提供录像机型号,在录像机或原厂 App 中可继续查看已有录像。';return;} + queryStart=new Date(date+'T00:00:00');queryEnd=new Date(queryStart);queryEnd.setDate(queryEnd.getDate()+1);queryCamera=id; + $('#play-info').textContent='正在查找录像…'; + try{const d=await api('/api/recordings?'+new URLSearchParams({camera:id,start:queryStart.toISOString(),end:queryEnd.toISOString()}));spans=d.items.map(s=>({...s,date:new Date(s.start)}));$('#play-info').textContent=spans.length?`找到 ${spans.length} 段连续录像`:'该日期暂无可回放录像';drawTimeline();$('#recording-list').innerHTML=spans.map(s=>``).join('');if(spans.length)playAt(new Date(Math.max(+spans[0].date,+queryStart)));}catch(e){$('#play-info').textContent=e.message;} +} +function drawTimeline() {const c=$('#timeline'),w=c.clientWidth;if(!w)return;const scale=window.devicePixelRatio||1;c.width=w*scale;c.height=76*scale;const ctx=c.getContext('2d');ctx.scale(scale,scale);ctx.fillStyle='#101f25';ctx.fillRect(0,0,w,76);ctx.strokeStyle='#2b454e';for(let i=0;i<=24;i++){const x=w*i/24;ctx.beginPath();ctx.moveTo(x,0);ctx.lineTo(x,i%6===0?76:12);ctx.stroke();}if(!queryStart||!queryEnd)return;ctx.fillStyle='#72cdb5';const total=queryEnd-queryStart;for(const s of spans){const a=Math.max(0,(s.date-queryStart)/total),b=Math.min(1,(+s.date+s.duration*1000-queryStart)/total);if(b>a)ctx.fillRect(a*w,25,Math.max(2,(b-a)*w),25);}} +function playAt(date) {const s=spans.find(s=>+date>=+s.date&&+date<+s.date+s.duration*1000);if(!s){toast('这个时间没有录像,请选择绿色时段');return;}const duration=Math.min(3600,(+s.date+s.duration*1000-date)/1000);const params=new URLSearchParams({camera:queryCamera,start:date.toISOString(),duration:String(duration)});$('#play-video').src='/media/playback?'+params;$('#play-video').play().catch(()=>{});$('#play-info').textContent='回放起点 '+date.toLocaleString()+' · 当前片段最多一小时';$('#play-empty').hidden=true;$('#download').href='/media/playback?'+params+'&download=1';$('#download').setAttribute('download','recording.mp4');$('#download').hidden=false;} +$('#query-recordings').onclick=queryRecordings;$('#play-camera').onchange=()=>{resetPlayback();const c=state.cameras.find(c=>c.id===$('#play-camera').value);$('#archive-source').value=c?.archiveSource||'local';};$('#archive-source').onchange=resetPlayback;$('#play-date').onchange=resetPlayback; +$('#seek-button').onclick=()=>{if(!queryCamera){toast('请先查询录像');return;}playAt(new Date($('#play-date').value+'T'+$('#seek-time').value));}; +$('#timeline').onclick=e=>{if(!queryStart)return;const rect=e.currentTarget.getBoundingClientRect();playAt(new Date(+queryStart+(queryEnd-queryStart)*(e.clientX-rect.left)/rect.width));}; +$('#play-video').onerror=()=>{$('#play-info').textContent='回放失败:可能没有完整录像,或浏览器不支持录像编码;可下载片段后播放。';}; +const today=new Date();$('#play-date').value=[today.getFullYear(),String(today.getMonth()+1).padStart(2,'0'),String(today.getDate()).padStart(2,'0')].join('-'); +window.addEventListener('resize',drawTimeline);window.addEventListener('beforeunload',stopPlayers); +setInterval(()=>{$('#clock').textContent=new Date().toLocaleString('zh-CN',{hour12:false});},1000); +setInterval(refresh,12000);auth(); + +function renderAssets(){ + $('#asset-list').innerHTML=state.assets.length?state.assets.filter(a=>!$('#site-filter').value||a.siteId===$('#site-filter').value).map(a=>`
摄像头对象

${esc(a.name)}

所属空间
${esc(siteName(a.siteId))}
品牌型号
${esc([a.brand,a.model].filter(Boolean).join(' / ')||'待填写')}
物理镜头
${a.lensCount} 个
已配置通道
${state.cameras.filter(c=>c.assetId===a.id).length} 个
安装位置
${esc(a.point||'待填写')}
`).join(''):empty('先建立实体摄像头对象','三台双镜头摄像头,建立三个对象;每个对象下分别配置镜头通道。',''); +} +function renderRecorders(){ + $('#recorder-list').innerHTML=state.recorders.length?state.recorders.map(r=>`
录像机

${esc(r.name)}

所属空间
${esc(siteName(r.siteId))}
品牌型号
${esc([r.brand,r.model].filter(Boolean).join(' / ')||'待确认')}
设备地址
${esc(r.host)}:${r.port}
凭据
${r.passwordConfigured?'已配置':'尚未填写'}
关联镜头
${state.cameras.filter(c=>c.recorderId===r.id).length} 个
原有录像回放
待型号适配
`).join(''):empty('连接现有录像机','填写录像机账号后,在各镜头通道选择这台录像机。',''); +} +function openAsset(id){if(!state.sites.length){toast('请先建立空间档案');openSite();return;}const f=$('#asset-form');f.reset();f.querySelector('.form-error').textContent='';f.elements.siteId.innerHTML=state.sites.map(s=>``).join('');const a=state.assets.find(a=>a.id===id);if(a)for(const [k,v]of Object.entries(a))if(f.elements[k])f.elements[k].value=v;$('#asset-dialog').showModal();} +function openRecorder(id){if(!state.sites.length){toast('请先建立空间档案');openSite();return;}const f=$('#recorder-form');f.reset();f.querySelector('.form-error').textContent='';f.elements.siteId.innerHTML=state.sites.map(s=>``).join('');const r=state.recorders.find(a=>a.id===id);if(r)for(const [k,v]of Object.entries(r))if(f.elements[k])f.elements[k].value=v;$('#recorder-dialog').showModal();} +function syncEndpoint(){const f=$('#camera-form'),isRecorder=f.elements.sourceKind.value==='recorder',r=state.recorders.find(r=>r.id===f.elements.recorderId.value);f.elements.recorderId.disabled=!isRecorder;for(const k of ['host','port','username','password'])f.elements[k].readOnly=isRecorder;if(isRecorder&&r){f.elements.host.value=r.host;f.elements.port.value=r.port;f.elements.username.value=r.username;f.elements.password.value='';}const a=state.assets.find(a=>a.id===f.elements.assetId.value);if(a){f.elements.siteId.value=a.siteId;f.elements.point.value=f.elements.point.value||a.point;}f.elements.siteId.disabled=true;} +$('#camera-form').elements.sourceKind.onchange=syncEndpoint;$('#camera-form').elements.recorderId.onchange=syncEndpoint;$('#camera-form').elements.assetId.onchange=syncEndpoint; +handleForm('asset-form','/api/assets',d=>({...d,lensCount:Number(d.lensCount)}));handleForm('recorder-form','/api/recorders',d=>({...d,port:Number(d.port)})); diff --git a/web/index.html b/web/index.html new file mode 100644 index 0000000..6b213a6 --- /dev/null +++ b/web/index.html @@ -0,0 +1,49 @@ + + + + + 赵府智家 · 视觉 + + + + +
+
ZHAOFU HOME / VISION

实时画面

从一个空间,看到每一个位置。

等待连接
+ +
摄像头—
已接通码流—
录像占用—
空间档案—
+
家庭与公司,分别管理
+

现场画面 LIVE VIEW

+ + + + + + +
赵府智家 · 视觉系统独立部署 / 数据自有
+
+
WELCOME HOME

欢迎回来

输入管理密码,进入视觉工作空间。

+

空间档案

+

镜头通道配置

账号和密码只保存在本机受限数据目录。RTSP 服务响应代表设备可达,实际码流接通后才显示在线。路径预设需要与设备型号、通道一致。

+

摄像头对象

+

录像机配置

驱动在当前版本提供路径模板。录像机历史录像检索、回放及通道自动导入,需要型号确认后接入,当前尚未实现。

+ + + diff --git a/web/style.css b/web/style.css new file mode 100644 index 0000000..5f147bc --- /dev/null +++ b/web/style.css @@ -0,0 +1,2 @@ +:root{font-family:Inter,"Microsoft YaHei",system-ui,sans-serif;color:#dae4e6;background:#10191d;font-synthesis:none;--muted:#8faaaF;--line:#2b3b40;--panel:#18252b;--accent:#74d5bb}*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,.button{border:1px solid transparent;background:var(--accent);color:#153b31;padding:11px 18px;border-radius:8px;font-weight:600;cursor:pointer;white-space:nowrap;text-decoration:none;font-size:14px}button:hover,.button:hover{filter:brightness(1.08)}button:disabled{opacity:.5;cursor:wait}.secondary{background:#263a40;color:#cfe7e5;border-color:#385058}.quiet{background:transparent;border-color:var(--line);color:var(--muted);padding:9px 13px;font-size:13px}input,select{background:#111e24;border:1px solid #3a4e55;color:#e3f0ef;border-radius:7px;padding:10px 11px;min-width:0;max-width:100%;outline:none}input:focus,select:focus{border-color:var(--accent)}label{font-size:13px;color:#a5bec1;display:flex;gap:8px;align-items:center}h1,h2,h3,p{margin-top:0}h1{font-size:30px;letter-spacing:1px;margin:8px 0 8px}h2{font-size:19px;font-weight:600}h3{font-size:16px}p{line-height:1.8}small{font-weight:400}.sidebar{position:fixed;left:0;top:0;bottom:0;width:238px;background:#111e24;border-right:1px solid var(--line);padding:32px 20px;display:flex;flex-direction:column}.brand{display:flex;gap:12px;align-items:center;color:#e9f3f1;text-decoration:none;font-size:21px;font-weight:600;padding:5px 8px 40px}.brand-icon{color:var(--accent);font-size:39px}.brand small{display:block;font-size:9px;letter-spacing:1.1px;margin-top:7px;color:var(--muted)}.nav-label{color:#6b868b;font-size:11px;letter-spacing:3px;padding:14px 15px}nav{display:grid;gap:8px}nav button{text-align:left;background:transparent;color:#8fa9ae;display:flex;gap:15px;font-size:18px;padding:14px 16px}nav button span{font-size:14px}nav button.active{background:#244038;color:#9ee8d3}.side-note{margin-top:auto;padding:20px 9px;font-size:12px;color:#8ebdb1}.side-note p{color:#5e8086;font-size:11px;margin:16px 0}.dot{display:inline-block;width:7px;height:7px;background:#7bd5b5;border-radius:50%;margin-right:5px}main{margin-left:238px;padding:38px 42px 18px;max-width:1800px}header{display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:27px}.eyebrow{font-size:10px;letter-spacing:3px;color:#77aa9e}header p{color:var(--muted);font-size:13px;margin:0}.header-status{display:grid;justify-items:end;gap:13px;padding-top:4px;font-size:11px;color:#718f96}.badge{font-size:11px;background:#243c36;color:#8bddbd;padding:6px 10px;border-radius:5px}.badge.off{background:#372d27;color:#d7ae87}.metrics{display:grid;grid-template-columns:repeat(4,1fr);border:1px solid var(--line);background:#152329;border-radius:12px;overflow:hidden}.metrics>div{padding:21px 25px;border-right:1px solid var(--line);display:flex;justify-content:space-between;align-items:center;gap:10px}.metrics>div:last-child{border:0}.metrics span{font-size:12px;color:var(--muted)}.metrics strong{font-size:26px;font-weight:500}.filter-row{display:flex;gap:16px;align-items:center;margin:26px 0;color:#728c93;font-size:12px}.filter-row>button{margin-left:auto}.filter-row select{max-width:280px}.section-head{display:flex;align-items:center;justify-content:space-between;gap:16px;margin:28px 0 17px}.section-head h2{margin:0}.section-head small{font-size:9px;color:#637f87;letter-spacing:2px;margin-left:12px}.section-head>div{display:flex;align-items:center;gap:16px}.live-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:20px}.camera-card{border:1px solid var(--line);border-radius:11px;background:var(--panel);overflow:hidden}.camera-card .video-panel{border:0;border-radius:0;margin:0}.video-panel{position:relative;aspect-ratio:16/9;background:#070e12;overflow:hidden;border:1px solid var(--line);border-radius:10px;margin-bottom:16px}.video-panel video{width:100%;height:100%;object-fit:contain;display:block}.video-empty{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:13px;color:#5c7b85;font-size:13px;pointer-events:none;background:radial-gradient(ellipse at center,#142a32 0,transparent 70%)}.video-empty .lens{font-size:36px;color:#456773}.video-error{position:absolute;left:14px;right:14px;bottom:48px;background:#271d1ce6;border-radius:6px;color:#e3b7a1;padding:9px 12px;font-size:12px}.camera-meta{display:flex;justify-content:space-between;gap:12px;padding:16px 18px}.camera-meta strong{font-size:14px}.camera-meta p{color:#728f96;font-size:11px;margin:6px 0 0}.camera-meta .badge{align-self:flex-start}.camera-actions{display:flex;gap:8px;padding:0 18px 14px}.camera-actions button{font-size:11px;padding:7px 10px}.empty{grid-column:1/-1;padding:62px 20px;text-align:center;background:var(--panel);border:1px dashed #354b52;border-radius:12px;color:#819da5}.empty h3{font-size:19px;color:#c4d5d6;font-weight:500}.empty p{font-size:13px;margin-bottom:22px}.panel{padding:22px;background:var(--panel);border:1px solid var(--line);border-radius:10px;margin-bottom:18px}.playback-controls{display:flex;align-items:end;gap:15px;flex-wrap:wrap}.playback-controls label{display:grid}.playback-controls>span{font-size:12px;color:var(--muted);margin:auto 0}.timeline-head{display:flex;justify-content:space-between;font-size:12px;margin-bottom:20px}.timeline-head span{color:var(--muted)}.legend{display:inline-block;background:var(--accent);width:15px;height:6px;margin-right:7px}#timeline{width:100%;height:76px;display:block;cursor:crosshair}.time-labels{display:flex;justify-content:space-between;font-size:10px;color:#74949c}.seek-row{margin-top:22px;display:flex;align-items:center;gap:12px;flex-wrap:wrap}.recording-list{display:grid;grid-template-columns:repeat(3,1fr);gap:12px}.recording-item{text-align:left;background:#203139;color:#bdd5d8;font-size:12px;border:1px solid var(--line);white-space:normal}.recording-item small{display:block;color:#719499;margin-top:7px}.discovery{display:flex;align-items:center;gap:14px}.discovery>div{margin-right:auto}.discovery p{font-size:12px;color:var(--muted);margin:5px 0 0}.discovery input{width:190px}.scan-chip{display:inline-flex;gap:16px;align-items:center;margin:0 12px 14px 0;padding:12px 16px;border:1px solid var(--line);border-radius:8px;font-size:13px}.scan-chip button{padding:6px 10px;font-size:11px}.table-wrap{overflow:auto}.device-table{width:100%;border-collapse:collapse;background:var(--panel);border:1px solid var(--line);font-size:13px}.device-table th{text-align:left;font-size:11px;color:#8ba9ae;font-weight:400;padding:15px}.device-table td{padding:18px 15px;border-top:1px solid var(--line)}.device-table td small{display:block;margin-top:7px;color:#75969d}.site-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.site-card{background:var(--panel);border:1px solid var(--line);padding:24px;border-radius:10px}.site-heading{display:flex;justify-content:space-between;gap:12px}.site-card h3{margin:12px 0}.site-card dl{font-size:12px}.site-card dl>div{display:flex;gap:18px;padding:7px 0}.site-card dt{color:#718d94;width:80px;flex-shrink:0}.site-card dd{margin:0;color:#b6cccf;word-break:break-word}.description{font-size:12px;color:var(--muted);line-height:1.9}.storage-grid{display:grid;grid-template-columns:1fr 1.2fr;gap:22px}.storage-grid form>label{display:grid;margin:20px 0}.storage-grid dl{font-size:13px}.storage-grid dl div{display:flex;justify-content:space-between;gap:15px;padding:15px 0;border-bottom:1px solid var(--line)}.storage-grid dt{color:var(--muted)}.storage-grid dd{margin:0}.audit-item{font-size:11px;padding:10px 0;border-top:1px solid var(--line);color:#9ab8bd}.audit-item small{display:block;color:#607f89;margin-bottom:5px}.banner{background:#493c24;border:1px solid #6b5430;color:#e1c69a;border-radius:8px;padding:13px 17px;font-size:13px;margin-bottom:22px}dialog{color:#dae4e6;background:#192a31;border:1px solid #3b555d;border-radius:15px;width:min(760px,94vw);max-height:90vh;padding:30px;box-shadow:0 25px 120px #0008}dialog::backdrop{background:#061015dd;backdrop-filter:blur(8px)}#auth-dialog{max-width:430px;padding:38px}#auth-form h2{font-size:28px;margin:18px 0 10px}#auth-form>label{display:grid;margin:22px 0}#auth-form p{color:#93afb5;font-size:13px}.dialog-heading{display:flex;justify-content:space-between;align-items:center;margin-bottom:25px}.dialog-heading h2{margin:0}.form-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px}.form-grid label{display:grid;gap:8px}.form-grid .full{grid-column:1/-1}.form-grid .check{display:flex}.check input{accent-color:var(--accent);width:16px;height:16px}.dialog-footer{display:flex;justify-content:flex-end;margin-top:20px;padding-top:20px;border-top:1px solid var(--line)}.form-error{font-size:12px;color:#efab97;line-height:1.6}.wide{width:100%}footer{font-size:10px;color:#54727c;display:flex;justify-content:space-between;margin-top:40px;padding-top:18px;border-top:1px solid var(--line)}#toast{position:fixed;bottom:28px;left:50%;transform:translateX(-50%);border:1px solid #4a7d70;background:#1a3c32;color:#b5efd9;padding:13px 22px;border-radius:9px;z-index:5;box-shadow:0 10px 30px #0005;font-size:13px}[hidden]{display:none!important}:focus-visible{outline:2px solid var(--accent);outline-offset:3px} +@media(min-width:1600px){.live-grid{grid-template-columns:repeat(3,minmax(0,1fr))}}@media(max-width:1100px){.sidebar{width:190px;padding:25px 14px}.brand{font-size:17px}.brand-icon{font-size:30px}.brand small{font-size:8px}main{margin-left:190px;padding:25px}.metrics>div{padding:18px 14px}.metrics strong{font-size:22px}.storage-grid{grid-template-columns:1fr}.section-head small{display:none}}@media(max-width:760px){.sidebar{position:static;width:auto;padding:18px 16px 8px;border-right:0;border-bottom:1px solid var(--line)}.brand{padding:0 3px 16px}.brand small{font-size:9px}.sidebar nav{display:flex;gap:3px;overflow:auto}.sidebar nav button{padding:10px;font-size:14px;gap:6px}.sidebar nav button span{font-size:11px}.nav-label,.side-note,.sidebar #logout{display:none}main{margin:0;padding:23px 16px}h1{font-size:25px}.header-status{font-size:9px}.metrics{grid-template-columns:1fr 1fr}.metrics>div{border-bottom:1px solid var(--line)}.metrics>div:nth-child(2){border-right:0}.live-grid,.site-grid{grid-template-columns:1fr}.filter-row{flex-wrap:wrap;gap:10px}.filter-row>span{display:none}.filter-row select{max-width:200px}.section-head{align-items:start}.section-head>div{flex-wrap:wrap;justify-content:flex-end;gap:8px}.section-head button{padding:9px 11px;font-size:12px}.section-head h2{font-size:16px}.section-head label{font-size:11px}.section-head select{padding:6px}.discovery{flex-wrap:wrap}.discovery>div{width:100%}.discovery input{flex:1}.recording-list{grid-template-columns:1fr 1fr}.timeline-head{gap:10px;font-size:10px}.form-grid{gap:13px}.form-grid label{font-size:12px}dialog{padding:23px}.form-grid .full{grid-column:1/-1}.playback-controls label{flex:1}.video-empty{font-size:11px}.camera-meta{padding:14px}.seek-row label{width:100%}#auth-dialog{padding:30px}footer{font-size:9px}} diff --git a/web/vendor/Apache-2.0.txt b/web/vendor/Apache-2.0.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/web/vendor/Apache-2.0.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/web/vendor/SHA256.json b/web/vendor/SHA256.json new file mode 100644 index 0000000..b9f128d --- /dev/null +++ b/web/vendor/SHA256.json @@ -0,0 +1,5 @@ +{ + "Apache-2.0.txt": "cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30", + "hls.LICENSE": "ca8773cf798c7ed997d4dd7c8e23c348699f8d5b7462636694cc14de6cda12db", + "hls.min.js": "a12e7ee1cd64a69dcdb314157e45dafcba705bfb0b1440b7935cb265d374423e" +} diff --git a/web/vendor/hls.LICENSE b/web/vendor/hls.LICENSE new file mode 100644 index 0000000..5123bda --- /dev/null +++ b/web/vendor/hls.LICENSE @@ -0,0 +1,28 @@ +Copyright (c) 2017 Dailymotion (http://www.dailymotion.com) + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + +src/remux/mp4-generator.js and src/demux/exp-golomb.ts implementation in this project +are derived from the HLS library for video.js (https://github.com/videojs/videojs-contrib-hls) + +That work is also covered by the Apache 2 License, following copyright: +Copyright (c) 2013-2015 Brightcove + + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/web/vendor/hls.min.js b/web/vendor/hls.min.js new file mode 100644 index 0000000..161cb34 --- /dev/null +++ b/web/vendor/hls.min.js @@ -0,0 +1,4 @@ +!function e(t){var r,i;r=this,i=function(){"use strict";function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r=e.length?{done:!0}:{done:!1,value:e[n++]}}}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 o(e,t,r){return(t=y(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function l(){return l=Object.assign?Object.assign.bind():function(e){for(var t=1;t3?(n=g===i)&&(l=a[(o=a[4])?5:(o=3,3)],a[4]=a[5]=e):a[0]<=c&&((n=r<2&&ci||i>g)&&(a[4]=r,a[5]=i,f.n=g,o=0))}if(n||r>1)return s;throw h=!0,i}return function(n,d,g){if(u>1)throw TypeError("Generator is already running");for(h&&1===d&&c(d,g),o=d,l=g;(t=o<2?e:l)||!h;){a||(o?o<3?(o>1&&(f.n=-1),c(o,l)):f.n=l:f.v=l);try{if(u=2,a){if(o||(n="next"),t=a[n]){if(!(t=t.call(a,l)))throw TypeError("iterator result is not an object");if(!t.done)return t;l=t.value,o<2&&(o=0)}else 1===o&&(t=a.return)&&t.call(a),o<2&&(l=TypeError("The iterator does not provide a '"+n+"' method"),o=1);a=e}else if((t=(h=f.n<0)?l:r.call(i,f))!==s)break}catch(t){a=e,o=1,l=t}finally{u=1}}return{value:t,done:h}}}(r,n,a),!0),u}var s={};function o(){}function l(){}function u(){}t=Object.getPrototypeOf;var d=[][i]?t(t([][i]())):(m(t={},i,(function(){return this})),t),h=u.prototype=o.prototype=Object.create(d);function f(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,u):(e.__proto__=u,m(e,n,"GeneratorFunction")),e.prototype=Object.create(h),e}return l.prototype=u,m(h,"constructor",u),m(u,"constructor",l),l.displayName="GeneratorFunction",m(u,n,"GeneratorFunction"),m(h),m(h,n,"Generator"),m(h,i,(function(){return this})),m(h,"toString",(function(){return"[object Generator]"})),(v=function(){return{w:a,m:f}})()}function m(e,t,r,i){var n=Object.defineProperty;try{n({},"",{})}catch(e){n=0}m=function(e,t,r,i){function a(t,r){m(e,t,(function(e){return this._invoke(t,r,e)}))}t?n?n(e,t,{value:r,enumerable:!i,configurable:!i,writable:!i}):e[t]=r:(a("next",0),a("throw",1),a("return",2))},m(e,t,r,i)}function p(e,t){return p=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},p(e,t)}function y(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function E(e){var t="function"==typeof Map?new Map:void 0;return E=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(h())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var n=new(e.bind.apply(e,i));return r&&p(n,r.prototype),n}(e,arguments,u(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),p(r,e)},E(e)}function T(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}var S="utf-16",A="utf-16be",I="utf-16le",L="utf-8";function R(e,t){if(e<0)return-R(-e,t);var r=Math.pow(10,t);if(Math.abs(e*r%1-.5)1||1===i&&null!=(t=this.levelkeys[r[0]])&&t.encrypted)return!0}return!1}},{key:"programDateTime",get:function(){return null===this._programDateTime&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime},set:function(e){x(e)?this._programDateTime=e:this._programDateTime=this.rawProgramDateTime=null}},{key:"ref",get:function(){return W(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}}])}(j),Q=function(e){function t(t,r,i,n,a){var s;(s=e.call(this,i)||this).fragOffset=0,s.duration=0,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.gap=!1,s.duration=t.decimalFloatingPoint("DURATION"),s.gap=t.bool("GAP"),s.independent=t.bool("INDEPENDENT"),s.relurl=t.enumeratedString("URI"),s.fragment=r,s.index=n;var o=t.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,a),a&&(s.fragOffset=a.fragOffset+a.duration),s}return d(t,e),a(t,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var e=this.elementaryStreams;return!!(e.audio||e.video||e.audiovideo||this.fragment.type===H.SUBTITLE&&this.stats.loading.end>0)}}])}(j);function $(e,t){var r=Object.getPrototypeOf(e);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i||$(r,t)}}function Z(e){switch(e.details){case B.FRAG_LOAD_TIMEOUT:case B.KEY_LOAD_TIMEOUT:case B.LEVEL_LOAD_TIMEOUT:case B.MANIFEST_LOAD_TIMEOUT:case B.AUDIO_TRACK_LOAD_TIMEOUT:case B.SUBTITLE_TRACK_LOAD_TIMEOUT:case B.ASSET_LIST_LOAD_TIMEOUT:return!0}return!1}function J(e){return e.details.startsWith("key")}function ee(e){return J(e)&&!!e.frag&&!e.frag.decryptdata}function te(e,t){var r=Z(t);return e.default[(r?"timeout":"error")+"Retry"]}function re(e,t){var r="linear"===e.backoff?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function ie(e){return c(c({},e),{errorRetry:null,timeoutRetry:null})}function ne(e,t,r,i){if(!e)return!1;var n=null==i?void 0:i.code,a=t499)}(n)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,i,a):a}function ae(e){return 0===e&&!1===navigator.onLine}function se(e,t){return t>0&&e.loadError>0&&0!==e.loadErrorTime&&self.performance.now()-e.loadErrorTime>t}var oe=function(){function e(e,t,r){void 0===t&&(t=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}var t=e.prototype;return t.sample=function(e,t){var r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e},t.getTotalWeight=function(){return this.totalWeight_},t.getEstimate=function(){if(this.alpha_){var e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_},e}(),le=function(){function e(e,t,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 oe(e),this.fast_=new oe(t),this.defaultTTFB_=i,this.ttfb_=new oe(e)}var t=e.prototype;return t.update=function(e,t){var r=this.slow_,i=this.fast_,n=this.ttfb_;r.halfLife!==e&&(this.slow_=new oe(e,r.getEstimate(),r.getTotalWeight())),i.halfLife!==t&&(this.fast_=new oe(t,i.getEstimate(),i.getTotalWeight())),n.halfLife!==e&&(this.ttfb_=new oe(e,n.getEstimate(),n.getTotalWeight()))},t.sample=function(e,t){if(!(t<=0)){var r=Math.min(this.minDelayMs_,t/1e5),i=8*t,n=Math.max(e,r)/1e3,a=i/n;this.fast_.sample(n,a),this.slow_.sample(n,a)}},t.sampleTTFB=function(e){var t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))},t.canEstimate=function(){return this.fast_.getTotalWeight()>=this.minWeight_},t.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},t.getEstimateTTFB=function(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_},t.destroy=function(){},a(e,[{key:"defaultEstimate",get:function(){return this.defaultEstimate_}}])}(),ue=function(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;var r="["+e+"]:";this.trace=de,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)},de=function(){},he={trace:de,debug:de,log:de,warn:de,info:de,error:de};function fe(){return l({},he)}function ce(e,t,r){return t[e]?t[e].bind(t):function(e,t){var r=self.console[e];return r?r.bind(self.console,(t?"["+t+"] ":"")+"["+e+"] >"):de}(e,r)}var ge=fe();function ve(e,t,r){var i=fe();if("object"==typeof console&&!0===e||"object"==typeof e){var n=["debug","log","info","warn","error"];n.forEach((function(t){i[t]=ce(t,e,r)}));try{i.log('Debug logs enabled for "'+t+'" in hls.js version 1.7.3')}catch(e){return fe()}n.forEach((function(t){ge[t]=ce(t,e)}))}else l(ge,i);return i}var me=ge;function pe(e){if(void 0===e&&(e=!0),"undefined"!=typeof self)return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function ye(e,t){var r=Object.keys(e),i=Object.keys(t),n=r.length,a=i.length;return!n||!a||n===a&&!r.some((function(e){return-1===i.indexOf(e)}))}function Ee(e,t){return t+10<=e.length&&73===e[t]&&68===e[t+1]&&51===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Te(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]}function Se(e,t){return Ee(e,t)&&Te(e,t+6)+10<=e.length-t}function Ae(e,t){return t+10<=e.length&&51===e[t]&&68===e[t+1]&&73===e[t+2]&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function Ie(e,t){for(var r=t,i=0;Ee(e,t);)i+=10,i+=Te(e,t+6),Ae(e,t+10)&&(i+=10),t+=i;if(i>0)return e.subarray(r,r+i)}function Le(e,t,r){return void 0===t&&(t=0),void 0===r&&(r=1/0),function(e,t,r,i){var n,a=T(n=e)?n:n.buffer,s=1;"BYTES_PER_ELEMENT"in i&&(s=i.BYTES_PER_ELEMENT);var o,l=(o=e)&&T(o.buffer)&&void 0!==o.byteLength&&void 0!==o.byteOffset?e.byteOffset:0,u=(l+e.byteLength)/s,d=(l+t)/s,h=Math.floor(Math.max(0,Math.min(d,u)));return new i(a,h,Math.floor(Math.min(h+Math.max(r,0),u))-h)}(e,t,r,Uint8Array)}function Re(e,t){void 0===t&&(t=!1);var r=t?e.indexOf(0):e.length,i=function(e,t){var r;void 0===t&&(t={}),r=T(e)?new DataView(e):new DataView(e.buffer,e.byteOffset,e.byteLength);var i=0,n=t.encoding;if(!n){var a=r.getUint8(0),s=r.getUint8(1);239==a&&187==s&&191==r.getUint8(2)?(n=L,i=3):254==a&&255==s?(n=A,i=2):255==a&&254==s?(n=I,i=2):n=L}if("undefined"!=typeof TextDecoder)return new TextDecoder(n).decode(r);for(var o,l=r.byteLength,u=n!==A,d="";i=194&&o<=223)if(i+1=128&&h<=191?(o=(31&o)<<6|63&h,i+=2):i++}else i++;else if(o>=224&&o<=239)if(i+2<=l-1){var f=r.getUint8(i+1),c=r.getUint8(i+2);f>=128&&f<=191&&c>=128&&c<=191?(o=(15&o)<<12|(63&f)<<6|63&c,i+=3):i++}else i++;else if(o>=240&&o<=244)if(i+3<=l-1){var g=r.getUint8(i+1),v=r.getUint8(i+2),m=r.getUint8(i+3);g>=128&&g<=191&&v>=128&&v<=191&&m>=128&&m<=191?(o=(7&o)<<18|(63&g)<<12|(63&v)<<6|63&m,i+=4):i++}else i++;else i++;break;case A:case S:case I:o=r.getUint16(i,u),i+=2}d+=String.fromCodePoint(o)}return d}(new DataView(e.buffer,e.byteOffset,r),{encoding:L});return t?i:i.replace(/\0/g,"")}function be(e){var t={key:e.type,description:"",data:"",mimeType:null,pictureType:null};if(!(e.size<2))if(3===e.data[0]){var r=e.data.subarray(1).indexOf(0);if(-1!==r){var i=Re(Le(e.data,1,r)),n=e.data[2+r],a=e.data.subarray(3+r).indexOf(0);if(-1!==a){var s,o,l=Re(Le(e.data,3+r,a));return s="--\x3e"===i?Re(Le(e.data,4+r+a)):T(o=e.data.subarray(4+r+a))?o:0==o.byteOffset&&o.byteLength==o.buffer.byteLength?o.buffer:new Uint8Array(o).buffer,t.mimeType=i,t.pictureType=n,t.description=l,t.data=s,t}}}else console.log("Ignore frame with unrecognized character encoding")}function ke(e){return"PRIV"===e.type?function(e){if(!(e.size<2)){var t=Re(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}}(e):"W"===e.type[0]?function(e){if("WXXX"===e.type){if(e.size<2)return;var t=1,r=Re(e.data.subarray(t),!0);t+=r.length+1;var i=Re(e.data.subarray(t));return{key:e.type,info:r,data:i}}var n=Re(e.data);return{key:e.type,info:"",data:n}}(e):"APIC"===e.type?be(e):function(e){if(!(e.size<2)){if("TXXX"===e.type){var t=1,r=e.data,i=Re(r.subarray(t),!0);t+=i.length+1;var n=Re(r.subarray(t));return{key:e.type,info:i,data:n}}var a=Re(e.data.subarray(1));return{key:e.type,info:"",data:a}}}(e)}function De(e){var t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=Te(e,4);return{type:t,size:r,data:e.subarray(10,10+r)}}var Pe=10,_e=10;function Ce(e){for(var t=0,r=[];Ee(e,t);){var i=Te(e,t+6);e[t+5]>>6&1&&(t+=Pe);for(var n=(t+=Pe)+i;t+_e>24,e[t+1]=r>>16&255,e[t+2]=r>>8&255,e[t+3]=255&r}function ze(e,t,r){var i=t.byteOffset-e.byteOffset-8,n=8+r,a=t.byteLength+8-n;a<8||(Xe(e,i,n),Xe(e,i+n,a),Xe(e,i+n+4,Ke.free))}function Qe(e,t){return[e.byteOffset-t-8,e.byteOffset-t+e.byteLength]}function $e(e,t){t.sort((function(e,t){return e[0]-t[0]}));for(var r=t.reduce((function(e,t){var r=t[0];return e+t[1]-r}),0),i=new Uint8Array(e.byteLength-r),n=0,a=0,s=0;s1?f+g:n;if(c&&e[f+4]===o&&e[f+5]===l&&e[f+6]===u&&e[f+7]===d){var m=Math.min(v,n);r===h?a.push(e.subarray(f+8,m)):Je(e,t,r+1,f+8,m,a)}f=v}}function et(e){var t=[],r=e[0],i=8,n=Ye(e,i);i+=4;var a=0,s=0;0===r?(a=Ye(e,i),s=Ye(e,i+4),i+=8):(a=je(e,i),s=je(e,i+8),i+=16),i+=2;var o=e.length+s,l=He(e,i);i+=2;for(var u=0;u>>31)return me.warn("SIDX has hierarchical references (not supported)"),null;var c=Ye(e,d);d+=4,t.push({referenceSize:f,subsegmentDuration:c,info:{duration:c/n,start:o,end:o+f-1}}),o+=f,i=d+=4}return{earliestPresentationTime:a,timescale:n,version:r,referencesCount:l,references:t}}function tt(e){for(var t=[],r=Ze(e,["moov","trak"]),i=0;i3&&(a+="."+at(u[1])+at(u[2])+at(u[3]),t=it("avc1"===l?"dva1":"dvav",i));break;case"mp4a":var d=Ze(r,[n])[0],h=Ze(d.subarray(28),["esds"])[0];if(h&&h.length>7){var f=4;if(3!==h[f++])break;f=nt(h,f),f+=2;var c=h[f++];if(128&c&&(f+=2),64&c&&(f+=h[f++]),4!==h[f++])break;f=nt(h,f);var g=h[f++];if(64!==g)break;if(a+="."+at(g),f+=12,5!==h[f++])break;f=nt(h,f);var v=h[f++],m=(248&v)>>3;31===m&&(m+=1+((7&v)<<3)+((224&h[f])>>5)),a+="."+m}break;case"hvc1":case"hev1":var p=Ze(i,["hvcC"])[0];if(p&&p.length>12){var y=p[1],E=["","A","B","C"][y>>6],T=31&y,S=Ye(p,2),A=(32&y)>>5?"H":"L",I=p[12],L=p.subarray(6,12);a+="."+E+T,a+="."+function(e){for(var t=0,r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}(S).toString(16).toUpperCase(),a+="."+A+I;for(var R="",b=L.length;b--;){var k=L[b];(k||R)&&(R="."+k.toString(16).toUpperCase()+R)}a+=R}t=it("hev1"==l?"dvhe":"dvh1",i);break;case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":a=it(a,i)||a;break;case"vp09":var D=Ze(i,["vpcC"])[0];if(D&&D.length>6){var P=D[4],_=D[5],C=D[6]>>4&15;a+="."+st(P)+"."+st(_)+"."+st(C)}break;case"av01":var w=Ze(i,["av1C"])[0];if(w&&w.length>2){var O=w[1]>>>5,M=31&w[1],x=w[2]>>>7?"H":"M",F=(64&w[2])>>6,N=(32&w[2])>>5,U=2===O&&F?N?12:10:F?10:8,B=(16&w[2])>>4,G=(8&w[2])>>3,K=(4&w[2])>>2,V=3&w[2];a+="."+O+"."+st(M)+x+"."+st(U)+"."+B+"."+G+K+V+"."+st(1)+"."+st(1)+"."+st(1)+".0",t=it("dav1",i)}}return{codec:a,encrypted:s,supplemental:t}}function it(e,t){var r=Ze(t,["dvvC"]),i=r.length?r[0]:Ze(t,["dvcC"])[0];if(i){var n=i[2]>>1&127,a=i[2]<<5&32|i[3]>>3&31;return e+"."+st(n)+"."+st(a)}}function nt(e,t){for(var r=t+5;128&e[t++]&&t0;a||(n=Ze(i,["encv"])),n.forEach((function(e){Ze(a?e.subarray(28):e.subarray(78),["sinf"]).forEach((function(e){var r=lt(e);r&&t(r,a)}))}))}}))}function lt(e){var t=Ze(e,["schm"])[0];if(t){var r=Ue(t.subarray(4,8));if("cbcs"===r||"cenc"===r){var i=Ze(e,["schi","tenc"])[0];if(i)return i}}}function ut(e){return"undefined"==typeof TextDecoder?Re(e):(Be||(Be=new TextDecoder("utf-8"))).decode(e).replace(/\0/g,"")}function dt(e,t,r,i,n){for(var a={},s=!1,o=function(e){for(var t=e.byteLength,r=[],i=0;i1?i+a:t;if(n&&109===e[i+4]&&111===e[i+5]&&111===e[i+6]&&102===e[i+7])for(var o=Math.min(s,t),l=i+8;l1?l+d:o;if(u&&116===e[l+4]&&114===e[l+5]&&97===e[l+6]&&102===e[l+7]){for(var f=Math.min(h,o),c=void 0,g=void 0,v=[],m=l+8;m1?m+y:f;if(p&&116===e[m+4]){var T=Math.min(E,f);102===e[m+5]&&104===e[m+6]&&100===e[m+7]?g||(g=e.subarray(m+8,T)):102===e[m+5]&&100===e[m+6]&&116===e[m+7]?c||(c=e.subarray(m+8,T)):114===e[m+5]&&117===e[m+6]&&110===e[m+7]&&v.push(e.subarray(m+8,T))}m=E}r.push({moofOffset:e.byteOffset+i,tfdt:c,tfhd:g,truns:v})}l=h}i=s}return r}(e),l=e.byteLength,u=0;up.ptsMax)&&(p.ptsMax=ae+w),X&&(X[$]={cts:te,duration:w,flags:J,size:Q})}_+=w,C+=w}!C&&I&&(C+=I*F)}else{for(var se,oe,le=_,ue=q,de=W,he=-1,fe=0,ce=0,ge=null!=(se=null==n?void 0:n.timeOffset)?se:0,ve=I/(null!=(oe=null==n?void 0:n.timescale)?oe:1),me=!0===(null==n?void 0:n.isHEVCFlavor),pe=me?2:1,ye=0;ye0){var Ae=q;do{var Ie=0===e[Ae]?e[Ae+1]<<16|e[Ae+2]<<8|e[Ae+3]:Ye(e,Ae),Le=e[Ae+=4],Re=me?Le>>1&63:31&Le;(me?39===Re||40===Re:6===Re)&>(e.subarray(Ae,Ae+Ie),pe,ge,n.samples),Ae+=Ie}while(Ael);De++)ce=De+1,ke+=8;if(T&&(n.timeOffset=ge),-1!==he&&fe<=l&&void 0===p.keyFrameIndex&&(p.keyFrameIndex=he,p.keyFrameStart=le+he*I),ce){(!x(p.ptsMin)||lep.ptsMax)&&(p.ptsMax=Pe)}var _e=I*F;_=le+_e,C+=_e}}p.duration+=C,p.duration&&(s=!0)}}if(!s){for(var Ce=1/0,we=0,Oe=Ze(e,["sidx"]),Me=0;Me>1&63;return 39===r||40===r}return 6==(31&t)}function gt(e,t,r,i){var n=vt(e),a=0;a+=t;for(var s=0,o=0,l=0;a=n.length)break;s+=l=n[a++]}while(255===l);o=0;do{if(a>=n.length)break;o+=l=n[a++]}while(255===l);var u=n.length-a,d=a;if(ou){me.error("Malformed SEI payload. "+o+" is too small, only "+u+" bytes left to parse.");break}if(4===s){if(181===n[d++]){var h=He(n,d);if(d+=2,49===h){var f=Ye(n,d);if(d+=4,1195456820===f){var c=n[d++];if(3===c){var g=n[d++],v=64&g,m=v?2+3*(31&g):0,p=new Uint8Array(m);if(v){p[0]=g;for(var y=1;y16){for(var E=[],T=0;T<16;T++){var S=n[d++].toString(16);E.push(1==S.length?"0"+S:S),3!==T&&5!==T&&7!==T&&9!==T||E.push("-")}for(var A=o-16,I=new Uint8Array(A),L=0;L0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i>24&255,o[1]=a>>16&255,o[2]=a>>8&255,o[3]=255&a,o.set(e,4),s=0,a=8;s>>24;if(0!==n&&1!==n)return{offset:r,size:t};var a,s=e.buffer,o=xe(new Uint8Array(s,r+12,16)),l=null,u=0;if(0===n)u=28;else{var d=e.getUint32(28);if(!d||i<32+16*d)return{offset:r,size:t};l=[];for(var h=0;h>3==2)if(32===a){for(var l=new Uint8Array(16),u=0;u<16;u++)l[u]=parseInt(String.fromCharCode(e[r+2*u],e[r+2*u+1]),16);t.push(l)}else 16===a&&t.push(e.subarray(r,r+16));r+=a}else r+=1===n?8:4;else for(;128&e[r++];);}return t}(a)),{version:n,systemId:o,kids:l,data:a,offset:r,size:t})}var Et,Tt,St,At=Lt("userAgent"),It=Lt("vendor");function Lt(e){try{return navigator[e]||""}catch(e){}return""}function Rt(){if(void 0===Et){var e=At.match(/Chrome\/(\d+)/i);Et=e?parseInt(e[1]):0}return Et}function bt(){return/\(Windows.+Firefox\//i.test(At)}var kt={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1},image:{mjpg:1}};function Dt(e,t){var r=kt[t];return!!r&&!!r[e.slice(0,4)]}function Pt(e,t,r){return void 0===r&&(r=!0),!e.split(",").some((function(e){return!_t(e,t,r)}))}function _t(e,t,r){var i;void 0===r&&(r=!0);var n=pe(r);return null!=(i=null==n?void 0:n.isTypeSupported(Ct(e,t)))&&i}function Ct(e,t){return t+"/mp4;codecs="+e}function wt(e){if(e){var t=e.substring(0,4);return kt.video[t]}return 2}function Ot(e){var t=bt();return e.split(",").reduce((function(e,r){var i=t&&ft(r)?9:kt.video[r];return i?(2*i+e)/(e?3:2):(kt.audio[r]+e)/(e?2:1)}),0)}var Mt={},xt=/flac|opus|mp4a\.40\.34/i;function Ft(e,t){return void 0===t&&(t=!0),e.replace(xt,(function(e){return function(e,t){if(void 0===t&&(t=!0),Mt[e])return Mt[e];for(var r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e],i=0;i4||-1!==["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e))&&(Ut(e,"audio")||Ut(e,"video")))return e;if(t){var r=t.split(",");if(r.length>1){if(e)for(var i=r.length;i--;)if(r[i].substring(0,4)===e.substring(0,4))return r[i];return r[0]}}return t||e}function Ut(e,t){return Dt(e,t)&&_t(e,t)}function Bt(e){if(e.startsWith("av01.")){for(var t=e.split("."),r=["0","111","01","01","01","0"],i=t.length;i>4&&i<10;i++)t[i]=r[i-4];return t.join(".")}return e}function Gt(e){var t=pe(e)||{isTypeSupported:function(){return!1}};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function Kt(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var Vt={supported:!1,smooth:!1,powerEfficient:!1},Ht={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]};function Yt(e,t){return{supported:!1,configurations:t,decodingInfoResults:[Vt],error:e}}function jt(e,t,r,i){void 0===i&&(i={});var n=e.videoCodec;if(!n&&!e.audioCodec||!r)return Promise.resolve(Ht);for(var a=[],s=function(e){var t,r=null==(t=e.videoCodec)?void 0:t.split(","),i=qt(e),n=e.width||640,a=e.height||480,s=e.frameRate||30,o=e.videoRange.toLowerCase();return r?r.map((function(e){var t={contentType:Ct(Bt(e),"video"),width:n,height:a,bitrate:i,framerate:s};return"sdr"!==o&&(t.transferFunction=o),t})):[]}(e),o=s.length,l=function(e,t,r){var i,n=null==(i=e.audioCodec)?void 0:i.split(","),a=qt(e);return n&&e.audioGroups?e.audioGroups.reduce((function(e,i){var s,o=i?null==(s=t.groups[i])?void 0:s.tracks:null;return o?o.reduce((function(e,t){if(t.groupId===i){var s=parseFloat(t.channels||"");n.forEach((function(t){var i={contentType:Ct(t,"audio"),bitrate:r?Wt(t,a):a};s&&(i.channels=""+s),e.push(i)}))}return e}),e):e}),[]):[]}(e,t,o>0),u=l.length,d=o||1*u||1;d--;){var h={type:"media-source"};if(o&&(h.video=s[d%o]),u){h.audio=l[d%u];var f=h.audio.bitrate;h.video&&f&&(h.video.bitrate-=f)}a.push(h)}if(n){var c=navigator.userAgent;if(n.split(",").some((function(e){return ft(e)}))&&bt())return Promise.resolve(Yt(new Error("Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: ("+c+")"),a))}return Promise.all(a.map((function(e){var t,n,a,s,o=(n="",a=(t=e).audio,(s=t.video)&&(n+=Kt(s.contentType)+"_r"+s.height+"x"+s.width+"f"+Math.ceil(s.framerate)+(s.transferFunction||"sd")+"_"+Math.ceil(s.bitrate/1e5)),a&&(n+=(s?"_":"")+Kt(a.contentType)+"_c"+a.channels),n);return i[o]||(i[o]=r.decodingInfo(e))}))).then((function(e){return{supported:!e.some((function(e){return!e.supported})),configurations:a,decodingInfoResults:e}})).catch((function(e){return{supported:!1,configurations:a,decodingInfoResults:[],error:e}}))}function Wt(e,t){if(t<=1)return 1;var r=128e3;return"ec-3"===e?r=768e3:"ac-3"===e&&(r=64e4),Math.min(t/2,r)}function qt(e){return 1e3*Math.ceil(Math.max(.9*e.bitrate,e.averageBitrate)/1e3)||1}function Xt(e,t,r){var i=encodeURIComponent(t),n=i+"="+encodeURIComponent(r),a=!1,s=[];e.search.substring(1).split("&").forEach((function(e){e===i||e.startsWith(i+"=")?a||(s.push(n),a=!0):e&&s.push(e)})),a||s.push(n),e.search=s.join("&")}var zt=["NONE","TYPE-0","TYPE-1",null],Qt=["SDR","PQ","HLG"],$t="",Zt="YES",Jt="v2";function er(e){var t=e.canSkipUntil,r=e.canSkipDateRanges,i=e.age;return t&&i-1;i--)if(r(e[i]))return i;for(var n=t+1;n-1&&v!==g,p=!!e||m;if(p||!l.paused&&l.playbackRate&&l.readyState){var y=s.mainForwardBufferInfo;if(p||null!==y){var E=r.bwEstimator.getEstimateTTFB(),T=Math.abs(l.playbackRate);if(!(f<=Math.max(E,h/(2*T)*1e3))){var S=y?y.len/T:0,A=d.loading.first?d.loading.first-d.loading.start:-1,I=d.loaded&&A>-1,L=r.getBwEstimate(),R=s.levels,b=R[g],k=Math.max(d.loaded,Math.round(h*(n.bitrate||b.averageBitrate)/8)),D=I?f-A:f;D<1&&I&&(D=Math.min(f,8*d.loaded/L));var P=I?1e3*d.loaded/D:0,_=E/1e3,C=P?(k-d.loaded)/P:8*k/L+_;if(!(C<=S)){var w,O=P?8*P:L,M=!0===(null==(t=(null==e?void 0:e.details)||s.latestLevelDetails)?void 0:t.live),F=s.config.abrBandWidthUpFactor,N=Number.POSITIVE_INFINITY;for(w=g-1;w>c;w--){var U=R[w].maxBitrate,B=!R[w].details||M;if((N=r.getTimeToLoadFrag(_,O,h*U,B))=C||N>10*h)){I?r.bwEstimator.sample(f-Math.min(E,A),d.loaded):r.bwEstimator.sampleTTFB(f);var K=R[w].maxBitrate;r.getBwEstimate()*F>K&&(r.firstAutoFloor=Math.min(w,s.firstLevel),r.resetEstimator(K));var V=r.findBestLevel(K,c,w,0,S,1,1);V>-1&&(w=V),r.warn("Fragment "+n.sn+(a?" part "+a.index:"")+" of level "+g+" is loading too slowly;\n Fragment duration: "+n.duration.toFixed(3)+"\n Time to underbuffer: "+S.toFixed(3)+" s\n Estimated load time for current fragment: "+C.toFixed(3)+" s\n Estimated load time for down switch fragment: "+N.toFixed(3)+" s\n TTFB estimate: "+(0|A)+" ms\n Current BW estimate: "+(x(L)?0|L:"Unknown")+" bps\n New BW estimate: "+(0|r.getBwEstimate())+" bps\n Switching to level "+w+" @ "+(0|K)+" bps"),s.nextLoadLevel=s.nextAutoLevel=w,r.clearTimer();var H=function(){r.clearTimer();var e=r.hls;if(r.fragCurrent===n&&e.loadLevel===w&&w>0){var t=r.getStarvationDelay();if(r.warn("Aborting inflight request "+(w>0?"and switching down":"")+"\n Fragment duration: "+n.duration.toFixed(3)+" s\n Time to underbuffer: "+t.toFixed(3)+" s"),n.abortRequests(),r.fragCurrent=r.partCurrent=null,w>c){var i=r.findBestLevel(e.levels[c].bitrate,c,w,0,t,1,1);-1===i&&(i=c),e.nextLoadLevel=e.nextAutoLevel=i,r.firstAutoFloor=Math.min(i,e.firstLevel),r.resetEstimator(e.levels[i].bitrate)}}};m||C>2*N?H():r.timer=self.setInterval(H,1e3*N),s.trigger(G.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:a,stats:d})}}}}}}}}},r.hls=t,r.bwEstimator=r.initEstimator(),r.registerListeners(),r}d(t,e);var r=t.prototype;return r.resetEstimator=function(e){this.hls&&(e&&(this.log("setting initial bwe to "+e),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator())},r.initEstimator=function(){var e=this.hls.config;return new le(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)},r.registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.FRAG_LOADING,this.onFragLoading,this),e.on(G.FRAG_LOADED,this.onFragLoaded,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.FRAG_LOADING,this.onFragLoading,this),e.off(G.FRAG_LOADED,this.onFragLoaded,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(G.ERROR,this.onError,this))},r.destroy=function(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null},r.onManifestLoading=function(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()},r.onLevelsUpdated=function(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null},r.onMaxAutoLevelUpdated=function(){this.firstSelection=-1,this.nextAutoLevelKey=""},r.onFragLoading=function(e,t){var r,i=t.frag;this.ignoreFragment(i)||(i.bitrateTest||(this.fragCurrent=i,this.partCurrent=null!=(r=t.part)?r:null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))},r.onLevelSwitching=function(e,t){this.clearTimer()},r.onError=function(e,t){if(!t.fatal)switch(t.details){case B.BUFFER_ADD_CODEC_ERROR:case B.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case B.FRAG_LOAD_TIMEOUT:var r=t.frag,i=this.fragCurrent,n=this.partCurrent;if(r&&X(r,i)){var a=performance.now(),s=n?n.stats:r.stats,o=a-s.loading.start,l=s.loading.first?s.loading.first-s.loading.start:-1;if(s.loaded&&l>-1){var u=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(o-Math.min(u,l),s.loaded)}else this.bwEstimator.sampleTTFB(o)}}},r.getTimeToLoadFrag=function(e,t,r,i){return e+r/t+(i?e+this.lastLevelLoadSec:0)},r.onLevelLoaded=function(e,t){var r=this.hls.config,i=t.stats.loading,n=i.end-i.first;x(n)&&(this.lastLevelLoadSec=n/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)},r.onFragLoaded=function(e,t){var r,i=t.frag,n=t.part,a=n?n.stats:i.stats;if(i.type===H.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(i)){if(this.clearTimer(),i.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,null!=(r=this.hls)&&r.config.abrMaxWithRealBitrate){var s=n?n.duration:i.duration,o=this.hls.levels[i.level],l=(o.loaded?o.loaded.bytes:0)+a.loaded,u=(o.loaded?o.loaded.duration:0)+s;o.loaded={bytes:l,duration:u},o.realBitrate=Math.round(8*l/u)}if(i.bitrateTest){var d={stats:a,frag:i,part:n,id:i.type};this.onFragBuffered(G.FRAG_BUFFERED,d),i.bitrateTest=!1}else this.lastLoadedFragLevel=i.level}},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part,n=null!=i&&i.stats.loaded?i.stats:r.stats;if(!n.aborted&&!this.ignoreFragment(r)){var a=((r.bitrate||0)>=1e5?n.parsing.end:n.loading.end)-n.loading.start-Math.min(n.loading.first-n.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,n.loaded),n.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}},r.ignoreFragment=function(e){return e.type!==H.MAIN||"initSegment"===e.sn},r.clearTimer=function(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)},r.getAutoLevelKey=function(){return this.getBwEstimate()+"_"+this.getStarvationDelay().toFixed(2)},r.getNextABRAutoLevel=function(){var e=this.fragCurrent,t=this.partCurrent,r=this.hls;if(!r)return-1;if(r.levels.length<=1)return r.loadLevel;var i=r.maxAutoLevel,n=r.config,a=r.minAutoLevel,s=t?t.duration:e?e.duration:0,o=this.getBwEstimate(),l=this.getStarvationDelay(),u=n.abrBandWidthFactor,d=n.abrBandWidthUpFactor;if(l){var h=this.findBestLevel(o,a,i,l,0,u,d);if(h>=0)return this.rebufferNotice=-1,h}var f=s?Math.min(s,n.maxStarvationDelay):n.maxStarvationDelay;if(!l){var c=this.bitrateTestDelay;c&&(f=(s?Math.min(s,n.maxLoadingDelay):n.maxLoadingDelay)-c,this.info("bitrate test took "+Math.round(1e3*c)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*f)+" ms"),u=d=1)}var g=this.findBestLevel(o,a,i,l,f,u,d);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info((l?"rebuffering expected":"buffer is empty")+", optimal quality level "+g)),g>-1)return g;var v=r.levels[a],m=r.loadLevelObj;return m&&(null==v?void 0:v.bitrate)0),f=Math.min(f,t.minHeight),c=Math.min(c,t.minFramerate),g=Math.min(g,t.minBitrate),T.filter((function(e){return t.videoRanges[e]>0})).length>0&&(h=!0)},A=a.length;A--;)S();f=x(f)?f:0,c=x(c)?c:0;var I=Math.max(1080,f),L=Math.max(30,c);g=x(g)?g:r,r=Math.max(g,r),h||(t=void 0);var R=a.length>1;return{codecSet:a.reduce((function(t,i){var n=e[i];if(i===t)return t;if(p=h?T.filter((function(e){return n.videoRanges[e]>0})):[],R){if(n.minBitrate>r)return sr(i,"min bitrate of "+n.minBitrate+" > current estimate of "+r),t;if(!n.hasDefaultAudio)return sr(i,"no renditions with default or auto-select sound found"),t;if(o&&i.indexOf(o.substring(0,4))%5!=0)return sr(i,'audio codec preference "'+o+'" not found'),t;if(s&&!u){if(!n.channels[s])return sr(i,"no renditions with "+s+" channel sound found (channels options: "+Object.keys(n.channels)+")"),t}else if((!o||u)&&d&&0===n.channels[2])return sr(i,"no renditions with stereo sound found"),t;if(n.minHeight>I)return sr(i,"min resolution of "+n.minHeight+" > maximum of "+I),t;if(n.minFramerate>L)return sr(i,"min framerate of "+n.minFramerate+" > maximum of "+L),t;if(!p.some((function(e){return n.videoRanges[e]>0})))return sr(i,"no variants with VIDEO-RANGE of "+ar(p)+" found"),t;if(l&&i.indexOf(l.substring(0,4))%5!=0)return sr(i,'video codec preference "'+l+'" not found'),t;if(n.maxScore=Ot(t)||n.fragmentError>e[t].fragmentError)?t:(v=n.minIndex,m=n.maxScore,i)}),void 0),videoRanges:p,preferHDR:E,minFramerate:c,minBitrate:g,minIndex:v}}(P,I,e,R,b),C=_.codecSet,w=_.videoRanges,O=_.minFramerate,M=_.minBitrate,F=_.minIndex,N=_.preferHDR;D=F,E=C,I=N?w[w.length-1]:w[0],L=O,e=Math.max(e,M),this.log("picked start tier "+ar(_))}else E=null==T?void 0:T.codecSet,I=null==T?void 0:T.videoRange;for(var U,B=h?h.duration:d?d.duration:0,G=this.bwEstimator.getEstimateTTFB()/1e3,K=[],V=function(){var t,l=g[H],d=H>c;if(!l)return 0;if(y.useMediaCapabilities&&!l.supportedResult&&!l.supportedPromise){var v=navigator.mediaCapabilities;"function"==typeof(null==v?void 0:v.decodingInfo)&&function(e,t,r,i,n,a){var s=e.videoCodec,o=e.audioCodec?e.audioGroups:null,l=null==a?void 0:a.audioCodec,u=null==a?void 0:a.channels,d=u?parseInt(u):l?1/0:2,h=null;if(null!=o&&o.length)try{h=1===o.length&&o[0]?t.groups[o[0]].channels:o.reduce((function(e,r){if(r){var i=t.groups[r];if(!i)throw new Error("Audio track group "+r+" not found");Object.keys(i.channels).forEach((function(t){e[t]=(e[t]||0)+i.channels[t]}))}return e}),{2:0})}catch(e){return!0}return void 0!==s&&(s.split(",").some((function(e){return ft(e)}))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(i,30)||"SDR"!==e.videoRange&&e.videoRange!==r||e.bitrate>Math.max(n,8e6))||!!h&&x(d)&&Object.keys(h).some((function(e){return parseInt(e)>d}))}(l,k,I,L,e,R)?(l.supportedPromise=jt(l,k,v,o.supportedCache),l.supportedPromise.then((function(e){if(o.hls){l.supportedResult=e;var t=o.hls.levels,r=t.indexOf(l);e.error?o.warn('MediaCapabilities decodingInfo error: "'+e.error+'" for level '+r+" "+ar(e)):e.supported?e.decodingInfoResults.some((function(e){return!1===e.smooth||!1===e.powerEfficient}))&&o.log("MediaCapabilities decodingInfo for level "+r+" not smooth or powerEfficient: "+ar(e)):(o.warn("Unsupported MediaCapabilities decodingInfo result for level "+r+" "+ar(e)),r>-1&&t.length>1&&(o.log("Removing unsupported level "+r),o.hls.removeLevel(r),-1===o.hls.loadLevel&&(o.hls.nextLoadLevel=0)))}})).catch((function(e){o.warn("Error handling MediaCapabilities decodingInfo: "+e)}))):l.supportedResult=Ht}if((E&&l.codecSet!==E||I&&l.videoRange!==I||d&&L>l.frameRate||!d&&L>0&&L=2*B&&0===n?l.averageBitrate:l.maxBitrate,_=o.getTimeToLoadFrag(G,p,P*b,!T||T.live);if(p>=P&&(H===u||0===l.loadError&&0===l.fragmentError||se(l,y.errorPenaltyExpireMs))&&(_<=G||!x(_)||S&&!o.bitrateTestDelay||_"+H+" adjustedbw("+Math.round(p)+")-bitrate="+Math.round(p-P)+" ttfb:"+G.toFixed(1)+" avgDuration:"+b.toFixed(1)+" maxFetchDuration:"+f.toFixed(1)+" fetchDuration:"+_.toFixed(1)+" firstSelection:"+A+" codecSet:"+l.codecSet+" videoRange:"+l.videoRange+" hls.loadLevel:"+m)),A&&(o.firstSelection=H),{v:H}}},H=r;H>=t;H--)if(0!==(U=V())&&U)return U.v;return-1},r.deriveNextAutoLevel=function(e){if(!this.hls)return-1;var t=this.hls,r=t.maxAutoLevel,i=t.minAutoLevel;return Math.min(Math.max(e,i),r)},a(t,[{key:"firstAutoLevel",get:function(){var e=this.hls;if(!e)return 0;var t=e.maxAutoLevel,r=e.minAutoLevel,i=this.getBwEstimate(),n=this.getStarvationDelay(),a=e.config.maxStarvationDelay,s=this.findBestLevel(i,r,t,n/2,a,1,1);if(s>-1)return s;var o=e.firstLevel,l=-1===this.firstAutoFloor?1/0:this.firstAutoFloor,u=Math.min(Math.max(o,r),t,l);return this.warn("Could not find best starting auto level. Defaulting to first in playlist "+o+" clamped to "+u),u}},{key:"forcedAutoLevel",get:function(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}},{key:"nextAutoLevel",get:function(){if(!this.hls)return-1;var e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(!(-1===e||t&&r&&this.nextAutoLevelKey!==this.getAutoLevelKey()))return e;var i=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(-1!==e){var n=this.hls.levels;if(n.length>Math.max(e,i)&&n[e].loadError<=n[i].loadError)return e}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i},set:function(e){var t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}}])}(ue),pr=function(e,t){for(var r=0,i=e.length-1,n=null,a=null;r<=i;){var s=t(a=e[n=(r+i)/2|0]);if(s>0)r=n+1;else{if(!(s<0))return a;i=n-1}}return null};function yr(e,t,r,i,n){void 0===r&&(r=0),void 0===i&&(i=0),void 0===n&&(n=.005);var a=null;if(e){a=t[1+e.sn-t[0].sn]||null;var s=e.endDTS-r;s>0&&s<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else 0===r&&0===t[0].start&&(a=t[0]);if(a&&((!e||e.level===a.level)&&0===Er(r,i,a)||function(e,t,r){if(0===(null==t?void 0:t.start)&&t.level0){var i=t.tagList.reduce((function(e,t){return"INF"===t[0]&&(e+=parseFloat(t[1])),e}),r);return e.start<=i}return!1}(a,e,Math.min(n,i))))return a;var o=pr(t,Er.bind(null,r,i));return!o||o===e&&a?a:o}function Er(e,t,r){if(void 0===e&&(e=0),void 0===t&&(t=0),r.start<=e&&r.start+r.duration>e)return 0;var i=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-i<=e?1:r.start-i>e&&r.start?-1:0}function Tr(e,t,r){var i=1e3*Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>e}function Sr(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){var i,n=e.fragments,a=e.fragmentHint;return a&&(n=n.concat(a)),pr(n,(function(e){return e.cct?-1:(i=e,e.end<=r?1:e.start>r?-1:0)})),i||null}return null}function Ar(e,t){return t===e.endSN&&e.fragmentHint?e.fragmentHint:e.fragments[1+t-e.startSN]||null}var Ir=0,Lr=2,Rr=3,br=5,kr=0,Dr=1,Pr=2,_r=4,Cr=8,wr=16,Or=function(e){function t(t){var r;return(r=e.call(this,"error-controller",t.logger)||this).hls=void 0,r.playlistError=0,r.hls=t,r.registerListeners(),r}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(G.ERROR,this.onError,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this)},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.ERROR,this.onError,this),e.off(G.ERROR,this.onErrorOut,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this))},r.destroy=function(){this.unregisterListeners(),this.hls=null},r.startLoad=function(e){},r.stopLoad=function(){this.playlistError=0},r.getVariantLevelIndex=function(e){return(null==e?void 0:e.type)===H.MAIN?e.level:this.getVariantIndex()},r.getVariantIndex=function(){var e,t=this.hls,r=t.currentLevel;return null!=(e=t.loadLevelObj)&&e.details||-1===r?t.loadLevel:r},r.variantHasKey=function(e,t){if(e){var r;if(null!=(r=e.details)&&r.hasKey(t))return!0;var i=e.audioGroups;if(i)return this.hls.allAudioTracks.filter((function(e){return i.indexOf(e.groupId)>=0})).some((function(e){var r;return null==(r=e.details)?void 0:r.hasKey(t)}))}return!1},r.onManifestLoading=function(){this.playlistError=0},r.onLevelUpdated=function(){this.playlistError=0},r.onError=function(e,t){var r;if(!t.fatal){var i=this.hls,n=t.context;switch(t.details){case B.FRAG_LOAD_ERROR:case B.FRAG_LOAD_TIMEOUT:case B.KEY_LOAD_ERROR:case B.KEY_LOAD_TIMEOUT:return void(t.errorAction=this.getFragRetryOrSwitchAction(t));case B.FRAG_PARSING_ERROR:if(null!=(r=t.frag)&&r.gap)return void(t.errorAction=Fr());case B.FRAG_GAP:case B.FRAG_DECRYPT_ERROR:return t.errorAction=this.getFragRetryOrSwitchAction(t),void(t.errorAction.action=Lr);case B.PLAYLIST_UNCHANGED_ERROR:case B.LEVEL_EMPTY_ERROR:case B.LEVEL_PARSING_ERROR:var a,s=t.parent===H.MAIN?t.level:i.loadLevel;return void(t.details===B.LEVEL_EMPTY_ERROR&&null!=(a=t.context)&&null!=(a=a.levelDetails)&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,s)));case B.LEVEL_LOAD_ERROR:case B.LEVEL_LOAD_TIMEOUT:return void("number"==typeof(null==n?void 0:n.level)&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.level)));case B.AUDIO_TRACK_LOAD_ERROR:case B.AUDIO_TRACK_LOAD_TIMEOUT:case B.SUBTITLE_LOAD_ERROR:case B.SUBTITLE_TRACK_LOAD_TIMEOUT:if(n){var o=i.loadLevelObj;if(o&&(n.type===V.AUDIO_TRACK&&o.hasAudioGroup(n.groupId)||n.type===V.SUBTITLE_TRACK&&o.hasSubtitleGroup(n.groupId)))return t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.loadLevel),t.errorAction.action=Lr,void(t.errorAction.flags=Dr)}return;case B.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:return void(t.errorAction={action:Lr,flags:Pr});case B.KEY_SYSTEM_SESSION_UPDATE_FAILED:case B.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case B.KEY_SYSTEM_NO_SESSION:return void(t.errorAction={action:Lr,flags:_r});case B.BUFFER_ADD_CODEC_ERROR:case B.REMUX_ALLOC_ERROR:case B.BUFFER_APPEND_ERROR:return void(t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)));case B.MEDIA_SOURCE_REQUIRES_RESET:return t.errorAction||(t.errorAction=this.getLevelSwitchAction(t,t.level)),void(t.errorAction.flags|=wr|Cr);case B.INTERNAL_EXCEPTION:case B.BUFFER_APPENDING_ERROR:case B.BUFFER_APPEND_NO_PROGRESS:case B.BUFFER_FULL_ERROR:case B.LEVEL_SWITCH_ERROR:case B.BUFFER_STALLED_ERROR:case B.BUFFER_SEEK_OVER_HOLE:case B.BUFFER_NUDGE_ON_STALL:return void(t.errorAction=Fr())}t.type===U.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=Fr())}},r.getPlaylistRetryOrSwitchAction=function(e,t){var r=te(this.hls.config.playlistLoadPolicy,e),i=this.playlistError++;if(ne(r,i,Z(e),e.response))return{action:br,flags:kr,retryConfig:r,retryCount:i};var n=this.getLevelSwitchAction(e,t);return r&&(n.retryConfig=r,n.retryCount=i),n},r.getFragRetryOrSwitchAction=function(e){var t=this.hls,r=this.getVariantLevelIndex(e.frag),i=t.levels[r],n=t.config,a=n.fragLoadPolicy,s=n.keyLoadPolicy,o=te(J(e)?s:a,e),l=t.levels.reduce((function(e,t){return e+t.fragmentError}),0);if(i&&(e.details!==B.FRAG_GAP&&i.fragmentError++,!ee(e)&&ne(o,l,Z(e),e.response)))return{action:br,flags:kr,retryConfig:o,retryCount:l};var u=this.getLevelSwitchAction(e,r);return o&&(u.retryConfig=o,u.retryCount=l),u},r.getLevelSwitchAction=function(e,t){var r=this.hls;null==t&&(t=r.loadLevel);var i=this.hls.levels[t];if(i){var n,a,s=e.details;i.loadError++,i.loadErrorTime=self.performance.now(),s===B.BUFFER_APPEND_ERROR&&i.fragmentError++;var o=-1,l=r.levels,u=r.loadLevel,d=r.minAutoLevel,h=r.maxAutoLevel;r.autoLevelEnabled||r.config.preserveManualLevelOnError||(r.loadLevel=-1);for(var f,c=null==(n=e.frag)?void 0:n.type,g=(c===H.AUDIO&&s===B.FRAG_PARSING_ERROR||"audio"===e.sourceBufferName&&Mr(e))&&l.some((function(e){var t=e.audioCodec;return i.audioCodec!==t})),v="video"===e.sourceBufferName&&Mr(e)&&l.some((function(e){var t=e.codecSet,r=e.audioCodec;return i.codecSet!==t&&i.audioCodec===r})),m=null!=(a=e.context)?a:{},p=m.type,y=m.groupId,E=function(){var t=(T+u)%l.length;if(t!==u&&t>=d&&t<=h&&(0===l[t].loadError||se(l[t],r.config.errorPenaltyExpireMs))){var n,a,f=l[t];if(s===B.FRAG_GAP&&c===H.MAIN&&e.frag){var m=l[t].details;if(m){var E=yr(e.frag,m.fragments,e.frag.start);if(null!=E&&E.gap)return 0}}else{if(p===V.AUDIO_TRACK&&f.hasAudioGroup(y)||p===V.SUBTITLE_TRACK&&f.hasSubtitleGroup(y))return 0;if(c===H.AUDIO&&null!=(n=i.audioGroups)&&n.some((function(e){return f.hasAudioGroup(e)}))||c===H.SUBTITLE&&null!=(a=i.subtitleGroups)&&a.some((function(e){return f.hasSubtitleGroup(e)}))||g&&i.audioCodec===f.audioCodec||v&&i.codecSet===f.codecSet||!g&&i.audioCodec!==f.audioCodec)return 0}return o=t,1}},T=l.length;T--&&(0===(f=E())||1!==f););if(o>-1&&r.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:Lr,flags:kr,nextAutoLevel:o}}return{action:Lr,flags:Dr}},r.onErrorOut=function(e,t){var r,i;switch(null==(r=t.errorAction)?void 0:r.action){case Ir:break;case Lr:this.sendAlternateToPenaltyBox(t),t.errorAction.resolved||t.details===B.FRAG_GAP||t.details===B.PLAYLIST_UNCHANGED_ERROR||xr(t)||(t.fatal=!0)}((null==(i=t.errorAction)?void 0:i.flags)||0)&wr&&this.hls.recoverMediaError(),t.fatal&&this.hls.stopLoad()},r.sendAlternateToPenaltyBox=function(e){var t=this.hls,r=e.errorAction;if(r){var i=r.nextAutoLevel;if(r.flags===kr)this.switchLevel(e,i);else if(r.flags&Cr)for(var n=this.hls.levels,a=n.length;a--;)"SDR"!==n[a].videoRange?(n[a].fragmentError++,n[a].loadError++):void 0===i&&(i=a);else if(r.flags&Pr){var s=this.getVariantLevelIndex(e.frag),o=t.levels[s],l=null==o?void 0:o.attrs["HDCP-LEVEL"];r.hdcpLevel=l;var u="NONE"===l;l&&!u?(t.maxHdcpLevel=zt[zt.indexOf(l)-1],r.resolved=!0,this.warn('Restricting playback to HDCP-LEVEL of "'+t.maxHdcpLevel+'" or lower')):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=_r)}if(r.flags&_r){var d=e.decryptdata;if(d){for(var h=this.hls.levels,f=h.length,c=f;c--;){var g,v;this.variantHasKey(h[c],d)&&(this.log("Banned key found in level "+c+" ("+h[c].bitrate+'bps) or audio group "'+(null==(g=h[c].audioGroups)?void 0:g.join(","))+'" ('+(null==(v=e.frag)?void 0:v.type)+" fragment) "+xe(d.keyId||[])),h[c].fragmentError++,h[c].loadError++,this.log("Removing level "+c+" with key error ("+e.error+")"),this.hls.removeLevel(c))}var m=e.frag;if(this.hls.levels.length=u.sn))if(l.buffered||l.loaded&&!a){var d=l.range[e];if(d)if(0!==d.time.length){if(d.time.some((function(e){var r=!s.isTimeBuffered(e.startPTS,e.endPTS,t);return r&&s.removeFragment(u),r})),i&&i!==u&&Rt()){var h=i.endPTS,f=u.startPTS;if(h&&f&&l.range.video){var c=f-h;c<0&&c>-.1&&(s.removeFragment(u),s.hls.trigger(G.BUFFER_FLUSHING,{startOffset:h+.004,endOffset:1/0,type:"video"}))}}}else s.removeFragment(u)}else u.type===r&&s.removeFragment(u)}}))},t.detectPartialFragments=function(e){var t=this,r=this.timeRanges,i=e.frag,n=e.part,a=e.id;if(r&&W(i)){var s=Hr(i),o=this.fragments[s];if(!(!o||o.buffered&&i.gap)){var l=!i.relurl;Object.keys(r).forEach((function(e){var s=i.elementaryStreams[e];if(s){var u=r[e],d=l||!0===s.partial;o.range[e]=t.getBufferedTimes(i,n,d,u),t.detectEvictedFragments(e,u,a,i,n)}})),o.loaded=null;var u=Object.keys(o.range);if(u.length){if(this.bufferedEnd(o,i),Vr(o)||this.removeParts(i.sn-1,i.type),!n){var d=Math.min(.004,i.duration);u.some((function(e){var r,n=null==(r=o.range[e])?void 0:r.time,a=0===n.length||1===n.length&&n[0].endPTS-n[0].startPTS=e})))},t.fragBuffered=function(e,t){var r=Hr(e),i=this.fragments[r];return!i&&t&&(i=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,this.bufferedEnd(i,e)),i},t.getBufferedTimes=function(e,t,r,i){for(var n={time:[],partial:r},a=e.start,s=e.end,o=e.minEndPTS||s,l=e.maxStartPTS||a,u=0;u=d&&o<=h){n.time.push({startPTS:Math.max(a,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(ad){var f=Math.max(a,i.start(u)),c=Math.min(s,i.end(u));c>f&&(n.partial=!0,n.time.push({startPTS:f,endPTS:c}))}else if(s<=d)break}return n},t.getPartialFragment=function(e){var t,r,i,n=null,a=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&Vr(u)&&(r=u.body.start-s,i=u.body.end+s,e>=r&&e<=i&&(t=Math.min(e-r,i-e),a<=t&&(n=u.body,a=t)))})),n},t.isEndListAppended=function(e){var t=this.endListFragments[e];return void 0!==t&&(t.buffered||Vr(t))},t.getState=function(e){var t=Hr(e),r=this.fragments[t];return r?r.buffered?Vr(r)?Br:Gr:Ur:Nr},t.isTimeBuffered=function(e,t,r){for(var i,n,a=0;a=i&&t<=n)return!0;if(t<=i)return!1}return!1},t.onManifestLoading=function(){this.removeAllFragments()},t.onFragLoaded=function(e,t){if(W(t.frag)&&!t.frag.bitrateTest){var r=t.frag,i=t.part?null:t,n=Hr(r);this.fragments[n]={body:r,appendedPTS:null,loaded:i,buffered:!1,range:Object.create(null)}}},t.onBufferAppended=function(e,t){var r=t.frag,i=t.part,n=t.timeRanges;if(W(r)){var a=r.type;if(i){var s=this.activePartLists[a];s||(this.activePartLists[a]=s=[]),s.push(i)}this.timeRanges=n}},t.onFragBuffered=function(e,t){this.detectPartialFragments(t)},t.hasFragment=function(e){var t=Hr(e);return!!this.fragments[t]},t.hasFragments=function(e){var t=this.fragments,r=Object.keys(t);if(!e)return r.length>0;for(var i=r.length;i--;){var n=t[r[i]];if((null==n?void 0:n.body.type)===e)return!0}return!1},t.hasParts=function(e){var t;return!(null==(t=this.activePartLists[e])||!t.length)},t.getBackBufferEvictionEnd=function(e,t,r){for(var i=this.fragments,n=0,a=0,s=Object.keys(i),o=0;o=r))return a}}return a>0?a:0},t.removeFragmentsInRange=function(e,t,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.starte&&(o.buffered||n)&&a.removeFragment(l)}}))},t.removeFragment=function(e){var t=Hr(e);e.clearElementaryStreamInfo();var r=this.activePartLists[e.type];if(r){var i=e.sn;this.activePartLists[e.type]=Yr(r,(function(e){return e.fragment.sn!==i}))}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]},t.removeAllFragments=function(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;var t=null==(e=this.hls)||null==(e=e.latestLevelDetails)?void 0:e.partList;t&&t.forEach((function(e){return e.clearElementaryStreamInfo()}))},e}();function Vr(e){var t,r,i,n;return e.buffered&&!!(e.body.gap||null!=(t=e.range.video)&&t.partial||null!=(r=e.range.audio)&&r.partial||null!=(i=e.range.audiovideo)&&i.partial||null!=(n=e.range.subs)&&n.partial)}function Hr(e){return e.type+"_"+e.level+"_"+e.sn}function Yr(e,t){return e.filter((function(e){var r=t(e);return r||e.clearElementaryStreamInfo(),r}))}var jr=0,Wr=1,qr=function(){function e(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}return e.prototype.decrypt=function(e,t){switch(this.aesMode){case jr:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case Wr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error("[AESCrypto] invalid aes mode "+this.aesMode)}},e}(),Xr=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.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 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],n=r[1],a=r[2],s=r[3],o=this.invSubMix,l=o[0],u=o[1],d=o[2],h=o[3],f=new Uint32Array(256),c=0,g=0,v=0;for(v=0;v<256;v++)f[v]=v<128?v<<1:v<<1^283;for(v=0;v<256;v++){var m=g^g<<1^g<<2^g<<3^g<<4;m=m>>>8^255&m^99,e[c]=m,t[m]=c;var p=f[c],y=f[p],E=f[y],T=257*f[m]^16843008*m;i[c]=T<<24|T>>>8,n[c]=T<<16|T>>>16,a[c]=T<<8|T>>>24,s[c]=T,T=16843009*E^65537*y^257*p^16843008*c,l[m]=T<<24|T>>>8,u[m]=T<<16|T>>>16,d[m]=T<<8|T>>>24,h[m]=T,c?(c=p^f[f[f[E^p]]],g^=f[f[g]]):c=g=1}},t.expandKey=function(e){for(var t=this.uint8ArrayToUint32Array_(e),r=!0,i=0;i=r.length?r:r.slice(s.start,s.end):(n=(i=r).byteLength,(a=n&&new DataView(i.buffer).getUint8(n-1))?i.slice(0,n-a):i)},t.reset=function(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)},t.decrypt=function(e,t,r,i,n){var a=this;return this.decryptRange=n,this.useSoftware||n?new Promise((function(n,s){var o=ArrayBuffer.isView(e)?e:new Uint8Array(e);a.softwareDecrypt(o,t,r,i);var l=a.flush();l?n(l.buffer):s(new Error("[softwareDecrypt] Failed to decrypt data"))})):this.webCryptoDecrypt(new Uint8Array(e),t,r,i)},t.softwareDecrypt=function(e,t,r,i){var n=this.currentIV,a=this.currentResult,s=this.remainderData;if(i!==jr||16!==t.byteLength)return me.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),s&&(e=ht(s,e),this.remainderData=null);var o=this.getValidChunk(e);if(!o.length)return null;n&&(r=n);var l=this.softwareDecrypter;l||(l=this.softwareDecrypter=new Xr),l.expandKey(t);var u=a;return this.currentResult=l.decrypt(o.buffer,0,r),this.currentIV=o.slice(-16).buffer,u||null},t.webCryptoDecrypt=function(e,t,r,i){var n=this;if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,i));this.key=t,this.fastAesKey=new zr(this.subtle,t,i)}return this.fastAesKey.expandKey().then((function(t){return n.subtle?(n.logOnce("WebCrypto AES decrypt"),new qr(n.subtle,new Uint8Array(r),i).decrypt(e.buffer,t)):Promise.reject(new Error("web crypto not initialized"))})).catch((function(a){return me.warn("[decrypter]: WebCrypto Error, disable WebCrypto API, "+a.name+": "+a.message),n.onWebCryptoError(e,t,r,i)}))},t.onWebCryptoError=function(e,t,r,i){var n=this.enableSoftwareAES;if(n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,i);var a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(n?" and softwareDecrypt":"")+": failed to decrypt data")},t.getValidChunk=function(e){var t=e,r=e.length-e.length%16;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t},t.logOnce=function(e){this.logEnabled&&(me.log("[decrypter]: "+e),this.logEnabled=!1)},e}(),$r=Math.pow(2,17),Zr=function(){function e(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}var t=e.prototype;return t.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},t.abort=function(){this.loader&&this.loader.abort()},t.load=function(e,t,r,i){var n=this,a=e.url;if(!a)return Promise.reject(new ri({type:U.NETWORK_ERROR,details:B.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error("Fragment does not have a "+(a?"part list":"url")),networkDetails:null}));this.abort();var s=this.config,o=s.fLoader,l=s.loader;return new Promise((function(u,d){if(n.loader&&n.loader.destroy(),e.gap){if(e.tagList.some((function(e){return"GAP"===e[0]})))return void d(ti(e));e.gap=!1}var h=n.loader=o?new o(s):new l(s),f=Jr(e,null,t);e.loader=h;var g=ie(s.fragLoadPolicy.default),v={loadPolicy:g,timeout:g.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:"initSegment"===e.sn?1/0:$r};h.stats.retry=e.stats.retry,e.stats=h.stats;var m={onSuccess:function(t,r,i,a){n.resetLoader(e,h);var s=t.data;i.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(s.slice(0,16)),s=s.slice(16)),u({frag:e,part:null,payload:s,networkDetails:a})},onError:function(t,r,i,s){n.resetLoader(e,h),d(new ri({type:U.NETWORK_ERROR,details:B.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:c({url:a,data:void 0},t),error:new Error("HTTP Error "+t.code+" "+t.text),networkDetails:i,stats:s}))},onAbort:function(t,r,i){n.resetLoader(e,h),d(new ri({type:U.NETWORK_ERROR,details:B.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:i,stats:t}))},onTimeout:function(t,r,i){n.resetLoader(e,h),d(new ri({type:U.NETWORK_ERROR,details:B.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error("Timeout after "+v.timeout+"ms"),networkDetails:i,stats:t}))}};if(r){var p=n.gateProgress(r,i);m.onProgress=function(t,r,i,n){return p({frag:e,part:null,payload:i,networkDetails:n})}}h.load(f,v,m)}))},t.gateProgress=function(e,t){var r=e;if(t){var i=[],n=!1;t.then((function(){n=!0,i.forEach((function(t){return e(t)})),i.length=0})).catch((function(){})),r=function(t){n?e(t):i.push(t)}}return r},t.loadPart=function(e,t,r){var i=this;this.abort();var n=this.config,a=n.fLoader,s=n.loader;return new Promise((function(o,l){if(i.loader&&i.loader.destroy(),e.gap||t.gap)l(ti(e,t));else{var u=i.loader=a?new a(n):new s(n),d=Jr(e,t);e.loader=u;var h=ie(n.fragLoadPolicy.default),f={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:$r};t.stats=u.stats,u.load(d,f,{onSuccess:function(n,a,s,l){i.resetLoader(e,u),i.updateStatsFromPart(e,t);var d={frag:e,part:t,payload:n.data,networkDetails:l};r(d),o(d)},onError:function(r,n,a,s){i.resetLoader(e,u),l(new ri({type:U.NETWORK_ERROR,details:B.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:c({url:d.url,data:void 0},r),error:new Error("HTTP Error "+r.code+" "+r.text),networkDetails:a,stats:s}))},onAbort:function(r,n,a){e.stats.aborted=t.stats.aborted,i.resetLoader(e,u),l(new ri({type:U.NETWORK_ERROR,details:B.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:a,stats:r}))},onTimeout:function(r,n,a){i.resetLoader(e,u),l(new ri({type:U.NETWORK_ERROR,details:B.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error("Timeout after "+f.timeout+"ms"),networkDetails:a,stats:r}))}})}}))},t.updateStatsFromPart=function(e,t){var r=e.stats,i=t.stats,n=i.total;if(r.loaded+=i.loaded,n){var a=Math.round(e.duration/t.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},t.resetLoader=function(e,t){e.loader=null,e.url=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()},e}();function Jr(e,t,r){void 0===t&&(t=null);var i=t||e,n={type:V.MEDIA_FRAGMENT,frag:e,part:t,responseType:"arraybuffer",url:i.url,headers:{},rangeStart:0,rangeEnd:0},a=ei(e,t,r);return a.resetIV&&(n.resetIV=!0),a.byteRange&&(n.rangeStart=a.byteRange.start,n.rangeEnd=a.byteRange.end),n}function ei(e,t,r){void 0===t&&(t=null);var i,n,a={},s=t||e,o=s.byteRangeStartOffset,l=s.byteRangeEndOffset;if(x(o)&&x(l))if("initSegment"!==e.sn&&!r||"AES-128"!==(n=null==(i=e.decryptdata)?void 0:i.method)&&"AES-256"!==n)a.byteRange={start:o,end:l};else{var u=16*Math.floor(o/16),d=16*Math.ceil(l/16);a.decryptRange={start:o-u,end:l-u},u>=16&&(a.resetIV=!0,u-=16),a.byteRange={start:u,end:d}}return a}function ti(e,t){var r=new Error("GAP "+(e.gap?"tag":"attribute")+" found"),i={type:U.MEDIA_ERROR,details:B.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(i.part=t),(t||e).stats.aborted=!0,new ri(i)}var ri=function(e){function t(t){var r;return(r=e.call(this,t.error.message)||this).data=void 0,r.data=t,r}return d(t,e),t}(E(Error)),ii=function(e){function t(t,r){var i;return(i=e.call(this,t,r)||this)._boundTick=void 0,i._tickTimer=null,i._tickInterval=null,i._tickCallCount=0,i._boundTick=i.tick.bind(i),i}d(t,e);var r=t.prototype;return r.destroy=function(){this.onHandlerDestroying(),this.onHandlerDestroyed()},r.onHandlerDestroying=function(){this.clearNextTick(),this.clearInterval()},r.onHandlerDestroyed=function(){},r.hasInterval=function(){return!!this._tickInterval},r.hasNextTick=function(){return!!this._tickTimer},r.setInterval=function(e){return!this._tickInterval&&(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)},r.clearInterval=function(){return!!this._tickInterval&&(self.clearInterval(this._tickInterval),this._tickInterval=null,!0)},r.clearNextTick=function(){return!!this._tickTimer&&(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0)},r.tick=function(){this._tickCallCount++,1===this._tickCallCount?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log("possible exception thrown in task-loop ("+this.constructor.name+".doTick)"),this._tickCallCount=0)},r.tickImmediate=function(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)},r.doTick=function(){},t}(ue),ni=function(e,t,r,i,n,a,s,o,l){void 0===i&&(i=0),void 0===n&&(n=-1),void 0===a&&(a=!1),this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing={start:0,executeStart:0,executeEnd:0,end:0},this.buffering={audio:{start:0,executeStart:0,executeEnd:0,end:0},video:{start:0,executeStart:0,executeEnd:0,end:0},audiovideo:{start:0,executeStart:0,executeEnd:0,end:0}},this.level=e,this.sn=t,this.id=r,this.size=i,this.part=n,this.partial=a,this.duration=s||0,this.decryptRange=l,this.iframe=o||!1},ai={length:0,start:function(){return 0},end:function(){return 0}},si=function(){function e(){}return e.isBuffered=function(t,r){if(t)for(var i=e.getBuffered(t),n=i.length;n--;)if(r>=i.start(n)&&r<=i.end(n))return!0;return!1},e.bufferedRanges=function(t){if(t){var r=e.getBuffered(t);return e.timeRangesToArray(r)}return[]},e.timeRangesToArray=function(e){for(var t=[],r=0;r1&&e.sort((function(e,t){return e.start-t.start||t.end-e.end}));var i=-1,n=[];if(r)for(var a=0;a=e[a].start&&t<=e[a].end&&(i=a);var s=n.length;if(s){var o=n[s-1].end;e[a].start-oo&&(n[s-1].end=e[a].end):n.push(e[a])}else n.push(e[a])}else n=e;for(var l,u=0,d=t,h=t,f=0;f=c&&t<=g&&(i=f),t+r>=c&&tNumber.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.optionalFloat=function(e,t){var r=this[e];return r?parseFloat(r):t},t.enumeratedString=function(e){return this[e]},t.enumeratedStringList=function(e,t){var r=this[e];return(r?r.split(/[ ,]+/):[]).reduce((function(e,t){return e[t.toLowerCase()]=!0,e}),t)},t.bool=function(e){return"YES"===this[e]},t.decimalResolution=function(e){var t=fi.exec(this[e]);if(null!==t)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}},e.parseAttrList=function(e,t){var r,i={};for(ci.lastIndex=0;null!==(r=ci.exec(e));){var n=r[1].trim(),a=r[2],s=0===a.indexOf('"')&&a.lastIndexOf('"')===a.length-1,o=!1;if(s)a=a.slice(1,-1);else switch(n){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":o=!0}if(t&&(s||o))a=ui(t,a);else if(!o&&!s)switch(n){case"CLOSED-CAPTIONS":if("NONE"===a)break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":me.warn(e+": attribute "+n+" is missing quotes")}i[n]=a}return i},a(e,[{key:"clientAttrs",get:function(){return Object.keys(this).filter((function(e){return"X-"===e.substring(0,2)}))}}])}();function vi(e){return"SCTE35-OUT"===e||"SCTE35-IN"===e||"SCTE35-CMD"===e}var mi=function(){return a((function(e,t,r){var i;if(void 0===r&&(r=0),this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(null==t?void 0:t.tagAnchor)||null,this.tagOrder=null!=(i=null==t?void 0:t.tagOrder)?i:r,t){var n=t.attr;for(var a in n)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==n[a]){me.warn('DATERANGE tag attribute: "'+a+'" does not match for tags with ID: "'+e.ID+'"'),this._badValueForSameId=a;break}e=l(new gi({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in e){var s=(null==t?void 0:t.endDate)||new Date(e["END-DATE"]);x(s.getTime())&&(this._endDate=s)}}),[{key:"id",get:function(){return this.attr.ID}},{key:"class",get:function(){return this.attr.CLASS}},{key:"cue",get:function(){var e=this._cue;return void 0===e?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}},{key:"startTime",get:function(){var e=this.tagAnchor;return null===e||null===e.programDateTime?(me.warn('Expected tagAnchor Fragment with PDT set for DateRange "'+this.id+'": '+e),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}},{key:"startDate",get:function(){return this._startDate}},{key:"endDate",get:function(){var e=this._endDate||this._dateAtEnd;if(e)return e;var t=this.duration;return null!==t?this._dateAtEnd=new Date(this._startDate.getTime()+1e3*t):null}},{key:"duration",get:function(){if("DURATION"in this.attr){var e=this.attr.decimalFloatingPoint("DURATION");if(x(e))return e}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:"isInterstitial",get:function(){return"com.apple.hls.interstitial"===this.class}},{key:"isValid",get:function(){return!!this.id&&!this._badValueForSameId&&x(this.startDate.getTime())&&(null===this.duration||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},{key:"invalidReason",get:function(){return this.id?this._badValueForSameId?"Date range "+this._badValueForSameId+" mismatch":x(this.startDate.getTime())?!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr?this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Interstitial Date range missing X-ASSET-(LIST|URI)":"Date range invalid start date":"Missing ID"}}])}(),pi=function(){function e(e){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.dateRangeTagCount=0,this.live=!0,this.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!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.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}var t=e.prototype;return t.reloaded=function(e){if(!e)return this.advanced=!0,void(this.updated=!0);var t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||0===t&&r>0,this.updated||this.advanced?this.misses=0:this.misses=e.misses+1},t.hasKey=function(e){return this.encryptedFragments.some((function(t){var r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)}))},a(e,[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&x(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var e=this.driftEndTime-this.driftStartTime;return e>0?1e3*(this.driftEnd-this.driftStart)/e:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}},{key:"fragmentStart",get:function(){return this.fragments.length?this.fragments[0].start:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].index:-1}},{key:"maxPartIndex",get:function(){var e=this.partList;if(e){var t=this.lastPartIndex;if(-1!==t){for(var r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}},{key:"lastPartSn",get:function(){var e;return null!=(e=this.partList)&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}},{key:"expired",get:function(){if(this.live&&this.age&&this.misses<3){var e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}}])}();function yi(e,t){return e.length===t.length&&!e.some((function(e,r){return e!==t[r]}))}function Ei(e,t){return!e&&!t||!(!e||!t)&&yi(e,t)}function Ti(e){return"AES-128"===e||"AES-256"===e||"AES-256-CTR"===e}function Si(e){switch(e){case"AES-128":case"AES-256":return jr;case"AES-256-CTR":return Wr;default:throw new Error("invalid full segment method "+e)}}function Ai(e){return Uint8Array.from(unescape(encodeURIComponent(e)),(function(e){return e.charCodeAt(0)}))}function Ii(e){var t=function(e,t,r){var i=e[t];e[t]=e[r],e[r]=i};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function Li(e){var t,r,i=e.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=Ne(l)):(t=Ai(l).subarray(0,16),(r=new Uint8Array(16)).set(t,16-t.length),n=r)}}return n}var Ri="undefined"!=typeof self?self:void 0,bi={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ki="org.w3.clearkey",Di="com.apple.streamingkeydelivery",Pi="com.microsoft.playready",_i="urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed";function Ci(e){switch(e){case Di:return bi.FAIRPLAY;case Pi:return bi.PLAYREADY;case _i:return bi.WIDEVINE;case ki:return bi.CLEARKEY}}var wi="edef8ba979d64acea3c827dcd51d21ed";function Oi(e){switch(e){case bi.FAIRPLAY:return Di;case bi.PLAYREADY:return Pi;case bi.WIDEVINE:return _i;case bi.CLEARKEY:return ki}}function Mi(e){var t=e.drmSystems,r=e.widevineLicenseUrl,i=t?[bi.FAIRPLAY,bi.WIDEVINE,bi.PLAYREADY,bi.CLEARKEY].filter((function(e){return!!t[e]})):[];return!i[bi.WIDEVINE]&&r&&i.push(bi.WIDEVINE),i}var xi,Fi=null!=Ri&&null!=(xi=Ri.navigator)&&xi.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Ni(e){var t=Ue(new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2)),r=t.substring(t.indexOf("<"),t.length),i=(new DOMParser).parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(i){var n=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute("VALUE");if(n){var a=Ne(n).subarray(0,16);return Ii(a),a}}return null}var Ui={},Bi=function(){function e(e,t,r,i,n,a){void 0===i&&(i=[1]),void 0===n&&(n=null),this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=e,this.uri=t,this.keyFormat=r,this.keyFormatVersions=i,this.iv=n,this.encrypted=!!e&&"NONE"!==e,this.isCommonEncryption=this.encrypted&&!Ti(e),null!=a&&a.startsWith("0x")&&(this.keyId=new Uint8Array(Fe(a)))}e.clearKeyUriToKeyIdMap=function(){Ui={}},e.setKeyIdForUri=function(e,t){Ui[e]=t},e.addKeyIdForUri=function(e){var t=Object.keys(Ui).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,t),Ui[e]=r,r};var t=e.prototype;return t.matches=function(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&yi(e.keyFormatVersions,this.keyFormatVersions)&&Ei(e.iv,this.iv)&&Ei(e.keyId,this.keyId)},t.isSupported=function(){if(this.method){if(Ti(this.method)||"NONE"===this.method)return!0;if("identity"===this.keyFormat)return"SAMPLE-AES"===this.method;switch(this.keyFormat){case Di:case _i:case Pi:case ki:return-1!==["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)}}return!1},t.getDecryptData=function(t,r){var i;if(!this.encrypted||!this.uri)return null;if(Ti(this.method)){var n=this.iv;return n||("number"!=typeof t&&(me.warn('missing IV for initialization segment with method="'+this.method+'" - compliance issue'),t=0),n=function(e){for(var t=new Uint8Array(16),r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}(t)),new e(this.method,this.uri,"identity",this.keyFormatVersions,n)}if(this.keyId){var a=Ui[this.uri];if(a&&!yi(this.keyId,a)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}var s,o=Li(this.uri);if(o)switch(this.keyFormat){case _i:if(this.pssh=o,!this.keyId){var l=pt(o.buffer).filter((function(e){return e.systemId===wi}));if(l.length){var u,d=l[0];this.keyId=null!=(u=d.kids)&&u.length?d.kids[0]:null}}this.keyId||(this.keyId=Gi(r));break;case Pi:var h=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mt(h,0,o),this.keyId=Ni(o);break;default:var f=o.subarray(0,16);if(16!==f.length){var c=new Uint8Array(16);c.set(f,16-f.length),f=c}this.keyId=f}return 16!==(null==(i=this.keyId)?void 0:i.byteLength)&&(s=function(e){var t=null==e?void 0:e[_i];return t?t.keyId:null}(r),s||(s=Gi(r))||(s=Ui[this.uri]),s&&(this.keyId=s,e.setKeyIdForUri(this.uri,s))),this},e}();function Gi(e){var t=null==e?void 0:e[Pi];if(t){var r=Li(t.uri);if(r)return Ni(r)}return null}var Ki=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,Vi=/#EXT-X-MEDIA:(.*)/g,Hi=/^#EXT(?:INF|-X-TARGETDURATION):/m,Yi=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),ji=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|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|INDEPENDENT-SEGMENTS|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Wi=function(){function e(){}return e.findGroup=function(e,t){for(var r=0;r0&&a.length0&&h.bool("CAN-SKIP-DATERANGES"),c.partHoldBack=h.optionalFloat("PART-HOLD-BACK",0),c.holdBack=h.optionalFloat("HOLD-BACK",0);break;case"PART-INF":c.partTarget&&nn(c,O,o);var Z=new gi(M);c.partTarget=Z.decimalFloatingPoint("PART-TARGET");break;case"PART":var J=c.partList;J||(J=c.partList=[]);var ee=y>0?J[J.length-1]:void 0,te=y++,re=new gi(M,c),ie=new Q(re,I,f,te,ee);J.push(ie),I.duration+=ie.duration;break;case"PRELOAD-HINT":var ne=new gi(M,c);c.preloadHint=ne;break;case"RENDITION-REPORT":var ae=new gi(M,c);c.renditionReports=c.renditionReports||[],c.renditionReports.push(ae);break;default:me.warn("line parsed but not handled: "+o)}}}A&&!A.relurl?(g.pop(),E-=A.duration,c.partList&&(c.fragmentHint=A)):c.partList&&(en(I,A,v),I.cc=T,c.fragmentHint=I,d&&rn(I,d,c)),c.targetduration||(c.playlistParsingError=new Error("Missing Target Duration"));var se=g.length,oe=g[0],le=g[se-1];if((E+=c.skippedSegments*c.targetduration)>0&&se&&le){c.averagetargetduration=E/se;var ue=le.sn;c.endSN="initSegment"!==ue?ue:0,c.live||(le.endList=!0),L>0&&(function(e,t,r){if(r||(r=e[t]),r)for(var i=t;i--;){var n=e[i];if(!n)return;n.programDateTime=r.programDateTime-1e3*n.duration,r=n}}(g,L,L>se-1?I:null),oe&&v.unshift(oe))}return c.fragmentHint&&(E+=c.fragmentHint.duration),c.totalduration=E,v.length&&c.dateRangeTagCount&&oe&&Xi(v,c),c.endCC=T,c},e}();function qi(e,t,r,i,n,a){var s;if(void 0===t)return null;var o=ui(i,t),l={attrs:e,bitrate:e.decimalInteger("BANDWIDTH")||e.decimalInteger("AVERAGE-BANDWIDTH"),name:e.NAME,url:Wi.resolve(o,r)},u=e.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),Zi(e.CODECS,l);var d=e["SUPPLEMENTAL-CODECS"];return d&&(l.supplemental={},Zi(d,l.supplemental)),null!=(s=l.unknownCodecs)&&s.length||n.push(l),a&&(l.iframes=!0),l}function Xi(e,t){var r=e.length;if(!r){if(!t.hasProgramDateTime)return;var i=t.fragments[t.fragments.length-1];e.push(i),r++}for(var n=e[r-1],a=t.live?1/0:t.totalduration,s=Object.keys(t.dateRanges),o=s.length;o--;){var l=t.dateRanges[s[o]],u=l.startDate.getTime();l.tagAnchor=n.ref;for(var d=r;d--;){var h;if((null==(h=e[d])?void 0:h.sn)=o||0===i)&&t<=o+1e3*(((null==(s=r[i+1])?void 0:s.start)||n)-a.start)){var l=a.sn-e.startSN,u=e.fragments;if(l>=0&&lr.length)for(var d=r[i+1]||u[u.length-1],h=Math.min(d.sn-e.startSN,u.length-1);h>l;h--){var f=u[h].programDateTime;if(t>=f&&te.sn?(n=r-e.start,i=e):(n=e.start-r,i=t),i.duration!==n&&i.setDuration(n)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function on(e,t,r,i,n,a,s,o){i-r<=0&&(o.warn("Fragment should have a positive duration",t),i=r+t.duration,a=n+t.duration);var l=r,u=i,d=t.startPTS,h=t.endPTS;if(x(d)){var f=Math.abs(d-r);e&&f>e.totalduration?o.warn("media timestamps and playlist times differ by "+f+"s for level "+t.level+" "+e.url):x(t.deltaPTS)?t.deltaPTS=Math.max(f,t.deltaPTS):t.deltaPTS=f,l=Math.max(r,d),r=Math.min(r,d),n=void 0!==t.startDTS?Math.min(n,t.startDTS):n,u=Math.min(i,h),i=Math.max(i,h),a=void 0!==t.endDTS?Math.max(a,t.endDTS):a}var c=r-t.start;0!==t.start&&t.setStart(r),t.setDuration(i-t.start),t.startPTS=r,t.maxStartPTS=l,t.startDTS=n,t.endPTS=i,t.minEndPTS=u,t.endDTS=a;var g,v=t.sn;if(!e||ve.endSN)return 0;var m=v-e.startSN,p=e.fragments;for(p[m]=t,g=m;g>0;g--)sn(p[g],p[g-1]);for(g=m;g=0;s--){var o=a[s].initSegment;if(o){n=o;break}}e.fragmentHint&&delete e.fragmentHint.endPTS,function(e,t,r){for(var i,n=t.skippedSegments,a=Math.max(e.startSN,t.startSN)-t.startSN,s=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=null!=(i=e.fragmentHint)&&i.duration?e.fragments.concat(e.fragmentHint):e.fragments,d=a;d<=s;d++){var h=u[o+d],f=l[d];if(n&&!f&&h&&(f=t.fragments[d]=h),h&&f){r(h,f,d,l);var c=h.relurl,g=f.relurl;if(c&&mn(c,g))return void(t.playlistParsingError=un("media sequence mismatch "+f.sn+":",e,t,0,f));if(h.cc!==f.cc)return void(t.playlistParsingError=un("discontinuity sequence mismatch ("+h.cc+"!="+f.cc+")",e,t,0,f))}}}(e,t,(function(e,r,a,s){if((!t.startCC||t.skippedSegments)&&r.cc!==e.cc){for(var o=e.cc-r.cc,l=a;l=0,o=0;if(s&&nt){var n=1e3*i[i.length-1].duration;n>0&&ne.startCC)}(t,e)){var i=Math.min(t.endCC,e.endCC),n=yn(t.fragments,i),a=yn(e.fragments,i);if(n&&a){var s=n.start-a.start;r.log("Aligning playlists using dicontinuity sequence "+i+" (diff: "+s+")"),Tn(s,e)}}}(t,e,r),t.alignedSliding||function(e,t,r){if(e.hasProgramDateTime&&t.hasProgramDateTime){var i,n,a=e.fragments,s=t.fragments;if(a.length&&s.length){var o=Math.min(t.endCC,e.endCC);t.startCCMath.max(60,e.totalduration))r.log("Cannot align playlists using PDT without overlap ("+Math.abs(d)+" > "+e.totalduration+")");else{var h=d-(n.start-i.start);r.log("Aligning playlists using PDT (diff: "+h+")"),Tn(h,e)}}}}}(t,e,r),t.alignedSliding||t.skippedSegments||dn(e,t,!1,r))}function An(e,t,r){In(e,t,r),e.addEventListener(t,r)}function In(e,t,r){e.removeEventListener(t,r)}function Ln(e){for(var t="",r=e.length,i=0;il.end){var c=of;(c||g)&&(!r.loader||!g&&s.isFragmentNearlyDownloaded(r)?s.fragPrevious=null:(s.log("Cancelling fragment load for seek (sn: "+r.sn+") - "+(c?"backward":"forward")+" seek"),r.abortRequests(),s.resetLoadingState()))}}if(i&&(s.fragmentTracker.removeFragmentsInRange(o,1/0,s.playlistType,!0),o>s.lastCurrentTime&&(s.lastCurrentTime=o),!s.loadingParts)){var v=Math.max(l.end,o),m=s.shouldLoadParts(s.getLevelDetails(),v);m&&(s.log("LL-Part loading ON after seeking to "+o+" with buffer @"+v),s.loadingParts=m)}var p=!si.isBuffered(i,o);s.hls.hasEnoughToStart&&!p||(s.log("Setting "+(p?"startPosition":"nextLoadPosition")+" to "+o+" for seek without enough to start"),s.nextLoadPosition=o,p&&(s.startPosition=o)),u<1&&s.state===Rn.IDLE&&s.tickImmediate()},s.onMediaEnded=function(){s.log("setting startPosition to 0 because media ended"),s.startPosition=s.lastCurrentTime=0},s.playlistType=a,s.hls=t,s.fragmentLoader=new Zr(t.config),s.initFragmentLoader=new Zr(t.config),s.keyLoader=i,s.fragmentTracker=r,s.config=t.config,s.decrypter=new Qr(t.config),s}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.ERROR,this.onError,this)},r.doTick=function(){this.onTickEnd()},r.onTickEnd=function(){},r.startLoad=function(e){},r.stopLoad=function(){if(this.state!==Rn.STOPPED){this.fragmentLoader.abort(),this.initFragmentLoader.abort(),this.keyLoader.abort(this.playlistType);var e=this.fragCurrent;null!=e&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Rn.STOPPED}},r.pauseBuffering=function(){this.buffering=!1},r.resumeBuffering=function(){this.buffering=!0},r._streamEnded=function(e,t){if(t.live||!this.media)return!1;var r=e.end||0,i=this.config.timelineOffset||0;if(r<=i)return!1;var n=e.buffered;this.config.maxBufferHole&&n&&n.length>1&&(e=si.bufferedInfo(n,e.start,0));var a=e.nextStart;if(a&&a>i&&a0&&null!=a&&a.key&&a.iv&&Ti(a.method)){var s=self.performance.now(),o=ei(i,null,t.iframesOnly).decryptRange;return t.decrypter.decrypt(new Uint8Array(n),a.key.buffer,a.iv.buffer,Si(a.method),o).catch((function(e){throw r.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:i}),t.fragmentLoader.abort(),e})).then((function(n){var a=self.performance.now();return r.trigger(G.FRAG_DECRYPTED,{frag:i,part:null,payload:n,stats:{tstart:s,tdecrypt:a}}),e.payload=n,t.completeInitSegmentLoad(e)}))}return t.completeInitSegmentLoad(e)}))},r.completeInitSegmentLoad=function(e){var t=e.frag.stats;e.frag.data=new Uint8Array(e.payload),t.parsing.start=t.buffering.start=self.performance.now(),t.parsing.end=t.buffering.end=self.performance.now()},r.loadInitSegmentIfNeeded=function(e){var t,r=this,i=e.initSegment;if(!this.bitrateTest&&W(e)&&i&&!i.data)return(!i.encrypted||null!=(t=i.decryptdata)&&t.key?this._loadInitSegment(i):this.keyLoader.load(i).then((function(){return r._loadInitSegment(i)}))).catch((function(t){if(r.state===Rn.STOPPED||r.state===Rn.ERROR)throw t;throw"data"in t&&(t.data.frag=e,r.fragmentLoader.abort(),r.handleFragLoadError(t)),r.resetFragmentLoading(e),t}))},r.unhandledEncryptionError=function(e,t){var r,i,n=e.tracks;if(n&&!t.encrypted&&(null!=(r=n.audio)&&r.encrypted||null!=(i=n.video)&&i.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){var a=this.media,s=new Error("Encrypted track with no key in "+this.fragInfo(t)+" (media "+(a?"attached mediaKeys: "+a.mediaKeys:"detached")+")");return this.warn(s.message),!(!a||a.mediaKeys)&&(this.hls.trigger(G.ERROR,{type:U.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_NO_KEYS,fatal:!1,error:s,frag:t}),this.resetTransmuxer(),!0)}return!1},r.fragContextChanged=function(e){var t=this.fragCurrent;return!e||!X(e,t)},r.fragBufferedComplete=function(e,t){var r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log("Buffered "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)+" > buffer:"+(r?Ln(si.getBuffered(r)):"(detached)")+")"),W(e)){var i;if(e.type!==H.SUBTITLE){var n=e.elementaryStreams;if(!Object.keys(n).some((function(e){return!!n[e]})))return void(this.state=Rn.IDLE)}var a=null==(i=this.levels)?void 0:i[e.level];null!=a&&a.fragmentError&&(t||this.fragmentTracker.getState(e)!==Br)&&(this.log("Resetting level fragment error count of "+a.fragmentError+" on frag buffered"),a.fragmentError=0,e.stats.retry=0)}this.state=Rn.IDLE},r._handleFragmentLoadComplete=function(e){var t=this.transmuxer;if(t){var r=e.frag,i=e.part,n=e.partsLoaded,a=!n||0===n.length||n.some((function(e){return!e})),s=ei(r,i).decryptRange,o=new ni(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!a,r.duration,this.iframesOnly,s);this.log("load complete "+r.type+" sn: "+r.sn+(i?" part: "+i.index:"")+" of "+this.fragInfo(r,!1,i)),t.flush(o)}},r._handleFragmentLoadProgress=function(e){},r.loadKeyFor=function(e,t,r){var i,n=this,a=null;return!e.encrypted||null!=(i=e.decryptdata)&&i.key?e.encrypted||(a=this.keyLoader.loadClear(e,t.encryptedFragments,this.startFragRequested))&&this.log("[eme] blocking frag sn: "+e.sn+" load until media-keys acquired"):(this.log("Loading key for "+e.sn+" of ["+t.startSN+"-"+t.endSN+"], "+this.playlistLabel()+" "+e.level),this.state=Rn.KEY_LOADING,a=this.keyLoader.load(e,r).then((function(e){if(!n.fragContextChanged(e.frag))return n.hls.trigger(G.KEY_LOADED,e),n.state===Rn.KEY_LOADING&&(n.state=Rn.IDLE),e})),this.hls.trigger(G.KEY_LOADING,{frag:e})),a},r._doFragLoad=function(e,t,r,i){var n=this;void 0===r&&(r=null),this.fragCurrent=e;var a=t.details;if(!this.levels||!a)throw new Error("frag load aborted, missing level"+(a?"":" detail")+"s");var s,o=this.fragPrevious;if(!q(e,o)){var l=this.shouldLoadParts(t.details,e.end);l!==this.loadingParts&&(this.log("LL-Part loading "+(l?"ON":"OFF")+" loading sn "+(null==o?void 0:o.sn)+"->"+e.sn),this.loadingParts=l)}if(r=Math.max(e.start,r||0),this.loadingParts){var u=a.partList;if(u&&i){r>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);var d=this.getNextPart(u,e,r);if(d>-1){var h=u[d];if(!q(e=this.fragCurrent=h.fragment,o)&&!this.shouldLoadParts(t.details,e.end))return this.log("LL-Part loading OFF @"+this.playhead+" next part: "+this.fragInfo(e,!1,h)),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(h,t.details))return Promise.resolve(null);var f,c=this.loadKeyFor(e,a);if(this.fragContextChanged(e))return Promise.resolve(null);this.log("Loading "+e.type+" sn: "+e.sn+" part: "+h.index+" ("+d+"/"+(u.length-1)+") of "+this.fragInfo(e,!1,h)+" cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+r+(h.byteRange.length?" range:"+h.byteRange.join("-"):"")),this.nextLoadPosition=h.start+h.duration,this.state=Rn.FRAG_LOADING;var g=this.loadInitSegmentIfNeeded(e);if(c||g){var v=!!c;f=Promise.all([c,g]).then((function(r){var a=r[0];return!v||a&&!n.fragContextChanged(a.frag)?n.doFragPartsLoad(e,h,t,i):null})).catch((function(e){return n.handleFragLoadError(e)}))}else f=this.doFragPartsLoad(e,h,t,i).catch((function(e){return n.handleFragLoadError(e)}));return this.hls.trigger(G.FRAG_LOADING,{frag:e,part:h,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):f}if(!e.url||this.loadedEndOfParts(u,r))return Promise.resolve(null)}}if(this.loadingParts)this.log("LL-Part loading OFF after next part miss @"+r+" Check buffer at sn: "+e.sn+" loaded parts: "+(null==(s=a.partList)?void 0:s.filter((function(e){return e.loaded})).map((function(e){return"["+e.start+"-"+e.end+"]"})))),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(e,t.details))return Promise.resolve(null);var m,p=this.loadInitSegmentIfNeeded(e),y=this.loadKeyFor(e,a,p);if(this.fragContextChanged(e))return this.log("Context changed in KEY_LOADING sn: "+e.sn+" "+e.relurl+" > "+(null==(m=this.fragCurrent)?void 0:m.relurl)),null==p||p.catch((function(){return null})),null==y||y.catch((function(){return null})),Promise.resolve(null);this.log("Loading "+e.type+" sn: "+e.sn+" of "+this.fragInfo(e,!1)+" cc: "+e.cc+" ["+a.startSN+"-"+a.endSN+"], target: "+r+(e.byteRange.length?" range:"+e.byteRange.join("-"):"")),x(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Rn.FRAG_LOADING;var E,T=this.config.progressive&&e.type!==H.SUBTITLE;return E=T&&y?y.then((function(t){return!t||n.fragContextChanged(t.frag)?null:n.fragmentLoader.load(e,n.iframesOnly,i,p)})).catch((function(e){return n.handleFragLoadError(e)})):Promise.all([this.fragmentLoader.load(e,this.iframesOnly,T?i:void 0,T?p:void 0),y,p]).then((function(e){var t=e[0];return!T&&i&&i(t),t})).catch((function(e){return n.handleFragLoadError(e)})),this.hls.trigger(G.FRAG_LOADING,{frag:e,targetBufferTime:r}),null===this.fragCurrent?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([E,p]).then((function(e){return e[0]}))},r.doFragPartsLoad=function(e,t,r,i){var n=this;return new Promise((function(a,s){var o,l=[],u=null==(o=r.details)?void 0:o.partList,d=function(t){n.fragmentLoader.loadPart(e,t,i).then((function(i){l[t.index]=i;var s=i.part;n.hls.trigger(G.FRAG_LOADED,i);var o=cn(r.details,e.sn,t.index+1)||gn(u,e.sn,t.index+1);if(!o)return a({frag:e,part:s,partsLoaded:l});d(o)})).catch(s)};d(t)}))},r.handleFragLoadError=function(e){if("data"in e){var t=e.data;t.frag&&t.details===B.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===U.KEY_SYSTEM_ERROR&&!t.fatal&&(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)),this.hls.trigger(G.ERROR,t)}else this.hls.trigger(G.ERROR,{type:U.OTHER_ERROR,details:B.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null},r._handleTransmuxerFlush=function(e){var t=this.getCurrentContext(e);if(t&&this.state===Rn.PARSING){var r=t.frag,i=t.part,n=t.level,a=self.performance.now();r.stats.parsing.end=a,i&&(i.stats.parsing.end=a);var s=this.getLevelDetails(),o=s&&r.sn>s.endSN||this.shouldLoadParts(s,r.end);o!==this.loadingParts&&(this.log("LL-Part loading "+(o?"ON":"OFF")+" after parsing segment ending @"+r.end),this.loadingParts=o),this.updateLevelTiming(r,i,n,e)}else this.fragCurrent||this.state===Rn.STOPPED||this.state===Rn.ERROR||(this.state=Rn.IDLE)},r.shouldLoadParts=function(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList&&!this.iframesOnly){var r,i=e.partList[0];if(t>=i.end+((null==(r=e.fragmentHint)?void 0:r.duration)||0)&&this.playhead>i.start-i.fragment.duration)return!0}}return!1},r.getCurrentContext=function(e){var t=this.levels,r=this.fragCurrent,i=e.level,n=e.sn,a=e.part;if(null==t||!t[i])return this.warn("Levels object was unset while buffering fragment "+n+" of "+this.playlistLabel()+" "+i+". The current chunk will not be buffered."),null;var s=t[i],o=s.details,l=a>-1?cn(o,n,a):null,u=l?l.fragment:fn(o,n,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:l,level:s}):null},r.bufferFragmentData=function(e,t,r,i,n){if(this.state===Rn.PARSING){W(t)&&!this.fragContextChanged(t)&&(this.fragPrevious=t);var a=e.data1,s=e.data2,o=a;if(s&&(o=ht(a,s)),o.length){var l=this.initPTS[t.cc],u=l?-l.baseTime/l.timescale:void 0,d={type:e.type,frag:t,part:r,chunkMeta:i,offset:u,parent:t.type,data:o};if(this.hls.trigger(G.BUFFER_APPENDING,d),e.dropped&&e.independent&&!r){if(n)return;this.flushBufferGap(t)}}}},r.flushBufferGap=function(e){var t=this.media;if(t)if(si.isBuffered(t,t.currentTime)){var r=t.currentTime,i=si.bufferInfo(t,r,0),n=e.duration,a=Math.min(2*this.config.maxFragLookUpTolerance,.25*n),s=Math.max(Math.min(e.start-a,i.end-a),r+a);e.start-s>a&&this.flushMainBuffer(s,e.start)}else this.flushMainBuffer(0,e.start)},r.getFwdBufferInfo=function(e,t){var r,i=this.playhead,n=this.lastCurrentTime>i||null!=(r=this.media)&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,i,t,n)},r.getFwdBufferInfoAtPos=function(e,t,r,i){var n=si.bufferInfo(e,t,i);if(0===n.len&&void 0!==n.nextStart){var a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(n.nextStart<=a.end||a.gap)){var s=Math.max(Math.min(n.nextStart,a.end)-t,i);return si.bufferInfo(e,t,s)}}return n},r.getMaxBufferLength=function(e){var t,r=this.config;return t=e?Math.max(8*r.maxBufferSize/e,r.maxBufferLength):r.maxBufferLength,Math.min(t,r.maxMaxBufferLength)},r.exceedsMaxBuffer=function(e,t,r){var i=e.nextStart;if(i&&r.start>i){var n=e.buffered;if(n){for(var a=e.len,s=e.bufferedIndex,o=n.length-1;o>s;o--)n[o].start=t}}return!1},r.reduceMaxBufferLength=function(e,t){var r=this.config,i=Math.max(Math.min(e-t,r.maxBufferLength),t/2),n=Math.max(e-3*t,r.maxMaxBufferLength/2,i);return n>=i&&(r.maxMaxBufferLength=n,this.warn("Reduce max buffer length to "+n+"s"),!0)},r.getAppendedFrag=function(e){var t=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,this.playlistType):null;return t&&"fragment"in t?t.fragment:t},r.getNextFragment=function(e,t){var r=t.fragments,i=r.length;if(!i)return null;var n=this.config,a=t.fragmentStart,s=n.lowLatencyMode&&!!t.partList,o=null;if(t.live){var l=n.initialLiveManifestSize;if(i=a?(d=c,h=c===f?"config":"next load start"):g?(d=g,h="live edge"):(d=e,h="buffer pos"),d1)return!0}return!1},r.getNextFragmentLoopLoading=function(e,t,r,i,n){var a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t))&&!a.gap&&r.nextStart){var s=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,i,0);if(null!==s&&r.len+s.len>=n){var o=a.sn;return this.loopSn!==o&&(this.log('buffer full after gaps in "'+i+'" playlist starting at sn: '+o),this.loopSn=o),null}}return this.loopSn=void 0,a},r.filterReplacedPrimary=function(e,t){if(!e)return e;if(Dn(this.config)&&("type"in e?e:e.fragment).type!==H.SUBTITLE){var r=this.hls.interstitialsManager,i=null==r?void 0:r.bufferingItem;if(i){var n=i.event;if(n){if(!n.appendInPlace&&(Math.abs(e.start-i.start)>1||0===i.start))return null}else{if(e.end<=i.start&&!1===(null==t?void 0:t.live))return null;if(e.start>=i.end&&i.nextEvent&&(i.nextEvent.appendInPlace&&!i.nextEvent.hasPlayed||e.start-i.end>1))return null}}if(kn(e,null==r?void 0:r.playerQueue,this.playhead))return null}return e},r.getNextPart=function(e,t,r){for(var i=-1,n=!1,a=!0,s=0,o=e.length;s-1&&r "+d.fragment.sn+")"),i},r.loadedEndOfParts=function(e,t){for(var r,i=e.length;i--;){if(!(r=e[i]).loaded)return!1;if(t>r.start)return!0}return!1},r.getInitialLiveFragment=function(e){var t=e.fragments,r=this.fragPrevious,i=null;if(r){if(e.hasProgramDateTime&&(i=function(e,t,r){if(null===t||!Array.isArray(e)||!e.length||!x(t))return null;if(t<(e[0].programDateTime||0))return null;if(t>=(e[e.length-1].endProgramDateTime||0))return null;for(var i=0;i=e.startSN&&n<=e.endSN){var a=t[n-e.startSN];r.cc===a.cc&&(i=a,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=Sr(e,r.cc,r.end))&&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?e.fragmentEnd:e.edge,e))}return i},r.getFragmentAtPosition=function(e,t,r){var i,n,a=this.config,s=this.fragPrevious,o=r.fragments,l=r.endSN,u=r.fragmentHint,d=a.maxFragLookUpTolerance,h=r.partList,f=!!(this.loadingParts&&null!=h&&h.length&&u);if(f&&!this.bitrateTest&&h[h.length-1].fragment.sn===u.sn&&(o=o.concat(u),l=u.sn),s&&this.fragmentTracker.getState(s)===Nr&&(s=null),i=et-d||null!=(n=this.media)&&n.paused||!this.startFragRequested?0:d):o[o.length-1]){var c=i.sn-r.startSN,g=this.fragmentTracker.getState(i);if((g===Gr||g===Br&&i.gap)&&(s=i),q(i,s)&&(!f||h[0].fragment.sn>i.sn||!r.live)){var v=o[c+1];i=i.sn"+e.startSN+" fragments: "+i),o}return n},r.waitForCdnTuneIn=function(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,3*e.partTarget)},r.setStartPosition=function(e,t){var r=this.startPosition;r=0&&(r=this.nextLoadPosition),r},r.handleFragLoadAborted=function(e,t){this.transmuxer&&e.type===this.playlistType&&W(e)&&e.stats.aborted&&(this.log("Fragment "+e.sn+(t?" part "+t.index:"")+" of "+this.playlistLabel()+" "+e.level+" was aborted"),this.resetFragmentLoading(e))},r.resetFragmentLoading=function(e){this.fragCurrent&&(this.fragContextChanged(e)||this.state===Rn.FRAG_LOADING_WAITING_RETRY)||(this.state=Rn.IDLE)},r.onFragmentOrKeyLoadError=function(e,t){if(t.chunkMeta&&!t.frag){var r=this.getCurrentContext(t.chunkMeta);r&&(t.frag=r.frag)}var i=t.frag,n=t.part;if(i&&this.levels&&i.type===e)if(this.fragContextChanged(i)){var a;this.warn("Frag load error must match current frag to retry "+i.relurl+" > "+(null==(a=this.fragCurrent)?void 0:a.relurl))}else{var s=t.details===B.FRAG_GAP;s&&this.fragmentTracker.addAsGap(i);var o=t.errorAction;if(o){var l=o.action,u=o.flags,d=o.retryCount,h=void 0===d?0:d,f=o.retryConfig,c=!!f,g=c&&l===br,v=c&&!o.resolved&&u&Dr,m=this.hls.latestLevelDetails,p=null==m?void 0:m.live;if(!g&&v&&W(i)&&p&&i.sn=t||r&&!ae(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Rn.IDLE)},r.reduceLengthAndFlushBuffer=function(e){if(this.state===Rn.PARSING||this.state===Rn.PARSED){var t=e.frag,r=e.parent,i=this.getFwdBufferInfo(this.mediaBuffer,r),n=i&&i.len>.5;n&&this.reduceMaxBufferLength(i.len,(null==t?void 0:t.duration)||10);var a=!n;return a?this.warn("Buffer full error while media.currentTime ("+this.playhead+") is not buffered, flush "+r+" buffer"):i.nextStart&&t&&i.nextStart>t.start&&this.flushMainBuffer(i.nextStart,Number.POSITIVE_INFINITY,r===H.AUDIO?r:void 0),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1},r.resetFragmentErrors=function(e){e===H.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Rn.STOPPED&&(this.state=Rn.IDLE)},r.afterBufferFlushed=function(e,t){if(e){var r=si.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,this.playlistType),this.state===Rn.ENDED&&this.resetLoadingState()}},r.resetLoadingState=function(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Rn.STOPPED&&(this.state=Rn.IDLE)},r.resetStartWhenNotLoaded=function(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;var e=this.getLevelDetails();null!=e&&e.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(e,e.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}},r.resetWhenMissingContext=function(e){this.log("Loading context changed while buffering sn "+e.sn+" of "+this.playlistLabel()+" "+(-1===e.level?"":e.level)+". This chunk will not be buffered."),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()},r.removeUnbufferedFrags=function(e){void 0===e&&(e=0),this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)},r.updateLevelTiming=function(e,t,r,i){var n=this,a=r.details;if(a){if(this.log("update level timing "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)),!Object.keys(e.elementaryStreams).reduce((function(t,s){var o=e.elementaryStreams[s];if(o){var l=o.endPTS-o.startPTS;if(l<=0)return n.warn("Could not parse fragment "+e.sn+" "+s+" duration reliably ("+l+")"),t||!1;var u=i.partial?0:on(a,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,n.iframesOnly,n);return n.hls.trigger(G.LEVEL_PTS_UPDATED,{details:a,level:r,drift:u,type:s,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t}),!1)){var s,o,l,u,d=null===(null==(s=this.transmuxer)?void 0:s.error),h=null!=(null==(o=this.transmuxer)?void 0:o.error),f=(null!=(l=null==(u=this.levels)?void 0:u.length)?l:0)>1;if((0===r.fragmentError||d&&(r.fragmentError<2||e.endList)||h&&f)&&this.treatAsGap(e,r),d){var c=new Error("Found no media in "+this.playlistLabel()+" "+e.level+" "+(t?"part: "+t.index+" of ":"")+"sn: "+e.sn+" at playlist time: "+e.start+". Resetting transmuxer to fallback to playlist timing");if(this.warn(c.message),this.hls.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,fatal:!1,error:c,frag:e,reason:"Found no media in msn "+e.sn+" of "+this.playlistLabel()+' "'+r.url+'"'}),!this.hls)return;this.resetTransmuxer()}}this.state=Rn.PARSED,this.log("Parsed "+e.type+" sn: "+e.sn+(t?" part: "+t.index:"")+" of "+this.fragInfo(e,!1,t)),this.hls.trigger(G.FRAG_PARSED,{frag:e,part:t,chunkMeta:i})}else this.warn("level.details undefined")},r.playlistLabel=function(){return this.playlistType+" playlist"},r.fragInfo=function(e,t,r){var i,n;return void 0===t&&(t=!0),this.playlistLabel()+" "+e.level+" ("+(r?"part":"frag")+":["+(null!=(i=t&&!r?e.startPTS:(r||e).start)?i:NaN)+"-"+(null!=(n=t&&!r?e.endPTS:(r||e).end)?n:NaN)+"]"+(r&&"main"===e.type?"INDEPENDENT="+(r.independent?"YES":"NO"):"")+")"},r.treatAsGap=function(e,t){t&&t.fragmentError++,this.fragmentTracker.addAsGap(e)},r.resetTransmuxer=function(){var e;null==(e=this.transmuxer)||e.reset()},r.isFragmentNearlyDownloaded=function(e){var t,r=null==(t=e.loader)?void 0:t.stats;if(!r)return!1;var i=r.loading.first>0,n=(r.total-r.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return i&&n<=.15},r.recoverWorkerError=function(e){"demuxerWorker"===e.event&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())},r.calculateOptimalSwitchPoint=function(e,t){var r=0,i=this.hls,n=this.media,a=this.config,s=this.levels,o=this.playlistType,l=this.getLevelDetails();if(n&&!n.paused&&s){var u,d=o===H.AUDIO?Wt(e.audioCodec,128e3):e.maxBitrate,h=1+i.ttfbEstimate/1e3,f=i.bandwidthEstimate*a.abrBandWidthUpFactor;r=h+d*(l&&(this.loadingParts?l.partTarget:l.averagetargetduration)||(null==(u=this.fragCurrent)?void 0:u.duration)||6)/f,e.details||(r+=h)}var c=this.playhead;return{fetchdelay:r,okToFlushForwardBuffer:!(null!=l&&l.live)||t.end-c>1.5*r}},r.scheduleTrackSwitch=function(e,t,r){var i=this.media,n=this.playlistType;if(i&&e){var a=r?this.getBufferedFrag(this.playhead+t):null;if(a){var s=this.followingBufferedFrag(a);if(s){var o;this.abortCurrentFrag();var l=s.maxStartPTS?s.maxStartPTS:s.start,u=s.duration,d=Math.max(a.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if(((null==(o=this.getLevelDetails())?void 0:o.fragmentStart)||0)>d)return;var h=n===H.MAIN?null:"audio";this.flushMainBuffer(d,Number.POSITIVE_INFINITY,h),this.cleanupBackBuffer()}}}},r.cleanupBackBuffer=function(){var e=this.media,t=this.playlistType;if(e){var r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){var i=t===H.AUDIO;this.flushMainBuffer(0,r.start-(i?0:1),i?"audio":null)}}},r.getBufferedFrag=function(e){return this.fragmentTracker.getBufferedFrag(e,this.playlistType)},r.followingBufferedFrag=function(e){return e?this.getBufferedFrag(e.end+.5):null},r.abortCurrentFrag=function(){var e=this.fragCurrent;switch(this.fragCurrent=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Rn.KEY_LOADING:case Rn.FRAG_LOADING:case Rn.FRAG_LOADING_WAITING_RETRY:case Rn.PARSING:case Rn.PARSED:this.state=Rn.IDLE}this.nextLoadPosition=this.playhead},r.checkFragPlaying=function(){var e=this.media,t=null;if(e&&e.readyState>1&&!1===e.seeking){var r=e.currentTime;if(si.isBuffered(e,r)?t=this.getAppendedFrag(r):si.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t&&(this.backtrackFragment=void 0,!q(t,this.fragPlaying)))return this.fragPlaying=t,!0}return!1},r.getBufferOutput=function(){return null},r.nextLevelSwitch=function(){var e=this.levels,t=this.media,r=this.hls,i=this.config,n=this.playlistType;if(null!=t&&t.readyState&&e&&r&&i){var a=this.getBufferOutput(),s=this.getFwdBufferInfo(a,n);if(!s)return;var o=e[n===H.AUDIO?r.nextAudioTrack:r.nextLoadLevel],l=this.calculateOptimalSwitchPoint(o,s),u=l.fetchdelay,d=l.okToFlushForwardBuffer;this.scheduleTrackSwitch(s,u,d)}this.tickImmediate()},a(t,[{key:"startPositionValue",get:function(){var e=this.nextLoadPosition,t=this.startPosition;if(-1===t&&e){var r=this.getLevelDetails();return null!=r&&r.live?(this.hls.liveSyncPosition||r.fragmentStart)+this.timelineOffset:e}return t}},{key:"bufferingEnabled",get:function(){return this.buffering}},{key:"backtrackFragment",get:function(){},set:function(e){}},{key:"couldBacktrack",get:function(){return!1},set:function(e){}},{key:"inFlightFrag",get:function(){return{frag:this.fragCurrent,state:this.state}}},{key:"timelineOffset",get:function(){var e,t=this.config.timelineOffset;return t?(null==(e=this.getLevelDetails())?void 0:e.appliedTimelineOffset)||t:0}},{key:"primaryPrefetch",get:function(){var e;return!(!Dn(this.config)||!(null==(e=this.hls.interstitialsManager)||null==(e=e.playingItem)?void 0:e.event))}},{key:"playhead",get:function(){var e;if(null!=(e=this.hls)&&e.hasEnoughToStart){var t,r=null==(t=this.media)?void 0:t.currentTime;return x(r)?r:this.lastCurrentTime}return this.getLoadPosition()}},{key:"iframesOnly",get:function(){var e;if(this.playlistType!==H.MAIN)return!1;var t=this.getLevelDetails();return t?t.iframesOnly:null==(e=this.levelLastLoaded)?void 0:e.iframes}},{key:"state",get:function(){return this._state},set:function(e){var t=this._state;t!==e&&(this._state=e,this.log(t+"->"+e))}}])}(ii);function kn(e,t,r){if(t)for(var i=t.length;i--;){var n=t[i].interstitial,a=n.startTime,s=Math.min(a+n.duration,n.resumeTime);if(n.appendInPlace){if(e.start>=a&&e.end<=s)return!0;if(r>e.start&&e.end>a&&e.start>>5}function On(e,t){return t+1=e.length)return!1;var i=wn(e,t);if(i<=r)return!1;var n=t+i;return n===e.length||On(e,n)}return!1}function xn(e,t,r,i,n){if(!e.samplerate){var a=function(e,t,r,i){var n=t[r+2],a=n>>2&15;if(!(a>12)){var s,o=1+(n>>6&3),l=t[r+3]>>6&3|(1&n)<<2,u=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350][a],d=a;5!==o&&29!==o||(d-=3);var h=(14&d)>>1,f=(1&d)<<7|l<<3,c=0;if(1===o&&a>=6){var g=a-3;s=[(c=5)<<3|h,f|(14&g)>>1,(1&g)<<7|8,0]}else s=[o<<3|h,f];var v="mp4a.40."+(c||o);return me.log("manifest codec:"+i+", parsed codec:"+v+", channels:"+l+", rate:"+u+" (ADTS object type:"+o+" sampling index:"+a+" esds config:["+s.join(",")+"])"),{config:s,samplerate:u,channelCount:l,codec:v,parsedCodec:v,manifestCodec:i}}var m=new Error("invalid ADTS sampling index:"+a);e.emit(G.ERROR,G.ERROR,{type:U.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,fatal:!0,error:m,reason:m.message})}(t,r,i,n);if(!a)return;l(e,a)}}function Fn(e){return 9216e4/e}function Nn(e,t,r,i,n){var a,s=i+n*Fn(e.samplerate),o=function(e,t){var r=Cn(e,t);if(t+r<=e.length){var i=wn(e,t)-r;if(i>0)return{headerLength:r,frameLength:i}}}(t,r);if(o){var l=o.frameLength,u=o.headerLength,d=u+l,h=Math.max(0,r+d-t.length);h?(a=new Uint8Array(d-u)).set(t.subarray(r+u,t.length),0):a=t.subarray(r+u,r+d);var f={unit:a,pts:s};return h||e.samples.push(f),{sample:f,length:d,missing:h}}var c=t.length-r;return(a=new Uint8Array(c)).set(t.subarray(r,t.length),0),{sample:{unit:a,pts:s},length:c,missing:-1}}var Un=function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e}({});function Bn(e,t){return void 0===e&&(e=""),void 0===t&&(t=9e4),{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var Gn=function(){function e(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}var t=e.prototype;return t.resetInitSegment=function(e,t,r,i){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},t.resetTimeStamp=function(e){this.initPTS=e,this.resetContiguity()},t.resetContiguity=function(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0},t.canParse=function(e,t){return!1},t.appendFrame=function(e,t,r){},t.demux=function(e,t){this.cachedData&&(e=ht(this.cachedData,e),this.cachedData=null);var r,i=Ie(e,0),n=i?i.length:0,a=this._audioTrack,s=this._id3Track,o=i?Me(i):void 0,l=e.length;for((null===this.basePTS||0===this.frameIndex&&x(o))&&(this.basePTS=Kn(o,t,this.initPTS),this.lastPTS=this.basePTS),null===this.lastPTS&&(this.lastPTS=this.basePTS),i&&i.length>0&&s.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:i,type:Un.audioId3,duration:Number.POSITIVE_INFINITY});nt.length)){var a=qn(t,r);if(a&&r+a.frameLength<=t.length){var s=i+n*(9e4*a.samplesPerFrame/a.sampleRate),o={unit:t.subarray(r,r+a.frameLength),pts:s,dts:s};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(o),{sample:o,length:a.frameLength,missing:0}}}}function qn(e,t){var r=e[t+1]>>3&3,i=e[t+1]>>1&3,n=e[t+2]>>4&15,a=e[t+2]>>2&3;if(1!==r&&0!==n&&15!==n&&3!==a){var s=e[t+2]>>1&1,o=e[t+3]>>6,l=1e3*Vn[14*(3===r?3-i:3===i?3:4)+n-1],u=Hn[3*(3===r?0:2===r?1:2)+a],d=3===o?1:2,h=Yn[r][i],f=jn[i],c=8*h*f,g=Math.floor(h*l/u+s)*f,v=Rt();return!!v&&v<=87&&2===i&&l>=224e3&&0===o&&(e[t+3]=128|e[t+3]),{sampleRate:u,channelCount:d,frameLength:g,samplesPerFrame:c}}}function Xn(e,t){return 255===e[t]&&224==(224&e[t+1])&&0!=(6&e[t+1])}function zn(e,t){return t+1=e.length)return void r();if(!(e[t].unit.length<32||(this.decryptAacSample(e,t,r),this.decrypter.isSync())))return}},t.getAvcEncryptedData=function(e){for(var t=16*Math.floor((e.length-48)/160)+16,r=new Int8Array(t),i=0,n=32;n=e.length)return void i();for(var n=e[t].units;!(r>=n.length);r++){var a=n[r];if(!(a.data.length<=48||1!==a.type&&5!==a.type||(this.decryptAvcSample(e,t,r,i,a),this.decrypter.isSync())))return}}},e}(),Zn=function(e){function t(t,r){var i;return(i=e.call(this)||this).observer=void 0,i.config=void 0,i.sampleAes=null,i.observer=t,i.config=r,i}d(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,n){e.prototype.resetInitSegment.call(this,t,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}},t.probe=function(e,t){if(!e)return!1;var r=Ie(e,0),i=(null==r?void 0:r.length)||0;if(Qn(e,i))return!1;for(var n=e.length;i0;){s[0]=e[t];var o=Math.min(i,8),l=8-o;a[0]=4278190080>>>24+l<>l,r=r?r<t.length)return-1;if(11!==t[r]||119!==t[r+1])return-1;var a=t[r+4]>>6;if(a>=3)return-1;var s=[48e3,44100,32e3][a],o=63&t[r+4],l=2*[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][3*o+a];if(r+l>t.length)return-1;var u=t[r+6]>>5,d=0;2===u?d+=2:(1&u&&1!==u&&(d+=2),4&u&&(d+=2));var h=(t[r+6]<<8|t[r+7])>>12-d&1,f=[2,1,2,3,3,4,4,5][u]+h,c=t[r+5]>>3,g=7&t[r+5],v=new Uint8Array([a<<6|c<<1|g>>2,(3&g)<<6|u<<3|h<<2|o>>4,o<<4&224]),m=i+n*(1536/s*9e4),p=t.subarray(r,r+l);return e.config=v,e.channelCount=f,e.samplerate=s,e.samples.push({unit:p,pts:m}),l}var ra=function(e){function t(){return e.apply(this,arguments)||this}d(t,e);var r=t.prototype;return r.resetInitSegment=function(t,r,i,n){e.prototype.resetInitSegment.call(this,t,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}},t.probe=function(e){if(!e)return!1;var t=Ie(e,0),r=(null==t?void 0:t.length)||0;if(t&&11===e[r]&&119===e[r+1]&&void 0!==Me(t)&&Jn(e,r)<=16)return!1;for(var i=e.length;r8&&Ye(e,i+4)===Ke[t])return!0;i=n>1?i+n:r}return!1}(e,"moof")},t.demux=function(e,t,r){this.timeOffset=t;var i=e,n=this.videoTrack,a=this.txtTrack;if(this.config.progressive){this.remainderData&&(i=ht(this.remainderData,e));var s=function(e){var t={valid:null,remainder:null},r=Ze(e,["moof"]);if(r.length<2)return t.remainder=e,t;var i=r[r.length-1];return t.valid=e.slice(0,i.byteOffset-8),t.remainder=e.slice(i.byteOffset-8),t}(i);this.remainderData=s.remainder,n.samples=s.valid||new Uint8Array}else n.samples=i;var o=this.extractID3Track(n,t),l=this.parseFragment(n,a,t,r);return{videoTrack:n,audioTrack:this.audioTrack,id3Track:o,textTrack:this.txtTrack,initData:this.initData,sampleData:l}},t.flush=function(e,t){var r=this.timeOffset,i=this.videoTrack,n=this.txtTrack;i.samples=this.remainderData||new Uint8Array,this.remainderData=null;var a=this.extractID3Track(i,this.timeOffset),s=this.parseFragment(i,n,r,t);return{videoTrack:i,audioTrack:Bn(),id3Track:a,textTrack:Bn(),initData:this.initData,sampleData:s}},t.parseFragment=function(e,t,r,i){var n=this.initData;if(n&&i){var a=function(e,t,r,i,n){void 0===n&&(n=!1);var a=[];return{samples:a,sampleData:{includeSampleDetails:n,tracks:dt(t.samples,r,i,n,{isHEVCFlavor:ft(t.codec),samples:a,timeOffset:e,timescale:t.timescale,trackId:t.id})}}}(r,e,n,this.logger,i.iframe),s=a.samples,o=a.sampleData;return t.samples=s,o}t.samples=function(e,t){var r=[],i=t.samples,n=t.timescale,a=t.id,s=!1;return Ze(i,["moof"]).map((function(o){var l=o.byteOffset-8;Ze(o,["traf"]).map((function(o){var u=Ze(o,["tfdt"]).map((function(e){var t=e[0],r=Ye(e,4);return 1===t&&(r*=Math.pow(2,32),r+=Ye(e,8)),r/n}))[0];return void 0!==u&&(e=u),Ze(o,["tfhd"]).map((function(u){var d=Ye(u,4),h=16777215&Ye(u,0),f=0!=(1&h),c=0,g=0!=(2&h),v=0!=(8&h),m=0,p=0!=(16&h),y=0,E=0!=(32&h),T=!f&&0!=(131072&h),S=8;d===a&&(f?(c=Ye(u,S),S+=4,c*=Math.pow(2,32),c+=Ye(u,S),S+=4):T&&(c=l),g&&(S+=4),v&&(m=Ye(u,S),S+=4),p&&(y=Ye(u,S),S+=4),E&&(S+=4),"video"===t.type&&(s=ft(t.codec)),Ze(o,["trun"]).map((function(a){var o=a[0],l=16777215&Ye(a,0),u=0!=(1&l),d=0,h=0!=(4&l),f=0!=(256&l),g=0,v=0!=(512&l),p=0,E=0!=(1024&l),T=0!=(2048&l),S=0,A=Ye(a,4),I=8;u&&(d=Ye(a,I),I+=4),h&&(I+=4);for(var L=c+d,R=0;R0&&0===t[f-1];)f--;if(!(h-f+(0===f?a:0)<2)){if(u>=0)s.push({data:t.subarray(u,f),type:d});else{var c=this.getLastNalUnit(e.samples);c&&(f>0?c.data=ht(c.data,t.subarray(0,f)):a>0&&(c.data=c.data.subarray(0,c.data.byteLength-a)),c.state=0)}if(!(l0&&0===t[g-1];)g--;o=i-g+(0===g?a:0)}if(u>=0)s.push({data:t.subarray(u),type:d,state:o});else if(0===s.length&&-1!==o){var v=this.getLastNalUnit(e.samples);v&&(v.data=ht(v.data,t),v.state=o)}return e.naluState=o,s},e}(),oa=function(){function e(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}var t=e.prototype;return t.loadWord=function(){var e=this.data,t=this.bytesAvailable,r=e.byteLength-t,i=new Uint8Array(4),n=Math.min(4,t);if(0===n)throw new Error("no bytes available");i.set(e.subarray(r,r+n)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=8*n,this.bytesAvailable-=n},t.skipBits=function(e){var t;e=Math.min(e,8*this.bytesAvailable+this.bitsAvailable),this.bitsAvailable>e?(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;if(e>32&&me.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else{if(!(this.bytesAvailable>0))throw new Error("no bits available");this.loadWord()}return(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)},e}(),la=function(e){function t(){return e.apply(this,arguments)||this}d(t,e);var r=t.prototype;return r.parsePES=function(e,t,r,i,n){var a,s=this,o=n.iframe,l=this.parseNALu(e,r.data,i),u=this.VideoSample,d=!1;r.data=null,u&&l.length&&!e.audFound&&(this.pushAccessUnit(u,e),u=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.forEach((function(i){var n,l;switch(i.type){case 1:if(o)break;var h=!1;a=!0;var f,c=i.data;if(d&&c.length>4){var g=s.readSliceType(c);2!==g&&4!==g&&7!==g&&9!==g||(h=!0)}h&&null!=(f=u)&&f.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null),u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.frame=!0,u.key=h;break;case 5:a=!0,null!=(n=u)&&n.frame&&!u.key&&(s.pushAccessUnit(u,e),u=s.VideoSample=null),u||(u=s.VideoSample=s.createVideoSample(!0,r.pts,r.dts)),u.key=!0,u.frame=!0;break;case 6:if(o)break;a=!0,gt(i.data,1,r.pts,t.samples);break;case 7:var v,m;a=!0,d=!0;var p=i.data,y=s.readSPS(p);if(!e.sps||e.width!==y.width||e.height!==y.height||(null==(v=e.pixelRatio)?void 0:v[0])!==y.pixelRatio[0]||(null==(m=e.pixelRatio)?void 0:m[1])!==y.pixelRatio[1]){e.width=y.width,e.height=y.height,e.pixelRatio=y.pixelRatio,e.sps=[p];for(var E=p.subarray(1,4),T="avc1.",S=0;S<3;S++){var A=E[S].toString(16);A.length<2&&(A="0"+A),T+=A}e.codec=T}break;case 8:a=!0,e.pps=[i.data];break;case 9:a=!0,e.audFound=!0,null!=(l=u)&&l.frame&&(s.pushAccessUnit(u,e),u=null),u||(u=s.VideoSample=s.createVideoSample(!1,r.pts,r.dts));break;case 12:a=!0;break;default:a=!1}u&&a&&u.units.push(i)})),i&&u&&(this.pushAccessUnit(u,e),this.VideoSample=null)},r.getNALuType=function(e,t){return 31&e[t]},r.readSliceType=function(e){var t=new oa(e);return t.readUByte(),t.readUEG(),t.readUEG()},r.skipScalingList=function(e,t){for(var r=8,i=8,n=0;n=16&&i.type<=23;o=d(c),u=!1}switch(i.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:o||(o=d(!1)),o.frame=!0,n=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:var g;n=!0,u&&null!=(g=o)&&g.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=d(!0)),o.key=!0,o.frame=!0;break;case 19:case 20:n=!0,null!=(h=o)&&h.frame&&!o.key&&(a.pushAccessUnit(o,e),o=a.VideoSample=null),o||(o=d(!0)),o.key=!0,o.frame=!0;break;case 39:n=!0,gt(i.data,2,r.pts,t.samples);break;case 32:n=!0,e.vps||("object"!=typeof e.params&&(e.params={}),e.params=l(e.params,a.readVPS(i.data)),a.initVPS=i.data),e.vps=[i.data];break;case 33:if(n=!0,u=!0,void 0===e.vps||e.vps[0]===a.initVPS||void 0===e.sps||a.matchSPS(e.sps[0],i.data)||(a.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){var v=a.readSPS(i.data);for(var m in e.width=v.width,e.height=v.height,e.pixelRatio=v.pixelRatio,e.codec=v.codecString,e.sps=[],"object"!=typeof e.params&&(e.params={}),v.params)e.params[m]=v.params[m]}a.pushParameterSet(e.sps,i.data,e.vps),o||(o=d(!1));break;case 34:if(n=!0,"object"==typeof e.params){if(!e.pps){e.pps=[];var p=a.readPPS(i.data);for(var y in p)e.params[y]=p[y]}a.pushParameterSet(e.pps,i.data,e.vps)}break;case 35:n=!0,e.audFound=!0,null!=(f=o)&&f.frame&&(a.pushAccessUnit(o,e),o=null),o||(o=d(!1));break;default:n=!1}o&&n&&o.units.push(i)})),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)},r.pushParameterSet=function(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)},r.startsNewAccessUnit=function(e,t,r,i){if(!e)return!1;if(!t.audFound&&0===i)return!0;if(!e.frame)return!1;var n=r.type,a=r.data;return!!(n>=32&&n<=35||39===n||n>=41&&n<=44||n>=48&&n<=55)||n<=31&&a.length>2&&0!=(128&a[2])},r.getNALuType=function(e,t){return(126&e[t])>>>1},r.ebsp2rbsp=function(e){for(var t=new Uint8Array(e.byteLength),r=0,i=0;i=2&&3===e[i]&&0===e[i-1]&&0===e[i-2]||(t[r]=e[i],r++);return new Uint8Array(t.buffer,0,r)},r.pushAccessUnit=function(t,r){e.prototype.pushAccessUnit.call(this,t,r),this.initVPS&&(this.initVPS=null)},r.readVPS=function(e){var t=new oa(e);return t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6),{numTemporalLayers:t.readBits(3)+1,temporalIdNested:t.readBoolean()}},r.readSPS=function(e){var t=new oa(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);var r=t.readBits(3);t.readBoolean();for(var i=t.readBits(2),n=t.readBoolean(),a=t.readBits(5),s=t.readUByte(),o=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),h=t.readUByte(),f=t.readUByte(),c=t.readUByte(),g=t.readUByte(),v=t.readUByte(),m=t.readUByte(),p=[],y=[],E=0;E0)for(var T=r;T<8;T++)t.readBits(2);for(var S=0;S1&&t.readEG();for(var N=0;N0&&ae<16?(ee=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][ae-1],te=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][ae-1]):255===ae&&(ee=t.readBits(16),te=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(ie=t.readBits(32),ne=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){var se=t.readBoolean(),oe=t.readBoolean(),le=!1;(se||oe)&&((le=t.readBoolean())&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),le&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(var ue=0;ue<=r;ue++){var de=!1;(re=t.readBoolean())||t.readBoolean()?t.readEG():de=t.readBoolean();var he=de?1:t.readUEG()+1;if(se)for(var fe=0;fe>Se&1)<<31-Se)>>>0;var Ae=Te.toString(16);return 1===a&&"2"===Ae&&(Ae="6"),{codecString:"hvc1."+ye+a+"."+Ae+"."+(n?"H":"L")+m+".B0",params:{general_tier_flag:n,general_profile_idc:a,general_profile_space:i,general_profile_compatibility_flags:[s,o,l,u],general_constraint_indicator_flags:[d,h,f,c,g,v],general_level_idc:m,bit_depth:_+8,bit_depth_luma_minus8:_,bit_depth_chroma_minus8:C,min_spatial_segmentation_idc:J,chroma_format_idc:A,frame_rate:{fixed:re,fps:ne/ie}},width:ge,height:ve,pixelRatio:[ee,te]}},r.readPPS=function(e){var t=new oa(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);var r=t.readBoolean(),i=t.readBoolean(),n=1;return i&&r?n=0:i?n=3:r&&(n=2),{parallelismType:n}},r.matchSPS=function(e,t){return Ue(e).substring(3)===Ue(t).substring(3)},t}(sa),da=188,ha=function(){function e(e,t,r,i){this.logger=void 0,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._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=e,this.config=t,this.typeSupported=r,this.logger=i,this.videoParser=null}e.probe=function(t,r){var i=e.syncOffset(t);return i>0&&r.warn("MPEG2-TS detected but first sync word found @ offset "+i),-1!==i},e.syncOffset=function(e){for(var t=e.length,r=Math.min(940,t-da)+1,i=0;i1&&(0===a&&s>2||o+da>r))return a}i++}return-1},e.createTrack=function(e,t){return{container:"video"===e||"audio"===e?"video/mp2t":void 0,type:e,id:Ve[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:"audio"===e?t:void 0}};var t=e.prototype;return t.resetInitSegment=function(t,r,i,n,a,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack("video"),this._videoTrack.duration=n,this.videoIntegrityChecker="skip"===this.config.handleMpegTsVideoIntegrityErrors?new Ea(this.logger):null,this._audioTrack=e.createTrack("audio",n),this._id3Track=e.createTrack("id3"),this._txtTrack=e.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=i,t&&this.demux(t,0,s,"SAMPLE-AES"===(null==a?void 0:a.method))},t.resetTimeStamp=function(){},t.resetContiguity=function(){var e=this._audioTrack,t=this._videoTrack,r=this._id3Track;e&&(e.pesData=null),t&&(t.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null},t.demux=function(t,r,i,n,a){var s;void 0===n&&(n=!1),void 0===a&&(a=!1),n||(this.sampleAes=null);var o=this._videoTrack,l=this.videoIntegrityChecker,u=this._audioTrack,d=this._id3Track,h=this._txtTrack,f=i.iframe,c=o.pid,g=o.pesData,v=u.pid,m=d.pid,p=this._klvPid,y=u.pesData,E=d.pesData,T=null,S=null,A=this.pmtParsed,I=this._pmtId,L=t.length;if(this.remainderData&&(L=(t=ht(this.remainderData,t)).length,this.remainderData=null),L>4>1){if((_=k+5+t[k+4])===k+da)continue}else _=k+4;switch(P){case c:D&&(!g||null!=l&&l.isCorrupted||!(s=pa(g,this.logger))||(this.readyVideoParser(o.segmentCodec),null!==this.videoParser&&this.videoParser.parsePES(o,h,s,!1,i)),g={data:[],size:0},null==l||l.reset(c)),null==l||l.handlePacket(t.subarray(k)),g&&(g.data.push(t.subarray(_,k+da)),g.size+=k+da-_);break;case v:if(f)break;if(D){if(y&&(s=pa(y,this.logger)))switch(u.segmentCodec){case"aac":this.parseAACPES(u,s,i);break;case"mp3":this.parseMPEGPES(u,s);break;case"ac3":this.parseAC3PES(u,s)}y={data:[],size:0}}y&&(y.data.push(t.subarray(_,k+da)),y.size+=k+da-_);break;case m:if(f)break;D&&(E&&(s=pa(E,this.logger))&&this.parseID3PES(d,s),E={data:[],size:0}),E&&(E.data.push(t.subarray(_,k+da)),E.size+=k+da-_);break;case p:if(f)break;D&&(T&&(s=pa(T,this.logger))&&this.parseKlvPES(d,s),T={data:[],size:0}),T&&(T.data.push(t.subarray(_,k+da)),T.size+=k+da-_);break;case 0:D&&(_+=t[_]+1),I=this._pmtId=ca(t,_);break;case I:D&&(_+=t[_]+1);var C=ga(t,_,this.typeSupported,n,this.observer,this.logger,this.config,i);(c=C.videoPid)>0&&(o.pid=c,o.segmentCodec=C.segmentVideoCodec),(v=C.audioPid)>0&&(u.pid=v,u.segmentCodec=C.segmentAudioCodec),(m=C.id3Pid)>0&&(d.pid=m),(p=C.klvPid)>0&&(this._klvPid=p),null===S||A||(this.logger.warn("MPEG-TS PMT found at "+k+" after unknown PID '"+S+"'. Backtracking to sync byte @"+R+" to parse all TS packets."),S=null,k=R-188),A=this.pmtParsed=!0;break;case 17:case 8191:break;default:S=P}}else b++;b>0&&va(this.observer,new Error("Found "+b+" TS packet/s that do not start with 0x47"),i,void 0,this.logger),o.pesData=g,u.pesData=y,d.pesData=E;var w={audioTrack:u,videoTrack:o,id3Track:d,textTrack:h};return a&&this.extractRemainingSamples(w,i),w},t.flush=function(e,t){var r,i=this.remainderData;return this.remainderData=null,r=i?this.demux(i,0,t,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r,t),this.sampleAes?this.decrypt(r,this.sampleAes):r},t.extractRemainingSamples=function(e,t){var r,i=e.audioTrack,n=e.videoTrack,a=e.id3Track,s=e.textTrack,o=n.pesData,l=i.pesData,u=a.pesData,d=this.videoIntegrityChecker;if(!o||null!=d&&d.isCorrupted||!(r=pa(o,this.logger))?n.pesData=o:(this.readyVideoParser(n.segmentCodec),null!==this.videoParser&&(this.videoParser.parsePES(n,s,r,!0,t),n.pesData=null)),l&&(r=pa(l,this.logger))){switch(i.segmentCodec){case"aac":this.parseAACPES(i,r,t);break;case"mp3":this.parseMPEGPES(i,r);break;case"ac3":this.parseAC3PES(i,r)}i.pesData=null}else null!=l&&l.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),i.pesData=l;u&&(r=pa(u,this.logger))?(this.parseID3PES(a,r),a.pesData=null):a.pesData=u},t.demuxSampleAes=function(e,t,r,i){var n=this.demux(e,r,i,!0,!this.config.progressive),a=this.sampleAes=new $n(this.observer,this.config,t);return this.decrypt(n,a)},t.readyVideoParser=function(e){null===this.videoParser&&("avc"===e?this.videoParser=new la:"hevc"===e&&(this.videoParser=new ua))},t.decrypt=function(e,t){return new Promise((function(r){var i=e.audioTrack,n=e.videoTrack;i.samples&&"aac"===i.segmentCodec?t.decryptAacSamples(i.samples,0,(function(){n.samples?t.decryptAvcSamples(n.samples,0,0,(function(){r(e)})):r(e)})):n.samples&&t.decryptAvcSamples(n.samples,0,0,(function(){r(e)}))}))},t.destroy=function(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null},t.parseAACPES=function(e,t,r){var i,n,a,s=0,o=this.aacOverFlow,l=t.data;if(o){this.aacOverFlow=null;var u=o.missing,d=o.sample.unit.byteLength;if(-1===u)l=ht(o.sample.unit,l);else{var h=d-u;o.sample.unit.set(l.subarray(0,u),h),e.samples.push(o.sample),s=o.missing}}for(i=s,n=l.length;i0;)o+=n;else this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS")},t.parseID3PES=function(e,t){if(void 0!==t.pts){var r=l({},t,{type:this._videoTrack?Un.emsg:Un.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(r)}else this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS")},t.parseKlvPES=function(e,t){var r,i=null!=(r=t.pts)?r:t.dts;if(void 0!==i){var n=t.data;if(n.length<16)this.logger.warn("[tsdemuxer]: KLV PES payload too short");else for(var a=0;an.length)break;var o=a;if((a+=16)>=n.length)break;var l=n[a];a+=1;var u=0;if(128&l){var d=127&l;if(0===d||d>4||a+d>n.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(var h=0;hn.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}var f=a+u,c=n.subarray(o,f),g={data:c,len:c.byteLength,pts:i,dts:null!=(s=t.dts)?s:i,type:Un.misbklv,duration:Number.POSITIVE_INFINITY};e.samples.push(g),a=f}}else this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS")},e}();function fa(e,t){return((31&e[t+1])<<8)+e[t+2]}function ca(e,t){return(31&e[t+10])<<8|e[t+11]}function ga(e,t,r,i,n,a,s,o){var l={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},u=t+3+((15&e[t+1])<<8|e[t+2])-4;for(t+=12+((15&e[t+10])<<8|e[t+11]);t0)for(var f=t+5,c=h;c>2;){switch(e[f]){case 106:-1===l.audioPid&&(!0!==r.ac3?a.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=d,l.segmentAudioCodec="ac3"));break;case 5:-1===l.klvPid&&s.enableEmsgKLVMetadata&&(l.klvPid=d,a.log("KLV metadata PID found: "+d))}var g=e[f+1]+2;f+=g,c-=g}break;case 194:case 135:return va(n,new Error("Unsupported EC-3 in M2TS found"),o,void 0,a),l;case 36:-1===l.videoPid&&(l.videoPid=d,l.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"))}t+=h+5}return l}function va(e,t,r,i,n){n.warn("parsing error: "+t.message),e.emit(G.ERROR,G.ERROR,{type:U.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,fatal:!1,levelRetry:i,chunkMeta:r,error:t,reason:t.message})}function ma(e,t){t.log(e+" with AES-128-CBC encryption found in unencrypted stream")}function pa(e,t){var r,i,n,a,s,o=0,l=e.data;if(!e||0===e.size)return null;for(;l[0].length<19&&l.length>1;)l[0]=ht(l[0],l[1]),l.splice(1,1);if(1===((r=l[0])[0]<<16)+(r[1]<<8)+r[2]){if((i=(r[4]<<8)+r[5])&&i>e.size-6)return null;var u=r[7];192&u&&(a=536870912*(14&r[9])+4194304*(255&r[10])+16384*(254&r[11])+128*(255&r[12])+(254&r[13])/2,64&u?a-(s=536870912*(14&r[14])+4194304*(255&r[15])+16384*(254&r[16])+128*(255&r[17])+(254&r[18])/2)>54e5&&(t.warn(Math.round((a-s)/9e4)+"s delta between PTS and DTS, align them"),a=s):s=a);var d=(n=r[8])+9;if(e.size<=d)return null;e.size-=d;for(var h=new Uint8Array(e.size),f=0,c=l.length;fg){d-=g;continue}r=r.subarray(d),g-=d,d=0}h.set(r,o),o+=g}return i&&(i-=n+3),{data:h,pts:a,dts:s,len:i}}return null}var ya,Ea=function(){function e(e){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=e}var t=e.prototype;return t.reset=function(e){this.pid=e,this.lastContinuityCounter=-1,this.integrityState="ok"},t.handlePacket=function(e){if(!(e.byteLength<4)){var t=fa(e,0);if(t===this.pid){var r=(48&e[3])>>4;if(0!==r){var i=15&e[3],n=this.lastContinuityCounter;this.lastContinuityCounter=i;var a=0!=(1&r);if(!(0!=(2&r)&&0!=e[4]&&0!=(128&e[5])||n<0)){var s=a?n+1&15:n;return i!==s?(this.logger.warn("MPEG-TS Continuity Counter check failed for PID='"+t+"', CC="+i+", Expected-CC="+s+" Last-CC="+n),void(this.integrityState="cc-failed")):0!=(128&e[1])?(this.logger.warn("MPEG-TS Packet had TEI flag set for PID='"+t+"'"),void(this.integrityState="tei-bit")):void 0}}}else this.logger.debug("Packet PID mismatch, expected "+this.pid+" got "+t)}},a(e,[{key:"isCorrupted",get:function(){return"ok"!==this.integrityState}}])}(),Ta=function(){function e(){}return e.getSilentFrame=function(e,t){if("mp4a.40.2"===e){if(1===t)return new Uint8Array([0,200,0,128,35,128]);if(2===t)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(3===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(4===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(5===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(6===t)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224])}else{if(1===t)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(2===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(3===t)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94])}},e}(),Sa={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])},Aa=new Uint8Array([0,0,0,0,0,0,0,0]),Ia=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),La=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Ra=new Uint8Array([0,0,0,0,0,0,0,0]),ba=new Uint8Array([0,0,0,0,0,0,0,1]),ka=new Uint8Array([105,115,111,109]),Da=new Uint8Array([97,118,99,49]),Pa=new Uint8Array([0,0,0,1]),_a=function(){function e(){}return e.box=function(e){for(var t=8,r=arguments.length,i=new Array(r>1?r-1:0),n=1;n>24&255,t>>16&255,t>>8&255,255&t,i>>24,i>>16&255,i>>8&255,255&i,n>>24,n>>16&255,n>>8&255,255&n,85,196,0,0]))},e.mdia=function(t){return e.box(Ke.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))},e.mfhd=function(t){return e.box(Ke.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(Ke.minf,e.box(Ke.smhd,Ra),e.DINF,e.stbl(t)):e.box(Ke.minf,e.box(Ke.vmhd,La),e.DINF,e.stbl(t))},e.moof=function(t,r,i){return e.box(Ke.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,[Ke.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].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,[Ke.mvex].concat(i))},e.mvhd=function(t,r){r*=t;var i=Math.floor(r/(Ge+1)),n=Math.floor(r%(Ge+1)),a=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,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 e.box(Ke.mvhd,a)},e.sdtp=function(t){var r,i,n=t.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=e.box(Ke.avcC,new Uint8Array([1,a[3],a[4],a[5],255,224|t.sps.length].concat(a).concat([t.pps.length]).concat(s))),l=t.width,u=t.height,d=t.pixelRatio[0],h=t.pixelRatio[1];return e.box(Ke.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,e.box(Ke.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(Ke.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,255&d,h>>24,h>>16&255,h>>8&255,255&h])))},e.esds=function(e){var t=e.config,r=t.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5,r].concat(t,[6,1,2]))},e.audioStsd=function(e){var t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,255&t,0,0])},e.mp4a=function(t){return e.box(Ke.mp4a,e.audioStsd(t),e.box(Ke.esds,e.esds(t)))},e.mp3=function(t){return e.box(Ke[".mp3"],e.audioStsd(t))},e.ac3=function(t){return e.box(Ke["ac-3"],e.audioStsd(t),e.box(Ke.dac3,t.config))},e.stsd=function(t){var r=t.segmentCodec;if("audio"===t.type){if("aac"===r)return e.box(Ke.stsd,ba,e.mp4a(t));if("ac3"===r&&t.config)return e.box(Ke.stsd,ba,e.ac3(t));if("mp3"===r&&"mp3"===t.codec)return e.box(Ke.stsd,ba,e.mp3(t))}else{if(!t.pps||!t.sps)throw new Error("video track missing pps or sps");if("avc"===r)return e.box(Ke.stsd,ba,e.avc1(t));if("hevc"===r&&t.vps)return e.box(Ke.stsd,ba,e.hvc1(t))}throw new Error("unsupported "+t.type+" segment codec ("+r+"/"+t.codec+")")},e.tkhd=function(t){var r=t.id,i=(t.duration||0)*(t.timescale||0),n=t.width||0,a=t.height||0,s=Math.floor(i/(Ge+1)),o=Math.floor(i%(Ge+1));return e.box(Ke.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]))},e.traf=function(t,r){var i=e.sdtp(t),n=t.id,a=Math.floor(r/(Ge+1)),s=Math.floor(r%(Ge+1));return e.box(Ke.traf,e.box(Ke.tfhd,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,255&n])),e.box(Ke.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])),e.trun(t,i.length+16+20+8+16+8+8),i)},e.trak=function(t){return t.duration=t.duration||4294967295,e.box(Ke.trak,e.tkhd(t),e.mdia(t))},e.trex=function(t){var r=t.id;return e.box(Ke.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,n,a,s,o,l,u=t.samples||[],d=u.length,h=12+16*d,f=new Uint8Array(h);for(r+=8+h,f.set(["video"===t.type?1:0,0,15,1,d>>>24&255,d>>>16&255,d>>>8&255,255&d,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 e.box(Ke.trun,f)},e.initSegment=function(t){var r=e.moov(t);return ht(e.FTYP,r)},e.hvc1=function(t){for(var r=t.params,i=[t.vps,t.sps,t.pps],n=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),i.length]),a=n.length,s=0;s>8,255&i[d][h].length]),a),a+=2,l.set(i[d][h],a),a+=i[d][h].length}var f=e.box(Ke.hvcC,l),c=t.width,g=t.height,v=t.pixelRatio[0],m=t.pixelRatio[1];return e.box(Ke.hvc1,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,c>>8&255,255&c,g>>8&255,255&g,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]),f,e.box(Ke.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(Ke.pasp,new Uint8Array([v>>24,v>>16&255,v>>8&255,255&v,m>>24,m>>16&255,m>>8&255,255&m])))},e}();ya=_a,_a.FTYP=ya.box(Ke.ftyp,ka,Pa,ka,Da),_a.DINF=ya.box(Ke.dinf,ya.box(Ke.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));var Ca=9e4;function wa(e,t,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var n=e*t*r;return i?Math.round(n):n}function Oa(e,t){return wa(e,1e3,1/Ca,t)}function Ma(e){var t=e.baseTime,r=e.timescale;return t/r+" ("+t+"/"+r+") trackId: "+e.trackId}var xa=8589934592;function Fa(e,t,r,i){return{duration:t,size:r,cts:i,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1,paddingValue:0}}}var Na=function(e){function t(t,r,i,n){var a;return(a=e.call(this,"mp4-remuxer",n)||this).observer=void 0,a.config=void 0,a.typeSupported=void 0,a.ISGenerated=!1,a._initPTS=null,a._initDTS=null,a.nextVideoTs=null,a.nextAudioTs=null,a.videoSampleDuration=null,a.isAudioContiguous=!1,a.isVideoContiguous=!1,a.videoTrackConfig=void 0,a.observer=t,a.config=r,a.typeSupported=i,a.ISGenerated=!1,a}d(t,e);var r=t.prototype;return r.destroy=function(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null},r.resetTimeStamp=function(e){var t=this._initPTS;t&&e&&e.trackId===t.trackId&&e.baseTime===t.baseTime&&e.timescale===t.timescale||this.log("Reset initPTS: "+(t?Ma(t):t)+" > "+(e?Ma(e):e)),this._initPTS=this._initDTS=e},r.resetNextTimestamp=function(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1},r.resetInitSegment=function(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0},r.getVideoStartPts=function(e){var t=!1,r=e[0].pts,i=e.reduce((function(e,i){var n=i.pts,a=n-e;return a<-4294967296&&(t=!0,a=(n=Ua(n,r))-e),a>0?e:n}),r);return t&&this.debug("PTS rollover detected"),i},r.remux=function(e,t,r,i,n,a,s,o,l){var u,d,h,f,c,g,v=n,m=n,p=!l.iframe&&e.pid>-1,y=t.pid>-1,E=t.samples.length,T=e.samples.length>0,S=s&&E>0||E>1;if((!p||T)&&(!y||S)||this.ISGenerated||s){if(this.ISGenerated){var A,I,L,R,b=this.videoTrackConfig;(b&&(t.width!==b.width||t.height!==b.height||(null==(A=t.pixelRatio)?void 0:A[0])!==(null==(I=b.pixelRatio)?void 0:I[0])||(null==(L=t.pixelRatio)?void 0:L[1])!==(null==(R=b.pixelRatio)?void 0:R[1]))||!b&&S||null===this.nextAudioTs&&T)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,n,a));var k,D=this.isVideoContiguous,P=-1;if(S&&(P=function(e){for(var t=0;t0){this.warn("Dropped "+P+" out of "+E+" video samples due to a missing keyframe");var _=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(P),t.dropped+=P,k=m+=(t.samples[0].pts-_)/t.inputTimeScale}else-1===P&&(this.warn("No keyframe found out of "+E+" video samples"),g=!1);if(this.ISGenerated){if(T&&S&&n){var C=this.getVideoStartPts(t.samples),w=(Ua(e.samples[0].pts,C)-C)/t.inputTimeScale;v+=Math.max(0,w),m+=Math.max(0,-w)}if(T){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,n,a)),d=this.remuxAudio(e,v,this.isAudioContiguous,a,y||S||o===H.AUDIO?m:void 0,l),S){var O=d?d.endPTS-d.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,n,a)),u=this.remuxVideo(t,m,D,O,l)}}else S&&(u=this.remuxVideo(t,m,D,0,l));u&&(u.firstKeyFrame=P,u.independent=-1!==P,u.firstKeyFramePTS=k)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(c=Ba(r,n,this._initPTS,this._initDTS)),i.samples.length&&(f=Ga(i,n,this._initPTS))),{audio:d,video:u,initSegment:h,independent:g,text:f,id3:c}},r.computeInitPts=function(e,t,r,i){var n=Math.round(r*t),a=Ua(e,n);if(a0?I-1:I].dts&&(E=!0)}E&&u.sort((function(e,t){var r=e.dts-t.dts,i=e.pts-t.pts;return r||i})),a=u[0].dts;var R=(s=u[u.length-1].dts)-a,b=R?Math.round(R/(h-1)):m||e.inputTimeScale/30;if(r){var k=a-A,D=k>b,P=k<-1;if((D||P)&&(D?this.warn((e.segmentCodec||"").toUpperCase()+": "+Oa(k,!0)+" ms ("+k+"dts) hole between fragments detected at "+t.toFixed(3)):this.warn((e.segmentCodec||"").toUpperCase()+": "+Oa(-k,!0)+" ms ("+k+"dts) overlapping between fragments detected at "+t.toFixed(3)),!P||A>=u[0].pts||Rt())){a=A;var _=u[0].pts-k;if(D)u[0].dts=a,u[0].pts=_;else for(var C=!0,w=0;w_&&C);w++){var O=u[w].pts;if(u[w].dts-=k,u[w].pts-=k,w0?te.dts-u[ee-1].dts:b;if(ue=ee>0?te.pts-u[ee-1].pts:b,de.stretchShortVideoTrack&&null!==this.nextAudioTs){var fe=Math.floor(de.maxBufferHole*o),ce=(i?p+i*o:this.nextAudioTs+c)-te.pts;ce>fe?((m=ce-he)<0?m=he:z=!0,this.log("It is approximately "+ce/90+" ms to the next segment; using duration "+m/90+" ms for the last video frame.")):m=he}else m=he}var ge=Math.round(te.pts-te.dts);if(Q=Math.min(Q,m),Z=Math.max(Z,m),$=Math.min($,ue),J=Math.max(J,ue),!r&&0===ee&&ge>m){var ve=Math.round(ge/b)*b;ve-ge==1&&(this.log("pad first CTS "+ge+" -> "+ve+" of sn: "+n.sn),ge=ve)}d.push(Fa(te.key,m,ie,ge))}if(d.length){var me=Rt();if(me){if(me<70){var pe=d[0].flags;pe.dependsOn=2,pe.isNonSync=0}}else if(function(){if(void 0===St){var e=At.match(/Safari\/(\d+)/i);St=e?parseInt(e[1]):0}return St}()&&J-$0&&(i&&Math.abs(E-(p+y))<9e3||Math.abs(Ua(v[0].pts,E)-(p+y))<20*d),v.forEach((function(e){e.pts=Ua(e.pts,E)})),!r||p<0){var T=v.length;if(v=v.filter((function(e){return e.pts>=0})),T!==v.length&&this.warn("Removed "+(v.length-T)+" of "+T+" samples (initPTS "+y+" / "+s+")"),!v.length)return;p=0===n?0:i&&!g?Math.max(0,E-y):v[0].pts-y}if("aac"===e.segmentCodec)for(var S=this.config.maxAudioFramesDrift,A=0,I=p+y;A=S*d&&k<1e4&&g){var D=Math.round(b/d);for(I=R-D*d;I<0&&D&&d;)D--,I+=d;0===A&&(this.nextAudioTs=p=I-y),this.warn("Injecting "+D+" audio frames @ "+((I-y)/s).toFixed(3)+"s due to "+Math.round(1e3*b/s)+" ms gap.");for(var P=0;P0))return;M+=m;try{C=new Uint8Array(M)}catch(e){return void this.observer.emit(G.ERROR,G.ERROR,{type:U.MUX_ERROR,details:B.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:a,error:e,bytes:M,reason:"fail allocating audio mdat "+M})}f||(Xe(C,0,M),Xe(C,4,Ke.mdat))}C&&C.set(V,m);var Y=V.byteLength;m+=Y,c.push(Fa(!0,u,Y,0)),O=H}var j=c.length;if(j){var W=c[c.length-1];p=O-y,this.nextAudioTs=p+o*W.duration;var q=f?new Uint8Array(0):_a.moof(e.sequenceNumber++,w/o,l({},e,{samples:c}));e.samples=[];var X=(w-y)/s,z=this.nextAudioTs/s,Q={data1:q,data2:C,startPTS:X,endPTS:z,startDTS:X,endDTS:z,type:"audio",hasAudio:!0,hasVideo:!1,nb:j};return this.isAudioContiguous=!0,Q}},t}(ue);function Ua(e,t){var r;if(null===t)return e;for(r=t4294967296;)e+=r;return e}function Ba(e,t,r,i){var n=e.samples.length;if(n){for(var a=e.inputTimeScale,s=0;ssinf>>tenc' box: "+xe(i)+" -> "+xe(r)),e.set(r,8))}))}}(e,t);else{var l=s||o;null!=l&&l.encrypted&&this.warn('Init segment with encrypted track with has no key ("'+l.codec+'")!')}s&&(i=Ya(s,Y.AUDIO,this)),o&&(n=Ya(o,Y.VIDEO,this));var u={};s&&o?u.audiovideo={container:"video/mp4",codec:i+","+n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:s?u.audio={container:"audio/mp4",codec:i,encrypted:s.encrypted,initSegment:e,id:"audio"}:o?u.video={container:"video/mp4",codec:n,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=u},r.remux=function(e,t,r,i,n,a,s,o,l,u,d){var h,f,c=this.initPTS,g=this.lastEndTime,v={audio:void 0,video:void 0,text:void 0,id3:r,initSegment:void 0};x(g)||(g=this.lastEndTime=n||0);var m=t.samples;if(!m.length)return v;var p=this.pendingInitSegment;p&&(this.pendingInitSegment=void 0,this.generateInitSegment(p,this.decryptdata,u));var y={initPTS:void 0,timescale:void 0,trackId:void 0},E=this.initData;if(null!=(h=E)&&h.length||(this.generateInitSegment(m),E=this.initData),null==(f=E)||!f.length)return this.warn("Failed to generate initSegment."),v;if(l.iframe&&E.audio&&E.video){var T,S,A=null==(T=this.initTracks)||null==(T=T.audiovideo)?void 0:T.initSegment,I=A?function(e){var t=Ze(e,["moov"]);if(1!==t.length||Ze(e,["moof"]).length)return null;for(var r=e.byteOffset,i=[],n=[],a=!1,s=Ze(t[0],["trak"]),o=0;oM||w>F)&&this.warn("audio and video track sample timestamps do not overlap. v: "+w+"-"+M+" a: "+O+"-"+F+"}",k,b);var U=!!b&&(!k||!c&&O=1&&E.video&&l.iframe){var V,H=k.trun,Y=k.start,j=1===H.length,W=H.length?j?H[0].samples:(V=H[0].samples).concat.apply(V,H.slice(1).map((function(e){return e.samples}))):[];if(W.length){for(var q=H[0],X=q,z=H.length;z--;)if(H[z].samples.length){X=H[z];break}var Q=X.lastSampleDurationOffset,$=q.defaultSampleDurationOffset,Z=Math.abs(l.duration-(M-w))>.05,J=W.length=n}(c,C,n,N)||ne!==c.timescale)){var oe=!1,le=U?"audio":"video";if(c){var ue=0!==n?C/n:1+C/1;oe=C>=0&&Math.abs(1-ue)<.001,this.log(le+" timestamps in track "+se+" at playlist time: "+(a?"":"~")+n+" maps to "+C+" with initPTS: "+c.baseTime/c.timescale+" ("+(ae/ne-c.baseTime/c.timescale)+"s diff) ("+_+") drift estimate: "+ue+" "+(oe?"(ignoring drift)":"remapping timestamps (initPTS)"))}oe||(this.log("Found initPTS in "+le+" track "+se+" at playlist time: "+n+" offset: "+(C-n)+" ("+ae+"/"+ne+")"),c=null,y.initPTS=ae,y.timescale=ne,y.trackId=se)}c?(y.initPTS=c.baseTime,y.timescale=c.timescale,y.trackId=c.trackId):(y.timescale&&void 0!==y.trackId&&void 0!==y.initPTS||(this.warn("Could not set initPTS"),y.initPTS=C,y.timescale=1,y.trackId=-1),this.initPTS=c={baseTime:y.initPTS,timescale:y.timescale,trackId:y.trackId});var de=C-c.baseTime/c.timescale,he=de+N,fe=P&&void 0!==(null==B?void 0:B.ptsMin)?B.ptsMin/B.timescale-c.baseTime/c.timescale:de,ce=void 0!==G&&k?G/k.timescale-c.baseTime/c.timescale:P&&null!=B&&B.ptsMax?B.ptsMax/B.timescale-c.baseTime/c.timescale:he;N>0?this.lastEndTime=he:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var ge={data1:K,data2:void 0,startPTS:fe,startDTS:de,endPTS:ce,endDTS:he,type:_,hasAudio:D,hasVideo:P,nb:1,dropped:0,encrypted:!!E.audio&&E.audio.encrypted||!!E.video&&E.video.encrypted};v.audio=D&&!P?ge:void 0,v.video=P?ge:void 0;var ve=this.isVideoContiguous,me=null==k?void 0:k.sampleCount;if(me){var pe=k.keyFrameIndex,ye=-1!==pe;ge.nb=me,ge.dropped=0===pe||ve?0:ye?pe:me,ge.independent=ye,ge.firstKeyFrame=pe,ye&&k.keyFrameStart&&(ge.firstKeyFramePTS=(k.keyFrameStart-c.baseTime)/c.timescale),ve||(v.independent=ye),this.isVideoContiguous||(this.isVideoContiguous=ye),ge.dropped&&this.warn("fmp4 does not start with IDR: firstIDR "+pe+"/"+me+" dropped: "+ge.dropped+" start: "+(ge.firstKeyFramePTS||"NA"))}return v.initSegment=y,v.id3=Ba(r,n,c,c),i.samples.length&&(v.text=Ga(i,n,c)),v},t}(ue);function Ha(e,t,r){return void 0===r&&(r=!1),void 0!==(null==e?void 0:e.start)?(e.start+(r?e.duration:0))/e.timescale:t}function Ya(e,t,r){var i=e.codec;return i&&i.length>4?i:t===Y.AUDIO?"ec-3"===i||"ac-3"===i||"alac"===i?i:"fLaC"===i||"Opus"===i?Ft(i,!1):(r.warn('Unhandled audio codec "'+i+'" in mp4 MAP'),i||"mp4a"):"mjpg"===i?i:(r.warn('Unhandled video codec "'+i+'" in mp4 MAP'),i||"avc1")}try{Ka=self.performance.now.bind(self.performance)}catch(e){Ka=Date.now}var ja=[{demux:na,remux:Va},{demux:ha,remux:Na},{demux:Zn,remux:Na},{demux:ra,remux:Na}];ja.splice(2,0,{demux:ea,remux:Na});var Wa=function(){function e(e,t,r,i,n,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=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=e,this.typeSupported=t,this.config=r,this.id=n,this.logger=a}var t=e.prototype;return t.configure=function(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()},t.push=function(e,t,r,i){var n=this;if(!this.observer)return qa(r);var a=r.transmuxing;a.executeStart=Ka();var s=new Uint8Array(e),o=this.currentTransmuxState,l=this.transmuxConfig;i&&(this.currentTransmuxState=i);var u=i||o,d=u.contiguous,h=u.discontinuity,f=u.trackSwitch,c=u.accurateTimeOffset,g=u.timeOffset,v=u.initSegmentChange,m=l.audioCodec,p=l.videoCodec,y=l.defaultInitPts,E=l.duration,T=l.initSegmentData,S=function(e,t){var r=null;return e.byteLength>0&&null!=(null==t?void 0:t.key)&&null!==t.iv&&null!=t.method&&(r=t),r}(s,t);if(S&&Ti(S.method)){var A=this.getDecrypter(),I=Si(S.method);return this.asyncResult=!0,this.decryptionPromise=A.decrypt(s,S.key.buffer,S.iv.buffer,I,r.decryptRange).then((function(e){var t=n.push(e,null,r);return n.decryptionPromise=null,t})),this.decryptionPromise}var L=this.needsProbing(h,f);if(L){var R=r.iframe&&T&&ha.probe(T,this.logger)?T:s,b=this.configureTransmuxer(R);if(b)return this.logger.warn("[transmuxer] "+b.message),this.observer.emit(G.ERROR,G.ERROR,{type:U.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),a.executeEnd=Ka(),qa(r)}(h||f||v||L)&&this.resetInitSegment(T,m,p,E,t,r),(h||v||L)&&this.resetInitialTimestamp(y),d||this.resetContiguity();var k=this.transmux(s,S,g,c,r);this.asyncResult=Xa(k);var D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,a.executeEnd=Ka(),k},t.flush=function(e){var t=this,r=e.transmuxing;r.executeStart=Ka();var i=this.decrypter,n=this.currentTransmuxState,a=this.decryptionPromise;if(a)return this.asyncResult=!0,a.then((function(){return t.flush(e)}));var s=[],o=n.timeOffset;if(i){var l=i.flush();l&&s.push(this.push(l.buffer,null,e))}var u=this.demuxer,d=this.remuxer;if(!u||!d){r.executeEnd=Ka();var h=[qa(e)];return this.asyncResult?Promise.resolve(h):h}var f=u.flush(o,e);return Xa(f)?(this.asyncResult=!0,f.then((function(r){return t.flushRemux(s,r,e),s}))):(this.flushRemux(s,f,e),this.asyncResult?Promise.resolve(s):s)},t.flushRemux=function(e,t,r){if(this.remuxer){var i=t.audioTrack,n=t.videoTrack,a=t.id3Track,s=t.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;this.logger.log("[transmuxer.ts]: Flushed "+this.id+" sn: "+r.sn+(r.part>-1?" part: "+r.part:"")+" of "+this.id+" playlist "+r.level);var d=this.remuxer.remux(i,n,a,s,u,l,!0,this.id,r,t.initData,t.sampleData);e.push({remuxResult:d,chunkMeta:r}),r.transmuxing.executeEnd=Ka()}},t.resetInitialTimestamp=function(e){var t=this.demuxer,r=this.remuxer;t&&r&&(t.resetTimeStamp(e),r.resetTimeStamp(e))},t.resetContiguity=function(){var e=this.demuxer,t=this.remuxer;e&&t&&(e.resetContiguity(),t.resetNextTimestamp())},t.resetInitSegment=function(e,t,r,i,n,a){var s=this.demuxer,o=this.remuxer;s&&o&&(s.resetInitSegment(e,t,r,i,n,a),o.resetInitSegment(e,t,r,n))},t.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0},t.transmux=function(e,t,r,i,n){return"SAMPLE-AES"===(null==t?void 0:t.method)?this.transmuxSampleAes(e,t,r,i,n):this.transmuxUnencrypted(e,r,i,n)},t.transmuxUnencrypted=function(e,t,r,i){var n=this.demuxer,a=this.remuxer;if(!n||!a)return qa(i);var s=n.demux(e,t,i,!1,!this.config.progressive),o=s.audioTrack,l=s.videoTrack,u=s.id3Track,d=s.textTrack;return{remuxResult:a.remux(o,l,u,d,t,r,!1,this.id,i,s.initData,s.sampleData),chunkMeta:i}},t.transmuxSampleAes=function(e,t,r,i,n){var a=this;return this.demuxer?this.demuxer.demuxSampleAes(e,t,r,n).then((function(e){return{remuxResult:a.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,r,i,!1,a.id,n,e.initData,e.sampleData),chunkMeta:n}})):Promise.reject(new Error("no demuxer"))},t.configureTransmuxer=function(e){var t=this.config,r=this.observer,i=this.typeSupported;if(r){var n;try{for(var a=0,s=ja.length;a1&&l.id===(null==p?void 0:p.stats.chunkCount),I=!E&&(1===T||0===T&&(1===S||A&&S<=0)),L=self.performance.now();(E||T||0===n.stats.parsing.start)&&(n.stats.parsing.start=L),!a||!S&&I||(a.stats.parsing.start=L);var R=!(p&&(null==(d=n.initSegment)?void 0:d.url)===(null==(h=p.initSegment)?void 0:h.url)),b=new Qa(y,I,o,E,v,R);if(!I||y||R){this.hls.logger.log("[transmuxer-interface]: Starting new transmux session for "+n.type+" sn: "+l.sn+(l.part>-1?" part: "+l.part:"")+" "+this.id+" playlist: "+l.level+" id: "+l.id+"\n discontinuity: "+y+"\n trackSwitch: "+E+"\n contiguous: "+I+"\n accurateTimeOffset: "+o+"\n timeOffset: "+v+"\n initSegmentChange: "+R);var k=new za(r,i,t,s,u);this.configureTransmuxer(k)}if(this.frag=n,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:c,cmd:"demux",data:e,decryptdata:m,chunkMeta:l,state:b},e instanceof ArrayBuffer?[e]:[]);else if(g){var D=g.push(e,m,l,b);Xa(D)?D.then((function(e){f.handleTransmuxComplete(e)})).catch((function(e){f.transmuxerError(e,l,"transmuxer-interface push error")})):this.handleTransmuxComplete(D)}},r.flush=function(e){var t=this;e.transmuxing.start=self.performance.now();var r=this.instanceNo,i=this.transmuxer;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:r,cmd:"flush",chunkMeta:e});else if(i){var n=i.flush(e);Xa(n)?n.then((function(r){t.handleFlushResult(r,e)})).catch((function(r){t.transmuxerError(r,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}},r.transmuxerError=function(e,t,r){this.hls&&(this.error=e,this.hls.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))},r.handleFlushResult=function(e,t){var r=this;e.forEach((function(e){r.handleTransmuxComplete(e)})),this.onFlush(t)},r.configureTransmuxer=function(e){var t=this.instanceNo,r=this.transmuxer;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)},r.handleTransmuxComplete=function(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)},t}(),ss=function(e){function t(t,r,i){var n;return(n=e.call(this,t,r,i,"audio-stream-controller",H.AUDIO)||this).mainAnchor=null,n.mainFragLoading=null,n.audioOnly=!1,n.bufferedTrack=null,n.switchingTrack=null,n.trackId=-1,n.nextTrackId=-1,n.waitingData=null,n.mainDetails=null,n.flushing=!1,n.bufferFlushed=!1,n.cachedTrackLoadedData=null,n.registerListeners(),n}d(t,e);var r=t.prototype;return r.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.resetItem()},r.resetItem=function(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null},r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(G.LEVEL_LOADED,this.onLevelLoaded,this),t.on(G.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(G.BUFFER_RESET,this.onBufferReset,this),t.on(G.BUFFER_CREATED,this.onBufferCreated,this),t.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(G.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(G.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(G.FRAG_LOADING,this.onFragLoading,this),t.on(G.FRAG_BUFFERED,this.onFragBuffered,this)},r.unregisterListeners=function(){var t=this.hls;t&&(e.prototype.unregisterListeners.call(this),t.off(G.LEVEL_LOADED,this.onLevelLoaded,this),t.off(G.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(G.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(G.BUFFER_RESET,this.onBufferReset,this),t.off(G.BUFFER_CREATED,this.onBufferCreated,this),t.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(G.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(G.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(G.FRAG_LOADING,this.onFragLoading,this),t.off(G.FRAG_BUFFERED,this.onFragBuffered,this))},r.onInitPtsFound=function(e,t){var r=t.frag,i=t.id,n=t.initPTS,a=t.timescale,s=t.trackId,o=t.timestampOffsets;if(i===H.MAIN){var l=r.cc,u=this.fragCurrent;if(this.initPTS=o,this.log("InitPTS for cc: "+l+" found from main: "+n/a+" ("+n+"/"+a+") trackId: "+s),this.mainAnchor=r,this.state===Rn.WAITING_INIT_PTS){var d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==l)&&this.syncWithAnchor(r,null==d?void 0:d.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==l?(u.abortRequests(),this.syncWithAnchor(r,u)):this.state===Rn.IDLE&&this.tick()}},r.getLoadPosition=function(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&!1!==(null==(t=this.switchingTrack)?void 0:t.flushImmediate)?this.nextLoadPosition:e.prototype.getLoadPosition.call(this)},r.syncWithAnchor=function(e,t){var r,i=(null==(r=this.mainFragLoading)?void 0:r.frag)||null;if(!t||(null==i?void 0:i.cc)!==t.cc){var n=(i||e).cc,a=Sr(this.getLevelDetails(),n,this.getLoadPosition());a&&(this.log("Syncing with main frag at "+a.start+" cc "+a.cc),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===Rn.IDLE&&this.doTickIdle())}},r.startLoad=function(e,t){if(!this.levels)return this.startPosition=e,void(this.state=Rn.STOPPED);var r=this.lastCurrentTime;this.stopLoad(),this.setInterval(100),r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @"+r.toFixed(3)),e=r),this.state=Rn.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this.startFragRequested=!1),this.tick()},r.doTick=function(){switch(this.state){case Rn.IDLE:this.doTickIdle();break;case Rn.WAITING_TRACK:var t=this.levels,r=this.trackId,i=null==t?void 0:t[r],n=null==i?void 0:i.details;if(n&&!this.waitForLive(i)){if(this.waitForCdnTuneIn(n))break;this.state=Rn.WAITING_INIT_PTS}break;case Rn.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case Rn.WAITING_INIT_PTS:var a=this.waitingData;if(a){var s=a.frag,o=a.part,l=a.cache,u=a.complete,d=this.mainAnchor;if(void 0!==this.initPTS[s.cc]){this.waitingData=null,this.state=Rn.FRAG_LOADING;var h={frag:s,part:o,payload:l.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(h),u&&e.prototype._handleFragmentLoadComplete.call(this,h)}else d&&d.cc!==a.frag.cc&&this.syncWithAnchor(d,a.frag)}else this.state=Rn.IDLE}this.onTickEnd()},r.resetLoadingState=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),e.prototype.resetLoadingState.call(this)},r.onTickEnd=function(){var e=this.media;null!=e&&e.readyState&&(this.lastCurrentTime=e.currentTime,this.checkFragmentChanged())},r.doTickIdle=function(){var e,t=this.hls,r=this.levels,i=this.media,n=this.trackId,a=t.config;if(this.buffering&&(i||this.primaryPrefetch||!this.startFragRequested&&a.startFragPrefetch)&&null!=r&&r[n]){var s=r[n],o=s.details;if(!o||this.waitForLive(s)||this.waitForCdnTuneIn(o))return this.state=Rn.WAITING_TRACK,void(this.startFragRequested=!1);var l=this.getBufferOutput();this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Y.AUDIO));var u=this.getFwdBufferInfo();if(null!==u){if(!this.switchingTrack&&this._streamEnded(u,o))return t.trigger(G.BUFFER_EOS,{type:"audio"}),void(this.state=Rn.ENDED);var d=u.len,h=t.maxBufferLength,f=o.fragments,c=f[0].start,g=this.getLoadPosition(),v=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?g:u.end;if(this.switchingTrack&&i){var m=g;o.PTSKnown&&m=this.timelineOffset&&(u.end>c||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track "+m+" -> "+c+" + 0.05"),i.currentTime=c+.05)}if(!(d>=h&&!this.switchingTrack&&vy.end){var E=this.fragmentTracker.getFragAtPos(v,H.MAIN);E&&E.end>y.end&&(y=E,this.mainFragLoading={frag:E,targetBufferTime:null})}if(p.start>y.end)return}this.loadFragment(p,s,v)}}else this.bufferFlushed=!0}}}},r.onMediaDetaching=function(t,r){this.bufferFlushed=this.flushing=!1,e.prototype.onMediaDetaching.call(this,t,r)},r.onAudioTracksUpdated=function(e,t){var r=t.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(e){return new rr(e)}))},r.onAudioTrackSwitching=function(e,t){var r=!!t.url;this.trackId=t.id;var i=this.fragCurrent;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),r?(this.switchingTrack=t,t.flushImmediate||(this.nextTrackId=t.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(t),this.state!==Rn.STOPPED&&(this.setInterval(100),this.state=Rn.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1},r.onLevelLoaded=function(e,t){this.mainDetails=t.details;var r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(G.AUDIO_TRACK_LOADED,r))},r.onAudioTrackLoaded=function(e,t){var r,i=this.levels,n=t.details,a=t.id,s=t.groupId,o=t.track;if(i){var l=this.mainDetails;if(!l||n.endCC>l.endCC||l.expired)return this.cachedTrackLoadedData=t,void(this.state!==Rn.STOPPED&&(this.state=Rn.WAITING_TRACK));this.cachedTrackLoadedData=null,this.log("Audio track "+a+' "'+o.name+'" of "'+s+'" loaded ['+n.startSN+","+n.endSN+"]"+(n.lastPartSn?"[part-"+n.lastPartSn+"-"+n.lastPartIndex+"]":"")+",duration:"+n.totalduration);var u=i[a],d=0;if(n.live||null!=(r=u.details)&&r.live){if(this.checkLiveUpdate(n),n.deltaUpdateFailed)return;var h;u.details&&(d=this.alignPlaylists(n,u.details,null==(h=this.levelLastLoaded)?void 0:h.details)),n.alignedSliding||(Sn(l,n,this),d=n.fragmentStart)}u.details=n,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(l,d),this.hls.trigger(G.AUDIO_TRACK_UPDATED,{details:n,id:a,groupId:t.groupId}),this.state!==Rn.WAITING_TRACK||this.waitForCdnTuneIn(n)||(this.state=Rn.IDLE),this.tick()}else this.warn("Audio tracks reset while loading track "+a+' "'+o.name+'" of "'+s+'"')},r._handleFragmentLoadProgress=function(e){var t,r=e.frag,i=e.part,n=e.payload,a=this.config,s=this.trackId,o=this.levels;if(o){var l=o[s];if(l){var u=l.details;if(!u)return this.warn("Audio track details undefined on fragment load progress"),void this.removeUnbufferedFrags(r.start);var d=a.defaultAudioCodec||l.audioCodec||"mp4a.40.2",h=this.transmuxer;h||(h=this.transmuxer=new as(this.hls,H.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var f=this.initPTS[r.cc],c=null==(t=r.initSegment)?void 0:t.data;if(void 0!==f){var g=i?i.index:-1,v=-1!==g,m=new ni(r.level,r.sn,r.stats.chunkCount,n.byteLength,g,v,r.duration);h.push(n,c,d,"",r,i,u.totalduration,!1,m,f)}else this.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+u.startSN+" ,"+u.endSN+"],track "+s),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new Pn,complete:!1}).cache.push(new Uint8Array(n)),this.state!==Rn.STOPPED&&(this.state=Rn.WAITING_INIT_PTS)}else this.warn("Audio track is undefined on fragment load progress")}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},r._handleFragmentLoadComplete=function(t){this.waitingData?this.waitingData.complete=!0:e.prototype._handleFragmentLoadComplete.call(this,t)},r.onBufferReset=function(){this.mediaBuffer=null},r.onBufferCreated=function(e,t){this.bufferFlushed=this.flushing=!1;var r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)},r.onFragLoading=function(e,t){!this.audioOnly&&t.frag.type===H.MAIN&&W(t.frag)&&(this.mainFragLoading=t,this.state===Rn.IDLE&&this.tick())},r.onFragBuffered=function(e,t){var r=t.frag,i=t.part;if(r.type===H.AUDIO)if(this.fragContextChanged(r))this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+(this.switchingTrack?this.switchingTrack.name:"false"));else{if(W(r)){var n=this.switchingTrack;n&&(this.bufferedTrack=n)}this.fragBufferedComplete(r,i),this.media&&this.tick()}else this.audioOnly||r.type!==H.MAIN||r.elementaryStreams.video||r.elementaryStreams.audiovideo||(this.audioOnly=!0,this.mainFragLoading=null)},r.getFwdBufferInfo=function(){var t=this.getBufferOutput();return e.prototype.getFwdBufferInfo.call(this,t,H.AUDIO)},r.getBufferOutput=function(){return this.mediaBuffer?this.mediaBuffer:this.media},r.checkFragmentChanged=function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying,r=null==e?void 0:e.level;return t&&t.level===r||(e&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0},r.onError=function(t,r){var i;if(r.fatal)this.state=Rn.ERROR;else switch(r.details){case B.FRAG_GAP:case B.FRAG_PARSING_ERROR:case B.FRAG_DECRYPT_ERROR:case B.FRAG_LOAD_ERROR:case B.FRAG_LOAD_TIMEOUT:case B.KEY_LOAD_ERROR:case B.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(H.AUDIO,r);break;case B.AUDIO_TRACK_LOAD_ERROR:case B.AUDIO_TRACK_LOAD_TIMEOUT:case B.LEVEL_PARSING_ERROR:r.levelRetry||this.state!==Rn.WAITING_TRACK||(null==(i=r.context)?void 0:i.type)!==V.AUDIO_TRACK||(this.state=Rn.IDLE);break;case B.BUFFER_APPEND_NO_PROGRESS:if("audio"!==r.parent)return;r.frag&&(r.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment "+r.frag.sn+" of track "+r.frag.level+" as a gap after "+r.appendsWithoutProgress+" appends without buffered range growth, to prevent loop loading"),this.fragmentTracker.addAsGap(r.frag));break;case B.BUFFER_ADD_CODEC_ERROR:case B.BUFFER_APPEND_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)||this.resetLoadingState();break;case B.BUFFER_FULL_ERROR:if("audio"!==r.parent)return;this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"));break;case B.INTERNAL_EXCEPTION:this.recoverWorkerError(r)}},r.onBufferFlushing=function(e,t){t.type!==Y.VIDEO&&(this.flushing=!0)},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==Y.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Rn.ENDED&&(this.state=Rn.IDLE);var i=this.getBufferOutput();i&&(this.afterBufferFlushed(i,r),this.tick())}},r._handleTransmuxComplete=function(t){var r,i="audio",n=this.hls,a=t.remuxResult,s=t.chunkMeta,o=this.getCurrentContext(s);if(o){var u=o.frag,d=o.part,h=o.level,f=h.details,c=a.audio,g=a.text,v=a.id3,m=a.initSegment;if(this.fragContextChanged(u)||!f)return this.fragmentTracker.removeFragment(u),void(null!=m&&m.tracks&&this.resetTransmuxer());if(this.state=Rn.PARSING,c&&this.switchingTrack&&!this.switchingTrack.flushImmediate){var p=this.config.nextAudioTrackBufferFlushForwardOffset,y=Math.max(this.getLoadPosition()+p,u.start);e.prototype.flushMainBuffer.call(this,y,Number.POSITIVE_INFINITY,H.AUDIO)}if(null!=m&&m.tracks){var E=u.initSegment||u;if(this.unhandledEncryptionError(m,u))return;this._bufferInitSegment(h,m.tracks,E,s),n.trigger(G.FRAG_PARSING_INIT_SEGMENT,{frag:E,id:i,tracks:m.tracks})}if(c){var T=c.startPTS,S=c.endPTS,A=c.startDTS,I=c.endDTS;d&&(d.elementaryStreams[Y.AUDIO]={startPTS:T,endPTS:S,startDTS:A,endDTS:I}),u.setElementaryStreamInfo(Y.AUDIO,T,S,A,I),this.bufferFragmentData(c,u,d,s)}if(null!=v&&null!=(r=v.samples)&&r.length){var L=l({id:i,frag:u,details:f},v);n.trigger(G.FRAG_PARSING_METADATA,L)}if(g){var R=l({id:i,frag:u,details:f},g);n.trigger(G.FRAG_PARSING_USERDATA,R)}}else this.resetWhenMissingContext(s)},r._bufferInitSegment=function(e,t,r,i){if(this.state===Rn.PARSING&&(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,t.audio)){var n=t.audio;n.id=H.AUDIO;var a=e.audioCodec;this.log("Init audio buffer, container:"+n.container+", codecs[level/parsed]=["+a+"/"+n.codec+"]"),1===(null==a?void 0:a.split(",").length)&&(n.levelCodec=a),this.hls.trigger(G.BUFFER_CODECS,t);var s=n.initSegment;if(null!=s&&s.byteLength){var o={type:"audio",frag:r,part:null,chunkMeta:i,parent:r.type,data:s};this.hls.trigger(G.BUFFER_APPENDING,o)}this.tickImmediate()}},r.loadFragment=function(t,r,i){var n,a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===Nr||a===Br)if(null!=(n=r.details)&&n.live&&!this.initPTS[t.cc]){this.log("Waiting for video PTS in continuity counter "+t.cc+" of live stream before loading audio fragment "+t.sn+" of level "+this.trackId),this.state=Rn.WAITING_INIT_PTS;var s=this.mainDetails;s&&s.fragmentStart!==r.details.fragmentStart&&Sn(s,r.details,this)}else e.prototype.loadFragment.call(this,t,r,i);else this.clearTrackerIfNeeded(t)},r.flushAudioIfNeeded=function(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){var r=this.bufferedTrack;dr({name:r.name,lang:r.lang,assocLang:r.assocLang,characteristics:r.characteristics,audioCodec:r.audioCodec,channels:r.channels},t,hr)||(cr(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}},r.completeAudioSwitch=function(e){var t=this.hls;this.bufferedTrack=e,this.switchingTrack=null,t.trigger(G.AUDIO_TRACK_SWITCHED,c({},e))},a(t,[{key:"nextAudioTrack",get:function(){return this.nextTrackId}}])}(bn),os=function(e){function t(t,r){var i;return(i=e.call(this,r,t.logger)||this).hls=void 0,i.canLoad=!1,i.timer=-1,i.loadingSync=!1,i.hls=t,i}d(t,e);var r=t.prototype;return r.destroy=function(){this.clearTimer(),this.hls=null},r.clearTimer=function(){-1!==this.timer&&(self.clearTimeout(this.timer),this.timer=-1)},r.startLoad=function(){this.canLoad=!0,this.loadPlaylist()},r.stopLoad=function(){this.canLoad=!1,this.clearTimer()},r.switchParams=function(e,t,r){var i=null==t?void 0:t.renditionReports;if(i){for(var n=-1,a=0;a=0&&h>t.partTarget&&(d+=1)}var f=r&&er(r);return new tr(u,d>=0?d:void 0,f)}}},r.loadPlaylist=function(e){this.clearTimer()},r.loadingPlaylist=function(e,t){this.clearTimer()},r.shouldLoadPlaylist=function(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)},r.getUrlWithDirectives=function(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn("Could not construct new URL with HLS Delivery Directives: "+e)}return e},r.playlistLoaded=function(e,t,r){var i=t.details,n=t.stats,a=i.fragments,s=self.performance.now(),o=n.loading.first?Math.max(0,Math.floor(s-n.loading.first)):0;i.advancedDateTime=Date.now()-o;var l=this.hls.config.timelineOffset;if(l!==i.appliedTimelineOffset){var u=Math.max(l||0,0);i.appliedTimelineOffset=u,a.forEach((function(e){null==e||e.setStart(e.playlistOffset+u)}))}if(i.live||null!=r&&r.live){var d,h="levelInfo"in t?t.levelInfo:t.track;i.reloaded(r);var f=null==(d=a[a.length-1])?void 0:d.type;if(i.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){var c=new Error(f+" playlist "+h.id+" hit max allowed unchanged reloads.");this.warn(c);var g=t.networkDetails,v=t.context;return void this.hls.trigger(G.ERROR,{type:U.NETWORK_ERROR,details:B.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:i.url,error:c,reason:c.message,level:t.level,parent:f,context:v,networkDetails:g,stats:n})}if(r){ln(r,i,this);var m=i.playlistParsingError;if(m){this.warn(m);var p=this.hls;if(!p.config.ignorePlaylistParsingErrors){var y=t.networkDetails;return void p.trigger(G.ERROR,{type:U.NETWORK_ERROR,details:B.LEVEL_PARSING_ERROR,fatal:!1,url:i.url,error:m,reason:m.message,level:t.level,parent:f,networkDetails:y,stats:n})}i.playlistParsingError=null}}-1===i.requestScheduled&&(i.requestScheduled=n.loading.start);var E=this.hls.mainForwardBufferInfo,T=E?E.end-E.len:0,S=hn(i,1e3*(i.edge-T));i.requestScheduled+S0){if(w>3*i.targetduration)this.log("Playlist last advanced "+C.toFixed(2)+"s ago. Omitting segment and part directives."),L=void 0,R=void 0;else if(null!=r&&r.tuneInGoal&&w-i.partTarget>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+O+" with playlist age: "+i.age),O=0;else{var M=Math.floor(O/i.targetduration);L+=M,void 0!==R&&(R+=Math.round(O%i.targetduration/i.partTarget)),this.log("CDN Tune-in age: "+i.ageHeader+"s last advanced "+C.toFixed(2)+"s goal: "+O+" skip sn "+M+" to part "+R)}i.tuneInGoal=O}if(A=this.getDeliveryDirectives(i,t.deliveryDirectives,L,R),b||!_)return i.requestScheduled=s,void this.loadingPlaylist(h,A)}else(i.canBlockReload||i.canSkipUntil)&&(A=this.getDeliveryDirectives(i,t.deliveryDirectives,L,R));A&&void 0!==L&&i.canBlockReload&&(i.requestScheduled=n.loading.first+Math.max(S-2*o,S/2)),this.scheduleLoading(h,A,i)}else this.clearTimer()},r.scheduleLoading=function(e,t,r){var i=this,n=r||e.details;if(n){var a=self.performance.now(),s=n.requestScheduled;if(a>=s&&!this.loadingSync)return this.loadingSync=!0,this.loadingPlaylist(e,t),void(this.loadingSync=!1);var o=Math.max(s-a,0);this.log("reload live playlist "+(e.name||e.bitrate+"bps")+" in "+Math.round(o)+" ms"),this.clearTimer(),this.timer=self.setTimeout((function(){return i.loadingPlaylist(e,t)}),o)}else this.loadingPlaylist(e,t)},r.getDeliveryDirectives=function(e,t,r,i){var n=er(e);return null!=t&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,i=t.part,n=$t),new tr(r,i,n)},r.checkRetry=function(e){var t=this,r=e.details,i=Z(e),n=e.errorAction,a=n||{},s=a.action,o=a.retryCount,l=void 0===o?0:o,u=a.retryConfig,d=!!n&&!!u&&(s===br||!n.resolved&&s===Lr);if(d){var h;if(l>=u.maxNumRetry)return!1;if(i&&null!=(h=e.context)&&h.deliveryDirectives)this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" without delivery-directives'),this.loadPlaylist();else{var f,c=ae(null==(f=e.response)?void 0:f.code);if(this.clearTimer(),c)this.log("Waiting for connection (offline)"),e.reason="offline",this.timer=self.setTimeout((function(){return t.checkOfflineStatus()}),1e3);else{var g=re(u,l);this.warn("Retrying playlist loading "+(l+1)+"/"+u.maxNumRetry+' after "'+r+'" in '+g+"ms"),this.timer=self.setTimeout((function(){return t.loadPlaylist()}),g)}}e.levelRetry=!0,n.resolved=!0}return d},r.checkOfflineStatus=function(){var e=this;this.clearTimer(),ae(0)?this.timer=self.setTimeout((function(){return e.checkOfflineStatus()}),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())},t}(ue);function ls(e,t){if(e.length!==t.length)return!1;for(var r=0;r-1)n=a[o];else{var l=ur(s,this.tracks);n=this.tracks[l]}}var u=this.findTrackId(n);-1===u&&n&&(u=this.findTrackId(null));var d={audioTracks:a};this.log("Updating audio tracks, "+a.length+" track(s) found in group(s): "+(null==r?void 0:r.join(","))),this.hls.trigger(G.AUDIO_TRACKS_UPDATED,d);var h=this.trackId;if(-1!==u&&-1===h)this.setAudioTrack(u);else if(a.length&&-1===h){var f,c=new Error("No audio track selected for current audio group-ID(s): "+(null==(f=this.groupIds)?void 0:f.join(","))+" track count: "+a.length);this.warn(c.message),this.hls.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:c})}}}},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===V.AUDIO_TRACK&&t.context.id===this.trackId&&gr(t.context.groupId,this.groupIds)&&this.checkRetry(t)},r.setAudioOption=function(e){var t=this.hls;if(t.config.audioPreference=e,e){var r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){var i=this.currentTrack;if(i&&dr(e,i,hr))return i;var n=ur(e,this.tracksInGroup,hr);if(n>-1){var a=this.tracksInGroup[n];return this.setAudioTrack(n,"flushImmediate"in e&&e.flushImmediate),a}if(i){var s=t.loadLevel;-1===s&&(s=t.firstAutoLevel);var o=function(e,t,r,i,n){var a=t[i],s=t.reduce((function(e,t,r){var i=t.uri;return(e[i]||(e[i]=[])).push(r),e}),{})[a.uri];s.length>1&&(i=Math.max.apply(Math,s));var o=a.videoRange,l=a.frameRate,u=a.codecSet.substring(0,4),d=fr(t,i,(function(t){if(t.videoRange!==o||t.frameRate!==l||t.codecSet.substring(0,4)!==u)return!1;var i=t.audioGroups,a=r.filter((function(e){return gr(e.groupId,i)}));return ur(e,a,n)>-1}));return d>-1?d:fr(t,i,(function(t){var i=t.audioGroups,a=r.filter((function(e){return gr(e.groupId,i)}));return ur(e,a,n)>-1}))}(e,t.levels,r,s,hr);if(-1===o)return null;t.nextLoadLevel=o}if(e.channels||e.audioCodec){var l=ur(e,r);if(l>-1)return r[l]}}}return null},r.setAudioTrack=function(e,t){void 0===t&&(t=!0);var r=this.tracksInGroup;if(e<0||e>=r.length)this.warn("Invalid audio track id: "+e);else{this.selectDefaultTrack=!1;var i=this.currentTrack,n=r[e],a=n.details&&!n.details.live;if(!(e===this.trackId&&n===i&&a||(this.log("Switching to audio-track "+e+' "'+n.name+'" lang:'+n.lang+" group:"+n.groupId+" channels:"+n.channels),this.trackId=e,this.currentTrack=n,this.hls.trigger(G.AUDIO_TRACK_SWITCHING,c(c({},n),{},{flushImmediate:t})),a))){var s=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(s)}}},r.findTrackId=function(e){for(var t=this.tracksInGroup,r=0;r":"\n"+this.list("video")+"\n"+this.list("audio")+"\n"+this.list("audiovideo")+"}"},t.list=function(e){var t,r;return null!=(t=this.queues)&&t[e]||null!=(r=this.tracks)&&r[e]?e+": ("+this.listSbInfo(e)+") "+this.listOps(e):""},t.listSbInfo=function(e){var t,r=null==(t=this.tracks)?void 0:t[e],i=null==r?void 0:r.buffer;return i?"SourceBuffer"+(i.updating?" updating":"")+(r.ended?" ended":"")+(r.ending?" ending":""):"none"},t.listOps=function(e){var t;return(null==(t=this.queues)?void 0:t[e].map((function(e){return e.label})).join(", "))||""},e}(),fs=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,cs="HlsJsTrackRemovedError",gs=function(e){function t(t){var r;return(r=e.call(this,t)||this).name=cs,r}return d(t,e),t}(E(Error)),vs=function(e){function t(t,r){var i,n;return(i=e.call(this,"buffer-controller",t.logger)||this).hls=void 0,i.fragmentTracker=void 0,i.fragmentAppendProgress=Object.create(null),i.appendsWithoutProgress=Object.create(null),i.details=null,i._objectUrl=null,i.operationQueue=null,i.bufferCodecEventsTotal=0,i.media=null,i.mediaSource=null,i.lastMpegAudioChunk=null,i.lastVideoAppendEnd=0,i.appendSource=void 0,i.transferData=void 0,i.overrides=void 0,i.appendErrors={audio:0,video:0,audiovideo:0},i.appendError=void 0,i._quotaEvictionPending={},i.tracks={},i.sourceBuffers=[[null,null],[null,null]],i._onEndStreaming=function(e){var t;i.hls&&"open"===(null==(t=i.mediaSource)?void 0:t.readyState)&&i.media&&!i.media.seeking&&i.hls.pauseBuffering()},i._onStartStreaming=function(e){i.hls&&i.hls.resumeBuffering()},i._onMediaSourceOpen=function(e){var t=i,r=t.media,n=t.mediaSource;e&&i.log("Media source opened"),r&&n&&(In(n,"sourceopen",i._onMediaSourceOpen),In(r,"emptied",i._onMediaEmptied),i.updateDuration(),i.hls.trigger(G.MEDIA_ATTACHED,{media:r,mediaSource:n}),null!==i.mediaSource&&i.checkPendingTracks())},i._onMediaSourceClose=function(){if(i.log("Media source closed"),i.media){var e=i.media.error,t=i,r=t.appendError,n=t.appendErrors,a=!1;!r&&e&&(a=Math.max(++n.audio,++n.video,++n.audiovideo)>=i.hls.config.appendErrorMaxRetry);var s=new Error("MediaSource closed while media attached"+ys(a,e));i.warn(s),i.hls.trigger(G.ERROR,l({fatal:a},r,{type:U.MEDIA_ERROR,details:B.MEDIA_SOURCE_REQUIRES_RESET,error:s}))}},i._onMediaSourceEnded=function(){i.log("Media source ended")},i._onMediaEmptied=function(){var e=i,t=e.mediaSrc,r=e._objectUrl;t!==r&&i.error("Media element src was set while attaching MediaSource ("+r+" > "+t+")")},i._onMediaError=function(){var e,t,r=i.media;r&&i.log("Media error (code: "+(null==(e=r.error)?void 0:e.code)+"): "+(null==(t=r.error)?void 0:t.message))},i.hls=t,i.fragmentTracker=r,i.appendSource=(n=pe(t.config.preferManagedMediaSource),"undefined"!=typeof self&&n===self.ManagedMediaSource),i.initTracks(),i.registerListeners(),i}d(t,e);var r=t.prototype;return r.hasSourceTypes=function(){return Object.keys(this.tracks).length>0},r.destroy=function(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null,this._onMediaEmptied=this._onMediaError=null},r.registerListeners=function(){var e=this.hls;e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.BUFFER_RESET,this.onBufferReset,this),e.on(G.BUFFER_APPENDING,this.onBufferAppending,this),e.on(G.BUFFER_CODECS,this.onBufferCodecs,this),e.on(G.BUFFER_EOS,this.onBufferEos,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.FRAG_PARSED,this.onFragParsed,this),e.on(G.FRAG_CHANGED,this.onFragChanged,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.BUFFER_RESET,this.onBufferReset,this),e.off(G.BUFFER_APPENDING,this.onBufferAppending,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.BUFFER_EOS,this.onBufferEos,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.FRAG_PARSED,this.onFragParsed,this),e.off(G.FRAG_CHANGED,this.onFragChanged,this),e.off(G.ERROR,this.onError,this)},r.transferMedia=function(){var e=this,t=this.media,r=this.mediaSource;if(!t)return null;var i={};if(this.operationQueue){var n=this.isUpdating();n||this.operationQueue.removeBlockers();var a=this.isQueued();(n||a)&&this.warn("Transfering MediaSource with"+(a?" operations in queue":"")+(n?" updating SourceBuffer(s)":"")+" "+this.operationQueue),this.operationQueue.destroy()}var s=this.transferData;return s&&!this.sourceBufferCount&&s.mediaSource===r?l(i,s.tracks):this.sourceBuffers.forEach((function(t){var r=t[0];r&&(i[r]=l({},e.tracks[r]),e.removeBuffer(r)),t[0]=t[1]=null})),{media:t,mediaSource:r,tracks:i}},r.initTracks=function(){this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks={},this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0},r.onManifestLoading=function(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()},r.onManifestParsed=function(e,t){var r,i=2;(t.audio&&!t.video||!t.altAudio)&&(i=1),this.bufferCodecEventsTotal=i,this.log(i+" bufferCodec event(s) expected."),null!=(r=this.transferData)&&r.mediaSource&&this.sourceBufferCount&&i&&this.bufferCreated()},r.onMediaAttaching=function(e,t){var r=this.media=t.media;this.transferData=this.overrides=void 0;var i=pe(this.appendSource);if(i){var n=!!t.mediaSource;(n||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);var a=this.mediaSource=t.mediaSource||new i;if(this.assignMediaSource(a),n)this._objectUrl=r.src,this.attachTransferred();else{var s=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");var o=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||o&&a instanceof o,ms(r),function(e,t){var r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}(r,s),r.load()}catch(e){r.src=s}else r.src=s}An(r,"emptied",this._onMediaEmptied),An(r,"error",this._onMediaError),this.appendSource&&An(r,"seeking",this._onStartStreaming)}},r.assignMediaSource=function(e){var t,r;this.log(((null==(t=this.transferData)?void 0:t.mediaSource)===e?"transferred":"created")+" media source: "+(null==(r=e.constructor)?void 0:r.name)),An(e,"sourceopen",this._onMediaSourceOpen),An(e,"sourceended",this._onMediaSourceEnded),An(e,"sourceclose",this._onMediaSourceClose),this.appendSource&&(An(e,"startstreaming",this._onStartStreaming),An(e,"endstreaming",this._onEndStreaming))},r.attachTransferred=function(){var e=this,t=this.media,r=this.transferData;if(r&&t){var i=this.tracks,n=r.tracks,a=n?Object.keys(n):null,s=a?a.length:0,o=function(){Promise.resolve().then((function(){e.media&&e.mediaSourceOpenOrEnded&&e._onMediaSourceOpen()}))};if(n&&a&&s){if(!this.tracksReady)return this.hls.config.startFragPrefetch=!0,void this.log("attachTransferred: waiting for SourceBuffer track info");if(this.log("attachTransferred: (bufferCodecEventsTotal "+this.bufferCodecEventsTotal+")\nrequired tracks: "+ar(i,(function(e,t){return"initSegment"===e?void 0:t}))+";\ntransfer tracks: "+ar(n,(function(e,t){return"initSegment"===e?void 0:t}))+"}"),!ye(n,i)){r.mediaSource=null,r.tracks=void 0;var l=t.currentTime,u=this.details,d=Math.max(l,(null==u?void 0:u.fragments[0].start)||0);return d-l>1?void this.log("attachTransferred: waiting for playback to reach new tracks start time "+l+" -> "+d):(this.warn('attachTransferred: resetting MediaSource for incompatible tracks ("'+Object.keys(n)+'"->"'+Object.keys(i)+'") start time: '+d+" currentTime: "+l),this.onMediaDetaching(G.MEDIA_DETACHING,{}),this.onMediaAttaching(G.MEDIA_ATTACHING,r),void(t.currentTime=d))}this.transferData=void 0,a.forEach((function(t){var r=t,i=n[r];if(i){var a=i.buffer;if(a){var s=e.fragmentTracker,o=i.id;if(s.hasFragments(o)||s.hasParts(o)){var l=si.getBuffered(a);s.detectEvictedFragments(r,l,o,null,null,!0)}var u=ps(r),d=[r,a];e.sourceBuffers[u]=d,a.updating&&e.operationQueue&&e.operationQueue.prependBlocker(r),e.trackSourceBuffer(r,i)}}})),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}},r.onMediaDetaching=function(e,t){var r=this,i=!!t.transferMedia;this.transferData=this.overrides=void 0;var n=this.media,a=this.mediaSource,s=this._objectUrl;if(a){if(this.log("media source "+(i?"transferring":"detaching")),i)this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.removeBuffer(t)})),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){var o="open"===a.readyState;try{for(var l=a.sourceBuffers,u=l.length;u--;)o&&l[u].abort(),a.removeSourceBuffer(l[u]);o&&a.endOfStream()}catch(e){this.warn("onMediaDetaching: "+e.message+" while calling endOfStream")}}this.sourceBufferCount&&this.onBufferReset()}In(a,"sourceopen",this._onMediaSourceOpen),In(a,"sourceended",this._onMediaSourceEnded),In(a,"sourceclose",this._onMediaSourceClose),this.appendSource&&(In(a,"startstreaming",this._onStartStreaming),In(a,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(In(n,"emptied",this._onMediaEmptied),In(n,"error",this._onMediaError),In(n,"seeking",this._onStartStreaming),i||(s&&self.URL.revokeObjectURL(s),this.mediaSrc===s?(n.removeAttribute("src"),this.appendSource&&ms(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)},r.onBufferReset=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];r&&e.resetBuffer(r)})),this.initTracks()},r.resetBuffer=function(e){var t,r=null==(t=this.tracks[e])?void 0:t.buffer;if(this.removeBuffer(e),r)try{var i;null!=(i=this.mediaSource)&&i.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(t){this.warn("onBufferReset "+e,t)}delete this.tracks[e]},r.removeBuffer=function(e){this.removeBufferListeners(e),this.sourceBuffers[ps(e)]=[null,null];var t=this.tracks[e];t&&(this.clearBufferAppendTimeoutId(t),t.buffer=void 0)},r.resetQueue=function(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new hs(this.tracks)},r.onBufferCodecs=function(e,t){var r,i=this,n=this.tracks,a=Object.keys(t);this.log('BUFFER_CODECS: "'+a+'" (current SB count '+this.sourceBufferCount+")");var s="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),o=!s&&this.sourceBufferCount&&this.media&&a.some((function(e){return!n[e]}));s||o?this.warn('Unsupported transition between "'+Object.keys(n)+'" and "'+a+'" SourceBuffers'):(a.forEach((function(e){var r,a,s=t[e],o=s.id,l=s.codec,u=s.levelCodec,d=s.container,h=s.metadata,f=s.supplemental,c=n[e],g=null==(r=i.transferData)||null==(r=r.tracks)?void 0:r[e],v=null!=g&&g.buffer?g:c,m=(null==v?void 0:v.pendingCodec)||(null==v?void 0:v.codec),p=null==v?void 0:v.levelCodec;c||(c=n[e]={buffer:void 0,listeners:[],codec:l,supplemental:f,container:d,levelCodec:u,metadata:h,id:o});var y=Nt(m,p),E=null==y?void 0:y.replace(fs,"$1"),T=Nt(l,u),S=null==(a=T)?void 0:a.replace(fs,"$1");T&&y&&E!==S&&("audio"===e.slice(0,5)&&(T=Ft(T,i.appendSource)),i.log("switching codec "+m+" to "+T),T!==(c.pendingCodec||c.codec)&&(c.pendingCodec=T),c.container=d,i.appendChangeType(e,d,T))})),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),this.sourceBufferCount||(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&"main"===(null==(r=t.audio)?void 0:r.id)&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks()))},r.appendChangeType=function(e,t,r){var i=this,n=t+";codecs="+r,a={label:"change-type="+n,execute:function(){var a=i.tracks[e];if(a){var s=a.buffer;null!=s&&s.changeType&&(i.log("changing "+e+" sourceBuffer type to "+n),s.changeType(n),a.codec=r,a.container=t)}i.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(t){i.warn("Failed to change "+e+" SourceBuffer type",t)}};this.append(a,e,this.isPending(this.tracks[e]))},r.blockAudio=function(e){var t,r=this,i=e.start,n=i+.05*e.duration;if(!0!==(null==(t=this.fragmentTracker.getAppendedFrag(i,H.MAIN))?void 0:t.gap)){var a={label:"block-audio",execute:function(){var e,t;(r.lastVideoAppendEnd>n||si.isBuffered(null==(e=r.tracks.video)?void 0:e.buffer,n)||!0===(null==(t=r.fragmentTracker.getAppendedFrag(n,H.MAIN))?void 0:t.gap))&&r.unblockAudio()},onStart:function(){},onComplete:function(){},onError:function(e){r.warn("Error executing block-audio operation",e)}};this.append(a,"audio",!0)}},r.unblockAudio=function(){this.operationQueue&&this.operationQueue.unblockAudio()},r.onBufferAppending=function(e,t){var r=this,i=this.tracks,n=t.data,a=t.type,s=t.parent,o=t.frag,l=t.part,u=t.chunkMeta,d=t.offset,h=u.buffering[a],f=W(o)&&!l&&!o.gap&&!u.partial&&!u.iframe,c=null,g=!1,v=o.sn,m=o.cc,p=self.performance.now();h.start=p;var y=o.stats.buffering,E=l?l.stats.buffering:null;0===y.start&&(y.start=p),0===(null==E?void 0:E.start)&&(E.start=p);var T=i.audio,S=!1;"audio"===a&&"audio/mpeg"===(null==T?void 0:T.container)&&(S=!this.lastMpegAudioChunk||1===u.id||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);var A=i.video,I=null==A?void 0:A.buffer;if(I&&"initSegment"!==v&&void 0!==d){var L=null==T?void 0:T.buffer,R=l||o;if("audio"===a&&"main"!==s&&!A.ending&&!A.ended&&L&&si.getBuffered(L).length){var b=R.start+.05*R.duration,k=si.getBuffered(I),D=this.currentOp("video");k.length||D?!si.isBuffered(I,b)&&this.lastVideoAppendEndR.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}var C=(l||o).start,w={label:"append-"+a,execute:function(){var e;h.executeStart=self.performance.now();var t=null==(e=r.tracks[a])?void 0:e.buffer;t&&(f&&(c=si.timeRangesToArray(si.getBuffered(t)),g=Ss(Ts(c,o),o)),S?r.updateTimestampOffset(t,C,.1,a,v,m):void 0!==d&&x(d)&&r.updateTimestampOffset(t,d,1e-6,a,v,m)),r.appendExecutor(n,a)},onStart:function(){},onComplete:function(){r.clearBufferAppendTimeoutId(r.tracks[a]);var e=self.performance.now();h.executeEnd=h.end=e,0===y.first&&(y.first=e),0===(null==E?void 0:E.first)&&(E.first=e);var t={};if(r.sourceBuffers.forEach((function(e){var r=e[0],i=e[1];r&&(t[r]=si.getBuffered(i))})),f){var i=r.getFragmentAppendProgress(o),n=t[a];if(n&&c){var d=Ts(si.timeRangesToArray(n),o);i.progressed||(i.progressed=d-Ts(c,o)>.001);var v=g&&Ss(d,o);i.fullyBuffered[a]=(void 0===i.fullyBuffered[a]||i.fullyBuffered[a])&&v}}r.hls.trigger(G.BUFFER_APPENDED,{type:a,frag:o,part:l,chunkMeta:u,parent:s,timeRanges:t})},onError:function(e){var t;r.clearBufferAppendTimeoutId(r.tracks[a]);var i=e.code===DOMException.QUOTA_EXCEEDED_ERR||"QuotaExceededError"==e.name||"quota"in e;if(i&&!r._quotaEvictionPending[a]){var d=r.getBackBufferEvictionTarget(a,n.byteLength,o.type);if(d>0){r._quotaEvictionPending[a]=!0,r.log('QuotaExceededError on "'+a+'" append sn: '+v+" - evicting back buffer to "+d.toFixed(3)+"s and retrying");var h=r.getFlushOp(a,0,d),c=r.getClearEvictionPendingOp(a);return void r.insertNext([h,w,c],a)}r.warn('QuotaExceededError on "'+a+'" sn: '+v+" - no back buffer available to evict")}f&&(r.getFragmentAppendProgress(o).errored=!0);var g={type:U.MEDIA_ERROR,parent:s,details:B.BUFFER_APPEND_ERROR,sourceBufferName:a,frag:o,part:l,chunkMeta:u,error:e,err:e,fatal:!1},m=null==(t=r.media)?void 0:t.error;if(e.name!==cs||0!==r.sourceBufferCount||r.media&&0!==r.pendingTrackCount){var p;i&&(g.details=B.BUFFER_FULL_ERROR);var y=++r.appendErrors[a],E=r.hls.config.appendErrorMaxRetry;r.warn("Failed "+y+"/"+(E+1)+' times to append segment in "'+a+'" sourceBuffer with error: '+e.message),y>=E&&(g.fatal=!i);var T=null==(p=r.mediaSource)?void 0:p.readyState;("ended"===T||"closed"===T||m)&&(r.warn('MediaSource readyState "'+T+'" during SourceBuffer'+ys(g.fatal,m)),g.details=B.MEDIA_SOURCE_REQUIRES_RESET)}else g.errorAction=Fr(!0);r.appendError=g,r.hls.trigger(G.ERROR,g),i&&r.hls&&r.trimBuffers(o.start,1)}};this.log('queuing "'+a+'" append sn: '+v+(l?" p: "+l.index:"")+" of "+s+" playlist "+o.level+" cc: "+m+" offset: "+d+" bytes: "+n.byteLength),this.append(w,a,this.isPending(this.tracks[a]))},r.getClearEvictionPendingOp=function(e){var t=this;return{label:"clear",execute:function(){t._quotaEvictionPending[e]=!1,t.shiftAndExecuteNext(e)},onStart:function(){},onComplete:function(){},onError:function(){}}},r.getFlushOp=function(e,t,r){var i=this;return this.log('queuing "'+e+'" remove '+t+"-"+r),{label:"remove",execute:function(){i.removeExecutor(e,t,r)},onStart:function(){},onComplete:function(){var n,a=null==(n=i.tracks[e])?void 0:n.buffer;i.log("Remove request "+t+"-"+r+" from "+e+" Source Buffer complete > buffer: "+(a?Ln(si.getBuffered(a)):"(detached)")),i.hls.trigger(G.BUFFER_FLUSHED,{type:e,start:t,end:r})},onError:function(n){i.warn("Failed to remove "+t+"-"+r+' from "'+e+'" SourceBuffer',n),i.hls.trigger(G.BUFFER_FLUSHED,{type:e,start:0,end:0,error:n})}}},r.onBufferFlushing=function(e,t){var r=this,i=t.type,n=t.startOffset,a=t.endOffset;i&&"audio"!==i||this.unblockAudio(),i?this.append(this.getFlushOp(i,n,a),i):this.sourceBuffers.forEach((function(e){var t=e[0];t&&r.append(r.getFlushOp(t,n,a),t)}))},r.onFragParsed=function(e,t){var r=this,i=t.frag,n=t.part,a=t.chunkMeta,s=[],o=n?n.elementaryStreams:i.elementaryStreams;o[Y.AUDIOVIDEO]?s.push("audiovideo"):(o[Y.AUDIO]&&s.push("audio"),o[Y.VIDEO]&&s.push("video")),0===s.length&&this.log("Fragments must have at least one ElementaryStreamType set. "+i.type+" "+i.level+" "+(n?"part: "+n.index+" of ":"")+"sn: "+i.sn),this.blockBuffers((function(){var e=self.performance.now();i.stats.buffering.end=e,n&&(n.stats.buffering.end=e);var t=n?n.stats:i.stats;r.checkAppendProgress(i,n,a,s),r.hls&&(r.hls.trigger(G.FRAG_BUFFERED,{frag:i,part:n,stats:t,id:i.type,chunkMeta:a}),!n&&i.gap&&t.retry&&r.log("Nothing buffered for "+i.type+" level: "+i.level+" sn: "+i.sn+" retries "+t.retry))}),s).catch((function(e){r.warn("Fragment buffered callback "+e.message),r.stepOperationQueue(r.sourceBufferTypes)}))},r.onFragChanged=function(e,t){var r,i,n=this,a=null==(r=this.hls)?void 0:r.config;if(a){var s=a.backBufferLength,o=a.frontBufferFlushThreshold;this.trimBuffers(o,s,t.frag,t.previousFrag);var l=t.frag.elementaryStreams,u=this.appendErrors,d=null==(i=this.appendError)?void 0:i.sourceBufferName;Object.keys(l).forEach((function(e){l[e]&&(u[e]=0,e===d&&(n.appendError=void 0),"audio"===e||"video"===e?(u.audiovideo=0,"audiovideo"===d&&(n.appendError=void 0)):(u.audio=0,u.video=0,"audiovideo"!==d&&(n.appendError=void 0)))}))}},r.onBufferEos=function(e,t){var r,i=this;this.sourceBuffers.forEach((function(e){var r=e[0];if(r){var n=i.tracks[r];t.type&&t.type!==r||(n.ending=!0,n.ended||(n.ended=!0,i.log(r+" buffer reached EOS")))}}));var n=!1!==(null==(r=this.overrides)?void 0:r.endOfStream);this.sourceBufferCount>0&&!this.sourceBuffers.some((function(e){var t,r=e[0];return r&&!(null!=(t=i.tracks[r])&&t.ended)}))?(this.unblockAudio(),n?(this.log("Queueing EOS"),this.blockUntilOpen((function(){i.tracksEnded();var e=i.mediaSource;"open"===(null==e?void 0:e.readyState)?(i.log("Calling mediaSource.endOfStream()"),e.endOfStream(),i.hls.trigger(G.BUFFERED_TO_END,void 0)):e&&i.log("Could not call mediaSource.endOfStream(). mediaSource.readyState: "+e.readyState)}))):(this.tracksEnded(),this.hls.trigger(G.BUFFERED_TO_END,void 0))):"video"===t.type&&this.unblockAudio()},r.tracksEnded=function(){var e=this;this.sourceBuffers.forEach((function(t){var r=t[0];if(null!==r){var i=e.tracks[r];i&&(i.ending=!1)}}))},r.onLevelUpdated=function(e,t){var r=t.details;r.fragments.length&&(this.details=r,this.updateDuration())},r.updateDuration=function(){var e=this;this.blockUntilOpen((function(){var t=e.getDurationAndRange();t&&e.updateMediaSource(t)}))},r.onError=function(e,t){if(t.details===B.BUFFER_APPEND_ERROR&&t.frag){var r,i=null==(r=t.errorAction)?void 0:r.nextAutoLevel;x(i)&&i!==t.frag.level&&this.resetAppendErrors()}},r.getBackBufferEvictionTarget=function(e,t,r){var i=this.media;return i?this.fragmentTracker.getBackBufferEvictionEnd(i.currentTime,r,t):0},r.getFragmentAppendProgress=function(e){var t,r=Es(e),i=this.fragmentAppendProgress[r];return(null==(t=i)?void 0:t.stats)!==e.stats&&(i={stats:e.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=i),i},r.checkAppendProgress=function(e,t,r,i){if(!(t||!W(e)||e.gap||r.iframe||r.partial)){var n=Es(e),a=this.fragmentAppendProgress[n];delete this.fragmentAppendProgress[n];var s=e.stats.buffering;if(!s.start||s.first){var o=(null==a?void 0:a.stats)===e.stats?a:void 0;if(null==o||!o.errored){var l=i.length>0&&i.every((function(e){return!0===(null==o?void 0:o.fullyBuffered[e])}));if(null!=o&&o.progressed||l)delete this.appendsWithoutProgress[n];else if(o||0!==i.length){var u=(this.appendsWithoutProgress[n]||0)+1,d=this.hls;u>=d.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[n]:this.appendsWithoutProgress[n]=u,this.warn("Fragment "+e.sn+" of "+e.type+" playlist "+e.level+" appended "+u+" time"+(u>1?"s":"")+" without buffered range growth"),d.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:e,chunkMeta:r,parent:e.type,appendsWithoutProgress:u,error:new Error("Fragment append did not increase buffered coverage ("+u+")")})}}}}},r.resetAppendProgress=function(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)},r.resetAppendErrors=function(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0},r.trimBuffers=function(e,t,r,i){var n=this.hls,a=this.details,s=this.media;if(s&&null!==a&&this.sourceBufferCount){var o=n.config,l=s.currentTime,u=a.levelTargetDuration;t=a.live&&null!==o.liveBackBufferLength?o.liveBackBufferLength:t;var d=-1/0;if(x(t)&&t>=0){var h=Math.max(t,u);d=Math.floor(l/u)*u-h}if(r){var f=this.getLoopBackBufferFlushEnd(r,null!=i?i:null);f>0&&(d=Math.max(d,f))}if(d>0&&this.flushBackBuffer(l,u,d),x(e)&&e>0){var c=Math.max(o.maxBufferLength,e),g=Math.max(c,u),v=Math.floor(l/u)*u+g;this.flushFrontBuffer(l,u,v)}}},r.getLoopBackBufferFlushEnd=function(e,t){var r,i=this.media;if(!1===(null==(r=this.hls)?void 0:r.config.loopBackBufferFlush)||null==i||!i.loop||!t||e.level<=t.level)return 0;var n=e.elementaryStreams,a=n.video,s=n.audiovideo;if(null!=a&&a.partial||null!=s&&s.partial)return 0;var o=this.getEarliestElementaryStreamStart(e)-.25;return o<=0?0:(this.log("Flushing lower quality back buffer for loop: level "+e.level+", range [0-"+o.toFixed(3)+"]"),o)},r.getEarliestElementaryStreamStart=function(e){var t=e.elementaryStreams,r=t.audio,i=t.video,n=t.audiovideo,a=e.start;return n?a=Math.min(a,n.startDTS):(r&&(a=Math.min(a,r.startDTS)),i&&(a=Math.min(a,i.startDTS))),a},r.flushBackBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(e){var t=e[0],n=e[1];if(n){var a=si.getBuffered(n);if(a.length>0&&r>a.start(0)){var s,o,l;i.hls.trigger(G.BACK_BUFFER_REACHED,{bufferEnd:r});var u=i.tracks[t];if(null!=(s=i.details)&&s.live)i.hls.trigger(G.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(null!=u&&u.ended&&(null==(o=i.media)||!o.loop||!1===(null==(l=i.hls)?void 0:l.config.loopBackBufferFlush)))return void i.log("Cannot flush "+t+" back buffer while SourceBuffer is in ended state");i.hls.trigger(G.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:t})}}}))},r.flushFrontBuffer=function(e,t,r){var i=this;this.sourceBuffers.forEach((function(t){var n=t[0],a=t[1];if(a){var s=si.getBuffered(a),o=s.length;if(o<2)return;var l=s.start(o-1),u=s.end(o-1);if(r>l||e>=l&&e<=u)return;i.hls.trigger(G.BUFFER_FLUSHING,{startOffset:l,endOffset:1/0,type:n})}}))},r.getDurationAndRange=function(){var e,t=this.details,r=this.mediaSource;if(!t||!this.media||"open"!==(null==r?void 0:r.readyState))return null;var i=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){var n=Math.max(0,t.fragmentStart);return{duration:1/0,start:n,end:Math.max(n,i)}}return{duration:1/0}}var a=null==(e=this.overrides)?void 0:e.duration;if(a)return x(a)?{duration:a}:null;var s=this.media.duration;return i>(x(r.duration)?r.duration:0)&&i>s||!x(s)?{duration:i}:null},r.updateMediaSource=function(e){var t=e.duration,r=e.start,i=e.end,n=this.mediaSource;n&&this.media&&"open"===n.readyState&&(n.duration!==t&&(x(t)&&this.log("Updating MediaSource duration to "+t.toFixed(3)),n.duration=t),void 0!==r&&void 0!==i&&(this.log("MediaSource duration is set to "+n.duration+". Setting seekable range to "+r+"-"+i+"."),n.setLiveSeekableRange(r,i)))},r.checkPendingTracks=function(){var e=this.bufferCodecEventsTotal,t=this.pendingTrackCount,r=this.tracks;if(this.log("checkPendingTracks (pending: "+t+" codec events expected: "+e+") "+ar(r)),this.tracksReady){var i,n=null==(i=this.transferData)?void 0:i.tracks;n&&Object.keys(n).length?this.attachTransferred():this.createSourceBuffers()}},r.bufferCreated=function(){var e=this;if(this.sourceBufferCount){var t={};this.sourceBuffers.forEach((function(r){var i=r[0],n=r[1];if(i){var a=e.tracks[i];t[i]={buffer:n,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}})),this.hls.trigger(G.BUFFER_CREATED,{tracks:t}),this.log("SourceBuffers created. Running queue: "+this.operationQueue),this.sourceBuffers.forEach((function(t){var r=t[0];e.executeNext(r)}))}else{var r=new Error("could not create source buffer for media codec(s)");this.hls.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:r,reason:r.message})}},r.createSourceBuffers=function(){var e=this.tracks,t=this.sourceBuffers,r=this.mediaSource;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(var i in e){var n=i,a=e[n];if(this.isPending(a)){var s=this.getTrackCodec(a,n),o=a.container+";codecs="+s;a.codec=s,this.log("creating sourceBuffer("+o+")"+(this.currentOp(n)?" Queued":"")+" "+ar(a));try{var l=r.addSourceBuffer(o),u=ps(n),d=[n,l];t[u]=d,a.buffer=l}catch(e){var h;return this.error("error while trying to add sourceBuffer: "+e.message),this.shiftAndExecuteNext(n),null==(h=this.operationQueue)||h.removeBlockers(),delete this.tracks[n],void this.hls.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:n,mimeType:o,parent:a.id})}this.trackSourceBuffer(n,a)}}this.bufferCreated()},r.clearBufferAppendTimeoutId=function(e){e&&(self.clearTimeout(e.bufferAppendTimeoutId),e.bufferAppendTimeoutId=void 0)},r.getTrackCodec=function(e,t){var r=e.supplemental,i=e.codec;r&&("video"===t||"audiovideo"===t)&&Pt(r,"video")&&(i=function(e,t){var r=[];if(e)for(var i=e.split(","),n=0;n=r&&(this.log("Updating "+i+" SourceBuffer timestampOffset to "+t+" (sn: "+n+" cc: "+a+")"),e.timestampOffset=t)},r.removeExecutor=function(e,t,r){var i=this.media,n=this.mediaSource,a=this.tracks[e],s=null==a?void 0:a.buffer;if(!i||!n||!s)throw new Error("Attempting to remove from the "+e+" SourceBuffer, but it does not exist");var o,l=x(i.duration)?i.duration:1/0,u=x(n.duration)?n.duration:1/0,d=Math.max(0,t);if(d>=u)return null==(o=this.currentOp(e))||o.onComplete(),void this.shiftAndExecuteNext(e);var h=Math.min(r,l,u);if(!(h>d)||a.ending&&!a.ended)throw new Error("Cannot remove "+(h<=d?"invalid range ("+d+" >= "+h+") ":"")+"from the "+e+" SourceBuffer"+(a.ending?" while track ending":""));a.ended=!1,this.log("Removing ["+d+","+h+"] from the "+e+" SourceBuffer"),s.remove(d,h)},r.appendExecutor=function(e,t){var r=this,i=this.tracks[t],n=null==i?void 0:i.buffer;if(!n)throw new gs("Attempting to append to the "+t+" SourceBuffer, but it does not exist");if(i.ending=!1,i.ended=!1,this.hls.config.appendTimeout!==1/0){var a=this.calculateAppendTimeoutTime(n);i.bufferAppendTimeoutId=self.setTimeout((function(){return r.appendTimeoutHandler(t,n,a)}),a)}n.appendBuffer(e)},r.appendTimeoutHandler=function(e,t,r){this.log("Received timeout after "+r+"ms for append on "+e+" source buffer. Aborting and triggering error.");try{t.abort()}catch(t){this.log("Failed to abort append on "+e+" source buffer after timeout.")}var i=this.currentOp(e);i&&i.onError(new Error(e+"-append-timeout"))},r.calculateAppendTimeoutTime=function(e){var t=10;this.details&&(t=this.details.levelTargetDuration);var r=2*t*1e3;if(null===this.media)return r;var i=si.bufferInfo(e,this.media.currentTime,0);return i.len?(r=Math.max(1e3*i.len,r),Math.max(this.hls.config.appendTimeout,r)):r},r.blockUntilOpen=function(e){var t=this;if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch((function(e){t.warn("SourceBuffer blocked callback "+e),t.stepOperationQueue(t.sourceBufferTypes)}));else try{e()}catch(e){this.warn("Callback run without blocking "+this.operationQueue+" "+e)}},r.isUpdating=function(){return this.sourceBuffers.some((function(e){var t=e[0],r=e[1];return t&&r.updating}))},r.isQueued=function(){var e=this;return this.sourceBuffers.some((function(t){var r=t[0];return r&&!!e.currentOp(r)}))},r.isPending=function(e){return!!e&&!e.buffer},r.isAudioBlocked=function(){var e;return"block-audio"===(null==(e=this.currentOp("audio"))?void 0:e.label)},r.isAudioBlocking=function(){return!!this.operationQueue&&this.operationQueue.audioBlocking()},r.blockBuffers=function(e,t){var r=this;if(void 0===t&&(t=this.sourceBufferTypes),!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);var i=this.operationQueue,n=2===t.length&&this.isAudioBlocking()?[this.appendBlocker("video")]:t.map((function(e){return r.appendBlocker(e)}));return Promise.all(n).then((function(t){i===r.operationQueue&&(e(),r.stepOperationQueue(r.sourceBufferTypes))}))},r.stepOperationQueue=function(e){var t=this;e.forEach((function(e){var r,i=null==(r=t.tracks[e])?void 0:r.buffer;!i||i.updating||"audio"===e&&t.isAudioBlocked()||t.shiftAndExecuteNext(e)}))},r.append=function(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)},r.insertNext=function(e,t){this.operationQueue&&this.operationQueue.insertNext(e,t)},r.appendBlocker=function(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)},r.currentOp=function(e){return this.operationQueue?this.operationQueue.current(e):null},r.executeNext=function(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)},r.shiftAndExecuteNext=function(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)},r.addBufferListener=function(e,t,r){var i=this.tracks[e];if(i){var n=i.buffer;if(n){var a=r.bind(this,e);i.listeners.push({event:t,listener:a}),An(n,t,a)}}},r.removeBufferListeners=function(e){var t=this.tracks[e];if(t){var r=t.buffer;r&&(t.listeners.forEach((function(e){In(r,e.event,e.listener)})),t.listeners.length=0)}},a(t,[{key:"mediaSourceOpenOrEnded",get:function(){var e,t=null==(e=this.mediaSource)?void 0:e.readyState;return"open"===t||"ended"===t}},{key:"sourceBufferTracks",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,r){var i=e.tracks[r];return t[r]={id:i.id,container:i.container,codec:i.codec,levelCodec:i.levelCodec},t}),{})}},{key:"bufferedToEnd",get:function(){var e=this;return this.sourceBufferCount>0&&!this.sourceBuffers.some((function(t){var r=t[0];if(r){var i=e.tracks[r];if(i)return!i.ended||i.ending}return!1}))}},{key:"tracksReady",get:function(){var e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}},{key:"mediaSrc",get:function(){var e,t,r=(null==(e=this.media)||null==(t=e.querySelector)?void 0:t.call(e,"source"))||this.media;return null==r?void 0:r.src}},{key:"pendingTrackCount",get:function(){var e=this;return Object.keys(this.tracks).reduce((function(t,r){return t+(e.isPending(e.tracks[r])?1:0)}),0)}},{key:"sourceBufferCount",get:function(){return this.sourceBuffers.reduce((function(e,t){return e+(t[0]?1:0)}),0)}},{key:"sourceBufferTypes",get:function(){return this.sourceBuffers.map((function(e){return e[0]})).filter((function(e){return!!e}))}}])}(ue);function ms(e){var t=e.querySelectorAll("source");[].slice.call(t).forEach((function(t){e.removeChild(t)}))}function ps(e){return"audio"===e?1:0}function ys(e,t){return(e?"":" - triggering recovery")+(t?" with HTMLMediaElement Error: "+t.message:"")}function Es(e){return e.type+"_"+e.sn+"_"+e.level}function Ts(e,t){for(var r=t.start,i=t.end,n=0,a=0;a=i)break;var o=Math.max(r,s.start),l=Math.min(i,s.end);l>o&&(n+=l-o)}return n}function Ss(e,t){return t.duration-e<=.05}var As=function(){function e(e){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.destroy=function(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0},t.registerListeners=function(){var e=this.hls;e&&(e.on(G.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.BUFFER_CODECS,this.onBufferCodecs,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this))},t.unregisterListener=function(){var e=this.hls;e&&(e.off(G.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this))},t.onFpsDropLevelCapping=function(e,t){if(this.hls){var r=this.hls.levels[t.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}},t.onMediaAttaching=function(e,t){var r=t.media;this.clientRect=null,this.hls&&(r instanceof HTMLVideoElement?(this.media=r,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())},t.onManifestParsed=function(e,t){this.restrictedLevels=[],t.video&&this.startCapping(),this.onLevelsUpdated()},t.onLevelsUpdated=function(){if(this.hls)if((this.timer||this.observer)&&(x(this.autoLevelCapping)||this.clientRect))this.detectPlayerSize();else if(void 0===this.observer&&void 0===this.timer){var e=this.hls.levels;e.length>1&&e.some((function(e){return!!e.videoCodec}))&&this.startCapping()}},t.onBufferCodecs=function(e,t){t.video&&this.startCapping()},t.onMediaDetaching=function(){this.stopCapping(),this.media=null},t.detectPlayerSize=function(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls)return void(this.clientRect=null);var e=this.hls.levels;if(e.length>1){var t=this.hls,r=this.getMaxLevel(e.length-1);r!==this.autoLevelCapping&&t.logger.log("Setting autoLevelCapping to "+r+": "+e[r].height+"p@"+e[r].bitrate+" for media "+this.mediaWidth+"x"+this.mediaHeight),t.autoLevelCapping=r,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}else 1===e.length&&this.stopCapping()}},t.getMaxLevel=function(t){var r=this;if(!this.hls)return-1;var i=this.hls.levels;if(!i.length)return-1;var n=i.filter((function(e,i){return r.isLevelAllowed(e)&&i<=t}));return this.observer||(this.clientRect=null),e.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)},t.observe=function(){var e=this,t=self.ResizeObserver;t&&(this.observer=new t((function(t){var r,i=null==(r=t[0])?void 0:r.contentRect;i&&(e.clientRect=i,e.detectPlayerSize())}))),this.observer&&this.media&&this.observer.observe(this.media)},t.startCapping=function(){var e;this.timer||this.observer||null==(e=this.hls)||!e.config.capLevelToPlayerSize||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())},t.stopCapping=function(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)},t.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},t.isLevelAllowed=function(e){return!this.restrictedLevels.some((function(t){return e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height}))},e.getMaxLevelByMediaSize=function(e,t,r){if(null==e||!e.length)return-1;for(var i,n,a=e.length-1,s=Math.max(t,r),o=0;o=s||l.height>=s)&&(i=l,!(n=e[o+1])||i.width!==n.width||i.height!==n.height)){a=o;break}}return a},a(e,[{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 e=1;if(!this.hls)return e;var t=this.hls.config,r=t.ignoreDevicePixelRatio,i=t.maxDevicePixelRatio;if(!r)try{e=self.devicePixelRatio}catch(e){}return Math.min(e,i)}}])}(),Is=function e(t,r){Array.isArray(t)&&(t=t.map((function(t){return t instanceof e?t:new e(t)}))),this.value=t,this.params=r},Ls="Dict";function Rs(e,t,r,i){return new Error("failed to "+e+' "'+(n=t,(Array.isArray(n)?JSON.stringify(n):n instanceof Map?"Map{}":n instanceof Set?"Set{}":"object"==typeof n?JSON.stringify(n):String(n))+'" as ')+r,{cause:i});var n}var bs="Bare Item",ks="Boolean",Ds="Byte Sequence",Ps="Decimal",_s="Integer",Cs="String",ws=/[\x00-\x1f\x7f]+/,Os=function(e){this.description=e},Ms="Token",xs="Key";function Fs(e,t,r){return Rs("serialize",e,t,r)}function Ns(e){if(!1===ArrayBuffer.isView(e))throw Fs(e,Ds);return":"+(t=e,btoa(String.fromCharCode.apply(String,t))+":");var t}function Us(e){if(function(e){return e<-999999999999999||99999999999999912)throw Fs(e,Ps);var r=t.toString();return r.includes(".")?r:r+".0"}function Gs(e){var t,r=(t=e).description||t.toString().slice(7,-1);if(!1===/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(r))throw Fs(r,Ms);return r}function Ks(e){switch(typeof e){case"number":if(!x(e))throw Fs(e,bs);return Number.isInteger(e)?Us(e):Bs(e);case"string":return function(e){if(ws.test(e))throw Fs(e,Cs);return'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'}(e);case"symbol":return Gs(e);case"boolean":return function(e){if("boolean"!=typeof e)throw Fs(e,ks);return e?"?1":"?0"}(e);case"object":if(e instanceof Date)return function(e){return"@"+Us(e.getTime()/1e3)}(e);if(e instanceof Uint8Array)return Ns(e);if(e instanceof Os)return Gs(e);default:throw Fs(e,bs)}}function Vs(e){if(!1===/^[a-z*][a-z0-9\-_.*]*$/.test(e))throw Fs(e,xs);return e}function Hs(e){return null==e?"":Object.entries(e).map((function(e){var t=e[0],r=e[1];return!0===r?";"+Vs(t):";"+Vs(t)+"="+Ks(r)})).join("")}function Ys(e){return e instanceof Is?""+Ks(e.value)+Hs(e.params):Ks(e)}function js(e,t){var r;if(void 0===t&&(t={whitespace:!0}),"object"!=typeof e||null==e)throw Fs(e,Ls);var i=e instanceof Map?e.entries():Object.entries(e),n=null!=(r=t)&&r.whitespace?" ":"";return Array.from(i).map((function(e){var t=e[0],r=e[1];r instanceof Is==0&&(r=new Is(r));var i,n=Vs(t);return!0===r.value?n+=Hs(r.params):(n+="=",Array.isArray(r.value)?n+="("+(i=r).value.map(Ys).join(" ")+")"+Hs(i.params):n+=Ys(r)),n})).join(","+n)}function Ws(e,t){return js(e,t)}var qs,Xs=["url"],zs=["version","eventTargets","sid","transmissionMode"],Qs=["customData","headers"],$s=function(e){return e instanceof Is?new Is(Math.round(e.value),e.params):Math.round(e)},Zs=function(e){return Array.isArray(e)?e.map($s):$s(e)},Js=function(e,t){return Array.isArray(e)?e.map((function(e){return Js(e,t)})):e instanceof Is&&"string"==typeof e.value?new Is(Js(e.value,t),e.params):(t.baseUrl&&(e=function(e,t){var r;try{r=new URL(e)}catch(t){return e}var i=new URL(t);if(r.origin!==i.origin)return e;for(var n=r.pathname.split("/").slice(1),a=i.pathname.split("/").slice(1,-1),s=Math.min(n.length,a.length),o=0;o=2&&(e instanceof Is&&"string"==typeof e.value?r=new Is([e]):"string"==typeof e&&(r=[e])),Js(r,t)},rtp:to,tb:Zs},io=2,no="pr",ao="b",so="rr",oo="ce",lo="bc",uo="e",ho=so,fo=oo,co=new Map([["ps","sta"],[no,"pr"],["c","cid"],[ao,"bg"],["bc","br"]]),go="event",vo="request",mo=["cen","e","h","ts"],po=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],yo=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Eo(e){return yo.test(e)}var To=new Set(po);function So(e){return To.has(e)||Eo(e)}var Ao=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],Io=new Set(Ao);function Lo(e){return Io.has(e)}var Ro=new Set(mo),bo=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),ko=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],Do=new Set(ko);function Po(e){return Do.has(e)||Eo(e)}var _o=new Set(["ot","sf","st","e","sta"]);function Co(e){return _o.has(e)}function wo(e){return"number"==typeof e?x(e):null!=e&&""!==e&&!1!==e}var Oo=((qs={})[go]=function(e){return So(e)||Lo(e)||Ro.has(e)},qs[vo]=So,qs);function Mo(e,t){var r;return Array.isArray(e)?(t&&(r=e.find((function(e){var r;return(null==(r=e.params)?void 0:r.ot)===t}))),r||(r=e[0]),Mo(r)):e instanceof Is?e.value:e}function xo(e,t){void 0===t&&(t={});var r={};if(null==e||"object"!=typeof e)return r;var i=t.version||e.v||io,n=t.reportingMode||vo,a=1===i?function(e){for(var t={},r=0,i=Object.entries(e);r1&&!l.includes("v")&&l.push("v");var c={version:i,reportingMode:n,baseUrl:t.baseUrl};l.sort();for(var g,v=s(l);!(g=v()).done;){var m,p,y=g.value,E=a[y],T=null!=(m=null==(p=t.formatters)?void 0:p[y])?m:ro[y];if("function"==typeof T&&(E=T(E,c)),"v"===y){if(1===i)continue;E=i}if("pr"!==y||1!==E||d&&a.e===no){d&&"ts"===y&&!x(E)&&(E=Date.now());var S=d&&!1===E&&"bg"===y&&a.e===ao;(wo(E)||S)&&(Co(y)&&"string"==typeof E&&(E=new Os(E)),r[y]=E)}}return r}var Fo="CMCD-Object",No="CMCD-Request",Uo="CMCD-Session",Bo="CMCD-Status",Go={REQUEST:No},Ko={ab:Fo,br:Fo,d:Fo,lab:Fo,lb:Fo,ot:Fo,tab:Fo,tb:Fo,tpb:Fo,bl:No,cs:No,dfa:No,dl:No,ltc:No,mtp:No,nor:No,nrr:No,pb:No,sn:No,sta:No,su:No,tbl:No,cid:Uo,msd:Uo,sf:Uo,sid:Uo,st:Uo,v:Uo,bg:Bo,bs:Bo,bsa:Bo,bsd:Bo,bsda:Bo,cdn:Bo,ec:Bo,nr:Bo,pr:Bo,pt:Bo,rtp:Bo};function Vo(e,t){var r={};if(!e)return r;for(var i,n=Object.keys(e),a=t?(i=t,Object.keys(i).reduce((function(e,t){var r;return null==(r=i[t])||r.forEach((function(r){return e[r]=t})),e}),{})):{},s=0,o=n;s0)}})),r&&this.processEventTargets()},t.sendEventReport=function(){var e,t=(e=v().m((function e(t,r){var i,n,a;return v().w((function(e){for(;;)switch(e.n){case 0:return i=ul(go,t),e.n=1,this.requester({url:t.url,method:"POST",headers:{"Content-Type":"application/cmcd"},body:r.map((function(e){return jo(e,i)})).join("\n")+"\n"});case 1:if(n=e.v,410!==(a=n.status)){e.n=2;break}this.disposeEventTarget(t),e.n=3;break;case 2:if(!(429===a||a>499&&a<600)){e.n=3;break}throw new Error("Event report failed with status "+a);case 3:return e.a(2)}}),e,this)})),function(){var t=this,r=arguments;return new Promise((function(n,a){var s=e.apply(t,r);function o(e){i(s,n,a,o,l,"next",e)}function l(e){i(s,n,a,o,l,"throw",e)}o(void 0)}))});return function(e,r){return t.apply(this,arguments)}}(),t.disarmInterval=function(e){clearInterval(e.intervalId),e.intervalId=void 0},t.disposeEventTarget=function(e){var t=this.eventTargets.get(e);t&&(this.disarmInterval(t),this.eventTargets.delete(e))},t.resetSession=function(){this.eventTargets.forEach((function(e){return e.sn=0})),this.requestTarget.sn=0,this.lastEmitted={}},e}(),ml="h",pl="v",yl="l",El="ll";new Set(ko),new Set(Wo);var Tl=["includeKeys"];function Sl(e){return Object.keys(e).every(Eo)}var Al=function(){function e(e){var t=this;this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=function(){t.initialized&&(t.starved=!0,t.setPlayerState(rl)),t.buffering=!0},this.onPlay=function(){t.initialized||t.setPlayerState(Jo)},this.onPlaying=function(){t.initialized||(t.initialized=!0),t.buffering=!1,t.setPlayerState(el)},this.onPause=function(){t.media&&!t.media.ended&&t.setPlayerState(il)},this.onSeeking=function(){t.initialized&&t.setPlayerState(tl)},this.onSeeked=function(){var e;t.initialized&&null!=(e=t.media)&&e.paused&&t.setPlayerState(il)},this.onRateChange=function(){t.reporter&&t.media&&t.reporter.update({pr:t.media.playbackRate})},this.applyPlaylistData=function(e){try{t.apply(e,{ot:qo,su:!t.initialized})}catch(e){t.hls.logger.warn("Could not generate manifest CMCD data.",e)}},this.applyFragmentData=function(e){try{var r=e.frag,i=e.part,n=t.hls.levels[r.level],a=t.getObjectType(r,n),s={d:1e3*(i||r).duration,ot:a};if(a===zo||a===Xo||a===Qo||null==a&&("main"===r.type||"audio"===r.type)){var o,l=n.bitrate/1e3;s.br=[l];var u=t.config.cmcd,d=null!=(o=null==u?void 0:u.rtpSafetyFactor)?o:5;if(s.rtp=100*Math.round(l*d/100),a===Qo||null==a&&"main"===r.type){var h=t.getTopBandwidth()/1e3;x(h)&&(s.tb=[h]);var f=t.getLowestBandwidth()/1e3;x(f)&&(s.lb=[f])}var c=t.getBufferLength(r);if(x(c)){var g;s.bl=[c];var v=(null==(g=t.media)?void 0:g.playbackRate)||1;s.dl=100*Math.round(c/v/100)}t.playheadLevel&&(s.pb=[t.playheadLevel.bitrate/1e3]);var m=t.hls.maxAutoLevel;if(m>=0){var p=t.hls.levels[m];p&&(s.tpb=[p.bitrate/1e3])}}var y=i?t.getNextPart(i):t.getNextFrag(r);null!=y&&y.url&&y.url!==r.url&&(y.byteRange.length>0?s.nor=[(E=y.url,T={r:y.byteRange[0]+"-"+y.byteRange[1]},new Is(E,T))]:s.nor=[y.url]),t.apply(e,s)}catch(e){t.hls.logger.warn("Could not generate segment CMCD data.",e)}var E,T},this.recordFragmentResponse=function(e,r,i){var n,a=t.config.cmcd,s=null==a||null==(n=a.eventTargets)?void 0:n.some((function(e){var t;return null==(t=e.events)?void 0:t.includes(ho)}));if(t.reporter&&i.loading.first>0&&s)try{t.reporter.recordResponseReceived({request:{url:e},status:r.code,resourceTiming:{startTime:i.loading.start,responseStart:i.loading.first,duration:i.loading.end-i.loading.start,encodedBodySize:i.total}})}catch(e){t.hls.logger.warn("Could not record fragment response CMCD data.",e)}},this.hls=e;var r=this.config=e.config;null!=r.cmcd&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.registerListeners())}var t=e.prototype;return t.createReporter=function(){var e,t,r=this.config.cmcd;if(null!=r){var i=r.version||1;if(this.reporter=new vl({sid:r.sessionId||this.hls.sessionId,cid:r.contentId,version:i,transmissionMode:!0===r.useHeaders?ll:ol,enabledKeys:null!=(e=r.includeKeys)?e:[].concat(i>=io?Wo:ko),eventTargets:(null!=(t=r.eventTargets)?t:[]).map((function(e){var t=e.includeKeys;return c(c({},g(e,Tl)),{},{enabledKeys:null!=t?t:Wo})}))},r.loader),this.reporter.update({sf:ml,sta:this.playerState}),r.reporterCallback){var n=this.reporter,a={updateCustomData:function(e){Sl(e)&&n.update(e)},recordCustomEvent:function(e,t){void 0===t&&(t={}),Sl(t)&&n.recordEvent(fo,c({cen:e},t))}};r.reporterCallback(a)}this.reporter.start()}},t.registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_DETACHED,this.onMediaDetached,this),e.on(G.MEDIA_ENDED,this.onMediaEnded,this),e.on(G.ERROR,this.onError,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.LEVEL_SWITCHED,this.onLevelSwitched,this),e.on(G.BUFFER_APPENDED,this.onBufferInfoChange,this),e.on(G.BUFFER_FLUSHED,this.onBufferInfoChange,this)},t.unregisterListeners=function(){var e=this.hls;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_DETACHED,this.onMediaDetached,this),e.off(G.MEDIA_ENDED,this.onMediaEnded,this),e.off(G.ERROR,this.onError,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.LEVEL_SWITCHED,this.onLevelSwitched,this),e.off(G.BUFFER_APPENDED,this.onBufferInfoChange,this),e.off(G.BUFFER_FLUSHED,this.onBufferInfoChange,this)},t.destroy=function(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null},t.onMediaAttaching=function(e,t){var r=this.media=t.media;this.setPlayerState(this.media.autoplay?Jo:sl),An(r,"waiting",this.onWaiting),An(r,"play",this.onPlay),An(r,"playing",this.onPlaying),An(r,"pause",this.onPause),An(r,"seeking",this.onSeeking),An(r,"seeked",this.onSeeked),An(r,"ratechange",this.onRateChange)},t.onMediaDetached=function(){var e=this.media;e&&(In(e,"waiting",this.onWaiting),In(e,"play",this.onPlay),In(e,"playing",this.onPlaying),In(e,"pause",this.onPause),In(e,"seeking",this.onSeeking),In(e,"seeked",this.onSeeked),In(e,"ratechange",this.onRateChange),this.media=null)},t.onMediaEnded=function(e,t){this.setPlayerState(nl)},t.onManifestLoading=function(e,t){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(sl)},t.onError=function(e,t){t.fatal&&(this.setPlayerState(al),this.reporter&&this.reporter.recordEvent(uo,{ec:[t.details]}))},t.onLevelSwitching=function(e,t){var r;if(this.reporter){var i={br:[t.bitrate/1e3]},n=null==(r=t.details)?void 0:r.fragments[0];n&&(i.ot=this.getObjectType(n,t)),this.reporter.recordEvent(lo,i)}},t.onLevelSwitched=function(e,t){var r=this.hls.levels[t.level];r&&(this.playheadLevel=r)},t.setPlayerState=function(e){this.playerState=e,this.reporter&&this.reporter.update({sta:e})},t.getStreamType=function(){var e=this.hls.latestLevelDetails;if(e)return e.live?e.partList&&e.canBlockReload?El:yl:pl},t.apply=function(e,t){var r;if(void 0===t&&(t={}),this.reporter){this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:null==(r=this.media)?void 0:r.playbackRate,st:this.getStreamType()});var i=t.ot===$o||t.ot===zo||t.ot===Qo;this.starved&&i&&(t.bs=!0,t.su=!0,this.starved=!1),null==t.su&&(t.su=this.buffering);var n=this.reporter.createRequestReport({url:e.url,headers:e.headers},t);e.url=n.url,e.headers=n.headers}},t.getNextFrag=function(e){var t,r=null==(t=this.hls.levels[e.level])?void 0:t.details;if(r){var i=e.sn-r.startSN;return r.fragments[i+1]}},t.getNextPart=function(e){var t,r=e.index,i=e.fragment,n=null==(t=this.hls.levels[i.level])||null==(t=t.details)?void 0:t.partList;if(n)for(var a=i.sn,s=n.length-1;s>=0;s--){var o=n[s];if(o.index===r&&o.fragment.sn===a)return n[s+1]}},t.getObjectType=function(e,t){var r=e.type;if("subtitle"===r)return Zo;if("initSegment"===e.sn)return $o;if("audio"===r)return Xo;if("main"===r){if(e.hasStreams){var i=e.elementaryStreams;if(i.audiovideo)return Qo;if(i.video)return zo;if(i.audio)return Xo}if(t){var n=t.audioCodec,a=t.videoCodec;if(!this.hls.audioTracks.length){if(n&&a)return Qo;if(n)return Xo}if(a)return zo}}},t.getTopBandwidth=function(){var e=0,t=this.hls,r=t.maxAutoLevel,i=r>-1?r+1:t.levels.length;return t.levels.slice(0,i).forEach((function(t){t.bitrate>e&&(e=t.bitrate)})),e>0?e:NaN},t.getLowestBandwidth=function(){var e=1/0,t=this.hls,r=t.maxAutoLevel,i=r>-1?r+1:t.levels.length;return t.levels.slice(0,i).forEach((function(t){t.bitrate0)return void this.scheduleRefresh(this.uri,e)}this.loadSteeringManifest(this.uri)}},r.stopLoad=function(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()},r.clearTimeout=function(){-1!==this.reloadTimer&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)},r.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null},r.removeLevel=function(e){var t=this.levels;t&&(this.levels=t.filter((function(t){return t!==e})))},r.onManifestLoading=function(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null},r.onManifestLoaded=function(e,t){var r=t.contentSteering;null!==r&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())},r.onManifestParsed=function(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks},r.onError=function(e,t){var r=t.errorAction;if((null==r?void 0:r.action)===Lr&&r.flags&Dr){var i=this.levels,n=this._pathwayPriority,a=this.pathwayId;if(t.context){var s=t.context,o=s.groupId,l=s.pathwayId,u=s.type;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!n&&i&&(n=this.pathways()),n&&n.length>1&&(this.updatePathwayPriority(n),r.resolved=this.pathwayId!==a,r.resolved||t.details===B.BUFFER_APPEND_ERROR&&!t.fatal||this.warn("Could not resolve "+t.details+' ("'+t.error.message+'") with content-steering for Pathway: '+a+" levels: "+(i?i.length:i)+" priorities: "+ar(n)+" penalized: "+ar(this.penalizedPathways)))}},r.filterParsedLevels=function(e){this.levels=e;var t=this.getLevelsForPathway(this.pathwayId);if(0===t.length){var r=e[0].pathwayId;this.log("No levels found in Pathway "+this.pathwayId+'. Setting initial Pathway to "'+r+'"'),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log("Found "+t.length+"/"+e.length+' levels in Pathway "'+this.pathwayId+'"'),t},r.getLevelsForPathway=function(e){return null===this.levels?[]:this.levels.filter((function(t){return e===t.pathwayId}))},r.updatePathwayPriority=function(e){var t;this._pathwayPriority=e;var r=this.penalizedPathways,i=performance.now();Object.keys(r).forEach((function(e){i-r[e]>3e5&&delete r[e]}));for(var n=0;n0){this.log('Setting Pathway to "'+a+'"'),this.pathwayId=a,vn(t),this.hls.trigger(G.LEVELS_UPDATED,{levels:t});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}}}},r.getPathwayForGroupId=function(e,t,r){for(var i=this.getLevelsForPathway(r).concat(this.levels||[]),n=0;n0}},{key:"resolved",get:function(){return this.ok}},{key:"useable",get:function(){var e=this;return this.ok?Promise.resolve():this.error?Promise.reject(this.error):new Promise((function(t,r){e.emitter.on("error",r),e.emitter.on("resolved",t)}))}}])}(),kl=function(e){function t(t,r){var i;return(i=e.call(this,r)||this).data=void 0,t.error||(t.error=new Error(r)),i.data=t,t.err=t.error,i}return d(t,e),t}(E(Error)),Dl=function(e){function t(r){var i;return(i=e.call(this,"eme",r.logger)||this).hls=void 0,i.config=void 0,i.media=null,i.mediaResolved=void 0,i.keyFormatPromise=null,i.keySystemAccessPromises={},i.sessionSetupByUri={},i.mediaKeySessions=[],i.activeKeys={},i.mediaKeys=null,i.setMediaKeysQueue=t.CDMCleanupPromise?[t.CDMCleanupPromise]:[],i.onMediaEncrypted=function(e){var t=e.initDataType,r=e.initData,n='"'+e.type+'" event: init data type: "'+t+'"';if(i.log(n),null!==r){if(!i.keyFormatPromise){var a=Object.keys(i.keySystemAccessPromises);a.length||(a=Mi(i.config));var s=a.map(Oi).filter((function(e){return!!e}));i.keyFormatPromise=i.getKeyFormatPromise(s)}i.keyFormatPromise.then((function(a){var s,o,l=Ci(a),u=i.activeLevelKeys();if(l===bi.FAIRPLAY&&"sinf"===t)try{var d=Ue(new Uint8Array(r)),h=lt(Ne(JSON.parse(d).sinf));if(!h)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=new Uint8Array(h.subarray(8,24))}catch(e){return void i.warn(n+" Failed to parse sinf: "+e)}else if(l===bi.PLAYREADY)s=Ni(new Uint8Array(r));else if(l===bi.WIDEVINE){var f=pt(r).filter((function(e){return e.systemId===wi}));if(f.length){var c,g=f[0];s=null!=(c=g.kids)&&c.length?g.kids[0]:null}}if(s)for(var v=xe(s),m=0;m0)for(var a,s=0,o=n.length;s in key message");return Ai(atob(c))},r.setupLicenseXHR=function(e,t,r,i,n){var a=this,s=this.config.licenseXhrSetup;return s?Promise.resolve().then((function(){return a.throwIfDestroyed(),s.call(a.hls,e,t,c(c({},r),{},{decryptdata:i}),n)})).catch((function(o){if(!r.mediaKeysSession)throw o;return e.open("POST",t,!0),s.call(a.hls,e,t,c(c({},r),{},{decryptdata:i}),n)})).then((function(r){return e.readyState||e.open("POST",t,!0),{xhr:e,licenseChallenge:r||n}})):(e.open("POST",t,!0),Promise.resolve({xhr:e,licenseChallenge:n}))},r.requestLicense=function(e,t,r){var i=this;return new Promise((function(n,a){var s,o,l,u,d,h=(s=e.keySystem,o=i.config,l=o.drmSystems,u=o.widevineLicenseUrl,(d=null==l?void 0:l[s])?d.licenseUrl:s===bi.WIDEVINE&&u?u:void 0);if(!h)return a(new Error('no license server URL configured for key-system "'+e.keySystem+'"'));var f=e.keyRequests[t.uri];if(!f)return a(new Error("License emitter removed"));i.log("Sending license request to URL: "+h);var g=i.config.keyLoadPolicy.default,v=new XMLHttpRequest;v.responseType="arraybuffer",v.onreadystatechange=function(){if(!i.hls||!e.mediaKeysSession)return a(new Error("invalid state"));if(4===v.readyState)if(200===v.status){f.requestErrors=[];var s=v.response;i.log("License received "+(s instanceof ArrayBuffer?s.byteLength:s));var o=i.config.licenseResponseCallback;if(o)try{s=o.call(i.hls,v,h,c(c({},e),{},{decryptdata:t}))}catch(e){i.error(e)}n(s)}else{var l=g.errorRetry,u=l?l.maxNumRetry:0;if(f.requestErrors.push({status:v.status,message:v.statusText}),f.requestErrors.length>u||v.status>=400&&v.status<500)a(new kl({type:U.KEY_SYSTEM_ERROR,details:B.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t,fatal:!0,networkDetails:v,response:{url:h,data:void 0,code:v.status,text:v.statusText}},"License Request XHR failed ("+h+"). Status: "+v.status+" ("+v.statusText+")"));else{var d=u-f.requestErrors.length;i.warn("Retrying license request, "+d+" attempts left"),i.requestLicense(e,t,r).then(n,a)}}},f.licenseXhr&&f.licenseXhr.readyState!==XMLHttpRequest.DONE&&f.licenseXhr.abort(),f.licenseXhr=v,i.setupLicenseXHR(v,h,e,t,r).then((function(t){var r=t.xhr,n=t.licenseChallenge;e.keySystem==bi.PLAYREADY&&(n=i.unpackPlayReadyKeyMessage(r,n)),r.send(n)})).catch(a)}))},r.onDestroying=function(){this.unregisterListeners(),this._clear()},r.onMediaAttached=function(e,t){if(this.config.emeEnabled){var r=t.media;this.media=r,An(r,"encrypted",this.onMediaEncrypted),An(r,"waitingforkey",this.onWaitingForKey);var i=this.mediaResolved;i?i():this.mediaKeys=r.mediaKeys}},r.onMediaDetached=function(){var e=this.media;e&&(In(e,"encrypted",this.onMediaEncrypted),In(e,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)},r._clear=function(){var e,r=this;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};var i=this.mediaResolved;if(i&&i(),this.mediaKeys||this.mediaKeySessions.length){var n=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Bi.clearKeyUriToKeyIdMap();var s=a.length;t.CDMCleanupPromise=Promise.all(a.map((function(e){return r.removeSession(e)})).concat((null==n||null==(e=n.setMediaKeys(null))?void 0:e.catch((function(e){r.log("Could not clear media keys: "+e),r.hls&&r.hls.trigger(G.ERROR,{type:U.OTHER_ERROR,details:B.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error("Could not clear media keys: "+e)})})))||Promise.resolve())).catch((function(e){r.log("Could not close sessions and clear media keys: "+e),r.hls&&r.hls.trigger(G.ERROR,{type:U.OTHER_ERROR,details:B.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close sessions and clear media keys: "+e)})})).then((function(){s&&r.log("finished closing key sessions and clearing media keys")}))}},r.onManifestLoading=function(){this._clear(),this.keyFormatPromise=null},r.onManifestLoaded=function(e,t){var r=t.sessionKeys;if(r&&this.config.emeEnabled&&!this.keyFormatPromise){var i=r.reduce((function(e,t){return-1===e.indexOf(t.keyFormat)&&e.push(t.keyFormat),e}),[]);this.log("Selecting key-system from session-keys "+i.join(", ")),this.keyFormatPromise=this.getKeyFormatPromise(i),this.keyFormatPromise.catch((function(){}))}},r.removeSession=function(e){var t=this,r=e.mediaKeysSession;if(r){this.log('Remove licenses and keys and close session "'+r.sessionId+'"'),Object.keys(e.keyRequests).forEach((function(t){var i=e.keyRequests[t];i.onmessage&&r.removeEventListener("message",i.onmessage),i.onkeystatuseschange&&r.removeEventListener("keystatuseschange",i.onkeystatuseschange),i.reset(),e.keyRequests[t]=void 0})),e.mediaKeysSession=void 0;var i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);var n=e.keyStatusTimeouts;n&&Object.keys(n).forEach((function(e){return self.clearTimeout(n[e])}));var a=function(e){var t;return!(!e||"persistent-license"!==e.sessionType&&(null==(t=e.sessionTypes)||!t.some((function(e){return"persistent-license"===e}))))}(this.config.drmSystemOptions)?new Promise((function(e,t){self.setTimeout((function(){return t(new Error("MediaKeySession.remove() timeout"))}),8e3),r.remove().then(e).catch(t)})):Promise.resolve();return a.catch((function(e){t.log("Could not remove session: "+e),t.hls&&t.hls.trigger(G.ERROR,{type:U.OTHER_ERROR,details:B.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error("Could not remove session: "+e)})})).then((function(){return r.close()})).then((function(){return r.closed})).catch((function(e){t.log("Could not close session: "+e),t.hls&&t.hls.trigger(G.ERROR,{type:U.OTHER_ERROR,details:B.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error("Could not close session: "+e)})}))}return Promise.resolve()},t}(ue);function Pl(e,t){var r=e.keyId,i=t.mediaKeysSession;if(r&&i){var n=t.mediaKeysSession.keyStatuses;if(n.size)return n.has(r)?n.get(r):t.keyStatuses[xe(r)]}}function _l(e,t){var r="output-restricted"===e,i=r?B.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:B.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new kl({type:U.KEY_SYSTEM_ERROR,details:i,fatal:!1,decryptdata:t},r?"HDCP level output restricted":'key status changed to "'+e+'"')}Dl.CDMCleanupPromise=void 0;var Cl=function(){function e(e){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=e,this.registerListeners()}var t=e.prototype;return t.setStreamController=function(e){this.streamController=e},t.registerListeners=function(){this.hls.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(G.MEDIA_DETACHING,this.onMediaDetaching,this)},t.unregisterListeners=function(){this.hls.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(G.MEDIA_DETACHING,this.onMediaDetaching,this)},t.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},t.onMediaAttaching=function(e,t){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=t.media instanceof self.HTMLVideoElement?t.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)}},t.onMediaDetaching=function(){this.media=null},t.checkFPS=function(e,t,r){var i=performance.now();if(t){if(this.lastTime){var n=i-this.lastTime,a=r-this.lastDroppedFrames,s=t-this.lastDecodedFrames,o=1e3*a/n,l=this.hls;if(l.trigger(G.FPS_DROP,{currentDropped:a,currentDecoded:s,totalDroppedFrames:r}),o>0&&a>l.config.fpsDroppedMonitoringThreshold*s){var u=l.currentLevel;l.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(-1===l.autoLevelCapping||l.autoLevelCapping>=u)&&(u-=1,l.trigger(G.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:l.currentLevel}),l.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=t}},t.checkFPSInterval=function(){var e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){var t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)},e}(),wl=function(e){function t(t,r){var i;return(i=e.call(this,"gap-controller",t.logger)||this).hls=void 0,i.fragmentTracker=void 0,i.media=null,i.mediaSource=void 0,i.nudgeRetry=0,i.skipRetry=0,i.stallReported=!1,i.stalled=null,i.moved=!1,i.seeking=!1,i.buffered={},i.lastCurrentTime=void 0,i.ended=0,i.waiting=0,i.onMediaPlaying=function(){i.ended=0,i.waiting=0},i.onMediaWaiting=function(){var e;null!=(e=i.media)&&e.seeking||(i.waiting=self.performance.now(),i.tick())},i.onMediaEnded=function(){var e;i.hls&&(i.ended=(null==(e=i.media)?void 0:e.currentTime)||1,i.hls.trigger(G.MEDIA_ENDED,{stalled:!1}))},i.hls=t,i.fragmentTracker=r,i.lastCurrentTime=i.getCurrentTime(),i.registerListeners(),i}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.BUFFER_APPENDED,this.onBufferAppended,this))},r.destroy=function(){e.prototype.destroy.call(this),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0},r.onMediaAttached=function(e,t){this.setInterval(100),this.mediaSource=t.mediaSource;var r=this.media=t.media;An(r,"playing",this.onMediaPlaying),An(r,"waiting",this.onMediaWaiting),An(r,"ended",this.onMediaEnded)},r.onMediaDetaching=function(e,t){this.clearInterval();var r=this.media;r&&(In(r,"playing",this.onMediaPlaying),In(r,"waiting",this.onMediaWaiting),In(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0},r.onBufferAppended=function(e,t){this.buffered=t.timeRanges},r.getCurrentTime=function(){var e,t=(null==(e=this.hls)?void 0:e.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,t):t},r.tick=function(){var e;if(null!=(e=this.media)&&e.readyState&&this.hasBuffered){var t=this.getCurrentTime();this.media.currentTimet&&this.nudgeOnVideoHole(e,t)),void(0===this.waiting&&this.stallResolved(e));if(l||o)o&&this.stallResolved(e);else{if(u)return this.skipRetry=this.nudgeRetry=0,this.stallResolved(e),void(!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(G.MEDIA_ENDED,{stalled:!1})));if(si.getBuffered(a).length){var d=si.bufferInfo(a,e,0),h=this.fragmentTracker;h&&this.hls&&Fl(d,e,h,this.hls);var f=d.nextStart||0;if(s&&h&&this.hls){var c=Ol(this.hls.inFlightFragments,e),g=d.len>2,v=!f||c||f-e>2&&!h.getPartialFragment(e);if(g||v)return;this.moved=!1}var m=null==(i=this.hls)?void 0:i.latestLevelDetails;if(!this.moved&&null!==this.stalled&&h){if(!(d.len>0||f))return;var p=Math.max(f,d.start||0)-e,y=null!=m&&m.live?2*m.targetduration:2,E=xl(e,h);if(p>0&&(p<=y||E))return void(a.paused||this._trySkipBufferHole(E))}var T=n.detectStallWithCurrentTimeMs,S=self.performance.now(),A=this.waiting,I=this.stalled;if(null===I){if(!(A>0&&S-A=T||A&&this.moved)&&this.hls){var R;if("ended"===(null==(R=this.mediaSource)?void 0:R.readyState)&&(null==m||!m.live)&&Math.abs(e-((null==m?void 0:m.edge)||0))<1){if(this.ended)return;return this.ended=e||1,void this.hls.trigger(G.MEDIA_ENDED,{stalled:!0})}if(this._reportStall(d),!this.media||!this.hls)return;if(a.currentTime!==e){var b=e;return e=a.currentTime,this.moved=!0,void this.log("currentTime changed "+b+" > "+e)}}var k=si.bufferInfo(a,e,n.maxBufferHole);this._tryFixBufferStall(k,L,e)}else this.skipRetry=this.nudgeRetry=0}}}},r.stallResolved=function(e){var t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){var r=self.performance.now()-t;this.log("playback not stuck anymore @"+e+", after "+Math.round(r)+"ms"),this.stallReported=!1,this.waiting=0,this.hls.trigger(G.STALL_RESOLVED,{})}},r.nudgeOnVideoHole=function(e,t){var r,i=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&null!=(r=this.buffered.audio)&&r.length&&i&&i.length>1&&e>i.end(0)){var n=si.bufferedInfo(si.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){var a=si.timeRangesToArray(i),s=si.bufferedInfo(a,t,0).bufferedIndex;if(s>-1&&ss)&&u-l<1&&e-l<2){var d=new Error("nudging playhead to flush pipeline after video hole. currentTime: "+e+" hole: "+l+" -> "+u+" buffered index: "+o);this.warn(d.message),this.media.currentTime+=1e-6;var h=xl(e,this.fragmentTracker);h&&"fragment"in h?h=h.fragment:h||(h=void 0);var f=si.bufferInfo(this.media,e,0);this.hls.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:d,reason:d.message,frag:h,buffer:f.len,bufferInfo:f})}}}}},r._tryFixBufferStall=function(e,t,r){var i,n,a=this.fragmentTracker,s=this.media,o=null==(i=this.hls)?void 0:i.config;if(s&&a&&o){var l=null==(n=this.hls)?void 0:n.latestLevelDetails,u=xl(r,a);if((u||null!=l&&l.live&&r1&&e.len>o.maxBufferHole||e.nextStart&&(e.nextStart-r1e3*o.highBufferWatchdogPeriod||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}},r.adjacentTraversal=function(e,t){var r=this.fragmentTracker,i=e.nextStart;if(r&&i){var n=r.getFragAtPos(t,H.MAIN),a=r.getFragAtPos(i,H.MAIN);if(n&&a)return a.sn-n.sn<2}return!1},r._reportStall=function(e){var t=this.hls,r=this.media,i=this.stallReported,n=this.stalled;if(!i&&null!==n&&r&&t){this.stallReported=!0;var a=new Error("Playback stalling at @"+r.currentTime+" due to low buffer ("+ar(e)+")");this.warn(a.message),t.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:n}})}},r._trySkipBufferHole=function(e){var t=this.fragmentTracker,r=this.media,i=this.hls,n=null==i?void 0:i.config;if(!r||!t||!n)return 0;var a=r.currentTime,s=si.bufferInfo(r,a,0);Fl(s,a,t,i);var o=a0&&s.len<1&&r.readyState<3,d=o-a;if(d>0&&(l||u)){if(d>n.maxBufferHole){var h=!1;if(0===a){var f=t.getAppendedFrag(0,H.MAIN);f&&o0)){g=!0;break}v+=p}if(g)return 0}}var y=n.nudgeMaxRetry,E=n.skipBufferHolePadding,T=++this.skipRetry>y,S=Math.max(o,a)+E;if(T||(this.warn("skipping hole, adjusting currentTime from "+a+" to "+S),this.moved=!0,r.currentTime=S),null==e||!e.gap||T){var A=new Error(T?"Playhead still not moving after seeking over buffer hole from "+a+" to "+S+" after "+n.nudgeMaxRetry+" attempts.":"fragment loaded with buffer holes, seeking from "+a+" to "+S),I={type:U.MEDIA_ERROR,details:B.BUFFER_SEEK_OVER_HOLE,fatal:T,error:A,reason:A.message,buffer:s.len,bufferInfo:s};e&&("fragment"in e?I.part=e:I.frag=e),i.trigger(G.ERROR,I)}return S}}return 0},r._tryNudgeBuffer=function(e){var t=this.hls,r=this.media,i=this.nudgeRetry,n=null==t?void 0:t.config;if(!r||!n)return 0;var a=r.currentTime;if(this.nudgeRetry++,i0}}])}(ii);function Ol(e,t){var r=Ml(e.main);if(r&&r.start<=t)return r;var i=Ml(e.audio);return i&&i.start<=t?i:null}function Ml(e){if(!e)return null;switch(e.state){case Rn.IDLE:case Rn.STOPPED:case Rn.ENDED:case Rn.ERROR:return null}return e.frag}function xl(e,t){return t.getAppendedFrag(e,H.MAIN)||t.getPartialFragment(e)}function Fl(e,t,r,i){var n=i.latestLevelDetails,a=xl(t,r);if(Dn(i.config)&&!e.nextStart&&n&&a&&i.interstitialsManager){var s="type"in a?a:a.fragment,o=Ar(n,s.sn);(null==o?void 0:o.level)===s.level&&kn(o,i.interstitialsManager.playerQueue,t)&&(e.nextStart=o.start)}}function Nl(e,t,r,i,n){void 0===i&&(i=""),void 0===n&&(n="disabled");var a=e.ownerDocument.createElement("track");return a.kind=t,a.label=r,i&&(a.srclang=i),a.src="data:,WEBVTT",a.track.mode=n,e.appendChild(a),a}function Ul(e){return e.forced&&(It.indexOf("Apple")>-1||/iPhone|iPad|iPod/.test(At))?"forced":e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function Bl(e,t){var r=e.mode;if("disabled"===r&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error("addCue is failed for: "+t)}catch(r){me.debug("[texttrack-utils]: "+r);try{var i=new self.TextTrackCue(t.startTime,t.endTime,t.text);i.id=t.id,e.addCue(i)}catch(e){me.debug("[texttrack-utils]: Legacy TextTrackCue fallback failed: "+e)}}"disabled"===r&&(e.mode=r)}function Gl(e,t,r,i){var n=e.mode;if("disabled"===n&&(e.mode="hidden"),e.cues&&e.cues.length>0)for(var a=function(e,t,r){var i=[],n=function(e,t){if(t<=e[0].startTime)return 0;var r=e.length-1;if(t>e[r].endTime)return-1;for(var i,n=0,a=r;n<=a;)if(te[i].startTime&&n-1)for(var a=n,s=e.length;a=t&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(e.cues,t,r),s=0;sHl&&(h=Hl),h-d<=0&&(h=d+.25);for(var f=0;f.01&&this.updateDateRangeCues(t.details)},t.updateDateRangeCues=function(e,t){var r=this;if(this.hls&&this.media){var i=this.hls.config,n=i.assetPlayerId,a=i.timelineOffset,s=i.enableDateRangeMetadataCues,o=i.interstitialsController;if(s){var l=Kl();if(n&&a&&!o){var u=e.fragmentStart,d=e.fragmentEnd,h=this.assetCue;h?(h.startTime=u,h.endTime=d):l&&(h=this.assetCue=Vl(l,u,d,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"))&&(h.id=n,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(h),h.addEventListener("enter",this.onEventCueEnter))}if(e.hasProgramDateTime){var f,c=this.id3Track,g=e.dateRanges,v=Object.keys(g),m=this.dateRangeCuesAppended;if(c&&t)if(null!=(f=c.track.cues)&&f.length)for(var p=Object.keys(m).filter((function(e){return-1===v.indexOf(e)})),y=function(){var e,t=p[E],i=null==(e=m[t])?void 0:e.cues;delete m[t],i&&Object.keys(i).forEach((function(e){var t=i[e];if(t){t.removeEventListener("enter",r.onEventCueEnter);try{c.track.removeCue(t)}catch(e){}}}))},E=p.length;E--;)y();else m=this.dateRangeCuesAppended={};var T=e.fragments[e.fragments.length-1];if(0!==v.length&&x(null==T?void 0:T.programDateTime)){this.id3Track||(this.id3Track=this.createTrack(this.media));for(var S=function(){var e=v[A],t=g[e],i=t.startTime,n=m[e],a=(null==n?void 0:n.cues)||{},s=(null==n?void 0:n.durationKnown)||!1,u=Hl,d=t.duration;if(t.endDate&&null!==d)u=i+d,s=!0;else if(t.endOnNext&&!s){var h=v.reduce((function(e,r){if(r!==t.id){var i=g[r];if(i.class===t.class&&i.startDate>t.startDate&&(!e||t.startDate.01&&(E.startTime=i,E.endTime=u):E.endTime=u;else if(l){var T=t.attr[y];vi(y)&&(T=Fe(T));var S=Vl(l,i,u,{key:y,data:T},Un.dateRange);S&&(S.id=e,r.id3Track.track.addCue(S),a[y]=S,o&&("X-ASSET-LIST"!==y&&"X-ASSET-URL"!==y||S.addEventListener("enter",r.onEventCueEnter)))}}}m[e]={cues:a,dateRange:t,durationKnown:s}},A=0;A1?(n=0,this.bitrateTest=!0):n=i.firstAutoLevel),i.nextLoadLevel=n,this.level=i.loadLevel,this._hasEnoughToStart=!!t}r>0&&-1===e&&!t&&this.initPTS.length&&(this.log("Override startPosition with lastCurrentTime @"+r),e=r),this.state=Rn.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,t||this.fragmentTracker.hasFragments(this.playlistType)||(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Rn.STOPPED},r.stopLoad=function(){this._forceStartLoad=!1,e.prototype.stopLoad.call(this)},r.doTick=function(){switch(this.state){case Rn.WAITING_LEVEL:var e=this.levels,t=this.level,r=null==e?void 0:e[t],i=null==r?void 0:r.details;if(i&&(!i.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(i))break;this.state=Rn.IDLE;break}if(this.hls.nextLoadLevel!==this.level){this.state=Rn.IDLE;break}break;case Rn.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate()}this.state===Rn.IDLE&&this.doTickIdle(),this.onTickEnd()},r.onTickEnd=function(){var t;e.prototype.onTickEnd.call(this),null!=(t=this.media)&&t.readyState&&!1===this.media.seeking&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()},r.doTickIdle=function(){var e=this.hls,t=this.levelLastLoaded,r=this.levels,i=this.media;if(null!==t&&(i||this.primaryPrefetch||!this.startFragRequested&&e.config.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)){var n=this.buffering?e.nextLoadLevel:e.loadLevel;if(null!=r&&r[n]){var a=r[n],s=this.getMainFwdBufferInfo();if(null!==s){var o=this.getLevelDetails();if(o&&this._streamEnded(s,o)){var l={type:this.targetBufferType()};return this.hls.trigger(G.BUFFER_EOS,l),void(this.state=Rn.ENDED)}if(this.buffering){e.loadLevel!==n&&-1===e.manualLevel&&this.log("Adapting to level "+n+" from level "+this.level),this.level=e.nextLoadLevel=n;var u=a.details;if(!u||this.state===Rn.WAITING_LEVEL||this.waitForLive(a))return this.level=n,this.state=Rn.WAITING_LEVEL,void(this.startFragRequested=!1);var d=s.len,h=this.getMaxBufferLength(a.maxBitrate);if(!(d>=h)){this.backtrackFragment&&this.backtrackFragment.start>s.end&&(this.backtrackFragment=void 0);var f=this.backtrackFragment?this.backtrackFragment.start:s.end,c=this.getNextFragment(f,u);if(this.couldBacktrack&&!this.fragPrevious&&c&&W(c)&&this.fragmentTracker.getState(c)!==Gr){var g,v=(null!=(g=this.backtrackFragment)?g:c).sn-u.startSN,m=u.fragments[v-1];m&&c.cc===m.cc&&(c=m,this.fragmentTracker.removeFragment(m))}else this.backtrackFragment&&s.len&&(this.backtrackFragment=void 0);if(c&&this.isLoopLoading(c,f)){if(!c.gap){var p=this.audioOnly&&!this.altAudio?Y.AUDIO:Y.VIDEO,y=(p===Y.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;y&&this.afterBufferFlushed(y,p)}c=this.getNextFragmentLoopLoading(c,u,s,H.MAIN,h)}c&&(this.exceedsMaxBuffer(s,h,c)||this.loadFragment(c,a,f))}}}}}},r.loadFragment=function(t,r,i){var n=this.fragmentTracker.getState(t);n===Nr||n===Br?this.bitrateTest?(this.log("Fragment "+t.sn+" of level "+t.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(t,r)):e.prototype.loadFragment.call(this,t,r,i):this.clearTrackerIfNeeded(t)},r.immediateLevelSwitch=function(){var t;this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==zl&&((null==(t=this.getLevelDetails())?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&e.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")},r.getBufferOutput=function(){return this.mediaBuffer&&this.altAudio===$l?this.mediaBuffer:this.media},r.checkFragmentChanged=function(){var e=this.fragPlaying;if(!this.checkFragPlaying())return!1;var t=this.fragPlaying;if(t){var r=t.level;this.hls.trigger(G.FRAG_CHANGED,{frag:t,previousFrag:e}),(null==e?void 0:e.level)!==r&&this.hls.trigger(G.LEVEL_SWITCHED,{level:r})}return!0},r.abortCurrentFrag=function(){this.backtrackFragment=void 0,e.prototype.abortCurrentFrag.call(this)},r.flushMainBuffer=function(t,r){e.prototype.flushMainBuffer.call(this,t,r,this.targetBufferType())},r.targetBufferType=function(){return this.altAudio!==$l||this.audioOnly?null:"video"},r.onMediaAttached=function(t,r){e.prototype.onMediaAttached.call(this,t,r);var i=r.media;An(i,"playing",this.onMediaPlaying),An(i,"seeked",this.onMediaSeeked)},r.onMediaDetaching=function(t,r){var i=this.media;i&&(In(i,"playing",this.onMediaPlaying),In(i,"seeked",this.onMediaSeeked)),this.videoBuffer=null,e.prototype.onMediaDetaching.call(this,t,r),r.transferMedia||(this._hasEnoughToStart=!1)},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.log("Trigger BUFFER_RESET"),this.hls.trigger(G.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=zl,this.audioOnly=!1},r.onManifestParsed=function(e,t){for(var r,i,n=!1,a=!1,s=0;s=o.startCC)return!0;delete i.initPTS[t]})),this.tick()}else this.warn("Levels were reset while loading level "+s)},r.synchronizeToLiveEdge=function(e){var t=this.config,r=this.media;if(r){var i=this.hls.liveSyncPosition,n=this.playhead,a=e.fragmentStart,s=e.edge,o=n>=a-t.maxFragLookUpTolerance&&n<=s;if(null!==i&&r.duration>i&&(n=this.config.appendErrorMaxRetry&&(this.warn("Marking fragment "+t.frag.sn+" of level "+t.frag.level+" as a gap after "+t.appendsWithoutProgress+" appends without buffered range growth, to prevent loop loading"),this.fragmentTracker.addAsGap(t.frag));break;case B.BUFFER_ADD_CODEC_ERROR:case B.BUFFER_APPEND_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case B.BUFFER_FULL_ERROR:if("main"!==t.parent)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case B.INTERNAL_EXCEPTION:this.recoverWorkerError(t)}},r.onFragLoadEmergencyAborted=function(){this.state=Rn.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()},r.onBufferFlushed=function(e,t){var r=t.type;if(r!==Y.AUDIO||!this.altAudio){var i=(r===Y.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;i&&(this.afterBufferFlushed(i,r),this.tick())}},r.onLevelsUpdated=function(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,-1===this.level&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels},r.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},r.seekToStartPos=function(){var e=this.media;if(e){var t=e.currentTime,r=this.startPosition;if(r>=0&&t0&&(oA.cc;if(!1!==i.independent){var R=u.startPTS,b=u.endPTS,k=u.startDTS,D=u.endDTS;if(o)o.elementaryStreams[u.type]={startPTS:R,endPTS:b,startDTS:k,endDTS:D};else if(u.firstKeyFrame&&u.independent&&1===n.id&&!L&&(this.couldBacktrack=!0),u.dropped&&u.independent){var P=this.getMainFwdBufferInfo(),_=(P?P.end:this.getLoadPosition())+this.config.maxBufferHole,C=u.firstKeyFramePTS?u.firstKeyFramePTS:R;if(!I&&_2&&(s.gap=!0);s.setElementaryStreamInfo(u.type,R,b,k,D),this.backtrackFragment&&(this.backtrackFragment=s),this.bufferFragmentData(u,s,o,n,I||L)}else{if(!I&&!L)return void this.backtrack(s);s.gap=!0}}if(g){var w=g.startPTS,O=g.endPTS,M=g.startDTS,F=g.endDTS;o&&(o.elementaryStreams[Y.AUDIO]={startPTS:w,endPTS:O,startDTS:M,endDTS:F}),s.setElementaryStreamInfo(Y.AUDIO,w,O,M,F),this.bufferFragmentData(g,s,o,n)}if(c&&null!=h&&h.samples.length){var N={id:t,frag:s,details:c,samples:h.samples};r.trigger(G.FRAG_PARSING_METADATA,N)}if(c&&d){var U={id:t,frag:s,details:c,samples:d.samples};r.trigger(G.FRAG_PARSING_USERDATA,U)}}}else this.resetWhenMissingContext(n)},r.logMuxedErr=function(e){this.warn((W(e)?"Media":"Init")+" segment with muxed audiovideo where only video expected: "+e.url)},r._bufferInitSegment=function(e,t,r,i){var n=this;if(this.state===Rn.PARSING){this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));var a=t.audio,s=t.video,o=t.audiovideo;if(a){var l=e.audioCodec,u=Nt(a.codec,l);if("mp4a"===u&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u=-1!==u.indexOf("mp4a.40.5")?"mp4a.40.2":"mp4a.40.5");var d=a.metadata;d&&"channelCount"in d&&1!==(d.channelCount||1)&&!function(){if(void 0===Tt){var e=At.match(/Firefox\/(\d+)/i);Tt=e?parseInt(e[1]):0}return Tt}()&&(u="mp4a.40.5")}u&&-1!==u.indexOf("mp4a.40.5")&&/Android/.test(At)&&"audio/mpeg"!==a.container&&(u="mp4a.40.2",this.log("Android: force audio codec to "+u)),l&&l!==u&&this.log('Swapping manifest audio codec "'+l+'" for "'+u+'"'),a.levelCodec=u,a.id=H.MAIN,this.log("Init audio buffer, container:"+a.container+", codecs[selected/level/parsed]=["+(u||"")+"/"+(l||"")+"/"+a.codec+"]"),delete t.audiovideo}if(s){s.levelCodec=e.videoCodec,s.id=H.MAIN;var h=s.codec;if(4===(null==h?void 0:h.length))switch(h){case"hvc1":case"hev1":s.codec="hvc1.1.6.L120.90";break;case"av01":s.codec="av01.0.04M.08";break;case"avc1":s.codec="avc1.42e01e"}this.log("Init video buffer, container:"+s.container+", codecs[level/parsed]=["+(e.videoCodec||"")+"/"+h+"]"+(s.codec!==h?" parsed-corrected="+s.codec:"")+(s.supplemental?" supplemental="+s.supplemental:"")),delete t.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(r),this.log("Init audiovideo buffer, container:"+o.container+", codecs[level/parsed]=["+e.codecs+"/"+o.codec+"]"),delete t.video,delete t.audio);var f=Object.keys(t);if(f.length){if(this.hls.trigger(G.BUFFER_CODECS,t),!this.hls)return;f.forEach((function(e){var a=t[e].initSegment;null!=a&&a.byteLength&&n.hls.trigger(G.BUFFER_APPENDING,{type:e,data:a,frag:r,part:null,chunkMeta:i,parent:r.type})}))}this.tickImmediate()}},r.getMainFwdBufferInfo=function(){var e=this.getBufferOutput();return this.getFwdBufferInfo(e,H.MAIN)},r.backtrack=function(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Rn.IDLE},a(t,[{key:"backtrackFragment",get:function(){return this._backtrackFragment},set:function(e){this._backtrackFragment=e}},{key:"couldBacktrack",get:function(){return this._couldBacktrack},set:function(e){this._couldBacktrack=e}},{key:"hasEnoughToStart",get:function(){return this._hasEnoughToStart}},{key:"maxBufferLength",get:function(){var e=this.levels,t=this.level,r=null==e?void 0:e[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}},{key:"nextLevel",get:function(){var e=this.nextBufferedFrag;return e?e.level:-1}},{key:"currentFrag",get:function(){var e;if(this.fragPlaying)return this.fragPlaying;var t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;return x(t)?this.getAppendedFrag(t):null}},{key:"currentProgramDateTime",get:function(){var e,t=(null==(e=this.media)?void 0:e.currentTime)||this.lastCurrentTime;if(x(t)){var r=this.getLevelDetails(),i=this.currentFrag||(r?yr(null,r.fragments,t):null);if(i){var n=i.programDateTime;if(null!==n){var a=n+1e3*(t-i.start);return new Date(a)}}}return null}},{key:"currentLevel",get:function(){var e=this.currentFrag;return e?e.level:-1}},{key:"nextBufferedFrag",get:function(){var e=this.currentFrag;return e?this.followingBufferedFrag(e):null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])}(bn),Jl=function(e){function t(){for(var t,r=arguments.length,i=new Array(r),n=0;n=n&&(e=n-.01),si.bufferInfo(t,e,0).len>0&&this.getBufferedAt(e))return t.currentTime=e,!0}return!1},r.getBufferedAt=function(e){return this.fragmentTracker.getBufferedFrag(e,H.MAIN)},r.cacheSet=function(e,t){if(this.hls){e.data=t;var r=this.cached;r.push(e),this.cachedSize+=t.buffer.byteLength;for(var i=this.hls.config.iframeCacheLimit;this.cachedSize>i&&r.length>1;){var n=r.shift();if(!n.data){this.cached=r.filter((function(e){return!!e.data})),this.cachedSize=r.reduce((function(e,t){var r=t.data;return r?r.buffer.byteLength:0}),0);break}this.cachedSize-=n.data.byteLength,n.data=void 0}}},r.onHandlerDestroying=function(){this.cached.length=0,this.cachedSize=0,e.prototype.onHandlerDestroying.call(this)},r._handleFragmentLoadProgress=function(t){var r=t.frag,i=t.part,n=t.payload;this.cacheFragmentData&&!i&&null!=n&&n.byteLength&&!r.data&&W(r)&&this.cacheSet(r,new Uint8Array(n.slice(0))),e.prototype._handleFragmentLoadProgress.call(this,t)},r.loadFragment=function(t,r,i){var n=this.fragmentTracker.getState(t);n!==Nr&&n!==Br||!this.canReplayCached(t)?e.prototype.loadFragment.call(this,t,r,i):this.replayCachedFragment(t)},r.canReplayCached=function(e){var t;if(!this.cacheFragmentData||null==(t=e.data)||!t.byteLength)return!1;var r=e.decryptdata;return"identity"!==(null==r?void 0:r.keyFormat)||!!r.key},r.replayCachedFragment=function(e){var t=e.data.slice().buffer;this.log("Buffering cached "+e.type+" sn: "+e.sn+" of level "+e.level+" ("+t.byteLength+" bytes)"),this.fragCurrent=e,this.startFragRequested=!0;var r=e.stats=new K;r.loading.start=r.loading.first=r.loading.end=self.performance.now(),r.loaded=r.total=t.byteLength,r.chunkCount=1,this.state=Rn.FRAG_LOADING;var i={frag:e,part:null,payload:t,networkDetails:null};this._handleFragmentLoadProgress(i),this.hls.trigger(G.FRAG_LOADED,i),this._handleFragmentLoadComplete(i)},r.fragBufferedComplete=function(t,r){e.prototype.fragBufferedComplete.call(this,t,r);var i=this.currentOp,n=this.nextOp;this.currentOp=this.nextOp=void 0,this.state=Rn.STOPPED,null!=i&&i[1].seekOnAppend&&(this.flushPipeline(i[0],!n),this.seekTo(i[0])||this.log("Could not seek to "+i[0]+" after fragment buffered (superseded or flushed) buffer: "+(this.media?Ln(si.getBuffered(this.media)):"none"))),n&&this.loadMediaAt.apply(this,n)},r.flushPipeline=function(e,t){if(t){var r=this.media;if(r){var i=si.bufferInfo(r,e,0),n=i.len?i.nextStart:0;n&&(this.fragmentTracker.removeFragmentsInRange(n,1/0,H.MAIN),this.flushMainBuffer(n,1/0))}this.hls.once(G.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(G.BUFFER_EOS,{type:"video"})},r.startLoad=function(){if(!this.startFragRequested){var e=this.hls;e.nextLoadLevel=-1===e.startLevel?0:e.firstAutoLevel}},r.seekToStartPos=function(){},r.setStartPosition=function(){},r.alignPlaylists=function(t,r,i){var n=this.initDetails;return this.initDetails=null,e.prototype.alignPlaylists.call(this,t,r,i||n||void 0)},r.getMainFwdBufferInfo=function(){var e=this.playhead,t=this.getBufferedAt(e);if(t){var r=t.duration;return{len:r,start:e,end:e+r,bufferedIndex:-1}}return{len:0,start:e,end:e,bufferedIndex:-1}},r._streamEnded=function(){var e=this.playhead,t=this.fragmentTracker.getBufferedFrag(e,H.MAIN);return!(null==t||!t.endList)},a(t,[{key:"playhead",get:function(){return this.nextLoadPosition}}])}(Zl),eu=function(e){function t(){for(var t,r=arguments.length,i=new Array(r),n=0;n=i.start&&e10&&this.iframeInstances.forEach((function(e){var t;e.loadingEnabled||e.startLoad((null==(t=i.hls)||null==(t=t.media)?void 0:t.currentTime)||0)}))},r.createIFramePlayer=function(e){var t;return this.createInstance(ql,null==(t=this.hls)?void 0:t.iframeVariants,e)},r.createImageIFramePlayer=function(e){var t,r=null==(t=this.hls)?void 0:t.iframeVariants.filter((function(e){return e.imageCodec}));return this.createInstance(Xl,r,e,"image-")},r.createInstance=function(e,t,r,i){var n=this.hls;if(!n)return null;var a=n.url,s=n.userConfig,o=n.latestLevelDetails,l=n.loadLevelObj,u=n.loadLevel,d=n.bandwidthEstimate,h=n.sessionId,f=this.stats,g=this.variableList;if(null==t||!t.length||!f||!a)return null;var v=(i||"")+"iframe-player-"+this.instanceCounter++,m=n.levels,p=l||m[u],y=vr(p,s.videoPreference),E=(null==p?void 0:p.pathwayId)||".",T=new e(c(c({},s),{},{loggerId:v,primarySessionId:h,videoPreference:y,abrEwmaDefaultEstimate:d,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},r),a,this.initPTS,o);return this.iframeInstances=this.iframeInstances.filter((function(e){return!e.url})),this.iframeInstances.push(T),T.trigger(G.MANIFEST_LOADED,{levels:t,contentSteering:{uri:"",pathwayId:E},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:f,networkDetails:null,url:a,variableList:g}),T},t}(ue);function nu(e){for(var t=5381,r=e.length;r;)t=33*t^e.charCodeAt(--r);return(t>>>0).toString()}var au=.025,su=function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e}({});function ou(e,t,r){return e.identifier+"-"+(r+1)+"-"+nu(t)}var lu=function(){function e(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}var t=e.prototype;return t.setDateRange=function(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)},t.reset=function(){var e;this.appendInPlaceStarted=!1,null==(e=this.assetListLoader)||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)},t.isAssetPastPlayoutLimit=function(e){var t;if(e>0&&e>=this.assetList.length)return!0;var r=this.playoutLimit;return!(e<=0||isNaN(r))&&(0===r||((null==(t=this.assetList[e])?void 0:t.startOffset)||0)>r)},t.findAssetIndex=function(e){return this.assetList.indexOf(e)},t.toString=function(){return'["'+(e=this).identifier+'" '+(e.cue.pre?"
":e.cue.post?"":"")+e.timelineStart.toFixed(2)+"-"+e.resumeTime.toFixed(2)+"]";var e},a(e,[{key:"identifier",get:function(){return this.dateRange.id}},{key:"startDate",get:function(){return this.dateRange.startDate}},{key:"startTime",get:function(){var e=this.dateRange.startTime;if(this.snapOptions.out){var t=this.dateRange.tagAnchor;if(t)return du(t,e)?uu(e,t):e}return e}},{key:"startOffset",get:function(){return this.cue.pre?0:this.startTime}},{key:"startIsAligned",get:function(){if(0===this.startTime||this.snapOptions.out)return!0;var e=this.dateRange.tagAnchor;if(e){var t=this.dateRange.startTime;return t-uu(t,e)<.1}return!1}},{key:"resumptionOffset",get:function(){var e=this.resumeOffset,t=x(e)?e:this.duration;return this.cumulativeDuration+t}},{key:"resumeTime",get:function(){var e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){var t=this.resumeAnchor;if(t)return du(t,e)?uu(e,t):e}return e}},{key:"appendInPlace",get:function(){return!!this.appendInPlaceStarted||!this.appendInPlaceDisabled&&!(this.cue.once||this.cue.pre||!this.startIsAligned||!(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||null!==this.assetListResponse}}])}();function uu(e,t){return e-t.starte.start-au&&t=i-.02},t.reachedPlayout=function(e){var t=this.interstitial.playoutLimit;return this.startOffset+e>=t},t.getAssetTime=function(e){var t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)},t.removeMediaListeners=function(){var e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))},t.bufferSnapShot=function(){var e;this.mediaAttached&&null!=(e=this.hls)&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)},t.destroy=function(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null},t.attachMedia=function(e){var t;this.loadSource(),null==(t=this.hls)||t.attachMedia(e)},t.detachMedia=function(){var e;this.removeMediaListeners(),this.mediaAttached=null,null==(e=this.hls)||e.detachMedia()},t.resumeBuffering=function(){var e;null==(e=this.hls)||e.resumeBuffering()},t.pauseBuffering=function(){var e;null==(e=this.hls)||e.pauseBuffering()},t.transferMedia=function(){var e;return this.bufferSnapShot(),(null==(e=this.hls)?void 0:e.transferMedia())||null},t.resetDetails=function(){var e=this.hls;if(e&&this.hasDetails){e.stopLoad();var t=function(e){return delete e.details};e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}},t.on=function(e,t,r){var i;null==(i=this.hls)||i.on(e,t)},t.once=function(e,t,r){var i;null==(i=this.hls)||i.once(e,t)},t.off=function(e,t,r){var i;null==(i=this.hls)||i.off(e,t)},t.toString=function(){var e;return"HlsAssetPlayer: "+cu(this.assetItem)+" "+(null==(e=this.hls)?void 0:e.sessionId)+" "+(this.appendInPlace?"append-in-place":"")},a(e,[{key:"appendInPlace",get:function(){return this.interstitial.appendInPlace}},{key:"destroyed",get:function(){var e;return!(null!=(e=this.hls)&&e.userConfig)}},{key:"assetId",get:function(){return this.assetItem.identifier}},{key:"interstitialId",get:function(){return this.assetItem.parentIdentifier}},{key:"media",get:function(){var e;return(null==(e=this.hls)?void 0:e.media)||null}},{key:"bufferedEnd",get:function(){var e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;var t=si.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}},{key:"currentTime",get:function(){var e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}},{key:"duration",get:function(){var e=this.assetItem.duration;if(!e)return 0;var t=this.interstitial.playoutLimit;if(t){var r=t-this.startOffset;if(r>0&&r1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}}])}(),vu=.033,mu=function(e){function t(t,r){var i;return(i=e.call(this,"interstitials-sched",r)||this).onScheduleUpdate=void 0,i.eventMap={},i.events=null,i.items=null,i.durations={primary:0,playout:0,integrated:0},i.onScheduleUpdate=t,i}d(t,e);var r=t.prototype;return r.destroy=function(){this.reset(),this.onScheduleUpdate=null},r.reset=function(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach((function(e){return e.reset()})),this.events=this.items=null},r.resetErrorsInRange=function(e,t){return this.events?this.events.reduce((function(r,i){return e<=i.startOffset&&t>i.startOffset?(delete i.error,r+1):r}),0):0},r.getEvent=function(e){return e&&this.eventMap[e]||null},r.hasEvent=function(e){return e in this.eventMap},r.findItemIndex=function(e,t){if(e.event)return this.findEventIndex(e.event.identifier);var r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);var i=this.items;if(i)for(i[r]||(void 0===t&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&null!=(n=i[r])&&n.event;){var n;r--}return r},r.findItemIndexAtTime=function(e,t){var r=this.items;if(r)for(var i=0;ia&&e1)for(var n=0;ns&&(t.005||Math.abs(e.playout.end-a[t].playout.end)>.005})))&&(this.items=s,this.onScheduleUpdate(t,a))}},r.parseDateRanges=function(e,t,r){for(var i=[],n=Object.keys(e),a=0;avu){var R=o,b=l;l+=L;var k=s;s+=L;var D={previousEvent:e[u-1]||null,nextEvent:t,start:R,end:R+L,playout:{start:k,end:s},integrated:{start:b,end:l}};i.push(D)}else L>0&&f&&(f.cumulativeDuration+=L,i[i.length-1].end=g)}h&&(S=T),t.timelineStart=T;var P=l;l+=m;var _=s;s+=v,i.push({event:t,start:T,end:S,playout:{start:_,end:s},integrated:{start:P,end:l}})}var C=p||t.resumeTime;o=h||C>a?a:!d&&S&&t.appendInPlaceStarted&&C-S>vu?S:C})),oau?(this.log('"'+e.identifier+'" resumption '+i+" not aligned with estimated timeline end "+n),!1):!Object.keys(t).some((function(n){var a=t[n].details,s=a.edge;if(i>=s)return r.log('"'+e.identifier+'" resumption '+i+" past "+n+" playlist end "+s),!1;var o=yr(null,a.fragments,i);if(!o)return r.log('"'+e.identifier+'" resumption '+i+" does not align with any fragments in "+n+" playlist ("+a.fragStart+"-"+a.fragmentEnd+")"),!0;var l="audio"===n?.175:0;return!(Math.abs(o.start-i)=n.end){var a,s=i.findItemIndex(n),o=i.schedule.findItemIndexAtTime(e);if(-1===o&&(o=s+(r?-1:1),i.log("seeked "+(r?"back ":"")+"to position not covered by schedule "+e+" (resolving from "+s+" to "+o+")")),!i.isInterstitial(n)&&null!=(a=i.media)&&a.paused&&(i.shouldPlay=!1),!r&&o>s){var l=i.schedule.findJumpRestrictedIndex(s+1,o);if(l>s)return void i.setSchedulePosition(l)}i.setSchedulePosition(o)}else{var u=i.playingAsset;if(u){var d,h=u.timelineStart,f=u.duration||0;(r&&e=h+f)&&(null!=(d=n.event)&&d.appendInPlace&&(i.clearAssetPlayers(n.event,n),i.flushFrontBuffer(e)),i.setScheduleToAssetAtTime(e,u))}else if(i.playingLastItem&&i.isInterstitial(n)){var c=n.event.assetList[0];c&&(i.endedItem=i.playingItem,i.playingItem=null,i.setScheduleToAssetAtTime(e,c))}}else i.checkBuffer()}}},i.onTimeupdate=function(){var e=i.currentTime;if(void 0!==e&&!i.playbackDisabled&&(-1!==i.timelinePos||i.effectivePlayingItem||i.checkStart(),e>i.timelinePos)){i.timelinePos=e,e>i.bufferedPos&&i.checkBuffer();var t=i.playingItem;if(t&&!i.playingLastItem){if(e>=t.end){i.timelinePos=t.end;var r=i.findItemIndex(t);i.setSchedulePosition(r+1)}var n=i.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&i.setScheduleToAssetAtTime(e,n)}}},i.onScheduleUpdate=function(e,t){var r=i.schedule;if(r){var n=i.playingItem,a=r.events||[],s=r.items||[],o=r.durations,l=e.map((function(e){return e.identifier})),u=!(!a.length&&!l.length);(u||t)&&i.log("INTERSTITIALS_UPDATED ("+a.length+"): "+a+"\nSchedule: "+s.map((function(e){return pu(e)}))+" pos: "+i.timelinePos),l.length&&i.log("Removed events "+l);var d=null,h=null;n&&(d=i.updateItem(n,i.timelinePos),i.itemsMatch(n,d)?i.playingItem=d:i.waitingItem=null),i.waitingItem=i.updateItem(i.waitingItem);var f=i.bufferingItem;if(f&&(h=i.updateItem(f,i.bufferedPos),i.itemsMatch(f,h)?i.bufferingItem=h:f.event&&(i.bufferingItem=i.playingItem,i.clearInterstitial(f.event,null))),e.forEach((function(e){e.assetList.forEach((function(e){i.clearAssetPlayer(e.identifier,null)}))})),i.playerQueue.forEach((function(e){if(e.interstitial.appendInPlace){var t=e.assetItem.timelineStart,r=e.timelineOffset-t;if(r)try{e.timelineOffset=t}catch(n){Math.abs(r)>au&&i.warn(n+' ("'+e.assetId+'" '+e.timelineOffset+"->"+t+")")}}})),u||t){if(i.hls.trigger(G.INTERSTITIALS_UPDATED,{events:a.slice(0),schedule:s.slice(0),durations:o,removedIds:l}),i.isInterstitial(n)&&l.indexOf(n.event.identifier)>-1)return i.warn('Interstitial "'+n.event.identifier+'" removed while playing'),void i.primaryFallback(n.event);n&&i.trimInPlace(d,n),f&&h!==d&&i.trimInPlace(h,f),i.checkBuffer()}}},i.hls=t,i.HlsPlayerClass=r,i.assetListLoader=new yu(t),i.schedule=new mu(i.onScheduleUpdate,t.logger),i.registerListeners(),i}d(t,e);var r=t.prototype;return r.registerListeners=function(){var e=this.hls;e&&(e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(G.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(G.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(G.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(G.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this),e.on(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(G.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(G.MEDIA_ENDED,this.onMediaEnded,this),e.on(G.ERROR,this.onError,this),e.on(G.DESTROYING,this.onDestroying,this))},r.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(G.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(G.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(G.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(G.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(G.BUFFER_CODECS,this.onBufferCodecs,this),e.off(G.BUFFER_APPENDED,this.onBufferAppended,this),e.off(G.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(G.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(G.MEDIA_ENDED,this.onMediaEnded,this),e.off(G.ERROR,this.onError,this),e.off(G.DESTROYING,this.onDestroying,this))},r.startLoad=function(){this.resumeBuffering()},r.stopLoad=function(){this.pauseBuffering()},r.resumeBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.resumeBuffering()},r.pauseBuffering=function(){var e;null==(e=this.getBufferingPlayer())||e.pauseBuffering()},r.destroy=function(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null},r.onDestroying=function(){var e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)},r.removeMediaListeners=function(e){In(e,"play",this.onPlay),In(e,"pause",this.onPause),In(e,"seeking",this.onSeeking),In(e,"timeupdate",this.onTimeupdate)},r.onMediaAttaching=function(e,t){var r=this.media=t.media;An(r,"seeking",this.onSeeking),An(r,"timeupdate",this.onTimeupdate),An(r,"play",this.onPlay),An(r,"pause",this.onPause)},r.onMediaAttached=function(e,t){var r=this.effectivePlayingItem,i=this.detachedData;if(this.detachedData=null,null===r)this.checkStart();else if(!i){this.clearScheduleState();var n=this.findItemIndex(r);this.setSchedulePosition(n)}},r.clearScheduleState=function(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null},r.onMediaDetaching=function(e,t){var r=!!t.transferMedia,i=this.media;if(this.media=null,!r&&(i&&this.removeMediaListeners(i),this.detachedData)){var n=this.getBufferingPlayer();n&&(this.log("Removing schedule state for detachedData and "+n),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,n.detachMedia()),this.shouldPlay=!1}},r.isInterstitial=function(e){return!(null==e||!e.event)},r.retreiveMediaSource=function(e,t){var r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)},r.transferMediaFromPlayer=function(e,t){var r=e.interstitial.appendInPlace,i=e.media;if(r&&i===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&i)return void(this.detachedData={media:i});var n=e.transferMedia();this.log("transfer MediaSource from "+e+" "+ar(n)),this.detachedData=n}else t&&i&&(this.shouldPlay||(this.shouldPlay=!i.paused))},r.transferMediaTo=function(e,t){var r,i,n=this;if(e.media!==t){var a,s=null,o=this.hls,l=e!==o,u=l&&e.interstitial.appendInPlace,d=null==(r=this.detachedData)?void 0:r.mediaSource;if(o.media)u&&(s=o.transferMedia(),this.detachedData=s),a="Primary";else{var h=this.getBufferingPlayer();h?(s=h.transferMedia(),this.detachedData=s,a=""+h):a=d?"detached MediaSource":"detached media"}if(!s)if(d)s=this.detachedData,this.log("using detachedData: MediaSource "+ar(s));else if(!this.detachedData||o.media===t){var f=this.playerQueue;f.length>1&&f.forEach((function(e){if(l&&e.interstitial.appendInPlace!==u){var t=e.interstitial;n.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&n.warn("Could not change append strategy for queued assets "+t)}})),this.hls.detachMedia(),this.detachedData={media:t}}var g=s&&"mediaSource"in s&&"closed"!==(null==(i=s.mediaSource)?void 0:i.readyState);if(this.log((g?"transfering MediaSource":"attaching media")+" to "+(l?e:"Primary")+" from "+a+" (media.currentTime: "+t.currentTime+")"),g||l){var v=g&&s?c({},s):{media:t},m=this.schedule;if(m&&l){var p=e.assetId===m.assetIdAtEnd;v.overrides={duration:m.duration,endOfStream:p||!1===e.appendInPlace}}if(!g&&u){var y=e,E=y.assetItem.timelineStart;if(E){var T=y.hls,S=Math.max(this.timelinePos-E,Number.EPSILON);T.startPosition!==S&&(this.log("Set "+y+" startPosition: "+S),T.config.startPosition=S,T.loadingEnabled&&T.startLoad(S))}}e.attachMedia(v)}else e.attachMedia(t)}},r.onInterstitialCueEnter=function(){this.onTimeupdate()},r.checkStart=function(){var e=this.schedule,t=null==e?void 0:e.events,r=this.hls;if(t&&!this.playbackDisabled&&this.media&&r){-1===this.bufferedPos&&(this.bufferedPos=0);var i=this.timelinePos,n=this.effectivePlayingItem;if(-1===i){if(!r.loadingEnabled)return void this.log("waiting for startLoad(  )");var a=r.startPosition;if(this.timelinePos=a,0===t.length)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Tu("checkStart (preroll)",a));var s=e.findEventIndex(t[0].identifier);this.setSchedulePosition(s)}else if(a>=0||!this.primaryLive){this.log(Tu("checkStart",a));var o=this.timelinePos=a>0?a:0,l=e.findItemIndexAtTime(o);this.setSchedulePosition(l)}else 0===r.liveSyncPosition?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Tu("checkStart (playing item)",n.start));var u=e.findItemIndex(n);this.setSchedulePosition(u)}}},r.advanceAssetBuffering=function(e,t){var r=e.event,i=r.findAssetIndex(t),n=fu(r,i);if(r.isAssetPastPlayoutLimit(n)){if(this.schedule){var a,s=this.getNextItemIndex(e,!0),o=null==(a=this.schedule.items)?void 0:a[s];o&&this.bufferedToItem(o)}}else this.bufferedToEvent(e,n)},r.livePrerollResumption=function(e,t){if(e.cue.pre&&this.primaryLive&&!x(e.resumeOffset)&&this.hls){var r=this.getLiveStartPos();if(t){var i=this.getBufferingPlayer();return r+(null!=i&&i.interstitial.cue.pre?i.remaining:0)}return r}},r.getNextItemIndex=function(e,t){if(this.schedule){var r=this.livePrerollResumption(e.event,t);if(void 0!==r)return this.log("find next item index @"+r),this.schedule.findItemIndexAtTime(r)}return this.findItemIndex(e)+1},r.advanceAfterAssetEnded=function(e,t,r){var i=fu(e,r);if(e.isAssetPastPlayoutLimit(i)){if(this.schedule){var n=this.schedule.items;if(n){var a=n[t],s=a.event?this.getNextItemIndex(a):t+1;if(s>=n.length)return void this.setSchedulePosition(-1);var o=e.resumeTime;this.timelinePos=0?i[e]:null;this.log("setSchedulePosition "+e+", "+t+" ("+(n?pu(n):n)+") pos: "+this.timelinePos);var a=this.waitingItem||this.playingItem,s=this.playingLastItem;if(this.isInterstitial(a)){var o=a.event,l=this.playingAsset,u=null==l?void 0:l.identifier,d=u?this.getAssetPlayer(u):null;if(d&&u&&(!this.eventItemsMatch(a,n)||void 0!==t&&u!==o.assetList[t].identifier)){var h,f=o.findAssetIndex(l);if(this.log("INTERSTITIAL_ASSET_ENDED "+(f+1)+"/"+o.assetList.length+" "+cu(l)),this.endedAsset=l,this.playingAsset=null,this.hls.trigger(G.INTERSTITIAL_ASSET_ENDED,{asset:l,assetListIndex:f,event:o,schedule:i.slice(0),scheduleIndex:e,player:d}),a!==this.playingItem)return void(this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(o,this.findItemIndex(this.playingItem),f));this.retreiveMediaSource(u,n),!d.media||null!=(h=this.detachedData)&&h.mediaSource||d.detachMedia()}if(!this.eventItemsMatch(a,n)&&(this.endedItem=a,this.playingItem=this.waitingItem=null,this.log("INTERSTITIAL_ENDED "+o+" "+pu(a)),o.hasPlayed=!0,this.hls.trigger(G.INTERSTITIAL_ENDED,{event:o,schedule:i.slice(0),scheduleIndex:e}),o.cue.once&&this.hls)){var c;this.updateSchedule();var g=null==(c=this.schedule)?void 0:c.items;if(n&&g){var v=this.findItemIndex(n),m=this.livePrerollResumption(o);if(void 0!==m){var p=m,y=this.getNextItemIndex(a);if(!this.isInterstitial(i[y])){var E,T=null==(E=this.primaryDetails)?void 0:E.fragments;if(o.snapOptions.in&&T){var S=yr(null,T,m);S&&(p=Math.min(Math.max(i[y].start,uu(p,S)),i[y].end))}}if(this.log(Tu("live join (preroll)",p)),this.timelinePos=p,y!==v&&(y||0===y))return void this.advanceSchedule(y,g,void 0,a,s)}this.advanceSchedule(v,g,t,a,s)}return}}this.advanceSchedule(e,i,t,a,s)}},r.advanceSchedule=function(e,t,r,i,n){var a=this,s=this.schedule;if(s){var o=t[e]||null,l=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach((function(t){var r=t.interstitial,i=s.findEventIndex(r.identifier);(ie+1)&&a.clearInterstitial(r,o)})),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);var d=o.event;if(void 0===r){var h=fu(d,(r=d.cue.pre?0:s.findAssetIndex(d,this.timelinePos))-1);if(d.isAssetPastPlayoutLimit(h)||d.appendInPlace&&this.timelinePos===o.end)return void this.advanceAfterAssetEnded(d,e,r);r=h}var f=this.waitingItem;this.assetsBuffered(o,l)||this.setBufferingItem(o);var c=this.preloadAssets(d,r);if(this.eventItemsMatch(o,f||i)||(this.waitingItem=o,this.log("INTERSTITIAL_STARTED "+pu(o)+" "+(d.appendInPlace?"append in place":"")),d.hasPlayed=!1,this.hls.trigger(G.INTERSTITIAL_STARTED,{event:d,schedule:t.slice(0),scheduleIndex:e})),!d.assetListLoaded)return void this.log("Waiting for ASSET-LIST to complete loading "+d);if(d.assetListLoader&&(d.assetListLoader.destroy(),d.assetListLoader=void 0),!l)return void this.log("Waiting for attachMedia to start Interstitial "+d);this.waitingItem=this.endedItem=null,this.playingItem=o;var g=d.assetList[r];if(!g)return void this.advanceAfterAssetEnded(d,e,r||0);if(c||(c=this.getAssetPlayer(g.identifier)),null===c||c.destroyed){var v=d.assetList.length;this.warn("asset "+(r+1)+"/"+v+" player destroyed "+d),(c=this.createAssetPlayer(d,g,r)).loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&d.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(c,r,t,e,l),this.shouldPlay&&Eu(c.media)}else o?(this.resumePrimary(o,e,i),this.shouldPlay&&Eu(this.hls.media)):n&&this.isInterstitial(i)&&(this.endedItem=null,this.playingItem=i,i.event.appendInPlace||this.attachPrimary(s.durations.primary,null))}},r.resumePrimary=function(e,t,r){var i,n;this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(e),this.endedItem=null,this.log("resuming "+pu(e));var a=this.timelinePos;if(null!=(i=this.detachedData)&&i.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(a):((a=e.end||al&&!r){var u=this.hls.liveSyncPosition;return this.log("primary resumption out of bounds ("+i+" ["+o+"-"+l+"]) snapping to liveSync "+u),u||o}}}return this.log("primary resumption itemStart: "+i),i},r.getLiveStartPos=function(){var e,t=this.hls.startPosition,r=this.hls.liveSyncPosition||0,i=3*((null==(e=this.primaryDetails)?void 0:e.targetduration)||10);return-1===t||r&&r-t=e.timelineStart+(e.duration||0)},r.attachPrimary=function(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;var i=this.primaryMedia;if(i){var n=this.hls;n.media?this.checkBuffer():(this.transferMediaTo(n,i),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Tu("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}},r.startLoadingPrimaryAt=function(e,t){var r=this.hls,i=r.loadingEnabled,n=r.bufferingEnabled,a=r.startPosition,s=r.hasEnoughToStart;if(this.log("Start loading primary @"+e+" bufferedPos: "+this.bufferedPos+" startPosition: "+a+" skip seek: "+t+" has enough "+s+" loadingEnabled: "+i+" bufferingEnabled: "+n),!t&&s||!i||Math.abs(a-e)>.1){var o=this.primaryDetails;if(null!=o&&o.live&&e+.5>=o.edge){var l=this.bufferingItem;return this.log("Resume primary loading when live passes "+e+" buffering item: "+(l?pu(l):null)),r.pauseBuffering(),void(this.bufferPastEdge=!0)}r.startLoad(e,t)}else n||r.resumeBuffering()},r.onManifestLoading=function(){var e;this.stopLoad(),null==(e=this.schedule)||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(G.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(G.BUFFER_CODECS,this.onBufferCodecs,this)},r.onLevelUpdated=function(e,t){if(-1!==t.level&&this.schedule){var r=this.hls.levels[t.level];if(r.details){var i=c(c({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=i;var n=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(i,this.hls.config.interstitialAppendInPlace,-1===n?0:n),this.schedule.items)if(this.effectivePlayingItem){if(this.bufferPastEdge){var a=this.primaryDetails,s=this.bufferedPos;if(null!=a&&a.live&&s+.5.25){e.event.assetList.forEach((function(t,i){e.event.isAssetPastPlayoutLimit(i)&&r.clearAssetPlayer(t.identifier,null)}));var i=e.end+.25,n=si.bufferInfo(this.primaryMedia,i,0);(n.end>i||(n.nextStart||0)>i)&&(this.log("trim buffered interstitial "+pu(e)+" (was "+pu(t)+")"),this.attachPrimary(i,null,!0),this.flushFrontBuffer(i))}},r.itemsMatch=function(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))},r.eventItemsMatch=function(e,t){var r;return!!t&&(e===t||e.event.identifier===(null==(r=t.event)?void 0:r.identifier))},r.findEventIndex=function(e){return this.schedule?this.schedule.findEventIndex(e):-1},r.getEventItem=function(e){if(this.schedule){var t,r=null==(t=this.schedule.items)?void 0:t[this.findEventIndex(e)];if(this.isInterstitial(r)&&r.event.identifier===e)return r}},r.findItemIndex=function(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1},r.updateSchedule=function(e){var t,r;void 0===e&&(e=!1);var i=this.mediaSelection;if(i){var n=(null==(t=this.hls)?void 0:t.liveSyncPosition)||0;null==(r=this.schedule)||r.updateSchedule(i,[],n,e)}},r.checkBuffer=function(e){var t,r=null==(t=this.schedule)?void 0:t.items;if(r){var i=si.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=i.len<1),this.updateBufferedPos(i.end,r,e)}},r.updateBufferedPos=function(e,t,r){var i=this.schedule,n=this.bufferingItem;if(!(this.bufferedPos>e)&&i)if(1===t.length&&this.itemsMatch(t[0],n))this.bufferedPos=e;else{var a=this.playingItem,s=this.findItemIndex(a),o=i.findItemIndexAtTime(e);if(this.bufferedPos=n.end||null!=(l=h.event)&&l.appendInPlace&&e+.01>=h.start)&&(o=d),this.isInterstitial(n)){var f=n.event;if(d-s>1&&!1===f.appendInPlace)return;if(0===f.assetList.length&&f.assetListLoader)return}if(this.bufferedPos=e,o>u&&o>s)this.bufferedToItem(h);else{var c=this.primaryDetails;this.primaryLive&&c&&e>c.edge-c.targetduration&&h.start0&&(o=Math.round(1e3*f)/1e3)}if(this.log("Load interstitial asset "+(t+1)+"/"+(r?1:i)+" "+e+(h?" live-start: "+h+" start-offset: "+o+" (timeline-start: "+l+")":"")),r)return this.createAsset(e,0,0,l,e.duration,r);var c=this.assetListLoader.loadAssetList(e,o);c&&(e.assetListLoader=c)}else if(!a&&i){for(var g=t;g=i.edge||(this.log("Removing front buffer starting at "+e),Object.keys(r).forEach((function(r){t.hls.trigger(G.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})})))}},r.getAssetPlayerQueueIndex=function(e){for(var t=this.playerQueue,r=0;r=0){var f=t.duration;f&&hu)&&(y=!1,i.log('Interstitial asset "'+g+'" duration change '+u+" > "+l),t.duration=l,i.updateSchedule())}};p.on(G.LEVEL_UPDATED,(function(e,t){var r=t.details;return E(r)})),p.on(G.LEVEL_PTS_UPDATED,(function(e,t){var r=t.details;return E(r)})),p.on(G.EVENT_CUE_ENTER,(function(){return i.onInterstitialCueEnter()}));var T=function(e,t){var r=i.getAssetPlayer(g);if(r&&t.tracks){r.off(G.BUFFER_CODECS,T),r.tracks=t.tracks;var n=i.primaryMedia;i.bufferingAsset===r.assetItem&&n&&!r.media&&i.bufferAssetPlayer(r,n)}};p.on(G.BUFFER_CODECS,T),p.on(G.BUFFERED_TO_END,(function(){var t=i.getAssetPlayer(g);if(i.log("buffered to end of asset "+t),t&&i.schedule){var r=i.getEventItem(e.identifier);r&&i.advanceAssetBuffering(r,t.assetItem)}}));var S=function(t){return function(){if(i.getAssetPlayer(g)&&i.schedule){i.shouldPlay=!0;var r=i.findEventIndex(e.identifier);i.advanceAfterAssetEnded(e,r,t)}}};return p.once(G.MEDIA_ENDED,S(r)),p.once(G.PLAYOUT_LIMIT_REACHED,S(1/0)),p.on(G.ERROR,(function(t,n){if(i.schedule){var a=i.getAssetPlayer(g);if(n.details===B.BUFFER_STALLED_ERROR)return null!=a&&a.appendInPlace?void i.handleInPlaceStall(e):(i.onTimeupdate(),void i.checkBuffer(!0));n.details!==B.BUFFER_SEEK_OVER_HOLE&&i.handleAssetItemError(n,e,i.findEventIndex(e.identifier),r,"Asset player error "+n.error+" "+e)}})),p.on(G.DESTROYING,(function(){if(i.getAssetPlayer(g)&&i.schedule){var t=new Error("Asset player destroyed unexpectedly "+g),n={fatal:!0,type:U.OTHER_ERROR,details:B.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};i.handleAssetItemError(n,e,i.findEventIndex(e.identifier),r,t.message)}})),this.log("INTERSTITIAL_ASSET_PLAYER_CREATED "+cu(t)),this.hls.trigger(G.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p},r.clearInterstitial=function(e,t){this.clearAssetPlayers(e,t),e.reset()},r.clearAssetPlayers=function(e,t){var r=this;e.assetList.forEach((function(e){r.clearAssetPlayer(e.identifier,t)}))},r.resetAssetPlayer=function(e){var t=this.getAssetPlayerQueueIndex(e);if(-1!==t){this.log('reset asset player "'+e+'" after error');var r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}},r.clearAssetPlayer=function(e,t){var r=this.getAssetPlayerQueueIndex(e);if(-1!==r){var i=this.playerQueue[r];this.log("clear "+i+" toSegment: "+(t?pu(t):t)),this.transferMediaFromPlayer(i,t),this.playerQueue.splice(r,1),i.destroy()}},r.emptyPlayerQueue=function(){for(var e;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]},r.startAssetPlayer=function(e,t,r,i,n){var a=e.interstitial,s=e.assetItem,o=e.assetId,l=a.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=s,(null==u?void 0:u.identifier)!==o&&(u&&(this.clearAssetPlayer(u.identifier,r[i]),delete u.error),this.log("INTERSTITIAL_ASSET_STARTED "+(t+1)+"/"+l+" "+cu(s)),this.hls.trigger(G.INTERSTITIAL_ASSET_STARTED,{asset:s,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:i,player:e})),this.bufferAssetPlayer(e,n)},r.bufferAssetPlayer=function(e,t){var r;if(this.schedule){var i=e.interstitial,n=e.assetItem,a=this.getEventItem(i.identifier);if(a)if(e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=n,e.bufferedInPlaceToEnd(this.primaryMedia,e.currentTime))this.advanceAssetBuffering(a,n);else{var s=this.getBufferingPlayer();if(s!==e){var o=i.appendInPlace;if(!o||!1!==(null==s?void 0:s.interstitial.appendInPlace)){var l=(null==s?void 0:s.tracks)||(null==(r=this.detachedData)?void 0:r.tracks)||this.requiredTracks;if(o&&n!==this.playingAsset){if(!e.tracks)return void this.log("Waiting for track info before buffering "+e);if(l&&!ye(l,e.tracks)){var u=new Error("Asset "+cu(n)+" SourceBuffer tracks ('"+Object.keys(e.tracks)+"') are not compatible with primary content tracks ('"+Object.keys(l)+"')"),d={fatal:!0,type:U.OTHER_ERROR,details:B.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},h=i.findAssetIndex(n);return void this.handleAssetItemError(d,i,this.findEventIndex(i.identifier),h,u.message)}}this.transferMediaTo(e,t)}}}}},r.handleInPlaceStall=function(e){var t=this.schedule,r=this.primaryMedia;if(t&&r){var i=r.currentTime,n=t.findAssetIndex(e,i),a=e.assetList[n];if(a){var s=this.getAssetPlayer(a.identifier);if(s){var o=s.currentTime||i-a.timelineStart,l=s.duration-o;if(this.warn("Stalled at "+o+" of "+(o+l)+" in "+s+" "+e+" (media.currentTime: "+i+")"),o&&(l/r.playbackRate<.5||s.bufferedInPlaceToEnd(r,s.currentTime))&&s.hls){var u=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,u,n)}}}}},r.advanceInPlace=function(e){var t=this.primaryMedia;if(t&&t.currentTimee?(this.log(r),t.currentTime=e):this.log("Cannot "+r)}},r.handleAssetItemError=function(e,t,r,i,n){if(e.details!==B.BUFFER_STALLED_ERROR){var a=t.assetList[i]||null;if(this.warn("INTERSTITIAL_ASSET_ERROR "+(a?cu(a):a)+" "+e.error),this.schedule){var s=(null==a?void 0:a.identifier)||"",o=this.getAssetPlayerQueueIndex(s),u=this.playerQueue[o]||null,d=this.schedule.items,h=l({},e,{fatal:!1,errorAction:Fr(!0),asset:a,assetListIndex:i,event:t,schedule:d,scheduleIndex:r,player:u});if(this.hls.trigger(G.INTERSTITIAL_ASSET_ERROR,h),e.fatal){var f=this.playingAsset,c=this.bufferingAsset,g=new Error(n);if(a&&(this.clearAssetPlayer(s,null),a.error=g),t.assetList.some((function(e){return!e.error})))for(var v=i;vv.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g)return a.error=new Error("Interstitial "+(o.length?"no longer within playback range":"asset-list is empty")+" "+this.timelinePos+" "+a),this.log(a.error.message),this.updateSchedule(!0),void this.primaryFallback(a);this.setBufferingItem(v)}this.setSchedulePosition(g)}else if((null==c?void 0:c.identifier)===s){var m=a.assetList[0];if(m){var p=this.getAssetPlayer(m.identifier);if(c.appendInPlace){var y=this.primaryMedia;p&&y&&this.bufferAssetPlayer(p,y)}else p&&p.loadSource()}}}},r.onError=function(e,t){if(this.schedule)switch(t.details){case B.ASSET_LIST_PARSING_ERROR:case B.ASSET_LIST_LOAD_ERROR:case B.ASSET_LIST_LOAD_TIMEOUT:var r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break;case B.BUFFER_STALLED_ERROR:var i=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(i)&&i.event.appendInPlace)return void this.handleInPlaceStall(i.event);var n=this.primaryMedia;this.log("Primary player stall @"+this.timelinePos+" currentTime: "+(null==n?void 0:n.currentTime)+" bufferedPos: "+this.bufferedPos),this.onTimeupdate(),this.checkBuffer(!0)}},a(t,[{key:"interstitialsManager",get:function(){if(!this.hls)return null;if(this.manager)return this.manager;var e=this,t=function(){return e.bufferingItem||e.waitingItem},r=function(t){return t?e.getAssetPlayer(t.identifier):t},i=function(t,i,a,s,o){if(t){var l=t[i].start,u=t.event;if(u){if("playout"===i||u.timelineOccupancy!==su.Point){var d=r(a);(null==d?void 0:d.interstitial)===u&&(l+=d.assetItem.startOffset+d[o])}}else l+=("bufferedPos"===s?n():e[s])-t.start;return l}return 0},n=function(){var t=e.bufferedPos;return t===Number.MAX_VALUE?a("primary"):Math.max(t,0)},a=function(t){var r,i;return null!=(r=e.primaryDetails)&&r.live?e.primaryDetails.edge:(null==(i=e.schedule)?void 0:i.durations[t])||0},s=function(t,n){var a,s,o=e.effectivePlayingItem;if((null==o||null==(a=o.event)||!a.restrictions.skip)&&e.schedule){e.log("seek to "+t+' "'+n+'"');var l=e.effectivePlayingItem,u=e.schedule.findItemIndexAtTime(t,n),d=null==(s=e.schedule.items)?void 0:s[u],h=e.getBufferingPlayer(),f=null==h?void 0:h.interstitial,c=null==f?void 0:f.appendInPlace,g=l&&e.itemsMatch(l,d);if(l&&(c||g)){var v=r(e.playingAsset),m=(null==v?void 0:v.media)||e.primaryMedia;if(m){var p="primary"===n?m.currentTime:i(l,n,e.playingAsset,"timelinePos","currentTime"),y=t-p,E=(c?p:m.currentTime)+y;if(E>=0&&(!v||c||E<=v.duration))return void(m.currentTime=E)}}if(d){var T=t;if("primary"!==n){var S=t-d[n].start;T=d.start+S}var A=!e.isInterstitial(d);if(e.isInterstitial(l)&&!l.event.appendInPlace||!A&&!d.event.appendInPlace){if(l){var I=e.findItemIndex(l);if(u>I){var L=e.schedule.findJumpRestrictedIndex(I+1,u);if(L>I)return void e.setSchedulePosition(L)}var R=0;if(A)e.timelinePos=T,e.checkBuffer();else for(var b=d.event.assetList,k=t-(d[n]||d).start,D=b.length;D--;){var P=b[D];if(P.duration&&k>=P.startOffset&&k0?t:0},set currentTime(e){s(e,"primary")},get duration(){return a("primary")},get seekableStart(){return e.seekableStart}},integrated:{get bufferedEnd(){return i(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return i(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(e){s(e,"integrated")},get duration(){return a("integrated")},get seekableStart(){return function(t,r){var i;if(0!==t&&"primary"!==r&&null!=(i=e.schedule)&&i.length){var n,a=e.schedule.findItemIndexAtTime(t),s=null==(n=e.schedule.items)?void 0:n[a];if(s)return t+(s[r].start-s.start)}return t}(e.seekableStart,"integrated")}},skip:function(){var t=e.effectivePlayingItem,r=null==t?void 0:t.event;if(r&&!r.restrictions.skip){var i=e.findItemIndex(t);if(r.appendInPlace){var n=t.playout.start+t.event.duration;s(n+.001,"playout")}else e.advanceAfterAssetEnded(r,i,1/0)}}}}},{key:"effectivePlayingItem",get:function(){return this.waitingItem||this.playingItem||this.endedItem}},{key:"effectivePlayingAsset",get:function(){return this.playingAsset||this.endedAsset}},{key:"playingLastItem",get:function(){var e,t=this.playingItem,r=null==(e=this.schedule)?void 0:e.items;return!!(this.playbackStarted&&t&&r)&&this.findItemIndex(t)===r.length-1}},{key:"playbackStarted",get:function(){return null!==this.effectivePlayingItem}},{key:"currentTime",get:function(){var e,t;if(null!==this.mediaSelection){var r=this.waitingItem||this.playingItem;if(!this.isInterstitial(r)||r.event.appendInPlace){var i=this.media;!i&&null!=(e=this.bufferingItem)&&null!=(e=e.event)&&e.appendInPlace&&(i=this.primaryMedia);var n=null==(t=i)?void 0:t.currentTime;if(void 0!==n&&x(n))return n}}}},{key:"primaryMedia",get:function(){var e;return this.media||(null==(e=this.detachedData)?void 0:e.media)||null}},{key:"playbackDisabled",get:function(){return!1===this.hls.config.enableInterstitialPlayback}},{key:"primaryDetails",get:function(){var e;return null==(e=this.mediaSelection)?void 0:e.main.details}},{key:"primaryLive",get:function(){var e;return!(null==(e=this.primaryDetails)||!e.live)}},{key:"seekableStart",get:function(){var e;return this.primaryLive&&(null==(e=this.primaryDetails)?void 0:e.fragmentStart)||0}}])}(ue),Au=function(){function e(e){var t=this;this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=function(){var e,r=t.media,i=t.levelDetails;if(r&&i&&t.hls){t.currentTime=r.currentTime;var n=t.hls.config,a=t.computeLatency();if(null!==a){t._latency=a;var s=n.lowLatencyMode,o=n.maxLiveSyncPlaybackRate;if(s&&1!==o&&i.live){var l=t.targetLatency;if(null!==l){var u=a-l,d=u.05&&t.forwardBufferLength>1&&!h){var f=Math.min(2,Math.max(1,o)),c=Math.round(2/(1+Math.exp(-.75*u-t.edgeStalled))*20)/20,g=Math.min(f,Math.max(1,c));t.changeMediaPlaybackRate(r,g)}else 1!==r.playbackRate&&0!==r.playbackRate&&t.changeMediaPlaybackRate(r,1)}}}}},this.hls=e,this.registerListeners()}var t=e.prototype;return t.destroy=function(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null},t.registerListeners=function(){var e=this.hls;e&&(e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(G.ERROR,this.onError,this),e.on(G.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))},t.unregisterListeners=function(){var e=this.hls;e&&(e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(G.ERROR,this.onError,this),e.off(G.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))},t.onMediaAttached=function(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)},t.onMediaDetaching=function(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)},t.onManifestLoading=function(){this._latency=null,this.stallCount=0},t.onLevelUpdated=function(e,t){var r=t.details;r.advanced&&this.onTimeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)},t.onAssetStarted=function(e,t){var r,i=this.hls,n=this.media||t.event.appendInPlace&&(null==i||null==(r=i.interstitialsManager)?void 0:r.playerQueue.reduce((function(e,t){return e||t.media}),null));i&&n&&n.playbackRate>1&&n.playbackRate<=i.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(n,1)},t.onError=function(e,t){var r;t.details===B.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&null!=(r=this.levelDetails)&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))},t.changeMediaPlaybackRate=function(e,t){var r,i;e.playbackRate!==t&&(null==(r=this.hls)||r.logger.debug("[latency-controller]: latency="+this.latency.toFixed(3)+", targetLatency="+(null==(i=this.targetLatency)?void 0:i.toFixed(3))+", forwardBufferLength="+this.forwardBufferLength.toFixed(3)+": adjusting playback rate from "+e.playbackRate+" to "+t),e.playbackRate=t)},t.estimateLiveEdge=function(){var e=this.levelDetails;return null===e?null:e.edge+e.age},t.computeLatency=function(){var e=this.estimateLiveEdge();return null===e?null:e-this.currentTime},a(e,[{key:"levelDetails",get:function(){var e;return(null==(e=this.hls)?void 0:e.latestLevelDetails)||null}},{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var e,t=null==(e=this.hls)?void 0:e.config;if(!t)return 0;if(void 0!==t.liveMaxLatencyDuration)return t.liveMaxLatencyDuration;var r=this.levelDetails;return r?t.liveMaxLatencyDurationCount*r.targetduration:0}},{key:"targetLatency",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return null;var t=this.hls.config,r=e.holdBack,i=e.partHoldBack,n=e.targetduration,a=t.liveSyncDuration,s=t.liveSyncDurationCount,o=t.lowLatencyMode,l=this.hls.userConfig,u=o&&i||r;(this._targetLatencyUpdated||l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==a?a:s*n);var d=n;return u+Math.min(this.stallCount*t.liveSyncOnStallIncrease,d)},set:function(e){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=e,this._targetLatencyUpdated=!0)}},{key:"liveSyncPosition",get:function(){var e=this.estimateLiveEdge(),t=this.targetLatency;if(null===e||null===t||!this.hls)return null;var r=this.levelDetails;if(null===r)return null;var i=r.edge,n=e-t-this.edgeStalled,a=i-r.totalduration,s=i-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,n),s)}},{key:"drift",get:function(){var e=this.levelDetails;return null===e?1:e.drift}},{key:"edgeStalled",get:function(){var e=this.levelDetails;if(null===e||!this.hls)return 0;var t=3*(this.hls.config.lowLatencyMode&&e.partTarget||e.targetduration);return Math.max(e.age-t,0)}},{key:"forwardBufferLength",get:function(){var e=this.media,t=this.levelDetails;if(!e||!t)return 0;var r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}}])}(),Iu=function(e){function t(t,r,i){var n;return(n=e.call(this,t,r,i,"subtitle-stream-controller",H.SUBTITLE)||this).currentTrackId=-1,n.tracksBuffered=[],n.mainDetails=null,n.registerListeners(),n}d(t,e);var r=t.prototype;return r.onHandlerDestroying=function(){this.unregisterListeners(),e.prototype.onHandlerDestroying.call(this),this.mainDetails=null},r.registerListeners=function(){e.prototype.registerListeners.call(this);var t=this.hls;t.on(G.LEVEL_LOADED,this.onLevelLoaded,this),t.on(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(G.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this)},r.unregisterListeners=function(){e.prototype.unregisterListeners.call(this);var t=this.hls;t.off(G.LEVEL_LOADED,this.onLevelLoaded,this),t.off(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(G.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(G.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this)},r.startLoad=function(e,t){this.stopLoad(),this.state=Rn.IDLE,this.setInterval(500),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()},r.onManifestLoading=function(){e.prototype.onManifestLoading.call(this),this.mainDetails=null},r.onMediaDetaching=function(t,r){this.tracksBuffered=[],e.prototype.onMediaDetaching.call(this,t,r)},r.onLevelLoaded=function(e,t){this.mainDetails=t.details},r.onSubtitleFragProcessed=function(e,t){var r=t.frag,i=t.part;if(t.success){var n=this.tracksBuffered[this.currentTrackId];if(n){for(var a,s=(i||r).start,o=0;o=n[o].start&&s<=n[o].end){a=n[o];break}var l=s+(i||r).duration;if(a?a.end=l:(a={start:s,end:l},n.push(a)),!i||l>=r.end){var u=this.fragmentTracker.fragBuffered(r);i&&u&&(u.range.subs={time:[{startPTS:r.start,endPTS:l}],partial:!0}),W(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,i),this.media&&this.tickImmediate()}}}},r.onBufferFlushing=function(e,t){var r=t.startOffset,i=t.endOffset;if(0===r&&i!==Number.POSITIVE_INFINITY){var n=i-1;if(n<=0)return;t.endOffsetSubtitles=Math.max(0,n),this.tracksBuffered.forEach((function(e){if(e)for(var t=0;t=n.length)&&o){this.log("Subtitle track "+s+" loaded ["+a.startSN+","+a.endSN+"]"+(a.lastPartSn?"[part-"+a.lastPartSn+"-"+a.lastPartIndex+"]":"")+",duration:"+a.totalduration),this.mediaBuffer=this.mediaBufferTimeRanges;var l=this.mainDetails,u=0;if(a.live||null!=(r=o.details)&&r.live){if(a.deltaUpdateFailed)return;if(!l)return void(this.startFragRequested=!1);var d;o.details&&(u=this.alignPlaylists(a,o.details,null==(d=this.levelLastLoaded)?void 0:d.details)),a.alignedSliding||(Sn(l,a,this),u=a.fragmentStart)}o.details=a,this.levelLastLoaded=o,l&&!this.startFragRequested&&this.setStartPosition(l,u),s===i&&(this.hls.trigger(G.SUBTITLE_TRACK_UPDATED,{details:a,id:s,groupId:t.groupId}),this.tickImmediate())}}else this.warn("Subtitle tracks were reset while loading level "+s)},r._handleFragmentLoadProgress=function(e){var t=e.frag,r=e.part,i=e.payload;r&&null!=i&&i.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(i,t,r)},r._handleFragmentLoadComplete=function(e){var t=e.frag,r=e.payload;!this.fragContextChanged(t)&&null!=r&&r.byteLength&&this.shouldDecrypt(t)&&this.decryptPayload(r,t,null)},r.shouldDecrypt=function(e){var t=e.decryptdata;return!!(null!=t&&t.key&&t.iv&&Ti(t.method))},r.decryptPayload=function(e,t,r){var i=this,n=t.decryptdata,a=performance.now();this.decrypter.decrypt(new Uint8Array(e),n.key.buffer,n.iv.buffer,Si(n.method)).then((function(e){i.fragContextChanged(t)||i.hls.trigger(G.FRAG_DECRYPTED,{frag:t,part:r,payload:e,stats:{tstart:a,tdecrypt:performance.now()}})})).catch((function(e){i.hls.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t,part:r}),r||(i.warn(e.name+": "+e.message),i.state=Rn.IDLE)}))},r.doTick=function(){if(this.state===Rn.IDLE&&this.levels){var e;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;var t=this.currentTrackId,r=this.levels[t],i=null==r?void 0:r.details;if(!i||this.waitForLive(r)||this.waitForCdnTuneIn(i))return void(this.startFragRequested=!1);var n=this.config,a=this.playhead,s=si.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],a,n.maxBufferHole),o=s.end,l=s.len;if(l>Math.max(this.hls.maxBufferLength+i.levelTargetDuration,(null==(e=this.hls.mainForwardBufferInfo)?void 0:e.len)||0)||l&&!this.buffering)return;var u=this.getNextFragment(o,i);if(!u)return;if(W(u)){var d,h=u.sn-i.startSN,f=i.fragments[h-1];u.cc!==(null==f?void 0:f.cc)||null!=(d=i.partList)&&d.length||this.fragmentTracker.getState(f)!==Nr||(u=f)}this.loadFragment(u,r,o)}},r.loadFragment=function(t,r,i){var n=this.fragmentTracker.getState(t);n!==Nr&&n!==Br||e.prototype.loadFragment.call(this,t,r,i)},a(t,[{key:"mediaBufferTimeRanges",get:function(){return new Lu(this.tracksBuffered[this.currentTrackId]||[])}}])}(bn),Lu=function(e){this.buffered=void 0;var t=function(t,r,i){if((r>>>=0)>i-1)throw new DOMException("Failed to execute '"+t+"' on 'TimeRanges': The index provided ("+r+") is greater than the maximum bound ("+i+")");return e[r][t]};this.buffered={get length(){return e.length},end:function(r){return t("end",r,e.length)},start:function(r){return t("start",r,e.length)}}},Ru=function(){if(null!=Ri&&Ri.VTTCue)return self.VTTCue;var e=["","lr","rl"],t=["start","middle","end","left","right"];function r(e,t){if("string"!=typeof t)return!1;if(!Array.isArray(e))return!1;var r=t.toLowerCase();return!!~e.indexOf(r)&&r}function i(e){return r(t,e)}function n(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",n({},l,{get:function(){return T},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",n({},l,{get:function(){return S},set:function(e){if(e<0||e>100)throw new Error("Size must be between 0 and 100.");S=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",n({},l,{get:function(){return A},set:function(e){var t=i(e);if(!t)throw new SyntaxError("An invalid or illegal string was specified.");A=t,this.hasBeenReset=!0}})),o.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}(),bu=function(){function e(){}return e.prototype.decode=function(e,t){if(!e)return"";if("string"!=typeof e)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))},e}();function ku(e){function t(e,t,r,i){return 3600*(0|e)+60*(0|t)+(0|r)+parseFloat(i||0)}var r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var Du=function(){function e(){this.values=Object.create(null)}var t=e.prototype;return t.set=function(e,t){this.get(e)||""===t||(this.values[e]=t)},t.get=function(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t},t.has=function(e){return e in this.values},t.alt=function(e,t,r){for(var i=0;i=0&&r<=100)return this.set(e,r),!0}return!1},e}();function Pu(e,t,r,i){var n=i?e.split(i):[e];for(var a in n)if("string"==typeof n[a]){var s=n[a].split(r);2===s.length&&t(s[0],s[1])}}var _u=new Ru(0,0,""),Cu="middle"===_u.align?"middle":"center";function wu(e,t,r){var i=e;function n(){var t=ku(e);if(null===t)throw new Error("Malformed timestamp: "+i);return e=e.replace(/^[^\sa-zA-Z-]+/,""),t}function a(){e=e.replace(/^\s+/,"")}if(a(),t.startTime=n(),a(),"--\x3e"!==e.slice(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);e=e.slice(3),a(),t.endTime=n(),a(),function(e,t){var i=new Du;Pu(e,(function(e,t){var n;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":n=t.split(","),i.integer(e,n[0]),i.percent(e,n[0])&&i.set("snapToLines",!1),i.alt(e,n[0],["auto"]),2===n.length&&i.alt("lineAlign",n[1],["start",Cu,"end"]);break;case"position":n=t.split(","),i.percent(e,n[0]),2===n.length&&i.alt("positionAlign",n[1],["start",Cu,"end","line-left","line-right","auto"]);break;case"size":i.percent(e,t);break;case"align":i.alt(e,t,["start",Cu,"end","left","right"])}}),/:/,/\s/),t.region=i.get("region",null),t.vertical=i.get("vertical","");var n=i.get("line","auto");"auto"===n&&-1===_u.line&&(n=-1),t.line=n,t.lineAlign=i.get("lineAlign","start"),t.snapToLines=i.get("snapToLines",!0),t.size=i.get("size",100),t.align=i.get("align",Cu);var a=i.get("position","auto");"auto"===a&&50===_u.position&&(a="start"===t.align||"left"===t.align?0:"end"===t.align||"right"===t.align?100:50),t.position=a}(e,t)}function Ou(e){return e.replace(//gi,"\n")}var Mu=function(){function e(){this.state="INITIAL",this.buffer="",this.decoder=new bu,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var t=e.prototype;return t.parse=function(e){var t=this;function r(){var e=t.buffer,r=0;for(e=Ou(e);r0&&f.push(e)},d.onparsingerror=function(e){u=e},d.onflush=function(){u?s(u):a(f)},h.forEach((function(e){if(y){if(e.startsWith("X-TIMESTAMP-MAP=")){y=!1,p=!0,e.slice(16).split(",").forEach((function(e){e.startsWith("LOCAL:")?g=e.slice(6):e.startsWith("MPEGTS:")&&(v=parseInt(e.slice(7)))}));try{m=function(e){var t=parseInt(e.slice(-3)),r=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),n=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!(x(t)&&x(r)&&x(i)&&x(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+e);return t+=1e3*r,(t+=6e4*i)+36e5*n}(g)/1e3}catch(e){u=e}return}""===e&&(y=!1)}d.parse(e+"\n")})),d.flush()}var Bu="stpp.ttml.im1t",Gu=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Ku=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Vu={left:"start",center:"center",right:"end",start:"start",end:"end"};function Hu(e,t,r,i){var n=Ze(new Uint8Array(e),["mdat"]);if(0!==n.length){var a,s,o,u,d=n.map((function(e){return Re(e)})),h=(a=t.baseTime,s=1,void 0===(o=t.timescale)&&(o=1),void 0===u&&(u=!1),wa(a,s,1/o,u));try{d.forEach((function(e){return r(function(e,t){var r=(new DOMParser).parseFromString(e,"text/xml"),i=r.getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");var n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:1},a=Object.keys(n).reduce((function(e,t){return e[t]=i.getAttribute("ttp:"+t)||n[t],e}),{});!i.getAttribute("ttp:tickRate")&&i.getAttribute("ttp:frameRate")&&(a.tickRate=Number(a.frameRate)*Number(a.subFrameRate));var s="preserve"!==i.getAttribute("xml:space"),o=ju(Yu(i,"styling","style")),u=ju(Yu(i,"layout","region")),d=Yu(i,"body","[begin]");return[].map.call(d,(function(e){var r=Wu(e,s);if(!r||!e.hasAttribute("begin"))return null;var i=zu(e.getAttribute("begin"),a),n=zu(e.getAttribute("dur"),a),d=zu(e.getAttribute("end"),a);if(null===i)throw Xu(e);if(null===d){if(null===n)throw Xu(e);d=i+n}var h=new Ru(i-t,d-t,r);h.id=Nu(h.startTime,h.endTime,h.text);var f=function(e,t,r){var i="http://www.w3.org/ns/ttml#styling",n=null,a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],s=null!=e&&e.hasAttribute("style")?e.getAttribute("style"):null;return s&&r.hasOwnProperty(s)&&(n=r[s]),a.reduce((function(r,a){var s=qu(t,i,a)||qu(e,i,a)||qu(n,i,a);return s&&(r[a]=s),r}),{})}(u[e.getAttribute("region")],o[e.getAttribute("style")],o),c=f.textAlign;if(c){var g=Vu[c];g&&(h.lineAlign=g),h.align=c}return l(h,f),h})).filter((function(e){return null!==e}))}(e,h))}))}catch(e){i(e)}}else i(new Error("Could not parse IMSC1 mdat"))}function Yu(e,t,r){var i=e.getElementsByTagName(t)[0];return i?[].slice.call(i.querySelectorAll(r)):[]}function ju(e){return e.reduce((function(e,t){var r=t.getAttribute("xml:id");return r&&(e[r]=t),e}),{})}function Wu(e,t){return[].slice.call(e.childNodes).reduce((function(e,r,i){var n;return"br"===r.nodeName&&i?e+"\n":null!=(n=r.childNodes)&&n.length?Wu(r,t):t?e+r.textContent.trim().replace(/\s+/g," "):e+r.textContent}),"")}function qu(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function Xu(e){return new Error("Could not parse ttml timestamp "+e)}function zu(e,t){if(!e)return null;var r=ku(e);return null===r&&(Gu.test(e)?r=function(e,t){var r=Gu.exec(e),i=(0|r[4])+(0|r[5])/t.subFrameRate;return 3600*(0|r[1])+60*(0|r[2])+(0|r[3])+i/t.frameRate}(e,t):Ku.test(e)&&(r=function(e,t){var r=Ku.exec(e),i=Number(r[1]);switch(r[2]){case"h":return 3600*i;case"m":return 60*i;case"ms":return i/1e3;case"f":return i/t.frameRate;case"t":return i/t.tickRate}return i}(e,t))),r}var Qu=function(e){function t(t){var r;return(r=e.call(this,t,"subtitle-track-controller")||this).media=null,r.tracks=[],r.groupIds=null,r.tracksInGroup=[],r.trackId=-1,r.currentTrack=null,r.selectDefaultTrack=!0,r.queuedDefaultTrack=-1,r.useTextTrackPolling=!1,r.subtitlePollingInterval=-1,r._subtitleDisplay=!0,r.asyncPollTrackChange=function(){return r.pollTrackChange(0)},r.onTextTracksChanged=function(){if(r.useTextTrackPolling||self.clearInterval(r.subtitlePollingInterval),r.media&&r.hls.config.renderTextTracksNatively){var e,t=-1,i=!1;if(r.currentTrack){var n,a=null==(n=r.currentTrack.trackNode)?void 0:n.track.mode;"showing"===a?(t=r.trackId,i=!0):"hidden"===a&&(t=r.trackId)}if(!i)for(var s=0;s-1&&(r._subtitleDisplay="showing"===(null==(e=r.tracksInGroup[t].trackNode)?void 0:e.track.mode)),r.setSubtitleTrack(t,!0)}},r.registerListeners(),r}d(t,e);var r=t.prototype;return r.destroy=function(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,e.prototype.destroy.call(this)},r.registerListeners=function(){var e=this.hls;e.on(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_PARSED,this.onManifestParsed,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(G.ERROR,this.onError,this)},r.unregisterListeners=function(){var e=this.hls;e.off(G.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_PARSED,this.onManifestParsed,this),e.off(G.LEVEL_LOADING,this.onLevelLoading,this),e.off(G.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(G.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(G.ERROR,this.onError,this)},r.createTracksInGroup=function(){var e,t=this;if(this.media&&this.hls.config.renderTextTracksNatively){this.tracksInGroup.forEach((function(e){e.trackNode||(e.trackNode=Nl(t.media,Ul(e),e.name,e.lang))}));var r=null==(e=this.currentTrack)||null==(e=e.trackNode)?void 0:e.track;"disabled"===(null==r?void 0:r.mode)&&(r.mode=this._subtitleDisplay?"showing":"hidden")}},r.onMediaAttached=function(e,t){var r=t.media;this.media=r;var i=this.trackId;this.queuedDefaultTrack>-1&&(i=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(i),this.createTracksInGroup(),this.useTextTrackPolling=!(r.textTracks&&"onchange"in r.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):r.textTracks.addEventListener("change",this.asyncPollTrackChange)},r.pollTrackChange=function(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)},r.onMediaDetaching=function(e,t){var r=this.media;if(r){var i=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,i||this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach((function(e){var t=e.trackNode;t&&(t.track.mode="hidden",t.remove(),e.trackNode=void 0)}))}},r.onManifestLoading=function(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0},r.onManifestParsed=function(e,t){this.tracks=t.subtitleTracks},r.onSubtitleTrackLoaded=function(e,t){var r=t.id,i=t.groupId,n=t.details,a=this.tracksInGroup[r];if(a&&a.groupId===i){var s=a.details;a.details=t.details,this.log("Subtitle track "+r+' "'+a.name+'" lang:'+a.lang+" group:"+i+" loaded ["+n.startSN+"-"+n.endSN+"]"),r===this.trackId&&this.playlistLoaded(r,t,s)}else this.warn("Subtitle track with id:"+r+" and group:"+i+" not found in active group "+(null==a?void 0:a.groupId))},r.onLevelLoading=function(e,t){this.switchLevel(t.level)},r.onLevelSwitching=function(e,t){this.switchLevel(t.level)},r.switchLevel=function(e){var t=this,r=this.hls.levels[e];if(r){var i=r.subtitleGroups||null,n=this.groupIds,a=this.currentTrack;if(!i||(null==n?void 0:n.length)!==(null==i?void 0:i.length)||null!=i&&i.some((function(e){return-1===(null==n?void 0:n.indexOf(e))}))){this.groupIds=i;var s=[];if(this.tracks.forEach((function(e){(e.textCodec===Bu?t.hls.config.enableIMSC1:t.hls.config.enableWebVTT)&&(!i||i.indexOf(e.groupId)>-1?(e.id=s.length,s.push(e)):e.trackNode&&(e.trackNode.remove(),e.trackNode=void 0))})),s.length===this.tracksInGroup.length){for(var o=!1,l=0;l-1)a=s[d];else{var h=ur(u,this.tracks);a=this.tracks[h]}}var f=this.findTrackId(a);-1===f&&a&&(f=this.findTrackId(null));var c={subtitleTracks:s};this.log("Updating subtitle tracks, "+s.length+' track(s) found in "'+(null==i?void 0:i.join(","))+'" group-id'),this.hls.trigger(G.SUBTITLE_TRACKS_UPDATED,c),this.setSubtitleTrack(f),this.createTracksInGroup()}}},r.findTrackId=function(e){for(var t=this.tracksInGroup,r=this.selectDefaultTrack,i=0;i-1){var n=this.tracksInGroup[i];return this.setSubtitleTrack(i,!0),n}if(r)return null;var a=ur(e,t);if(a>-1)return t[a]}}return null},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=t.id,n=t.groupId,a=this.getUrlWithDirectives(t.url,r),s=t.details,o=null==s?void 0:s.age;this.log("Loading subtitle "+i+' "'+t.name+'" lang:'+t.lang+" group:"+n+(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):"")+" "+a),this.hls.trigger(G.SUBTITLE_TRACK_LOADING,{url:a,id:i,groupId:n,deliveryDirectives:r||null,track:t})},r.toggleTrackModes=function(){var e=this;if(this.media&&this.hls.config.renderTextTracksNatively){var t=this.currentTrack;this.tracksInGroup.forEach((function(r){if(r.trackNode){var i=r===t?e._subtitleDisplay?"showing":"hidden":"disabled",n=r.trackNode.track;n.mode!==i&&(n.mode=i)}}))}},r.setSubtitleTrack=function(e,t){void 0===t&&(t=!1);var r=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=e),e<-1||e>=r.length||!x(e))this.warn("Invalid subtitle track id: "+e);else{var i=this.currentTrack,n=r[e]||null;if(this.trackId=e,this.currentTrack=n,t&&this.toggleTrackModes(),n){var a=!!n.details&&!n.details.live;if(n!==i||!a){this.log("Switching to subtitle-track "+e+(n?' "'+n.name+'" lang:'+n.lang+" group:"+n.groupId:""));var s=n.id,o=n.groupId,l=void 0===o?"":o,u=n.name,d=n.type,h=n.url;this.hls.trigger(G.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:d,url:h});var f=this.switchParams(n.url,null==i?void 0:i.details,n.details);this.loadPlaylist(f)}}else i&&this.hls.trigger(G.SUBTITLE_TRACK_SWITCH,{id:e})}},a(t,[{key:"subtitleDisplay",get:function(){return this._subtitleDisplay},set:function(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}},{key:"allSubtitleTracks",get:function(){return this.tracks}},{key:"subtitleTracks",get:function(){return this.tracksInGroup}},{key:"subtitleTrack",get:function(){return this.trackId},set:function(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e,!0)}}])}(os),$u={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},Zu=function(e){return String.fromCharCode($u[e]||e)},Ju=15,ed=42,td={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},rd={17:2,18:4,21:6,22:8,23:10,19:13,20:15},id={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},nd={25:2,26:4,29:6,30:8,31:10,27:13,28:15},ad=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],sd=function(){function e(){this.time=null,this.verboseLevel=0}return e.prototype.log=function(e,t){if(this.verboseLevel>=e){var r="function"==typeof t?t():t;me.log(this.time+" ["+e+"] "+r)}},e}(),od=function(e){for(var t=[],r=0;r=ed&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=41)},t.moveCursor=function(e){var t=Math.min(this.pos+e,ed);if(e>1)for(var r=this.pos+1;r=144&&this.backSpace();var r=Zu(e);this.pos>=ed?this.logger.log(0,(function(){return"Cannot insert "+e.toString(16)+" ("+r+") at position "+t.pos+". Skipping it!"})):(this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1))},t.clearFromPos=function(e){var t;for(t=e;t0&&(r=e?"["+t.join(" | ")+"]":t.join("\n")),r},t.getTextAndFormat=function(){return this.rows},e}(),cd=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 fd(r),this.nonDisplayedMemory=new fd(r),this.lastOutputScreen=new fd(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(2,(function(){return"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=this,r=0;r=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(2,"MIDROW: "+ar(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}(),gd=function(){function e(e,t,r){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory={a:null,b:null},this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new sd,this.field=e,this.outputFilters=[null,t,r]}var t=e.prototype;return t.getHandler=function(e){return this.outputFilters[e]},t.setHandler=function(e,t){var r;this.outputFilters[e]=t,null==(r=this.channels[e])||r.setHandler(t)},t.getChannel=function(e){var t=this.channels[e];return t||(t=this.channels[e]=new cd(this.field+e-1,this.outputFilters[e],this.logger)),t},t.addData=function(e,t){var r=this;this.logger.time=e;for(var i=function(e){var i=127&t[e],n=127&t[e+1],a=!1,s=null;if(0===i&&0===n)return 0;r.logger.log(3,(function(){return"["+od([t[e],t[e+1]])+"] -> ("+od([i,n])+")"}));var o=r.cmdHistory;if(i>=16&&i<=31){if(function(e,t,r){return r.a===e&&r.b===t}(i,n,o))return vd(null,null,o),r.logger.log(3,(function(){return"Repeated command ("+od([i,n])+") is dropped"})),0;vd(i,n,r.cmdHistory),(a=r.parseCmd(i,n))||(a=r.parseMidrow(i,n)),a||(a=r.parsePAC(i,n)),a||(a=r.parseBackgroundAttributes(i,n))}else vd(null,null,o);if(!a&&(s=r.parseChars(i,n))){var l=r.currentChannel;l&&l>0?r.getChannel(l).insertChars(s):r.logger.log(2,"No channel found yet. TEXT-MODE?")}a||s||r.logger.log(2,(function(){return"Couldn't parse cleaned data "+od([i,n])+" orig: "+od([t[e],t[e+1]])}))},n=0;n=32&&t<=47||(23===e||31===e)&&t>=33&&t<=35))return!1;var r=20===e||21===e||23===e?1:2,i=this.getChannel(r);return 20===e||21===e||28===e||29===e?32===t?i.ccRCL():33===t?i.ccBS():34===t?i.ccAOF():35===t?i.ccAON():36===t?i.ccDER():37===t?i.ccRU(2):38===t?i.ccRU(3):39===t?i.ccRU(4):40===t?i.ccFON():41===t?i.ccRDC():42===t?i.ccTR():43===t?i.ccRTD():44===t?i.ccEDM():45===t?i.ccCR():46===t?i.ccENM():47===t&&i.ccEOC():i.ccTO(t-32),this.currentChannel=r,!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(0,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(t),this.logger.log(3,(function(){return"MIDROW ("+od([e,t])+")"})),!0)}return!1},t.parsePAC=function(e,t){var r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(16===e||24===e)&&t>=64&&t<=95))return!1;var i=e<=23?1:2;return r=t>=64&&t<=95?1===i?td[e]:id[e]:1===i?rd[e]:nd[e],this.getChannel(i).setPAC(this.interpretPAC(r,t)),this.currentChannel=i,!0},t.interpretPAC=function(e,t){var r,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,n=null,a=null;return e>=25?(r=2,a=e-8):(r=1,a=e),a>=17&&a<=19?(i=17===a?t+80:18===a?t+112:t+144,this.logger.log(2,(function(){return"Special char '"+Zu(i)+"' in channel "+r})),n=[i]):e>=32&&e<=127&&(n=0===t?[e]:[e,t]),n&&this.logger.log(3,(function(){return"Char codes =  "+od(n).join(",")})),n},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=ad[r],t%2==1&&(i.background=i.background+"_semi")):45===t?i.background="transparent":(i.foreground="black",47===t&&(i.underline=!0));var n=e<=23?1:2;return this.getChannel(n).setBkgData(i),!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=[],this.startTime=null},e}(),pd=function(){function e(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,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=e,this.config=e.config,this.Cues=e.config.cueHandler,this.cueCache={},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}},e.on(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(G.FRAG_LOADING,this.onFragLoading,this),e.on(G.FRAG_LOADED,this.onFragLoaded,this),e.on(G.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(G.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(G.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(G.BUFFER_APPENDED,this.onBufferAppended,this),e.on(G.BUFFER_FLUSHING,this.onBufferFlushing,this)}var t=e.prototype;return t.destroy=function(){var e=this.hls;e.off(G.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(G.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(G.FRAG_LOADING,this.onFragLoading,this),e.off(G.FRAG_LOADED,this.onFragLoaded,this),e.off(G.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(G.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(G.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(G.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(G.BUFFER_APPENDED,this.onBufferAppended,this),e.off(G.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0},t.initCea608Parsers=function(){var e=new md(this,"textTrack1"),t=new md(this,"textTrack2"),r=new md(this,"textTrack3"),i=new md(this,"textTrack4");this.cea608Parser1=new gd(1,e,t),this.cea608Parser2=new gd(3,r,i)},t.addCues=function(e,t,r,i,n){for(var a,s,o,l,u=!1,d=n.length;d--;){var h=n[d],f=(a=h[0],s=h[1],o=t,l=r,Math.min(s,l)-Math.max(a,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||n.push([t,r]),this.config.renderTextTracksNatively){var c=this.cueCache[e];if(c){var g=this.Cues.newCue(null,t,r,i);g.length&&c.push.apply(c,g)}else{var v=this.captionsTracks[e].track;this.Cues.newCue(v,t,r,i)}}else{var m,p=this.Cues.newCue(null,t,r,i),y=null==(m=this.captionsProperties[e])?void 0:m.media;this.hls.trigger(G.CUES_PARSED,{type:"captions",cues:p,track:e,closedCaptions:y})}},t.onInitPtsFound=function(e,t){var r=this,i=t.id,n=t.timestampOffsets,a=this.unparsedVttFrags;i===H.MAIN&&(this.initPTS=n),a.length&&(this.unparsedVttFrags=[],a.forEach((function(e){r.initPTS[e.frag.cc]?r.onFragLoaded(G.FRAG_LOADED,e):r.hls.trigger(G.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})})))},t.createCaptionsTrack=function(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)},t.createNativeTrack=function(e){if(!this.captionsTracks[e]){var t=this.captionsProperties,r=this.captionsTracks,i=this.cueCache,n=this.media,a=t[e],s=a.label,o=a.languageCode;n&&(i[e]=[],r[e]=Nl(n,"captions",s,o,"hidden"))}},t.createNonNativeTrack=function(e){if(!this.nonNativeCaptionsTracks[e]){var t=this.captionsProperties[e];if(t){var r={_id:e,label:t.label,kind:"captions",default:!!t.media&&!!t.media.default,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger(G.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}}},t.onMediaAttaching=function(e,t){this.media=t.media},t.onMediaDetaching=function(e,t){var r=!!t.transferMedia;if(this.media=null,!r){if(this.config.renderTextTracksNatively){var i=this.captionsTracks,n=this.cueCache;for(var a in i)i[a].remove(),delete n[a]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}},t.onManifestLoading=function(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs={ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}},this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())},t.onSubtitleTracksUpdated=function(e,t){var r=t.subtitleTracks||[];if(r.length&&!this.config.renderTextTracksNatively&&!ls(this.tracks,r)){var i=r.map((function(e){return{label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}}));this.hls.trigger(G.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:i})}this.tracks=r},t.onManifestLoaded=function(e,t){var r=this;this.config.enableCEA708Captions&&t.captions&&t.captions.forEach((function(e){var t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(t){var i="textTrack"+t[1],n=r.captionsProperties[i];n&&(n.label=e.name,e.lang&&(n.languageCode=e.lang),n.media=e)}}))},t.closedCaptionsForLevel=function(e){var t=this.hls.levels[e.level];return null==t?void 0:t.attrs["CLOSED-CAPTIONS"]},t.onFragLoading=function(e,t){if(this.enabled&&t.frag.type===H.MAIN){var r,i,n=this.cea608Parser1,a=this.cea608Parser2,s=this.lastSn,o=t.frag,l=o.cc,u=o.sn,d=null!=(r=null==(i=t.part)?void 0:i.index)?r:-1;n&&a&&(u!==s+1||u===s&&d!==this.lastPartIndex+1||l!==this.lastCc)&&(n.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=d}},t.onFragLoaded=function(e,t){var r,i=t.frag,n=t.payload;if(i.level=r&&a.endTime<=i&&t.splice(n,1)}}))}this.config.renderTextTracksNatively&&0===r&&void 0!==n&&this.tracks.forEach((function(e){var t,i=null==(t=e.trackNode)?void 0:t.track;i&&Gl(i,r,n)}))}},t.extractCea608Data=function(e){for(var t=[[],[]],r=31&e[0],i=2,n=0;n=16?o--:o++;var g=Ou(l.trim()),v=Nu(t,r,g);null!=e&&null!=(f=e.cues)&&f.getCueById(v)||((a=new d(t,r,g)).id=v,a.line=h+1,a.align="left",a.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(a))}return e&&u.length&&(u.sort((function(e,t){return"auto"===e.line||"auto"===t.line?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line})),u.forEach((function(t){return Bl(e,t)}))),u}},Td=function(){function e(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new K}var t=e.prototype;return t.destroy=function(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null},t.load=function(e,t,r){var i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()},t.abort=function(){var e;this.abortInternal(),null!=(e=this.callbacks)&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())},t.loadtimeout=function(){if(this.config){var e=this.config.loadPolicy.timeoutRetry;if(ne(e,this.stats.retry,!0))this.retry(e);else{var t;me.warn("timeout while loading "+(null==(t=this.context)?void 0:t.url));var r=this.callbacks;r&&(this.abortInternal(),r.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}},t.retry=function(e){var t=this,r=this.context,i=this.stats;this.retryDelay=re(e,i.retry),i.retry++,me.warn((status?"HTTP Status "+status:"Timeout")+" while loading "+(null==r?void 0:r.url)+", retrying "+i.retry+"/"+e.maxNumRetry+" in "+this.retryDelay+"ms"),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout((function(){return t.loadInternal()}),this.retryDelay)},e}(),Sd=/(\d+)-(\d+)\/(\d+)/,Ad=function(e){function t(t){var r;return(r=e.call(this)||this).fetchSetup=void 0,r.request=null,r.response=null,r.controller=null,r.fetchSetup=t.fetchSetup||Id,r}d(t,e);var r=t.prototype;return r.destroy=function(){this.request=null,e.prototype.destroy.call(this),this.response=null,this.controller=null,this.fetchSetup=null},r.abortInternal=function(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())},r.getNetworkDetails=function(){return this.response},r.resetInternalLoader=function(){this.response=null},r.loadInternal=function(){var e=this,t=this.config,r=this.context,i=this.stats;if(t&&r){i.loading.first=0,i.loaded=0,i.aborted=!1,this.controller=new self.AbortController;var n=function(e,t){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(l({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}(r,this.controller.signal),a="arraybuffer"===r.responseType,s=a?"byteLength":"length",o=t.loadPolicy,u=o.maxTimeToFirstByteMs,d=o.maxLoadTimeMs;this.request=this.fetchSetup(r,n),self.clearTimeout(this.requestTimeout),t.timeout=u&&x(u)?u:d,this.requestTimeout=self.setTimeout((function(){e.loadtimeout()}),t.timeout),(Xa(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then((function(n){var s;e.response=n;var o=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(e.requestTimeout),t.timeout=d,e.requestTimeout=self.setTimeout((function(){e.loadtimeout()}),d-(o-i.loading.start)),!n.ok){var l=n.status,u=n.statusText;throw new Ld(u||"fetch, bad network response",l,n)}i.loading.first=o,i.total=function(e){var t=e.get("Content-Range");if(t){var r=function(e){var t=Sd.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}(t);if(x(r))return r}var i=e.get("Content-Length");if(i)return parseInt(i)}(n.headers)||i.total;var h=null==(s=e.callbacks)?void 0:s.onProgress;return h&&x(t.highWaterMark)?e.loadProgressively(n,i,r,t.highWaterMark,h):a?n.arrayBuffer():"json"===r.responseType?n.json():n.text()})).then((function(n){var a,o,l=e.response;if(!l)throw new Error("loader destroyed");self.clearTimeout(e.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);var u=n[s];u&&(i.loaded=i.total=u);var d={url:l.url,data:n,code:l.status},h=null==(a=e.callbacks)?void 0:a.onProgress;h&&!x(t.highWaterMark)&&h(i,r,n,l),null==(o=e.callbacks)||o.onSuccess(d,i,r,l)})).catch((function(n){if(self.clearTimeout(e.requestTimeout),!i.aborted){var a,s=n&&n.code||0,o=n?n.message:null,l=t.loadPolicy.errorRetry;ne(l,i.retry,!1,{url:r.url,data:void 0,code:s})?e.retry(l):(me.error(s+" while loading "+r.url),null==(a=e.callbacks)||a.onError({code:s,text:o},r,n?n.details:null,i))}}))}},r.getCacheAge=function(){var e=null;if(this.response){var t=this.response.headers.get("age");e=t?parseFloat(t):null}return e},r.getResponseHeader=function(e){return this.response?this.response.headers.get(e):null},r.loadProgressively=function(e,t,r,i,n){void 0===i&&(i=0);var a=new Pn,s=e.body.getReader(),o=function(){return s.read().then((function(s){if(s.done)return a.dataLength&&n(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return t.loaded+=u,u=i&&n(t,r,a.flush().buffer,e)):n(t,r,l.buffer,e),o()})).catch((function(){return Promise.reject()}))};return o()},t}(Td);function Id(e,t){return new self.Request(e.url,t)}var Ld=function(e){function t(t,r,i){var n;return(n=e.call(this,t)||this).code=void 0,n.details=void 0,n.code=r,n.details=i,n}return d(t,e),t}(E(Error)),Rd=/^age:\s*[\d.]+\s*$/im,bd=function(e){function t(t){var r;return(r=e.call(this)||this).xhrSetup=void 0,r.loader=null,r.xhrSetup=t.xhrSetup||null,r}d(t,e);var r=t.prototype;return r.destroy=function(){e.prototype.destroy.call(this),this.loader=null,this.xhrSetup=null},r.abortInternal=function(){var e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,4!==e.readyState&&(this.stats.aborted=!0,e.abort()))},r.getNetworkDetails=function(){return this.loader},r.resetInternalLoader=function(){this.loader=null},r.loadInternal=function(){var e=this,t=this.config,r=this.context;if(t&&r){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(e.loader===i&&!e.stats.aborted)return a.call(e,i,r.url,r)})).catch((function(t){if(e.loader===i&&!e.stats.aborted)return i.open("GET",r.url,!0),a.call(e,i,r.url,r)})).then((function(){e.loader!==i||e.stats.aborted||e.openAndSendXhr(i,r,t)})).catch((function(t){var a;null==(a=e.callbacks)||a.onError({code:i.status,text:t.message},r,i,n)})):this.openAndSendXhr(i,r,t)}},r.openAndSendXhr=function(e,t,r){e.readyState||e.open("GET",t.url,!0);var i=t.headers,n=r.loadPolicy,a=n.maxTimeToFirstByteMs,s=n.maxLoadTimeMs;if(i)for(var o in i)e.setRequestHeader(o,i[o]);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,self.clearTimeout(this.requestTimeout),r.timeout=a&&x(a)?a:s,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()},r.readystatechange=function(){var e=this.context,t=this.loader,r=this.stats;if(e&&t){var i=t.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),t.onreadystatechange=null,t.onprogress=null;var a=t.status,s="text"===t.responseType?t.responseText:null;if(a>=200&&a<300){var o=null!=s?s:t.response;if(null!=o){var l,u;r.loading.end=Math.max(self.performance.now(),r.loading.first);var d="arraybuffer"===t.responseType?o.byteLength:o.length;r.loaded=r.total=d,r.bwEstimate=8e3*r.total/(r.loading.end-r.loading.first);var h=null==(l=this.callbacks)?void 0:l.onProgress;h&&h(r,e,o,t);var f={url:t.responseURL,data:o,code:a};return e.rangeEnd&&d!==e.rangeEnd-e.rangeStart&&me.warn("Payload length "+d+" does not match requested Range: bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),void(null==(u=this.callbacks)||u.onSuccess(f,r,e,t))}}var c,g=n.loadPolicy.errorRetry;ne(g,r.retry,!1,{url:e.url,data:void 0,code:a})?this.retry(g):(me.error(a+" while loading "+e.url),null==(c=this.callbacks)||c.onError({code:a,text:t.statusText},e,t,r))}}},r.loadprogress=function(e){var t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)},r.getCacheAge=function(){var e=null;if(this.loader&&Rd.test(this.loader.getAllResponseHeaders())){var t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e},r.getResponseHeader=function(e){return this.loader&&new RegExp("^"+e+":\\s*[\\d.]+\\s*$","im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null},t}(Td),kd=c(c({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:6e7,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:bd,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:Fi,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2097152,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs: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}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,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,streamController:Zl,abrController:mr,bufferController:vs,capLevelController:As,errorController:Or,fpsController:Cl,id3TrackController:Yl,gapController:wl,latencyController:Au},{cueHandler:Ed,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:Iu,subtitleTrackController:Qu,timelineController:pd,audioStreamController:ss,audioTrackController:ds,emeController:Dl,cmcdController:Al,contentSteeringController:Il,iframeController:iu,interstitialsController:Su});function Dd(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(void 0!==t.liveMaxLatencyDurationCount&&(void 0===t.liveSyncDurationCount||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(void 0!==t.liveMaxLatencyDuration&&(void 0===t.liveSyncDuration||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(void 0!==t.liveMaxUnchangedPlaylistRefresh){var i=t.liveMaxUnchangedPlaylistRefresh,n=(a=i,s=2,o=1/0,Math.max(s,Math.min(a,o)));n!==i&&r.warn('hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from '+i+" to "+n+"."),t.liveMaxUnchangedPlaylistRefresh=n}var a,s,o,l=Pd(e),u=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return["manifest","level","frag"].forEach((function(e){var i=("level"===e?"playlist":e)+"LoadPolicy",n=void 0===t[i],a=[];u.forEach((function(r){var s=e+"Loading"+r,o=t[s];if(void 0!==o&&n){a.push(s);var u=l[i].default;switch(t[i]={default:u},r){case"TimeOut":u.maxLoadTimeMs=o,u.maxTimeToFirstByteMs=o;break;case"MaxRetry":u.errorRetry.maxNumRetry=o,u.timeoutRetry.maxNumRetry=o;break;case"RetryDelay":u.errorRetry.retryDelayMs=o,u.timeoutRetry.retryDelayMs=o;break;case"MaxRetryTimeout":u.errorRetry.maxRetryDelayMs=o,u.timeoutRetry.maxRetryDelayMs=o}}})),a.length&&r.warn('hls.js config: "'+a.join('", "')+'" setting(s) are deprecated, use "'+i+'": '+ar(t[i]))})),c(c({},l),t)}function Pd(e){return e&&"object"==typeof e?Array.isArray(e)?e.map(Pd):Object.keys(e).reduce((function(t,r){return t[r]=Pd(e[r]),t}),{}):e}function _d(e,t){var r=e.loader;r!==Ad&&r!==bd?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(e){}return!1}()&&(e.loader=Ad,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Cd=function(e){function t(t,r){var i;return(i=e.call(this,t,"level-controller")||this)._levels=[],i._firstLevel=-1,i._maxAutoLevel=-1,i._startLevel=void 0,i.currentLevel=null,i.currentLevelIndex=-1,i.manualLevelIndex=-1,i.steering=void 0,i.lastABRSwitchTime=-1,i._iframeVariants=[],i.onParsedComplete=void 0,i.steering=r,i._registerListeners(),i}d(t,e);var r=t.prototype;return r._registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(G.LEVEL_LOADED,this.onLevelLoaded,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(G.FRAG_BUFFERED,this.onFragBuffered,this),e.on(G.ERROR,this.onError,this)},r._unregisterListeners=function(){var e=this.hls;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(G.LEVEL_LOADED,this.onLevelLoaded,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(G.FRAG_BUFFERED,this.onFragBuffered,this),e.off(G.ERROR,this.onError,this)},r.destroy=function(){this._unregisterListeners(),this.steering=null,this.resetLevels(),e.prototype.destroy.call(this)},r.stopLoad=function(){this._levels.forEach((function(e){e.loadError=0,e.fragmentError=0})),e.prototype.stopLoad.call(this)},r.resetLevels=function(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]},r.onManifestLoading=function(e,t){this.resetLevels()},r.onManifestLoaded=function(e,t){var r=this,i=this.hls.config.preferManagedMediaSource,n=[],a={},s={},o=!1,l=!1,u=!1,d=!1;t.levels.forEach((function(e){var t=e.attrs,h=Md(e,i),f=e.audioCodec,c=e.videoCodec,g=e.imageCodec,v=e.width,m=e.height;if(h){o||(o=!(!v||!m)),l||(l=!!c),u||(u=!!f),d||(d=!!g);var p=t.CODECS,y=t["FRAME-RATE"],E=t["HDCP-LEVEL"],T=t["PATHWAY-ID"],S=t.RESOLUTION,A=t["VIDEO-RANGE"],I=(T||".")+"-"+e.bitrate+"-"+S+"-"+y+"-"+p+"-"+A+"-"+E;if(a[I])if(a[I].uri===e.url||e.attrs["PATHWAY-ID"])e.iframes||(a[I].addGroupId("audio",t.AUDIO),a[I].addGroupId("text",t.SUBTITLES));else{var L=s[I]+=1;e.attrs["PATHWAY-ID"]=new Array(L+1).join(".");var R=r.createLevel(e);a[I]=R,n.push(R)}else{var b=r.createLevel(e);a[I]=b,s[I]=1,n.push(b)}}else r.log('Some or all CODECS not supported "'+t.CODECS+'"')})),this.filterAndSortMediaOptions(n,t,o,l,u,d)},r.createLevel=function(e){var t=new rr(e),r=e.supplemental;if(null!=r&&r.videoCodec&&!Od(r.videoCodec,this.hls.config.preferManagedMediaSource)){var i=new Error('SUPPLEMENTAL-CODECS not supported "'+r.videoCodec+'"');this.log(i.message),t.supportedResult=Yt(i,[])}return t},r.filterAndSortMediaOptions=function(e,t,r,i,n,a){var s,o=this,l=[],u=[],d=e,h=(null==(s=t.stats)?void 0:s.parsing)||{},f=this.hls.config.preferManagedMediaSource;if((r||i)&&n&&(d=d.filter((function(e){var t,r=e.videoCodec,i=e.videoRange,n=e.width,a=e.height;return(!!r||!(!n||!a))&&!!(t=i)&&Qt.indexOf(t)>-1}))),i&&a&&(d=d.filter((function(e){return!e.imageCodec}))),0===d.length)return Promise.resolve().then((function(){if(o.hls){var e="no level with compatible codecs found in manifest",r=e;t.levels.length&&(r="one or more CODECS in variant not supported: "+ar(t.levels.map((function(e){return e.attrs.CODECS})).filter((function(e,t,r){return r.indexOf(e)===t}))),o.warn(r),e+=" ("+r+")");var i=new Error(e);o.hls.trigger(G.ERROR,{type:U.MEDIA_ERROR,details:B.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:i,reason:r})}})),void(h.end=performance.now());t.audioTracks&&xd(l=t.audioTracks.filter((function(e){return!e.audioCodec||wd(e.audioCodec,f)}))),t.subtitles&&xd(u=t.subtitles);var c=d.slice(0);d.sort((function(e,t){if(e.attrs["HDCP-LEVEL"]!==t.attrs["HDCP-LEVEL"])return(e.attrs["HDCP-LEVEL"]||"")>(t.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return Qt.indexOf(e.videoRange)-Qt.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){var i=wt(e.videoCodec),n=wt(t.videoCodec);if(i!==n)return n-i}if(e.uri===t.uri&&e.codecSet!==t.codecSet){var a=Ot(e.codecSet),s=Ot(t.codecSet);if(a!==s)return s-a}return e.averageBitrate!==t.averageBitrate?e.averageBitrate-t.averageBitrate:0}));var g=c[0];if(this.steering&&(d=this.steering.filterParsedLevels(d)).length!==c.length)for(var v=0;vE&&E===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=T)}break}var S=t.iframeVariants.filter((function(e){return Md(e,f)}));this._iframeVariants=S;var A=n&&!i,I=this.hls.config,L=!(!I.audioStreamController||!I.audioTrackController),R={levels:d,audioTracks:l,subtitleTracks:u,iframeVariants:S,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:n,video:i,altAudio:L&&!A&&l.some((function(e){return!!e.url}))};h.end=performance.now(),this.hls.trigger(G.MANIFEST_PARSED,R)},r.onError=function(e,t){!t.fatal&&t.context&&t.context.type===V.LEVEL&&t.context.level===this.level&&this.checkRetry(t)},r.onFragBuffered=function(e,t){var r=t.frag;if(r.type===H.MAIN){var i=r.elementaryStreams;if(!Object.keys(i).some((function(e){return!!i[e]})))return;var n=this._levels[r.level];null!=n&&n.loadError&&(this.log("Resetting level error count of "+n.loadError+" on frag buffered"),n.loadError=0)}},r.onLevelLoaded=function(e,t){var r,i,n=t.level,a=t.details,s=t.levelInfo;if(!s)return this.warn("Invalid level index "+n),void(null!=(i=t.deliveryDirectives)&&i.skip&&(a.deltaUpdateFailed=!0));if(s===this.currentLevel||t.withoutMultiVariant){0===s.fragmentError&&(s.loadError=0);var o=s.details;o===t.details&&o.advanced&&(o=void 0),this.playlistLoaded(n,t,o)}else null!=(r=t.deliveryDirectives)&&r.skip&&(a.deltaUpdateFailed=!0)},r.loadPlaylist=function(t){e.prototype.loadPlaylist.call(this),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)},r.loadingPlaylist=function(t,r){e.prototype.loadingPlaylist.call(this,t,r);var i=this.getUrlWithDirectives(t.uri,r),n=this.currentLevelIndex,a=t.attrs["PATHWAY-ID"],s=t.details,o=null==s?void 0:s.age;this.log("Loading level index "+n+(void 0!==(null==r?void 0:r.msn)?" at sn "+r.msn+" part "+r.part:"")+(a?" Pathway "+a:"")+(o&&s.live?" age "+o.toFixed(1)+(s.type&&" "+s.type||""):"")+" "+i),this.hls.trigger(G.LEVEL_LOADING,{url:i,level:n,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:r||null})},r.removeLevel=function(e){var t,r=this;if(1!==this._levels.length){var i=this._levels.filter((function(t,i){return i!==e||(r.steering&&r.steering.removeLevel(t),t===r.currentLevel&&(r.currentLevel=null,r.currentLevelIndex=-1,t.details&&t.details.fragments.forEach((function(e){return e.level=-1}))),!1)}));vn(i),this._levels=i,this.currentLevelIndex>-1&&null!=(t=this.currentLevel)&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);var n=i.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger(G.LEVELS_UPDATED,{levels:i})}},r.onLevelsUpdated=function(e,t){var r=t.levels;this._levels=r},r.checkMaxAutoUpdated=function(){var e=this.hls,t=e.autoLevelCapping,r=e.maxAutoLevel,i=e.maxHdcpLevel;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(G.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:i}))},a(t,[{key:"iframeVariants",get:function(){return 0===this._iframeVariants.length?null:this._iframeVariants}},{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"loadLevelObj",get:function(){return this.currentLevel}},{key:"level",get:function(){return this.currentLevelIndex},set:function(e){var t=this._levels;if(0!==t.length){if(e<0||e>=t.length){var r=new Error("invalid level idx"),i=e<0;if(this.hls.trigger(G.ERROR,{type:U.OTHER_ERROR,details:B.LEVEL_SWITCH_ERROR,level:e,fatal:i,error:r,reason:r.message}),i)return;e=Math.min(e,t.length-1)}var n=this.currentLevelIndex,a=this.currentLevel,s=a?a.attrs["PATHWAY-ID"]:void 0,o=t[e],l=o.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=o,n!==e||!a||s!==l){this.log("Switching to level "+e+" ("+(o.height?o.height+"p ":"")+(o.videoRange?o.videoRange+" ":"")+(o.codecSet?o.codecSet+" ":"")+"@"+o.bitrate+")"+(l?" with Pathway "+l:"")+" from level "+n+(s?" with Pathway "+s:""));var u={level:e,attrs:o.attrs,details:o.details,bitrate:o.bitrate,averageBitrate:o.averageBitrate,maxBitrate:o.maxBitrate,realBitrate:o.realBitrate,width:o.width,height:o.height,codecSet:o.codecSet,audioCodec:o.audioCodec,videoCodec:o.videoCodec,audioGroups:o.audioGroups,subtitleGroups:o.subtitleGroups,loaded:o.loaded,loadError:o.loadError,fragmentError:o.fragmentError,name:o.name,id:o.id,uri:o.uri,url:o.url,urlId:0,audioGroupIds:o.audioGroupIds,textGroupIds:o.textGroupIds};this.hls.trigger(G.LEVEL_SWITCHING,u);var d=o.details;if(!d||d.live){var h=this.switchParams(o.uri,null==a?void 0:a.details,d);this.loadPlaylist(h)}}}}},{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.hls.firstAutoLevel}return this._startLevel},set:function(e){this._startLevel=e}},{key:"pathways",get:function(){return this.steering?this.steering.pathways():[]}},{key:"pathwayPriority",get:function(){return this.steering?this.steering.pathwayPriority:null},set:function(e){if(this.steering){var t=this.steering.pathways(),r=e.filter((function(e){return-1!==t.indexOf(e)}));if(e.length<1)return void this.warn("pathwayPriority "+e+" should contain at least one pathway from list: "+t);this.steering.pathwayPriority=r}}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(e){var t=this.currentLevelIndex;if(-1===this.manualLevelIndex&&e!==t&&-1!==e){var r=this.hls.config.abrSwitchInterval;if(r>0){var i=performance.now(),n=i-this.lastABRSwitchTime,a=1e3*r;if(this.lastABRSwitchTime>-1&&n "+e+" ("+Math.round(n)+"ms < "+a+"ms / "+r+"s)");this.lastABRSwitchTime=i,this.log("Allowing ABR level switch: "+t+" -> "+e+" ("+Math.round(n)+"ms >= "+a+"ms / "+r+"s)")}}this.level=e,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=e)}}])}(os);function wd(e,t){return Pt(e,"audio",t)}function Od(e,t){return Pt(e,"video",t)}function Md(e,t){var r=e.audioCodec,i=e.videoCodec;r&&(e.audioCodec=r=Ft(r,t)||void 0),i&&(i=e.videoCodec=function(e){for(var t=e.split(","),r=0;r2&&"avc1"===i[0]&&(t[r]="avc1."+parseInt(i[1]).toString(16)+("000"+parseInt(i[2]).toString(16)).slice(-4))}return t.join(",")}(i));var n=e.unknownCodecs;return!((null==n?void 0:n.length)||r&&!wd(r,t)||i&&!Od(i,t))}function xd(e){var t={};e.forEach((function(e){var r=e.groupId||"";e.id=t[r]=t[r]||0,t[r]++}))}var Fd=function(e){function t(t,r){var i;return(i=e.call(this,"key-loader",r)||this).config=void 0,i.keyLoaderInfo={},i.emeController=null,i.config=t,i}d(t,e);var r=t.prototype;return r.abort=function(e){for(var t in this.keyLoaderInfo){var r=this.keyLoaderInfo[t].loader;if(r){var i;if(e&&e!==(null==(i=r.context)?void 0:i.frag.type))return;r.abort()}}},r.destroy=function(){for(var e in this.keyLoaderInfo){var t=this.keyLoaderInfo[e].loader;t&&t.destroy()}this.emeController=null,this.keyLoaderInfo={}},r.loadClear=function(e,t,r){return this.emeController?this.emeController.loadClear(e,t,r):null},r.load=function(e,t){var r=this;return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then((function(i){return r.loadInternal(e,t,i)})):this.loadInternal(e,t)},r.loadInternal=function(e,t,r){var i=this;r&&e.setKeyFormat(r);var n=e.decryptdata;if(!n){var a=new Error(r?"Expected frag.decryptdata to be defined after setting format "+r:"Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: "+(this.emeController&&this.config.emeEnabled)+")");return Promise.reject(Nd(e,B.KEY_LOAD_ERROR,a))}var s=e;switch(n.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return"identity"===n.keyFormat?this.loadKeyHTTP(s):t?t.then((function(){return i.loadKeyEME(s)})):this.loadKeyEME(s);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(s);default:return Promise.reject(Nd(e,B.KEY_LOAD_ERROR,new Error('Key supplied with unsupported METHOD: "'+n.method+'"')))}},r.loadKeyEME=function(e){if(this.emeController&&this.config.emeEnabled){var t;if(!e.decryptdata.keyId&&null!=(t=e.initSegment)&&t.data){var r=function(e){var t=[];return ot(e,(function(e){return t.push(e.subarray(8,24))})),t}(e.initSegment.data);if(r.length){var i=r[0],n=e.decryptdata.uri;if(i.some((function(e){return 0!==e})))this.log("Using keyId found in init segment "+xe(i)+" keyUri: "+n),Bi.setKeyIdForUri(n,i);else{var a=Bi.addKeyIdForUri(n);this.log("Patching empty keyId with "+xe(a)+" keyUri: "+n),i=a}e.decryptdata.keyId=i}}return this.emeController.loadKey(e).then((function(){return{frag:e,keyInfo:{decryptdata:e.decryptdata}}}))}return Promise.reject(Nd(e,B.KEY_LOAD_ERROR,new Error("emeEnabled with controller: "+(this.emeController&&this.config.emeEnabled)+")")))},r.loadKeyHTTP=function(e){var t=this,r=e.decryptdata,i=r.uri;if(!i)return Promise.reject(Nd(e,B.KEY_LOAD_ERROR,new Error('Invalid key URI: "'+i+'"')));var n=this.keyLoaderInfo[i];if(n){if(n.decryptdata.key)return r.key=n.decryptdata.key,n.keyLoadPromise=null,Promise.resolve({frag:e,keyInfo:n});if(n.keyLoadPromise)return n.keyLoadPromise.then((function(t){return r.key=n.decryptdata.key,c(c({},t),{},{frag:e})}))}this.log("Loading"+(r.keyId?" keyId: "+xe(r.keyId):"")+" URI: "+r.uri+" from "+e.type+" "+e.level);var a=this.config,s=new(0,a.loader)(a);e.keyLoader=s;var o=this.keyLoaderInfo[i]={decryptdata:r,keyLoadPromise:null,loader:s};return o.keyLoadPromise=new Promise((function(r,n){var l={type:V.KEY,keyInfo:o,frag:e,responseType:"arraybuffer",url:i},u=a.keyLoadPolicy.default,d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:function(e,i,a,s){var o=a.frag,l=a.keyInfo,u=a.url;if(!o.decryptdata||l!==t.keyLoaderInfo[u])return n(Nd(o,B.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),s));l.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=l.loader=l.keyLoadPromise=null,r({frag:o,keyInfo:l})},onError:function(r,a,s,o){t.resetLoader(a),n(Nd(e,B.KEY_LOAD_ERROR,new Error("HTTP Error "+r.code+" loading key "+r.text),s,c({url:i,data:void 0},r)))},onTimeout:function(r,i,a){t.resetLoader(i),n(Nd(e,B.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),a))},onAbort:function(r,i,a){t.resetLoader(i),n(Nd(e,B.INTERNAL_ABORTED,new Error("key loading aborted"),a))}};s.load(l,d,h)}))},r.resetLoader=function(e){var t=e.frag,r=e.keyInfo,i=e.url,n=r.loader;t.keyLoader===n&&(t.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[i],n&&n.destroy()},t}(ue);function Nd(e,t,r,i,n){return void 0===t&&(t=B.KEY_LOAD_ERROR),new ri({type:U.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:n,error:r,networkDetails:i||null})}function Ud(e){switch(e.type){case V.AUDIO_TRACK:return H.AUDIO;case V.SUBTITLE_TRACK:return H.SUBTITLE;default:return H.MAIN}}function Bd(e,t){var r=e.url;return void 0!==r&&0!==r.indexOf("data:")||(r=t.url),r}var Gd=function(){function e(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}var t=e.prototype;return t.startLoad=function(e){},t.stopLoad=function(){this.destroyInternalLoaders()},t.registerListeners=function(){var e=this.hls;e.on(G.MANIFEST_LOADING,this.onManifestLoading,this),e.on(G.LEVEL_LOADING,this.onLevelLoading,this),e.on(G.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(G.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(G.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.unregisterListeners=function(){var e=this.hls;e.off(G.MANIFEST_LOADING,this.onManifestLoading,this),e.off(G.LEVEL_LOADING,this.onLevelLoading,this),e.off(G.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(G.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(G.LEVELS_UPDATED,this.onLevelsUpdated,this)},t.createInternalLoader=function(e){var t=this.hls.config,r=t.pLoader,i=t.loader,n=new(r||i)(t);return this.loaders[e.type]=n,n},t.getInternalLoader=function(e){return this.loaders[e.type]},t.resetInternalLoader=function(e){this.loaders[e]&&delete this.loaders[e]},t.destroyInternalLoaders=function(){for(var e in this.loaders){var t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}},t.destroy=function(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()},t.onManifestLoading=function(e,t){var r=t.url;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:V.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})},t.onLevelLoading=function(e,t){var r=t.id,i=t.level,n=t.pathwayId,a=t.url,s=t.deliveryDirectives,o=t.levelInfo;this.load({id:r,level:i,pathwayId:n,responseType:"text",type:V.LEVEL,url:a,deliveryDirectives:s,levelOrTrack:o})},t.onAudioTrackLoading=function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:V.AUDIO_TRACK,url:n,deliveryDirectives:a,levelOrTrack:s})},t.onSubtitleTrackLoading=function(e,t){var r=t.id,i=t.groupId,n=t.url,a=t.deliveryDirectives,s=t.track;this.load({id:r,groupId:i,level:null,responseType:"text",type:V.SUBTITLE_TRACK,url:n,deliveryDirectives:a,levelOrTrack:s})},t.onLevelsUpdated=function(e,t){var r=this.loaders[V.LEVEL];if(r){var i=r.context;i&&!t.levels.some((function(e){return e===i.levelOrTrack}))&&(r.abort(),delete this.loaders[V.LEVEL])}},t.load=function(e){var t,r,i,n=this,a=this.hls.config,s=this.getInternalLoader(e);if(s){var o=this.hls.logger,u=s.context;if((null==u?void 0:u.levelOrTrack)===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives))return void(u.url===e.url?o.log("[playlist-loader]: ignore "+e.url+" ongoing request"):o.log("[playlist-loader]: ignore "+e.url+" in favor of "+u.url));o.log("[playlist-loader]: aborting previous loader for type: "+e.type),s.abort()}if(r=e.type===V.MANIFEST?a.manifestLoadPolicy.default:l({},a.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),s=this.createInternalLoader(e),x(null==(t=e.deliveryDirectives)?void 0:t.part)&&(e.type===V.LEVEL&&null!==e.level?i=this.hls.levels[e.level].details:e.type===V.AUDIO_TRACK&&null!==e.id?i=this.hls.audioTracks[e.id].details:e.type===V.SUBTITLE_TRACK&&null!==e.id&&(i=this.hls.subtitleTracks[e.id].details),i)){var d=i.partTarget,h=i.targetduration;if(d&&h){var f=1e3*Math.max(3*d,.8*h);r=l({},r,{maxTimeToFirstByteMs:Math.min(f,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(f,r.maxTimeToFirstByteMs)})}}var c=r.errorRetry||r.timeoutRetry||{},g={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},v={onSuccess:function(e,t,r,i){var a=n.getInternalLoader(r);n.resetInternalLoader(r.type);var s=e.data;t.parsing.start=performance.now(),Wi.isMediaPlaylist(s)||r.type!==V.MANIFEST?n.handleTrackOrLevelPlaylist(e,t,r,i||null,a):n.handleMasterPlaylist(e,t,r,i)},onError:function(e,t,r,i){n.handleNetworkError(t,r,!1,e,i)},onTimeout:function(e,t,r){n.handleNetworkError(t,r,!0,void 0,e)}};s.load(e,g,v)},t.checkAutostartLoad=function(){if(this.hls){var e=this.hls,t=e.config,r=t.autoStartLoad,i=t.startPosition,n=e.forceStartLoad;(r||n)&&(this.hls.logger.log((r?"auto":"force")+" startLoad with configured startPosition "+i),this.hls.startLoad(i))}},t.handleMasterPlaylist=function(e,t,r,i){var n=this,a=this.hls,s=e.data,o=Bd(e,r),l=Wi.parseMasterPlaylist(s,o);if(l.playlistParsingError)return t.parsing.end=performance.now(),void this.handleManifestParsingError(e,r,l.playlistParsingError,i,t);var u=l.contentSteering,d=l.levels,h=l.iframeVariants,f=l.sessionData,c=l.sessionKeys,g=l.startTimeOffset,v=l.variableList;this.variableList=v,d.forEach((function(e){var t=e.unknownCodecs;if(t)for(var r=n.hls.config.preferManagedMediaSource,i=e.audioCodec,a=e.videoCodec,s=t.length;s--;){var o=t[s];Pt(o,"audio",r)?(e.audioCodec=i=i?i+","+o:o,kt.audio[i.substring(0,4)]=2,t.splice(s,1)):Pt(o,"video",r)&&(e.videoCodec=a=a?a+","+o:o,kt.video[a.substring(0,4)]=2,t.splice(s,1))}}));var m=Wi.parseMasterPlaylistMedia(s,o,l),p=m.AUDIO,y=void 0===p?[]:p,E=m.SUBTITLES,T=m["CLOSED-CAPTIONS"];y.length&&(y.some((function(e){return!e.url}))||!d[0].audioCodec||d[0].attrs.AUDIO||(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new gi({}),bitrate:0,url:""}))),a.trigger(G.MANIFEST_LOADED,{levels:d,audioTracks:y,subtitles:E,iframeVariants:h,captions:T,contentSteering:u,url:o,stats:t,networkDetails:i,sessionData:f,sessionKeys:c,startTimeOffset:g,variableList:v})},t.handleTrackOrLevelPlaylist=function(e,t,r,i,n){var a=this.hls,s=r.id,o=r.level,l=r.type,u=Bd(e,r),d=x(o)?o:x(s)?s:0,h=Ud(r),f=Wi.parseLevelPlaylist(e.data,u,d,h,0,this.variableList);if(l===V.MANIFEST){var c={attrs:new gi({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=t.loading.start+hn(f,0),a.trigger(G.MANIFEST_LOADED,{levels:[c],audioTracks:[],iframeVariants:[],url:u,stats:t,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,e,t,r,i,n)},t.handleManifestParsingError=function(e,t,r,i,n){this.hls.trigger(G.ERROR,{type:U.NETWORK_ERROR,details:B.MANIFEST_PARSING_ERROR,fatal:t.type===V.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:i,stats:n})},t.handleNetworkError=function(e,t,r,i,n){void 0===r&&(r=!1);var a="A network "+(r?"timeout":"error"+(i?" (status "+i.code+")":""))+" occurred while loading "+e.type;e.type===V.LEVEL?a+=": "+e.level+" id: "+e.id:e.type!==V.AUDIO_TRACK&&e.type!==V.SUBTITLE_TRACK||(a+=" id: "+e.id+' group-id: "'+e.groupId+'"');var s=new Error(a);this.hls.logger.warn("[playlist-loader]: "+a);var o=B.UNKNOWN,l=!1,u=this.getInternalLoader(e);switch(e.type){case V.MANIFEST:o=r?B.MANIFEST_LOAD_TIMEOUT:B.MANIFEST_LOAD_ERROR,l=!0;break;case V.LEVEL:o=r?B.LEVEL_LOAD_TIMEOUT:B.LEVEL_LOAD_ERROR,l=!1;break;case V.AUDIO_TRACK:o=r?B.AUDIO_TRACK_LOAD_TIMEOUT:B.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case V.SUBTITLE_TRACK:o=r?B.SUBTITLE_TRACK_LOAD_TIMEOUT:B.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(e.type);var d={type:U.NETWORK_ERROR,details:o,fatal:l,url:e.url,loader:u,context:e,error:s,networkDetails:t,stats:n};if(i){var h=e.url;t&&"url"in t&&(h=t.url),d.response=c({url:h,data:void 0},i)}this.hls.trigger(G.ERROR,d)},t.handlePlaylistLoaded=function(e,t,r,i,n,a){var s=this.hls,o=i.type,l=i.level,u=i.levelOrTrack,d=i.id,h=i.groupId,f=i.deliveryDirectives,c=Bd(t,i),g=Ud(i),v="number"==typeof i.level&&g===H.MAIN?l:void 0;u&&"iframes"in u&&u.iframes&&!e.iframesOnly&&(e.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),e.iframesOnly=!0);var m=e.playlistParsingError;if(m){if(this.hls.logger.warn(m+" "+e.url),!s.config.ignorePlaylistParsingErrors)return void s.trigger(G.ERROR,{type:U.NETWORK_ERROR,details:B.LEVEL_PARSING_ERROR,fatal:!1,url:c,error:m,reason:m.message,response:t,context:i,level:v,parent:g,networkDetails:n,stats:r});e.playlistParsingError=null}if(e.fragments.length)switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),a.getCacheAge&&!isNaN(e.ageHeader)||(e.ageHeader=0)),o){case V.MANIFEST:case V.LEVEL:if(v)if(u){if(u!==s.levels[v]){var p=s.levels.indexOf(u);p>-1&&(v=p)}}else v=0;s.trigger(G.LEVEL_LOADED,{details:e,levelInfo:u||s.levels[0],level:v||0,id:d||0,stats:r,networkDetails:n,deliveryDirectives:f,withoutMultiVariant:o===V.MANIFEST,context:i});break;case V.AUDIO_TRACK:s.trigger(G.AUDIO_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:f,context:i});break;case V.SUBTITLE_TRACK:s.trigger(G.SUBTITLE_TRACK_LOADED,{details:e,track:u,id:d||0,groupId:h||"",stats:r,networkDetails:n,deliveryDirectives:f,context:i})}else{var y=e.playlistParsingError=new Error("No Segments found in Playlist");s.trigger(G.ERROR,{type:U.NETWORK_ERROR,details:B.LEVEL_EMPTY_ERROR,fatal:!1,url:c,error:y,reason:y.message,response:t,context:i,level:v,parent:g,networkDetails:n,stats:r})}},e}(),Kd=function(){function e(t){void 0===t&&(t={}),this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new w,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;var r=this.logger=ve(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),i=this.config=Dd(e.DefaultConfig,t,r);this.userConfig=t,i.progressive&&_d(i,r);var n=i.streamController,a=i.abrController,s=i.bufferController,o=i.capLevelController,l=i.errorController,u=i.fpsController,d=i.id3TrackController,h=i.iframeController,f=i.gapController,c=new l(this),g=this.abrController=new a(this),v=new Kr(this),m=i.interstitialsController,p=m?this.interstitialsController=new m(this,e):null,y=s?this.bufferController=new s(this,v):null,E=o?this.capLevelController=new o(this):null,T=u?new u(this):null,S=i.cmcdController,A=S?this.cmcdController=new S(this):null,I=new Gd(this),L=i.contentSteeringController,R=L?new L(this):null,b=this.levelController=new Cd(this,R),k=d?new d(this):void 0,D=new Fd(this.config,this.logger),P=this.streamController=new n(this,v,D),_=this.gapController=f?new f(this,v):void 0;E&&E.setStreamController(P);var C=[I,b,P];p&&C.splice(1,0,p),R&&C.splice(1,0,R),this.networkControllers=C;var O=[g];y&&O.push(y),_&&O.push(_),E&&O.push(E),T&&(T.setStreamController(P),O.push(T)),k&&O.push(k),O.push(v),this.audioTrackController=this.createController(i.audioTrackController,C);var M=i.audioStreamController;M&&C.push(this.audioStreamController=new M(this,v,D)),this.subtitleTrackController=this.createController(i.subtitleTrackController,C);var x=i.subtitleStreamController;x&&C.push(this.subtititleStreamController=new x(this,v,D)),this.createController(i.timelineController,O),D.emeController=this.emeController=this.createController(i.emeController,O),A&&O.push(A),this.latencyController=this.createController(i.latencyController,O),this.coreComponents=O,this.iframeController=h?new h(this,e):void 0,C.push(c);var F=c.onErrorOut;"function"==typeof F&&this.on(G.ERROR,F,c),this.on(G.MANIFEST_LOADED,I.onManifestLoaded,I)}e.isMSESupported=function(){return Wl()},e.isSupported=function(){return function(){if(!Wl())return!1;var e=pe();return"function"==typeof(null==e?void 0:e.isTypeSupported)&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some((function(t){return e.isTypeSupported(Ct(t,"video"))}))||["mp4a.40.2","fLaC"].some((function(t){return e.isTypeSupported(Ct(t,"audio"))})))}()},e.getMediaSource=function(){return pe()};var t=e.prototype;return t.createController=function(e,t){if(e){var r=new e(this);return t&&t.push(r),r}return null},t.on=function(e,t,r){void 0===r&&(r=this),this._emitter.on(e,t,r)},t.once=function(e,t,r){void 0===r&&(r=this),this._emitter.once(e,t,r)},t.removeAllListeners=function(e){this._emitter.removeAllListeners(e)},t.off=function(e,t,r,i){void 0===r&&(r=this),this._emitter.off(e,t,r,i)},t.listeners=function(e){return this._emitter.listeners(e)},t.emit=function(e,t,r){return this._emitter.emit(e,t,r)},t.trigger=function(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error("An internal error happened while handling event "+e+'. Error message: "'+t.message+'". Here is a stacktrace:',t),!this.triggeringException){this.triggeringException=!0;var r=e===G.ERROR;this.trigger(G.ERROR,{type:U.OTHER_ERROR,details:B.INTERNAL_EXCEPTION,fatal:r,event:e,error:t}),this.triggeringException=!1}}return!1},t.listenerCount=function(e){return this._emitter.listenerCount(e)},t.destroy=function(){this.logger.log("destroy"),this.trigger(G.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach((function(e){return e.destroy()})),this.networkControllers.length=0,this.coreComponents.forEach((function(e){return e.destroy()})),this.coreComponents.length=0,this.iframeController=void 0;var e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null},t.attachMedia=function(e){if(!e||"media"in e&&!e.media){var t=new Error("attachMedia failed: invalid argument ("+e+")");this.trigger(G.ERROR,{type:U.OTHER_ERROR,details:B.ATTACH_MEDIA_ERROR,fatal:!0,error:t})}else{this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());var r="media"in e,i=r?e.media:e,n=r?e:{media:i};this._media=i,this.trigger(G.MEDIA_ATTACHING,n)}},t.detachMedia=function(){this.logger.log("detachMedia");var e={};this.trigger(G.MEDIA_DETACHING,e),this._media=null,this.trigger(G.MEDIA_DETACHED,e)},t.transferMedia=function(){var e;this._media=null;var t=(null==(e=this.bufferController)?void 0:e.transferMedia())||null,r={transferMedia:t};return this.trigger(G.MEDIA_DETACHING,r),this.trigger(G.MEDIA_DETACHED,r),t},t.loadSource=function(e){var t;this.stopLoad();var r=this.media,i=this._url,n=this._url=M.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log("loadSource:"+n),r&&i&&(i!==n||null!=(t=this.bufferController)&&t.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(G.MANIFEST_LOADING,{url:e})},t.startLoad=function(e,t){void 0===e&&(e=-1),this.logger.log("startLoad("+e+(t?", ":"")+")"),this.started=!0,this.resumeBuffering();for(var r=0;r-1?this.abrController.forcedAutoLevel:e},set:function(e){this.logger.log("set startLevel:"+e),-1!==e&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}},{key:"capLevelToPlayerSize",get:function(){return this.config.capLevelToPlayerSize},set:function(e){var t=this.capLevelController,r=!!e;t&&r!==this.config.capLevelToPlayerSize&&(r?t.startCapping():(t.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}},{key:"autoLevelCapping",get:function(){return this._autoLevelCapping},set:function(e){this._autoLevelCapping!==e&&(this.logger.log("set autoLevelCapping:"+e),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}},{key:"bandwidthEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimate():NaN},set:function(e){this.abrController.resetEstimator(e)}},{key:"abrEwmaDefaultEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.defaultEstimate:NaN}},{key:"ttfbEstimate",get:function(){var e=this.abrController.bwEstimator;return e?e.getEstimateTTFB():NaN}},{key:"maxHdcpLevel",get:function(){return this._maxHdcpLevel},set:function(e){(function(e){return zt.indexOf(e)>-1})(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}},{key:"autoLevelEnabled",get:function(){return-1===this.levelController.manualLevel}},{key:"manualLevel",get:function(){return this.levelController.manualLevel}},{key:"minAutoLevel",get:function(){var e=this.levels,t=this.config.minAutoBitrate;if(!e)return 0;for(var r=e.length,i=0;i=t)return i;return 0}},{key:"maxAutoLevel",get:function(){var e,t=this.levels,r=this.autoLevelCapping,i=this.maxHdcpLevel;if(e=-1===r&&null!=t&&t.length?t.length-1:r,i)for(var n=e;n--;){var a=t[n].attrs["HDCP-LEVEL"];if(a&&a<=i)return n}return e}},{key:"firstAutoLevel",get:function(){return this.abrController.firstAutoLevel}},{key:"nextAutoLevel",get:function(){return this.abrController.nextAutoLevel},set:function(e){this.abrController.nextAutoLevel=e}},{key:"playingDate",get:function(){return this.streamController.currentProgramDateTime}},{key:"mainForwardBufferInfo",get:function(){return this.streamController.getMainFwdBufferInfo()}},{key:"audioForwardBufferInfo",get:function(){var e;return(null==(e=this.audioStreamController)?void 0:e.getFwdBufferInfo())||null}},{key:"maxBufferLength",get:function(){return this.streamController.maxBufferLength}},{key:"allAudioTracks",get:function(){var e=this.audioTrackController;return e?e.allAudioTracks:[]}},{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:"nextAudioTrack",get:function(){var e,t;return null!=(e=null==(t=this.audioStreamController)?void 0:t.nextAudioTrack)?e:-1},set:function(e){var t=this.audioTrackController;t&&(t.nextAudioTrack=e)}},{key:"allSubtitleTracks",get:function(){var e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}},{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:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var e=this.subtitleTrackController;return!!e&&e.subtitleDisplay},set:function(e){var t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(e){this.config.lowLatencyMode=e}},{key:"liveSyncPosition",get:function(){var e,t;return null!=(e=null==(t=this.latencyController)?void 0:t.liveSyncPosition)?e:null}},{key:"latency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.latency)||0}},{key:"maxLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.maxLatency)||0}},{key:"targetLatency",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.targetLatency)||null},set:function(e){this.latencyController&&(this.latencyController.targetLatency=e)}},{key:"drift",get:function(){var e;return(null==(e=this.latencyController)?void 0:e.drift)||null}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}},{key:"pathways",get:function(){return this.levelController.pathways}},{key:"pathwayPriority",get:function(){return this.levelController.pathwayPriority},set:function(e){this.levelController.pathwayPriority=e}},{key:"bufferedToEnd",get:function(){var e;return!(null==(e=this.bufferController)||!e.bufferedToEnd)}},{key:"interstitialsManager",get:function(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}},{key:"iframeVariants",get:function(){var e=this.levelController.iframeVariants;return e||[]}}],[{key:"version",get:function(){return rs}},{key:"Events",get:function(){return G}},{key:"MetadataSchema",get:function(){return Un}},{key:"ErrorTypes",get:function(){return U}},{key:"ErrorDetails",get:function(){return B}},{key:"DefaultConfig",get:function(){return e.defaultConfig?e.defaultConfig:kd},set:function(t){e.defaultConfig=t}}])}();return Kd.defaultConfig=void 0,Kd},"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