diff --git a/autodl/README.md b/autodl/README.md deleted file mode 100644 index f5cfb53..0000000 --- a/autodl/README.md +++ /dev/null @@ -1,57 +0,0 @@ - -# autodl 使用教程 - -## autodl 镜像地址 -https://www.codewithgpu.com/i/lipku/metahuman-stream/base - -## 代码目录 -/root/metahuman-stream/ - -## 依赖安装 -``` -cd metahuman-stream -git pull -pip install -r requirements.txt -``` - -## 开始运行 -建议直接使用rtcpush 普通webrtc模式存在显示不了的情况 -### 在任意公网ip启动 srs服务 -``` -export CANDIDATE='<服务器外网ip>' -docker run --rm --env CANDIDATE=$CANDIDATE \ - -p 1935:1935 -p 8080:8080 -p 1985:1985 -p 8000:8000/udp \ - registry.cn-hangzhou.aliyuncs.com/ossrs/srs:5 \ - objs/srs -c conf/rtc.conf -``` -### 推流到 srs 服务器 -``` -python app.py --listenport 6006 --transport rtcpush --push_url 'http://<阿里云服务外网ip>:1985/rtc/v1/whip/?app=live&stream=livestream' -``` - -### 访问 -访问的是静态的rtcpushapi.html -http:///rtcpushapi.html -你需要修改 项目目录中的 web/rtcpushapi.html - -将 -``` -var url = "http://"+host+":1985/rtc/v1/whep/?app=live&stream=livestream" -``` - -替换成 -``` -var url = "http://公网ip:1985/rtc/v1/whep/?app=live&stream=livestream" -``` - -调整如下: - - -成功则如下图 -![img.png](./img/success.png) - -## 注意事项 -1. autodl 如果是个人用户需要使用官方的ssh代理工具进行端口代理,才可以访问6006 -2. 声音延迟需要后台优化srs的功能 -3. musetalk 暂不支持rtmp推流 但是支持rtcpush -4. musetalk 教程即将更新 \ No newline at end of file diff --git a/autodl/img/20240530112922.jpg b/autodl/img/20240530112922.jpg deleted file mode 100644 index ebb189e..0000000 Binary files a/autodl/img/20240530112922.jpg and /dev/null differ diff --git a/autodl/img/success.png b/autodl/img/success.png deleted file mode 100644 index 468ef19..0000000 Binary files a/autodl/img/success.png and /dev/null differ diff --git a/funasr/funasr_wss_server.py b/funasr/funasr_wss_server.py deleted file mode 100644 index b008c6f..0000000 --- a/funasr/funasr_wss_server.py +++ /dev/null @@ -1,315 +0,0 @@ -import asyncio -import json -import websockets -import time -import logging -import tracemalloc -import numpy as np -import argparse -import ssl - - -parser = argparse.ArgumentParser() -parser.add_argument("--host", - type=str, - default="0.0.0.0", - required=False, - help="host ip, localhost, 0.0.0.0") -parser.add_argument("--port", - type=int, - default=10095, - required=False, - help="grpc server port") -parser.add_argument("--asr_model", - type=str, - default="iic/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-pytorch", - help="model from modelscope") -parser.add_argument("--asr_model_revision", - type=str, - default="v2.0.4", - help="") -parser.add_argument("--asr_model_online", - type=str, - default="iic/speech_paraformer-large_asr_nat-zh-cn-16k-common-vocab8404-online", - help="model from modelscope") -parser.add_argument("--asr_model_online_revision", - type=str, - default="v2.0.4", - help="") -parser.add_argument("--vad_model", - type=str, - default="iic/speech_fsmn_vad_zh-cn-16k-common-pytorch", - help="model from modelscope") -parser.add_argument("--vad_model_revision", - type=str, - default="v2.0.4", - help="") -parser.add_argument("--punc_model", - type=str, - default="iic/punc_ct-transformer_zh-cn-common-vad_realtime-vocab272727", - help="model from modelscope") -parser.add_argument("--punc_model_revision", - type=str, - default="v2.0.4", - help="") -parser.add_argument("--ngpu", - type=int, - default=1, - help="0 for cpu, 1 for gpu") -parser.add_argument("--device", - type=str, - default="cuda", - help="cuda, cpu") -parser.add_argument("--ncpu", - type=int, - default=4, - help="cpu cores") -parser.add_argument("--certfile", - type=str, - default="ssl_key/server.crt", - required=False, - help="certfile for ssl") - -parser.add_argument("--keyfile", - type=str, - default="ssl_key/server.key", - required=False, - help="keyfile for ssl") -args = parser.parse_args() - - -websocket_users = set() - -print("model loading") -from funasr import AutoModel - -# asr -model_asr = AutoModel(model=args.asr_model, - model_revision=args.asr_model_revision, - ngpu=args.ngpu, - ncpu=args.ncpu, - device=args.device, - disable_pbar=True, - disable_log=True, - ) -# asr -model_asr_streaming = AutoModel(model=args.asr_model_online, - model_revision=args.asr_model_online_revision, - ngpu=args.ngpu, - ncpu=args.ncpu, - device=args.device, - disable_pbar=True, - disable_log=True, - ) -# vad -model_vad = AutoModel(model=args.vad_model, - model_revision=args.vad_model_revision, - ngpu=args.ngpu, - ncpu=args.ncpu, - device=args.device, - disable_pbar=True, - disable_log=True, - # chunk_size=60, - ) - -if args.punc_model != "": - model_punc = AutoModel(model=args.punc_model, - model_revision=args.punc_model_revision, - ngpu=args.ngpu, - ncpu=args.ncpu, - device=args.device, - disable_pbar=True, - disable_log=True, - ) -else: - model_punc = None - - - -print("model loaded! only support one client at the same time now!!!!") - -async def ws_reset(websocket): - print("ws reset now, total num is ",len(websocket_users)) - - websocket.status_dict_asr_online["cache"] = {} - websocket.status_dict_asr_online["is_final"] = True - websocket.status_dict_vad["cache"] = {} - websocket.status_dict_vad["is_final"] = True - websocket.status_dict_punc["cache"] = {} - - await websocket.close() - - -async def clear_websocket(): - for websocket in websocket_users: - await ws_reset(websocket) - websocket_users.clear() - - - -async def ws_serve(websocket, path): - frames = [] - frames_asr = [] - frames_asr_online = [] - global websocket_users - # await clear_websocket() - websocket_users.add(websocket) - websocket.status_dict_asr = {} - websocket.status_dict_asr_online = {"cache": {}, "is_final": False} - websocket.status_dict_vad = {'cache': {}, "is_final": False} - websocket.status_dict_punc = {'cache': {}} - websocket.chunk_interval = 10 - websocket.vad_pre_idx = 0 - speech_start = False - speech_end_i = -1 - websocket.wav_name = "microphone" - websocket.mode = "2pass" - print("new user connected", flush=True) - - try: - async for message in websocket: - if isinstance(message, str): - messagejson = json.loads(message) - - if "is_speaking" in messagejson: - websocket.is_speaking = messagejson["is_speaking"] - websocket.status_dict_asr_online["is_final"] = not websocket.is_speaking - if "chunk_interval" in messagejson: - websocket.chunk_interval = messagejson["chunk_interval"] - if "wav_name" in messagejson: - websocket.wav_name = messagejson.get("wav_name") - if "chunk_size" in messagejson: - chunk_size = messagejson["chunk_size"] - if isinstance(chunk_size, str): - chunk_size = chunk_size.split(',') - websocket.status_dict_asr_online["chunk_size"] = [int(x) for x in chunk_size] - if "encoder_chunk_look_back" in messagejson: - websocket.status_dict_asr_online["encoder_chunk_look_back"] = messagejson["encoder_chunk_look_back"] - if "decoder_chunk_look_back" in messagejson: - websocket.status_dict_asr_online["decoder_chunk_look_back"] = messagejson["decoder_chunk_look_back"] - if "hotword" in messagejson: - websocket.status_dict_asr["hotword"] = messagejson["hotword"] - if "mode" in messagejson: - websocket.mode = messagejson["mode"] - - websocket.status_dict_vad["chunk_size"] = int(websocket.status_dict_asr_online["chunk_size"][1]*60/websocket.chunk_interval) - if len(frames_asr_online) > 0 or len(frames_asr) > 0 or not isinstance(message, str): - if not isinstance(message, str): - frames.append(message) - duration_ms = len(message)//32 - websocket.vad_pre_idx += duration_ms - - # asr online - frames_asr_online.append(message) - websocket.status_dict_asr_online["is_final"] = speech_end_i != -1 - if len(frames_asr_online) % websocket.chunk_interval == 0 or websocket.status_dict_asr_online["is_final"]: - if websocket.mode == "2pass" or websocket.mode == "online": - audio_in = b"".join(frames_asr_online) - try: - await async_asr_online(websocket, audio_in) - except: - print(f"error in asr streaming, {websocket.status_dict_asr_online}") - frames_asr_online = [] - if speech_start: - frames_asr.append(message) - # vad online - try: - speech_start_i, speech_end_i = await async_vad(websocket, message) - except: - print("error in vad") - if speech_start_i != -1: - speech_start = True - beg_bias = (websocket.vad_pre_idx-speech_start_i)//duration_ms - frames_pre = frames[-beg_bias:] - frames_asr = [] - frames_asr.extend(frames_pre) - # asr punc offline - if speech_end_i != -1 or not websocket.is_speaking: - # print("vad end point") - if websocket.mode == "2pass" or websocket.mode == "offline": - audio_in = b"".join(frames_asr) - try: - await async_asr(websocket, audio_in) - except: - print("error in asr offline") - frames_asr = [] - speech_start = False - frames_asr_online = [] - websocket.status_dict_asr_online["cache"] = {} - if not websocket.is_speaking: - websocket.vad_pre_idx = 0 - frames = [] - websocket.status_dict_vad["cache"] = {} - else: - frames = frames[-20:] - - - except websockets.ConnectionClosed: - print("ConnectionClosed...", websocket_users,flush=True) - await ws_reset(websocket) - websocket_users.remove(websocket) - except websockets.InvalidState: - print("InvalidState...") - except Exception as e: - print("Exception:", e) - - -async def async_vad(websocket, audio_in): - - segments_result = model_vad.generate(input=audio_in, **websocket.status_dict_vad)[0]["value"] - # print(segments_result) - - speech_start = -1 - speech_end = -1 - - if len(segments_result) == 0 or len(segments_result) > 1: - return speech_start, speech_end - if segments_result[0][0] != -1: - speech_start = segments_result[0][0] - if segments_result[0][1] != -1: - speech_end = segments_result[0][1] - return speech_start, speech_end - - -async def async_asr(websocket, audio_in): - if len(audio_in) > 0: - # print(len(audio_in)) - rec_result = model_asr.generate(input=audio_in, **websocket.status_dict_asr)[0] - # print("offline_asr, ", rec_result) - if model_punc is not None and len(rec_result["text"])>0: - # print("offline, before punc", rec_result, "cache", websocket.status_dict_punc) - rec_result = model_punc.generate(input=rec_result['text'], **websocket.status_dict_punc)[0] - # print("offline, after punc", rec_result) - if len(rec_result["text"])>0: - # print("offline", rec_result) - mode = "2pass-offline" if "2pass" in websocket.mode else websocket.mode - message = json.dumps({"mode": mode, "text": rec_result["text"], "wav_name": websocket.wav_name,"is_final":websocket.is_speaking}) - await websocket.send(message) - - -async def async_asr_online(websocket, audio_in): - if len(audio_in) > 0: - # print(websocket.status_dict_asr_online.get("is_final", False)) - rec_result = model_asr_streaming.generate(input=audio_in, **websocket.status_dict_asr_online)[0] - # print("online, ", rec_result) - if websocket.mode == "2pass" and websocket.status_dict_asr_online.get("is_final", False): - return - # websocket.status_dict_asr_online["cache"] = dict() - if len(rec_result["text"]): - mode = "2pass-online" if "2pass" in websocket.mode else websocket.mode - message = json.dumps({"mode": mode, "text": rec_result["text"], "wav_name": websocket.wav_name,"is_final":websocket.is_speaking}) - await websocket.send(message) - -if len(args.certfile)>0: - ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) - - # Generate with Lets Encrypt, copied to this location, chown to current user and 400 permissions - ssl_cert = args.certfile - ssl_key = args.keyfile - - ssl_context.load_cert_chain(ssl_cert, keyfile=ssl_key) - start_server = websockets.serve(ws_serve, args.host, args.port, subprotocols=["binary"], ping_interval=None,ssl=ssl_context) -else: - start_server = websockets.serve(ws_serve, args.host, args.port, subprotocols=["binary"], ping_interval=None) -asyncio.get_event_loop().run_until_complete(start_server) -asyncio.get_event_loop().run_forever() diff --git a/funasr/html/readme.md b/funasr/html/readme.md deleted file mode 100644 index 7edded7..0000000 --- a/funasr/html/readme.md +++ /dev/null @@ -1 +0,0 @@ -在浏览器中打开 samples/html/static/index.html,输入ASR服务器地址,支持麦克风输入,也支持文件输入 \ No newline at end of file diff --git a/funasr/html/static/echo.html b/funasr/html/static/echo.html deleted file mode 100644 index 7e24dbc..0000000 --- a/funasr/html/static/echo.html +++ /dev/null @@ -1,132 +0,0 @@ - - - - - - - - - - - - - -
-

metahuman voice test

-
-
-

input text

- - -
- -
-
- -
- -
- -
------------------------------------------------------------------------------------------------------------------------------
-
- -
- asr服务器地址(必填): -
- -
- -
-
-
- 选择录音模式:
- -   - - -
- - - - - - -
- 热词设置(一行一个关键字,空格隔开权重,如"阿里巴巴 20"): - - - -
-
语音识别结果显示:
-
- - -
-
请点击开始
-
- - - - -
- - -
-
- - - - - - - \ No newline at end of file diff --git a/funasr/html/static/index.html b/funasr/html/static/index.html deleted file mode 100644 index 5e4177c..0000000 --- a/funasr/html/static/index.html +++ /dev/null @@ -1,87 +0,0 @@ - - - - - - 语音识别 - - - - - - - - - -

FunASR Demo

-

这里是FunASR开源项目体验demo,集成了VAD、ASR与标点等工业级别的模型,支持长音频离线文件转写,实时语音识别等,开源项目地址:https://github.com/alibaba-damo-academy/FunASR

- -
- -
- asr服务器地址(必填): -
- -
- -
-
-
- 选择录音模式:
- -    - - -
- -
-
- 选择asr模型模式:
- -    -    - - -
- - -
-
- 热词设置(一行一个关键字,空格隔开权重,如"阿里巴巴 20"): -
- - - -
- -
- 语音识别结果显示: -
- - -
-
请点击开始
-
- - - - -
- - -
-
- - - - - - - - - diff --git a/funasr/html/static/main.js b/funasr/html/static/main.js deleted file mode 100644 index 52ff5c0..0000000 --- a/funasr/html/static/main.js +++ /dev/null @@ -1,637 +0,0 @@ -/** - * Copyright FunASR (https://github.com/alibaba-damo-academy/FunASR). All Rights - * Reserved. MIT License (https://opensource.org/licenses/MIT) - */ -/* 2022-2023 by zhaoming,mali aihealthx.com */ - - -// 连接; 定义socket连接类对象与语音对象 -var wsconnecter = new WebSocketConnectMethod({msgHandle:getJsonMessage,stateHandle:getConnState}); -var audioBlob; - -// 录音; 定义录音对象,wav格式 -var rec = Recorder({ - type:"pcm", - bitRate:16, - sampleRate:16000, - onProcess:recProcess -}); - - - - -var sampleBuf=new Int16Array(); -// 定义按钮响应事件 -var btnStart = document.getElementById('btnStart'); -btnStart.onclick = record; -var btnStop = document.getElementById('btnStop'); -btnStop.onclick = stop; -btnStop.disabled = true; -btnStart.disabled = true; - -btnConnect= document.getElementById('btnConnect'); -btnConnect.onclick = start; - -var awsslink= document.getElementById('wsslink'); - - -var rec_text=""; // for online rec asr result -var offline_text=""; // for offline rec asr result -var info_div = document.getElementById('info_div'); - -var upfile = document.getElementById('upfile'); - - - -var isfilemode=false; // if it is in file mode -var file_ext=""; -var file_sample_rate=16000; //for wav file sample rate -var file_data_array; // array to save file data - -var totalsend=0; - -var startTime = Date.now(); - -var now_ipaddress=window.location.href; -now_ipaddress=now_ipaddress.replace("https://","wss://"); -now_ipaddress=now_ipaddress.replace("static/index.html",""); -// var localport=window.location.port; -// now_ipaddress=now_ipaddress.replace(localport,"10095"); -// document.getElementById('wssip').value=now_ipaddress; -// addresschange(); -function addresschange() -{ - - var Uri = document.getElementById('wssip').value; - document.getElementById('info_wslink').innerHTML="点此处手工授权(IOS手机)"; - Uri=Uri.replace(/wss/g,"https"); - console.log("addresschange uri=",Uri); - - awsslink.onclick=function(){ - window.open(Uri, '_blank'); - } - -} - -upfile.onclick=function() -{ - btnStart.disabled = true; - btnStop.disabled = true; - btnConnect.disabled=false; - -} - -// from https://github.com/xiangyuecn/Recorder/tree/master -var readWavInfo=function(bytes){ - //读取wav文件头,统一成44字节的头 - if(bytes.byteLength<44){ - return null; - }; - var wavView=bytes; - var eq=function(p,s){ - for(var i=0;i=chunk_size){ - - sendBuf=sampleBuf.slice(0,chunk_size); - totalsend=totalsend+sampleBuf.length; - sampleBuf=sampleBuf.slice(chunk_size,sampleBuf.length); - wsconnecter.wsSend(sendBuf); - - - } - - stop(); - - - -} - - -function on_recoder_mode_change() -{ - var item = null; - var obj = document.getElementsByName("recoder_mode"); - for (var i = 0; i < obj.length; i++) { //遍历Radio - if (obj[i].checked) { - item = obj[i].value; - break; - } - - - } - if(item=="mic") - { - document.getElementById("mic_mode_div").style.display = 'block'; - document.getElementById("rec_mode_div").style.display = 'none'; - - - btnStart.disabled = true; - btnStop.disabled = true; - btnConnect.disabled=false; - isfilemode=false; - } - else - { - document.getElementById("mic_mode_div").style.display = 'none'; - document.getElementById("rec_mode_div").style.display = 'block'; - - btnStart.disabled = true; - btnStop.disabled = true; - btnConnect.disabled=true; - isfilemode=true; - info_div.innerHTML='请点击选择文件'; - - - } -} - - -function getHotwords(){ - - var obj = document.getElementById("varHot"); - - if(typeof(obj) == 'undefined' || obj==null || obj.value.length<=0){ - return null; - } - let val = obj.value.toString(); - - console.log("hotwords="+val); - let items = val.split(/[(\r\n)\r\n]+/); //split by \r\n - var jsonresult = {}; - const regexNum = /^[0-9]*$/; // test number - for (item of items) { - - let result = item.split(" "); - if(result.length>=2 && regexNum.test(result[result.length-1])) - { - var wordstr=""; - for(var i=0;iwaitTime){ - //自动发送消息 - var f = document.getElementById("echo-form"); - f.submit = function(e){ - e.preventDefault(); - var message=document.getElementById('message').value; - console.log('Sending: ' + message); - ws.send(message); - document.getElementById('message').value=''; - } - - recive_msg = false; - startTime = currentTime; - // rec_text=""; - // var varArea_message=document.getElementById('message'); - // varArea_message.value=""; - return; - } - - - - - //console.log(jsonMsg); - console.log( "message: " + JSON.parse(jsonMsg.data)['text'] ); - var rectxt=""+JSON.parse(jsonMsg.data)['text']; - - - var asrmodel=JSON.parse(jsonMsg.data)['mode']; - var is_final=JSON.parse(jsonMsg.data)['is_final']; - var timestamp=JSON.parse(jsonMsg.data)['timestamp']; - if(asrmodel=="2pass-offline" || asrmodel=="offline") - { - - offline_text=offline_text+handleWithTimestamp(rectxt,timestamp); //rectxt; //.replace(/ +/g,""); - rec_text=offline_text; - } - else - { - rec_text=rec_text+rectxt; //.replace(/ +/g,""); - } - var varArea=document.getElementById('varArea'); - var varArea_message=document.getElementById('message'); - - varArea.value=rec_text; - varArea_message.value=rec_text; - console.log( "offline_text: " + asrmodel+","+offline_text); - console.log( "rec_text: " + rec_text); - console.log( "isfilemode: " + isfilemode); - console.log( "is_final: " + is_final); - if (isfilemode==true && is_final==false){ - console.log("call stop ws!"); - play_file(); - wsconnecter.wsStop(); - - info_div.innerHTML="请点击连接"; - - btnStart.disabled = true; - btnStop.disabled = true; - btnConnect.disabled=false; - } - - - -} - -// 连接状态响应 -function getConnState( connState ) { - if ( connState === 0 ) { //on open - - - info_div.innerHTML='连接成功!请点击开始'; - if (isfilemode==true){ - info_div.innerHTML='请耐心等待,大文件等待时间更长'; - start_file_send(); - } - else - { - btnStart.disabled = false; - btnStop.disabled = true; - btnConnect.disabled=true; - } - } else if ( connState === 1 ) { - //stop(); - } else if ( connState === 2 ) { - stop(); - console.log( 'connecttion error' ); - - alert("连接地址"+document.getElementById('wssip').value+"失败,请检查asr地址和端口。或试试界面上手动授权,再连接。"); - btnStart.disabled = true; - btnStop.disabled = true; - btnConnect.disabled=false; - - - info_div.innerHTML='请点击连接'; - } -} - -function record() -{ - - rec.open( function(){ - rec.start(); - console.log("开始"); - btnStart.disabled = true; - btnStop.disabled = false; - btnConnect.disabled=true; - }); - -} - - - -// 识别启动、停止、清空操作 -function start() { - - // 清除显示 - clear(); - //控件状态更新 - console.log("isfilemode"+isfilemode); - - //启动连接 - var ret=wsconnecter.wsStart(); - // 1 is ok, 0 is error - if(ret==1){ - info_div.innerHTML="正在连接asr服务器,请等待..."; - isRec = true; - btnStart.disabled = true; - btnStop.disabled = true; - btnConnect.disabled=true; - - return 1; - } - else - { - info_div.innerHTML="请点击开始"; - btnStart.disabled = true; - btnStop.disabled = true; - btnConnect.disabled=false; - - return 0; - } -} - - -function stop() { - var chunk_size = new Array( 5, 10, 5 ); - var request = { - "chunk_size": chunk_size, - "wav_name": "h5", - "is_speaking": false, - "chunk_interval":10, - "mode":getAsrMode(), - }; - console.log(request); - if(sampleBuf.length>0){ - wsconnecter.wsSend(sampleBuf); - console.log("sampleBuf.length"+sampleBuf.length); - sampleBuf=new Int16Array(); - } - wsconnecter.wsSend( JSON.stringify(request) ); - - - - - - - // 控件状态更新 - - isRec = false; - info_div.innerHTML="发送完数据,请等候,正在识别..."; - - if(isfilemode==false){ - btnStop.disabled = true; - btnStart.disabled = true; - btnConnect.disabled=true; - //wait 3s for asr result - setTimeout(function(){ - console.log("call stop ws!"); - wsconnecter.wsStop(); - btnConnect.disabled=false; - info_div.innerHTML="请点击连接";}, 3000 ); - - - - rec.stop(function(blob,duration){ - - console.log(blob); - var audioBlob = Recorder.pcm2wav(data = {sampleRate:16000, bitRate:16, blob:blob}, - function(theblob,duration){ - console.log(theblob); - var audio_record = document.getElementById('audio_record'); - audio_record.src = (window.URL||webkitURL).createObjectURL(theblob); - audio_record.controls=true; - //audio_record.play(); - - - } ,function(msg){ - console.log(msg); - } - ); - - - - },function(errMsg){ - console.log("errMsg: " + errMsg); - }); - } - // 停止连接 - - - -} - -function clear() { - - var varArea=document.getElementById('varArea'); - - varArea.value=""; - rec_text=""; - offline_text=""; - -} - - -function recProcess( buffer, powerLevel, bufferDuration, bufferSampleRate,newBufferIdx,asyncEnd ) { - if ( isRec === true ) { - var data_48k = buffer[buffer.length-1]; - - var array_48k = new Array(data_48k); - var data_16k=Recorder.SampleData(array_48k,bufferSampleRate,16000).data; - - sampleBuf = Int16Array.from([...sampleBuf, ...data_16k]); - var chunk_size=960; // for asr chunk_size [5, 10, 5] - info_div.innerHTML=""+bufferDuration/1000+"s"; - while(sampleBuf.length>=chunk_size){ - sendBuf=sampleBuf.slice(0,chunk_size); - sampleBuf=sampleBuf.slice(chunk_size,sampleBuf.length); - wsconnecter.wsSend(sendBuf); - - - - } - - - - } - -} -var recive_msg = true; -$(document).ready(function() { - var host = window.location.hostname - var ws = new WebSocket("ws://"+host+":8000/humanecho"); - //document.getElementsByTagName("video")[0].setAttribute("src", aa["video"]); - ws.onopen = function() { - console.log('Connected'); - }; - ws.onmessage = function(e) { - console.log('Received: ' + e.data); - recive_msg = true; - data = e - var vid = JSON.parse(data.data); - console.log(typeof(vid),vid) - //document.getElementsByTagName("video")[0].setAttribute("src", vid["video"]); - - }; - ws.onclose = function(e) { - console.log('Closed'); - }; - - flvPlayer = mpegts.createPlayer({type: 'flv', url: "http://"+host+":8080/live/livestream.flv", isLive: true, enableStashBuffer: false}); - flvPlayer.attachMediaElement(document.getElementById('video_player')); - flvPlayer.load(); - flvPlayer.play(); - - $('#echo-form').on('submit', function(e) { - e.preventDefault(); - var message = $('#message').val(); - console.log('Sending: ' + message); - ws.send(message); - $('#message').val(''); - }); - }); \ No newline at end of file diff --git a/funasr/html/static/mpegts-1.7.3.min.js b/funasr/html/static/mpegts-1.7.3.min.js deleted file mode 100644 index da8af61..0000000 --- a/funasr/html/static/mpegts-1.7.3.min.js +++ /dev/null @@ -1,9 +0,0 @@ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.mpegts=t():e.mpegts=t()}(window,(function(){return function(e){var t={};function i(n){if(t[n])return t[n].exports;var a=t[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,i),a.l=!0,a.exports}return i.m=e,i.c=t,i.d=function(e,t,n){i.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:n})},i.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},i.t=function(e,t){if(1&t&&(e=i(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var n=Object.create(null);if(i.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var a in e)i.d(n,a,function(t){return e[t]}.bind(null,a));return n},i.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return i.d(t,"a",t),t},i.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},i.p="",i(i.s=14)}([function(e,t,i){"use strict";var n=i(6),a=i.n(n),r=function(){function e(){}return e.e=function(t,i){t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var n="["+t+"] > "+i;e.ENABLE_CALLBACK&&e.emitter.emit("log","error",n),e.ENABLE_ERROR&&(console.error?console.error(n):console.warn?console.warn(n):console.log(n))},e.i=function(t,i){t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var n="["+t+"] > "+i;e.ENABLE_CALLBACK&&e.emitter.emit("log","info",n),e.ENABLE_INFO&&(console.info?console.info(n):console.log(n))},e.w=function(t,i){t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var n="["+t+"] > "+i;e.ENABLE_CALLBACK&&e.emitter.emit("log","warn",n),e.ENABLE_WARN&&(console.warn?console.warn(n):console.log(n))},e.d=function(t,i){t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var n="["+t+"] > "+i;e.ENABLE_CALLBACK&&e.emitter.emit("log","debug",n),e.ENABLE_DEBUG&&(console.debug?console.debug(n):console.log(n))},e.v=function(t,i){t&&!e.FORCE_GLOBAL_TAG||(t=e.GLOBAL_TAG);var n="["+t+"] > "+i;e.ENABLE_CALLBACK&&e.emitter.emit("log","verbose",n),e.ENABLE_VERBOSE&&console.log(n)},e}();r.GLOBAL_TAG="mpegts.js",r.FORCE_GLOBAL_TAG=!1,r.ENABLE_ERROR=!0,r.ENABLE_INFO=!0,r.ENABLE_WARN=!0,r.ENABLE_DEBUG=!0,r.ENABLE_VERBOSE=!0,r.ENABLE_CALLBACK=!1,r.emitter=new a.a,t.a=r},function(e,t,i){"use strict";t.a={IO_ERROR:"io_error",DEMUX_ERROR:"demux_error",INIT_SEGMENT:"init_segment",MEDIA_SEGMENT:"media_segment",LOADING_COMPLETE:"loading_complete",RECOVERED_EARLY_EOF:"recovered_early_eof",MEDIA_INFO:"media_info",METADATA_ARRIVED:"metadata_arrived",SCRIPTDATA_ARRIVED:"scriptdata_arrived",TIMED_ID3_METADATA_ARRIVED:"timed_id3_metadata_arrived",SMPTE2038_METADATA_ARRIVED:"smpte2038_metadata_arrived",SCTE35_METADATA_ARRIVED:"scte35_metadata_arrived",PES_PRIVATE_DATA_DESCRIPTOR:"pes_private_data_descriptor",PES_PRIVATE_DATA_ARRIVED:"pes_private_data_arrived",STATISTICS_INFO:"statistics_info",RECOMMEND_SEEKPOINT:"recommend_seekpoint"}},function(e,t,i){"use strict";i.d(t,"c",(function(){return a})),i.d(t,"b",(function(){return r})),i.d(t,"a",(function(){return s}));var n=i(3),a={kIdle:0,kConnecting:1,kBuffering:2,kError:3,kComplete:4},r={OK:"OK",EXCEPTION:"Exception",HTTP_STATUS_CODE_INVALID:"HttpStatusCodeInvalid",CONNECTING_TIMEOUT:"ConnectingTimeout",EARLY_EOF:"EarlyEof",UNRECOVERABLE_EARLY_EOF:"UnrecoverableEarlyEof"},s=function(){function e(e){this._type=e||"undefined",this._status=a.kIdle,this._needStash=!1,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null}return e.prototype.destroy=function(){this._status=a.kIdle,this._onContentLengthKnown=null,this._onURLRedirect=null,this._onDataArrival=null,this._onError=null,this._onComplete=null},e.prototype.isWorking=function(){return this._status===a.kConnecting||this._status===a.kBuffering},Object.defineProperty(e.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"status",{get:function(){return this._status},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"needStashBuffer",{get:function(){return this._needStash},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onContentLengthKnown",{get:function(){return this._onContentLengthKnown},set:function(e){this._onContentLengthKnown=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onURLRedirect",{get:function(){return this._onURLRedirect},set:function(e){this._onURLRedirect=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(e){this._onDataArrival=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onError",{get:function(){return this._onError},set:function(e){this._onError=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onComplete",{get:function(){return this._onComplete},set:function(e){this._onComplete=e},enumerable:!1,configurable:!0}),e.prototype.open=function(e,t){throw new n.c("Unimplemented abstract function!")},e.prototype.abort=function(){throw new n.c("Unimplemented abstract function!")},e}()},function(e,t,i){"use strict";i.d(t,"d",(function(){return r})),i.d(t,"a",(function(){return s})),i.d(t,"b",(function(){return o})),i.d(t,"c",(function(){return d}));var n,a=(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),r=function(){function e(e){this._message=e}return Object.defineProperty(e.prototype,"name",{get:function(){return"RuntimeException"},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"message",{get:function(){return this._message},enumerable:!1,configurable:!0}),e.prototype.toString=function(){return this.name+": "+this.message},e}(),s=function(e){function t(t){return e.call(this,t)||this}return a(t,e),Object.defineProperty(t.prototype,"name",{get:function(){return"IllegalStateException"},enumerable:!1,configurable:!0}),t}(r),o=function(e){function t(t){return e.call(this,t)||this}return a(t,e),Object.defineProperty(t.prototype,"name",{get:function(){return"InvalidArgumentException"},enumerable:!1,configurable:!0}),t}(r),d=function(e){function t(t){return e.call(this,t)||this}return a(t,e),Object.defineProperty(t.prototype,"name",{get:function(){return"NotImplementedException"},enumerable:!1,configurable:!0}),t}(r)},function(e,t,i){"use strict";var n={};!function(){var e=self.navigator.userAgent.toLowerCase(),t=/(edge)\/([\w.]+)/.exec(e)||/(opr)[\/]([\w.]+)/.exec(e)||/(chrome)[ \/]([\w.]+)/.exec(e)||/(iemobile)[\/]([\w.]+)/.exec(e)||/(version)(applewebkit)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+).*(version)[ \/]([\w.]+).*(safari)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("trident")>=0&&/(rv)(?::| )([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(firefox)[ \/]([\w.]+)/.exec(e)||[],i=/(ipad)/.exec(e)||/(ipod)/.exec(e)||/(windows phone)/.exec(e)||/(iphone)/.exec(e)||/(kindle)/.exec(e)||/(android)/.exec(e)||/(windows)/.exec(e)||/(mac)/.exec(e)||/(linux)/.exec(e)||/(cros)/.exec(e)||[],a={browser:t[5]||t[3]||t[1]||"",version:t[2]||t[4]||"0",majorVersion:t[4]||t[2]||"0",platform:i[0]||""},r={};if(a.browser){r[a.browser]=!0;var s=a.majorVersion.split(".");r.version={major:parseInt(a.majorVersion,10),string:a.version},s.length>1&&(r.version.minor=parseInt(s[1],10)),s.length>2&&(r.version.build=parseInt(s[2],10))}if(a.platform&&(r[a.platform]=!0),(r.chrome||r.opr||r.safari)&&(r.webkit=!0),r.rv||r.iemobile){r.rv&&delete r.rv;a.browser="msie",r.msie=!0}if(r.edge){delete r.edge;a.browser="msedge",r.msedge=!0}if(r.opr){a.browser="opera",r.opera=!0}if(r.safari&&r.android){a.browser="android",r.android=!0}for(var o in r.name=a.browser,r.platform=a.platform,n)n.hasOwnProperty(o)&&delete n[o];Object.assign(n,r)}(),t.a=n},function(e,t,i){"use strict";t.a={OK:"OK",FORMAT_ERROR:"FormatError",FORMAT_UNSUPPORTED:"FormatUnsupported",CODEC_UNSUPPORTED:"CodecUnsupported"}},function(e,t,i){"use strict";var n,a="object"==typeof Reflect?Reflect:null,r=a&&"function"==typeof a.apply?a.apply:function(e,t,i){return Function.prototype.apply.call(e,t,i)};n=a&&"function"==typeof a.ownKeys?a.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}e.exports=o,e.exports.once=function(e,t){return new Promise((function(i,n){function a(i){e.removeListener(t,r),n(i)}function r(){"function"==typeof e.removeListener&&e.removeListener("error",a),i([].slice.call(arguments))}g(e,t,r,{once:!0}),"error"!==t&&function(e,t,i){"function"==typeof e.on&&g(e,"error",t,i)}(e,a,{once:!0})}))},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var d=10;function _(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function h(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function c(e,t,i,n){var a,r,s,o;if(_(i),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,i.listener?i.listener:i),r=e._events),s=r[t]),void 0===s)s=r[t]=i,++e._eventsCount;else if("function"==typeof s?s=r[t]=n?[i,s]:[s,i]:n?s.unshift(i):s.push(i),(a=h(e))>0&&s.length>a&&!s.warned){s.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+s.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=s.length,o=d,console&&console.warn&&console.warn(o)}return e}function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function l(e,t,i){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:i},a=u.bind(n);return a.listener=i,n.wrapFn=a,a}function f(e,t,i){var n=e._events;if(void 0===n)return[];var a=n[t];return void 0===a?[]:"function"==typeof a?i?[a.listener||a]:[a]:i?function(e){for(var t=new Array(e.length),i=0;i0&&(s=t[0]),s instanceof Error)throw s;var o=new Error("Unhandled error."+(s?" ("+s.message+")":""));throw o.context=s,o}var d=a[e];if(void 0===d)return!1;if("function"==typeof d)r(d,this,t);else{var _=d.length,h=m(d,_);for(i=0;i<_;++i)r(h[i],this,t)}return!0},o.prototype.addListener=function(e,t){return c(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return c(this,e,t,!0)},o.prototype.once=function(e,t){return _(t),this.on(e,l(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return _(t),this.prependListener(e,l(this,e,t)),this},o.prototype.removeListener=function(e,t){var i,n,a,r,s;if(_(t),void 0===(n=this._events))return this;if(void 0===(i=n[e]))return this;if(i===t||i.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,i.listener||t));else if("function"!=typeof i){for(a=-1,r=i.length-1;r>=0;r--)if(i[r]===t||i[r].listener===t){s=i[r].listener,a=r;break}if(a<0)return this;0===a?i.shift():function(e,t){for(;t+1=0;n--)this.removeListener(e,t[n]);return this},o.prototype.listeners=function(e){return f(this,e,!0)},o.prototype.rawListeners=function(e){return f(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]}},function(e,t,i){"use strict";i.d(t,"d",(function(){return n})),i.d(t,"b",(function(){return a})),i.d(t,"a",(function(){return r})),i.d(t,"c",(function(){return s}));var n=function(e,t,i,n,a){this.dts=e,this.pts=t,this.duration=i,this.originalDts=n,this.isSyncPoint=a,this.fileposition=null},a=function(){function e(){this.beginDts=0,this.endDts=0,this.beginPts=0,this.endPts=0,this.originalBeginDts=0,this.originalEndDts=0,this.syncPoints=[],this.firstSample=null,this.lastSample=null}return e.prototype.appendSyncPoint=function(e){e.isSyncPoint=!0,this.syncPoints.push(e)},e}(),r=function(){function e(){this._list=[]}return e.prototype.clear=function(){this._list=[]},e.prototype.appendArray=function(e){var t=this._list;0!==e.length&&(t.length>0&&e[0].originalDts=t[a].dts&&et[n].lastSample.originalDts&&e=t[n].lastSample.originalDts&&(n===t.length-1||n0&&(a=this._searchNearestSegmentBefore(i.originalBeginDts)+1),this._lastAppendLocation=a,this._list.splice(a,0,i)},e.prototype.getLastSegmentBefore=function(e){var t=this._searchNearestSegmentBefore(e);return t>=0?this._list[t]:null},e.prototype.getLastSampleBefore=function(e){var t=this.getLastSegmentBefore(e);return null!=t?t.lastSample:null},e.prototype.getLastSyncPointBefore=function(e){for(var t=this._searchNearestSegmentBefore(e),i=this._list[t].syncPoints;0===i.length&&t>0;)t--,i=this._list[t].syncPoints;return i.length>0?i[i.length-1]:null},e}()},function(e,t,i){"use strict";var n=function(){function e(){this.mimeType=null,this.duration=null,this.hasAudio=null,this.hasVideo=null,this.audioCodec=null,this.videoCodec=null,this.audioDataRate=null,this.videoDataRate=null,this.audioSampleRate=null,this.audioChannelCount=null,this.width=null,this.height=null,this.fps=null,this.profile=null,this.level=null,this.refFrames=null,this.chromaFormat=null,this.sarNum=null,this.sarDen=null,this.metadata=null,this.segments=null,this.segmentCount=null,this.hasKeyframesIndex=null,this.keyframesIndex=null}return e.prototype.isComplete=function(){var e=!1===this.hasAudio||!0===this.hasAudio&&null!=this.audioCodec&&null!=this.audioSampleRate&&null!=this.audioChannelCount,t=!1===this.hasVideo||!0===this.hasVideo&&null!=this.videoCodec&&null!=this.width&&null!=this.height&&null!=this.fps&&null!=this.profile&&null!=this.level&&null!=this.refFrames&&null!=this.chromaFormat&&null!=this.sarNum&&null!=this.sarDen;return null!=this.mimeType&&e&&t},e.prototype.isSeekable=function(){return!0===this.hasKeyframesIndex},e.prototype.getNearestKeyframe=function(e){if(null==this.keyframesIndex)return null;var t=this.keyframesIndex,i=this._search(t.times,e);return{index:i,milliseconds:t.times[i],fileposition:t.filepositions[i]}},e.prototype._search=function(e,t){var i=0,n=e.length-1,a=0,r=0,s=n;for(t=e[a]&&t0){var i=e.getConfig();t.emit("change",i)}},e.registerListener=function(t){e.emitter.addListener("change",t)},e.removeListener=function(t){e.emitter.removeListener("change",t)},e.addLogListener=function(t){r.a.emitter.addListener("log",t),r.a.emitter.listenerCount("log")>0&&(r.a.ENABLE_CALLBACK=!0,e._notifyChange())},e.removeLogListener=function(t){r.a.emitter.removeListener("log",t),0===r.a.emitter.listenerCount("log")&&(r.a.ENABLE_CALLBACK=!1,e._notifyChange())},e}();s.emitter=new a.a,t.a=s},function(e,t,i){"use strict";var n=i(6),a=i.n(n),r=i(0),s=i(4),o=i(8);function d(e,t,i){var n=e;if(t+i=128){t.push(String.fromCharCode(65535&r)),n+=2;continue}}else if(i[n]<240){if(d(i,n,2))if((r=(15&i[n])<<12|(63&i[n+1])<<6|63&i[n+2])>=2048&&55296!=(63488&r)){t.push(String.fromCharCode(65535&r)),n+=3;continue}}else if(i[n]<248){var r;if(d(i,n,3))if((r=(7&i[n])<<18|(63&i[n+1])<<12|(63&i[n+2])<<6|63&i[n+3])>65536&&r<1114112){r-=65536,t.push(String.fromCharCode(r>>>10|55296)),t.push(String.fromCharCode(1023&r|56320)),n+=4;continue}}t.push(String.fromCharCode(65533)),++n}return t.join("")},c=i(3),u=(_=new ArrayBuffer(2),new DataView(_).setInt16(0,256,!0),256===new Int16Array(_)[0]),l=function(){function e(){}return e.parseScriptData=function(t,i,n){var a={};try{var s=e.parseValue(t,i,n),o=e.parseValue(t,i+s.size,n-s.size);a[s.data]=o.data}catch(e){r.a.e("AMF",e.toString())}return a},e.parseObject=function(t,i,n){if(n<3)throw new c.a("Data not enough when parse ScriptDataObject");var a=e.parseString(t,i,n),r=e.parseValue(t,i+a.size,n-a.size),s=r.objectEnd;return{data:{name:a.data,value:r.data},size:a.size+r.size,objectEnd:s}},e.parseVariable=function(t,i,n){return e.parseObject(t,i,n)},e.parseString=function(e,t,i){if(i<2)throw new c.a("Data not enough when parse String");var n=new DataView(e,t,i).getUint16(0,!u);return{data:n>0?h(new Uint8Array(e,t+2,n)):"",size:2+n}},e.parseLongString=function(e,t,i){if(i<4)throw new c.a("Data not enough when parse LongString");var n=new DataView(e,t,i).getUint32(0,!u);return{data:n>0?h(new Uint8Array(e,t+4,n)):"",size:4+n}},e.parseDate=function(e,t,i){if(i<10)throw new c.a("Data size invalid when parse Date");var n=new DataView(e,t,i),a=n.getFloat64(0,!u),r=n.getInt16(8,!u);return{data:new Date(a+=60*r*1e3),size:10}},e.parseValue=function(t,i,n){if(n<1)throw new c.a("Data not enough when parse Value");var a,s=new DataView(t,i,n),o=1,d=s.getUint8(0),_=!1;try{switch(d){case 0:a=s.getFloat64(1,!u),o+=8;break;case 1:a=!!s.getUint8(1),o+=1;break;case 2:var h=e.parseString(t,i+1,n-1);a=h.data,o+=h.size;break;case 3:a={};var l=0;for(9==(16777215&s.getUint32(n-4,!u))&&(l=3);o32)throw new c.b("ExpGolomb: readBits() bits exceeded max 32bits!");if(e<=this._current_word_bits_left){var t=this._current_word>>>32-e;return this._current_word<<=e,this._current_word_bits_left-=e,t}var i=this._current_word_bits_left?this._current_word:0;i>>>=32-this._current_word_bits_left;var n=e-this._current_word_bits_left;this._fillCurrentWord();var a=Math.min(n,this._current_word_bits_left),r=this._current_word>>>32-a;return this._current_word<<=a,this._current_word_bits_left-=a,i=i<>>e))return this._current_word<<=e,this._current_word_bits_left-=e,e;return this._fillCurrentWord(),e+this._skipLeadingZero()},e.prototype.readUEG=function(){var e=this._skipLeadingZero();return this.readBits(e+1)-1},e.prototype.readSEG=function(){var e=this.readUEG();return 1&e?e+1>>>1:-1*(e>>>1)},e}(),p=function(){function e(){}return e._ebsp2rbsp=function(e){for(var t=e,i=t.byteLength,n=new Uint8Array(i),a=0,r=0;r=2&&3===t[r]&&0===t[r-1]&&0===t[r-2]||(n[a]=t[r],a++);return new Uint8Array(n.buffer,0,a)},e.parseSPS=function(t){for(var i=t.subarray(1,4),n="avc1.",a=0;a<3;a++){var r=i[a].toString(16);r.length<2&&(r="0"+r),n+=r}var s=e._ebsp2rbsp(t),o=new f(s);o.readByte();var d=o.readByte();o.readByte();var _=o.readByte();o.readUEG();var h=e.getProfileString(d),c=e.getLevelString(_),u=1,l=420,p=8,m=8;if((100===d||110===d||122===d||244===d||44===d||83===d||86===d||118===d||128===d||138===d||144===d)&&(3===(u=o.readUEG())&&o.readBits(1),u<=3&&(l=[0,420,422,444][u]),p=o.readUEG()+8,m=o.readUEG()+8,o.readBits(1),o.readBool()))for(var g=3!==u?8:12,v=0;v0&&M<16?(D=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][M-1],C=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][M-1]):255===M&&(D=o.readByte()<<8|o.readByte(),C=o.readByte()<<8|o.readByte())}if(o.readBool()&&o.readBool(),o.readBool()&&(o.readBits(4),o.readBool()&&o.readBits(24)),o.readBool()&&(o.readUEG(),o.readUEG()),o.readBool()){var x=o.readBits(32),U=o.readBits(32);I=o.readBool(),B=(O=U)/(P=2*x)}}var N=1;1===D&&1===C||(N=D/C);var G=0,V=0;0===u?(G=1,V=2-R):(G=3===u?1:2,V=(1===u?2:1)*(2-R));var F=16*(E+1),j=16*(A+1)*(2-R);F-=(T+L)*G,j-=(w+k)*V;var z=Math.ceil(F*N);return o.destroy(),o=null,{codec_mimetype:n,profile_idc:d,level_idc:_,profile_string:h,level_string:c,chroma_format_idc:u,bit_depth:p,bit_depth_luma:p,bit_depth_chroma:m,ref_frames:S,chroma_format:l,chroma_format_string:e.getChromaFormatString(l),frame_rate:{fixed:I,fps:B,fps_den:P,fps_num:O},sar_ratio:{width:D,height:C},codec_size:{width:F,height:j},present_size:{width:z,height:j}}},e._skipScalingList=function(e,t){for(var i=8,n=8,a=0;a=2&&3===t[r]&&0===t[r-1]&&0===t[r-2]||(n[a]=t[r],a++);return new Uint8Array(n.buffer,0,a)},e.parseVPS=function(t){var i=e._ebsp2rbsp(t),n=new f(i);n.readByte(),n.readByte();n.readBits(4);n.readBits(2);n.readBits(6);return{num_temporal_layers:n.readBits(3)+1,temporal_id_nested:n.readBool()}},e.parseSPS=function(t){var i=e._ebsp2rbsp(t),n=new f(i);n.readByte(),n.readByte();for(var a=0,r=0,s=0,o=0,d=(n.readBits(4),n.readBits(3)),_=(n.readBool(),n.readBits(2)),h=n.readBool(),c=n.readBits(5),u=n.readByte(),l=n.readByte(),p=n.readByte(),m=n.readByte(),g=n.readByte(),v=n.readByte(),y=n.readByte(),b=n.readByte(),S=n.readByte(),E=n.readByte(),A=n.readByte(),R=[],T=[],L=0;L0)for(L=d;L<8;L++)n.readBits(2);for(L=0;L1&&n.readSEG();for(L=0;L0&&Q<=16?(W=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][Q-1],X=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][Q-1]):255===Q&&(W=n.readBits(16),X=n.readBits(16))}if(n.readBool()&&n.readBool(),n.readBool())n.readBits(3),n.readBool(),n.readBool()&&(n.readByte(),n.readByte(),n.readByte());n.readBool()&&(n.readUEG(),n.readUEG());n.readBool(),n.readBool(),n.readBool();if(n.readBool()&&(n.readUEG(),n.readUEG(),n.readUEG(),n.readUEG()),n.readBool())if(J=n.readBits(32),Z=n.readBits(32),n.readBool())if(n.readUEG(),n.readBool()){var $=!1,ee=!1,te=!1;if($=n.readBool(),ee=n.readBool(),$||ee){(te=n.readBool())&&(n.readByte(),n.readBits(5),n.readBool(),n.readBits(5));n.readBits(4),n.readBits(4);te&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5)}for(L=0;L<=d;L++){var ie=n.readBool();Y=ie;var ne=!1,ae=1;ie||(ne=n.readBool());var re=!1;if(ne?n.readSEG():re=n.readBool(),re||(ae=n.readUEG()+1),$)for(V=0;V>>2!=0,s=0!=(1&t[4]),o=(n=t)[a=5]<<24|n[a+1]<<16|n[a+2]<<8|n[a+3];return o<9?i:{match:!0,consumed:o,dataOffset:o,hasAudioTrack:r,hasVideoTrack:s}},e.prototype.bindDataSource=function(e){return e.onDataArrival=this.parseChunks.bind(this),this},Object.defineProperty(e.prototype,"onTrackMetadata",{get:function(){return this._onTrackMetadata},set:function(e){this._onTrackMetadata=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onMediaInfo",{get:function(){return this._onMediaInfo},set:function(e){this._onMediaInfo=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onMetaDataArrived",{get:function(){return this._onMetaDataArrived},set:function(e){this._onMetaDataArrived=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onScriptDataArrived",{get:function(){return this._onScriptDataArrived},set:function(e){this._onScriptDataArrived=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onError",{get:function(){return this._onError},set:function(e){this._onError=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onDataAvailable",{get:function(){return this._onDataAvailable},set:function(e){this._onDataAvailable=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"timestampBase",{get:function(){return this._timestampBase},set:function(e){this._timestampBase=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"overridedDuration",{get:function(){return this._duration},set:function(e){this._durationOverrided=!0,this._duration=e,this._mediaInfo.duration=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"overridedHasAudio",{set:function(e){this._hasAudioFlagOverrided=!0,this._hasAudio=e,this._mediaInfo.hasAudio=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"overridedHasVideo",{set:function(e){this._hasVideoFlagOverrided=!0,this._hasVideo=e,this._mediaInfo.hasVideo=e},enumerable:!1,configurable:!0}),e.prototype.resetMediaInfo=function(){this._mediaInfo=new o.a},e.prototype._isInitialMetadataDispatched=function(){return this._hasAudio&&this._hasVideo?this._audioInitialMetadataDispatched&&this._videoInitialMetadataDispatched:this._hasAudio&&!this._hasVideo?this._audioInitialMetadataDispatched:!(this._hasAudio||!this._hasVideo)&&this._videoInitialMetadataDispatched},e.prototype.parseChunks=function(t,i){if(!(this._onError&&this._onMediaInfo&&this._onTrackMetadata&&this._onDataAvailable))throw new c.a("Flv: onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var n=0,a=this._littleEndian;if(0===i){if(!(t.byteLength>13))return 0;n=e.probe(t).dataOffset}this._firstParse&&(this._firstParse=!1,i+n!==this._dataOffset&&r.a.w(this.TAG,"First time parsing but chunk byteStart invalid!"),0!==(s=new DataView(t,n)).getUint32(0,!a)&&r.a.w(this.TAG,"PrevTagSize0 !== 0 !!!"),n+=4);for(;nt.byteLength)break;var o=s.getUint8(0),d=16777215&s.getUint32(0,!a);if(n+11+d+4>t.byteLength)break;if(8===o||9===o||18===o){var _=s.getUint8(4),h=s.getUint8(5),u=s.getUint8(6)|h<<8|_<<16|s.getUint8(7)<<24;0!==(16777215&s.getUint32(7,!a))&&r.a.w(this.TAG,"Meet tag which has StreamID != 0!");var l=n+11;switch(o){case 8:this._parseAudioData(t,l,d,u);break;case 9:this._parseVideoData(t,l,d,u,i+n);break;case 18:this._parseScriptData(t,l,d)}var f=s.getUint32(11+d,!a);f!==11+d&&r.a.w(this.TAG,"Invalid PrevTagSize "+f),n+=11+d+4}else r.a.w(this.TAG,"Unsupported tag type "+o+", skipped"),n+=11+d+4}return this._isInitialMetadataDispatched()&&this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack),n},e.prototype._parseScriptData=function(e,t,i){var n=l.parseScriptData(e,t,i);if(n.hasOwnProperty("onMetaData")){if(null==n.onMetaData||"object"!=typeof n.onMetaData)return void r.a.w(this.TAG,"Invalid onMetaData structure!");this._metadata&&r.a.w(this.TAG,"Found another onMetaData tag!"),this._metadata=n;var a=this._metadata.onMetaData;if(this._onMetaDataArrived&&this._onMetaDataArrived(Object.assign({},a)),"boolean"==typeof a.hasAudio&&!1===this._hasAudioFlagOverrided&&(this._hasAudio=a.hasAudio,this._mediaInfo.hasAudio=this._hasAudio),"boolean"==typeof a.hasVideo&&!1===this._hasVideoFlagOverrided&&(this._hasVideo=a.hasVideo,this._mediaInfo.hasVideo=this._hasVideo),"number"==typeof a.audiodatarate&&(this._mediaInfo.audioDataRate=a.audiodatarate),"number"==typeof a.videodatarate&&(this._mediaInfo.videoDataRate=a.videodatarate),"number"==typeof a.width&&(this._mediaInfo.width=a.width),"number"==typeof a.height&&(this._mediaInfo.height=a.height),"number"==typeof a.duration){if(!this._durationOverrided){var s=Math.floor(a.duration*this._timescale);this._duration=s,this._mediaInfo.duration=s}}else this._mediaInfo.duration=0;if("number"==typeof a.framerate){var o=Math.floor(1e3*a.framerate);if(o>0){var d=o/1e3;this._referenceFrameRate.fixed=!0,this._referenceFrameRate.fps=d,this._referenceFrameRate.fps_num=o,this._referenceFrameRate.fps_den=1e3,this._mediaInfo.fps=d}}if("object"==typeof a.keyframes){this._mediaInfo.hasKeyframesIndex=!0;var _=a.keyframes;this._mediaInfo.keyframesIndex=this._parseKeyframesIndex(_),a.keyframes=null}else this._mediaInfo.hasKeyframesIndex=!1;this._dispatch=!1,this._mediaInfo.metadata=a,r.a.v(this.TAG,"Parsed onMetaData"),this._mediaInfo.isComplete()&&this._onMediaInfo(this._mediaInfo)}Object.keys(n).length>0&&this._onScriptDataArrived&&this._onScriptDataArrived(Object.assign({},n))},e.prototype._parseKeyframesIndex=function(e){for(var t=[],i=[],n=1;n>>4;if(2===s||10===s){var o=0,d=(12&a)>>>2;if(d>=0&&d<=4){o=this._flvSoundRateTable[d];var _=1&a,h=this._audioMetadata,c=this._audioTrack;if(h||(!1===this._hasAudio&&!1===this._hasAudioFlagOverrided&&(this._hasAudio=!0,this._mediaInfo.hasAudio=!0),(h=this._audioMetadata={}).type="audio",h.id=c.id,h.timescale=this._timescale,h.duration=this._duration,h.audioSampleRate=o,h.channelCount=0===_?1:2),10===s){var u=this._parseAACAudioData(e,t+1,i-1);if(null==u)return;if(0===u.packetType){if(h.config){if(S(u.data.config,h.config))return;r.a.w(this.TAG,"AudioSpecificConfig has been changed, re-generate initialization segment")}var l=u.data;h.audioSampleRate=l.samplingRate,h.channelCount=l.channelCount,h.codec=l.codec,h.originalCodec=l.originalCodec,h.config=l.config,h.refSampleDuration=1024/h.audioSampleRate*h.timescale,r.a.v(this.TAG,"Parsed AudioSpecificConfig"),this._isInitialMetadataDispatched()?this._dispatch&&(this._audioTrack.length||this._videoTrack.length)&&this._onDataAvailable(this._audioTrack,this._videoTrack):this._audioInitialMetadataDispatched=!0,this._dispatch=!1,this._onTrackMetadata("audio",h),(g=this._mediaInfo).audioCodec=h.originalCodec,g.audioSampleRate=h.audioSampleRate,g.audioChannelCount=h.channelCount,g.hasVideo?null!=g.videoCodec&&(g.mimeType='video/x-flv; codecs="'+g.videoCodec+","+g.audioCodec+'"'):g.mimeType='video/x-flv; codecs="'+g.audioCodec+'"',g.isComplete()&&this._onMediaInfo(g)}else if(1===u.packetType){var f=this._timestampBase+n,p={unit:u.data,length:u.data.byteLength,dts:f,pts:f};c.samples.push(p),c.length+=u.data.length}else r.a.e(this.TAG,"Flv: Unsupported AAC data type "+u.packetType)}else if(2===s){if(!h.codec){var g;if(null==(l=this._parseMP3AudioData(e,t+1,i-1,!0)))return;h.audioSampleRate=l.samplingRate,h.channelCount=l.channelCount,h.codec=l.codec,h.originalCodec=l.originalCodec,h.refSampleDuration=1152/h.audioSampleRate*h.timescale,r.a.v(this.TAG,"Parsed MPEG Audio Frame Header"),this._audioInitialMetadataDispatched=!0,this._onTrackMetadata("audio",h),(g=this._mediaInfo).audioCodec=h.codec,g.audioSampleRate=h.audioSampleRate,g.audioChannelCount=h.channelCount,g.audioDataRate=l.bitRate,g.hasVideo?null!=g.videoCodec&&(g.mimeType='video/x-flv; codecs="'+g.videoCodec+","+g.audioCodec+'"'):g.mimeType='video/x-flv; codecs="'+g.audioCodec+'"',g.isComplete()&&this._onMediaInfo(g)}var v=this._parseMP3AudioData(e,t+1,i-1,!1);if(null==v)return;f=this._timestampBase+n;var y={unit:v,length:v.byteLength,dts:f,pts:f};c.samples.push(y),c.length+=v.length}}else this._onError(m.a.FORMAT_ERROR,"Flv: Invalid audio sample rate idx: "+d)}else this._onError(m.a.CODEC_UNSUPPORTED,"Flv: Unsupported audio codec idx: "+s)}},e.prototype._parseAACAudioData=function(e,t,i){if(!(i<=1)){var n={},a=new Uint8Array(e,t,i);return n.packetType=a[0],0===a[0]?n.data=this._parseAACAudioSpecificConfig(e,t+1,i-1):n.data=a.subarray(1),n}r.a.w(this.TAG,"Flv: Invalid AAC packet, missing AACPacketType or/and Data!")},e.prototype._parseAACAudioSpecificConfig=function(e,t,i){var n,a,r=new Uint8Array(e,t,i),s=null,o=0,d=null;if(o=n=r[0]>>>3,(a=(7&r[0])<<1|r[1]>>>7)<0||a>=this._mpegSamplingRates.length)this._onError(m.a.FORMAT_ERROR,"Flv: AAC invalid sampling frequency index!");else{var _=this._mpegSamplingRates[a],h=(120&r[1])>>>3;if(!(h<0||h>=8)){5===o&&(d=(7&r[1])<<1|r[2]>>>7,(124&r[2])>>>2);var c=self.navigator.userAgent.toLowerCase();return-1!==c.indexOf("firefox")?a>=6?(o=5,s=new Array(4),d=a-3):(o=2,s=new Array(2),d=a):-1!==c.indexOf("android")?(o=2,s=new Array(2),d=a):(o=5,d=a,s=new Array(4),a>=6?d=a-3:1===h&&(o=2,s=new Array(2),d=a)),s[0]=o<<3,s[0]|=(15&a)>>>1,s[1]=(15&a)<<7,s[1]|=(15&h)<<3,5===o&&(s[1]|=(15&d)>>>1,s[2]=(1&d)<<7,s[2]|=8,s[3]=0),{config:s,samplingRate:_,channelCount:h,codec:"mp4a.40."+o,originalCodec:"mp4a.40."+n}}this._onError(m.a.FORMAT_ERROR,"Flv: AAC invalid channel configuration")}},e.prototype._parseMP3AudioData=function(e,t,i,n){if(!(i<4)){this._littleEndian;var a=new Uint8Array(e,t,i),s=null;if(n){if(255!==a[0])return;var o=a[1]>>>3&3,d=(6&a[1])>>1,_=(240&a[2])>>>4,h=(12&a[2])>>>2,c=3!==(a[3]>>>6&3)?2:1,u=0,l=0;switch(o){case 0:u=this._mpegAudioV25SampleRateTable[h];break;case 2:u=this._mpegAudioV20SampleRateTable[h];break;case 3:u=this._mpegAudioV10SampleRateTable[h]}switch(d){case 1:34,_>>4;if(0!=(128&s)){var d=15&s,_=String.fromCharCode.apply(String,new Uint8Array(e,t,i).slice(1,5));if("hvc1"!==_)return void this._onError(m.a.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: "+_);this._parseEnhancedHEVCVideoPacket(e,t+5,i-5,n,a,o,d)}else{var h=15&s;if(7===h)this._parseAVCVideoPacket(e,t+1,i-1,n,a,o);else{if(12!==h)return void this._onError(m.a.CODEC_UNSUPPORTED,"Flv: Unsupported codec in video frame: "+h);this._parseHEVCVideoPacket(e,t+1,i-1,n,a,o)}}}},e.prototype._parseAVCVideoPacket=function(e,t,i,n,a,s){if(i<4)r.a.w(this.TAG,"Flv: Invalid AVC packet, missing AVCPacketType or/and CompositionTime");else{var o=this._littleEndian,d=new DataView(e,t,i),_=d.getUint8(0),h=(16777215&d.getUint32(0,!o))<<8>>8;if(0===_)this._parseAVCDecoderConfigurationRecord(e,t+4,i-4);else if(1===_)this._parseAVCVideoData(e,t+4,i-4,n,a,s,h);else if(2!==_)return void this._onError(m.a.FORMAT_ERROR,"Flv: Invalid video packet type "+_)}},e.prototype._parseHEVCVideoPacket=function(e,t,i,n,a,s){if(i<4)r.a.w(this.TAG,"Flv: Invalid HEVC packet, missing HEVCPacketType or/and CompositionTime");else{var o=this._littleEndian,d=new DataView(e,t,i),_=d.getUint8(0),h=(16777215&d.getUint32(0,!o))<<8>>8;if(0===_)this._parseHEVCDecoderConfigurationRecord(e,t+4,i-4);else if(1===_)this._parseHEVCVideoData(e,t+4,i-4,n,a,s,h);else if(2!==_)return void this._onError(m.a.FORMAT_ERROR,"Flv: Invalid video packet type "+_)}},e.prototype._parseEnhancedHEVCVideoPacket=function(e,t,i,n,a,s,o){if(i<4)r.a.w(this.TAG,"Flv: Invalid HEVC packet, missing HEVCPacketType or/and CompositionTime");else{var d=this._littleEndian,_=new DataView(e,t,i);if(0===o)this._parseHEVCDecoderConfigurationRecord(e,t,i);else if(1===o){var h=(4294967040&_.getUint32(0,!d))>>8;this._parseHEVCVideoData(e,t+3,i-3,n,a,s,h)}else if(3===o)this._parseHEVCVideoData(e,t,i,n,a,s,0);else if(2!==o)return void this._onError(m.a.FORMAT_ERROR,"Flv: Invalid video packet type "+o)}},e.prototype._parseAVCDecoderConfigurationRecord=function(e,t,i){if(i<7)r.a.w(this.TAG,"Flv: Invalid AVCDecoderConfigurationRecord, lack of data!");else{var n=this._videoMetadata,a=this._videoTrack,s=this._littleEndian,o=new DataView(e,t,i);if(n){if(void 0!==n.avcc){var d=new Uint8Array(e,t,i);if(S(d,n.avcc))return;r.a.w(this.TAG,"AVCDecoderConfigurationRecord has been changed, re-generate initialization segment")}}else!1===this._hasVideo&&!1===this._hasVideoFlagOverrided&&(this._hasVideo=!0,this._mediaInfo.hasVideo=!0),(n=this._videoMetadata={}).type="video",n.id=a.id,n.timescale=this._timescale,n.duration=this._duration;var _=o.getUint8(0),h=o.getUint8(1);o.getUint8(2),o.getUint8(3);if(1===_&&0!==h)if(this._naluLengthSize=1+(3&o.getUint8(4)),3===this._naluLengthSize||4===this._naluLengthSize){var c=31&o.getUint8(5);if(0!==c){c>1&&r.a.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: SPS Count = "+c);for(var u=6,l=0;l1&&r.a.w(this.TAG,"Flv: Strange AVCDecoderConfigurationRecord: PPS Count = "+w),u++;for(l=0;l=i){r.a.w(this.TAG,"Malformed Nalu near timestamp "+f+", offset = "+u+", dataSize = "+i);break}var m=_.getUint32(u,!d);if(3===l&&(m>>>=8),m>i-l)return void r.a.w(this.TAG,"Malformed Nalus near timestamp "+f+", NaluSize > DataSize!");var g=31&_.getUint8(u+l);5===g&&(p=!0);var v=new Uint8Array(e,t+u,l+m),y={type:g,data:v};h.push(y),c+=v.byteLength,u+=l+m}if(h.length){var b=this._videoTrack,S={units:h,length:c,isKeyframe:p,dts:f,cts:o,pts:f+o};p&&(S.fileposition=a),b.samples.push(S),b.length+=c}},e.prototype._parseHEVCVideoData=function(e,t,i,n,a,s,o){for(var d=this._littleEndian,_=new DataView(e,t,i),h=[],c=0,u=0,l=this._naluLengthSize,f=this._timestampBase+n,p=1===s;u=i){r.a.w(this.TAG,"Malformed Nalu near timestamp "+f+", offset = "+u+", dataSize = "+i);break}var m=_.getUint32(u,!d);if(3===l&&(m>>>=8),m>i-l)return void r.a.w(this.TAG,"Malformed Nalus near timestamp "+f+", NaluSize > DataSize!");var g=31&_.getUint8(u+l);19!==g&&20!==g||(p=!0);var v=new Uint8Array(e,t+u,l+m),y={type:g,data:v};h.push(y),c+=v.byteLength,u+=l+m}if(h.length){var b=this._videoTrack,S={units:h,length:c,isKeyframe:p,dts:f,cts:o,pts:f+o};p&&(S.fileposition=a),b.samples.push(S),b.length+=c}},e}(),R=function(){function e(){}return e.prototype.destroy=function(){this.onError=null,this.onMediaInfo=null,this.onMetaDataArrived=null,this.onTrackMetadata=null,this.onDataAvailable=null,this.onTimedID3Metadata=null,this.onSMPTE2038Metadata=null,this.onSCTE35Metadata=null,this.onPESPrivateData=null,this.onPESPrivateDataDescriptor=null},e}(),T=function(){this.program_pmt_pid={}};!function(e){e[e.kMPEG1Audio=3]="kMPEG1Audio",e[e.kMPEG2Audio=4]="kMPEG2Audio",e[e.kPESPrivateData=6]="kPESPrivateData",e[e.kADTSAAC=15]="kADTSAAC",e[e.kLOASAAC=17]="kLOASAAC",e[e.kAC3=129]="kAC3",e[e.kID3=21]="kID3",e[e.kSCTE35=134]="kSCTE35",e[e.kH264=27]="kH264",e[e.kH265=36]="kH265"}(E||(E={}));var L,w=function(){this.pid_stream_type={},this.common_pids={h264:void 0,h265:void 0,adts_aac:void 0,loas_aac:void 0,opus:void 0,ac3:void 0,mp3:void 0},this.pes_private_data_pids={},this.timed_id3_pids={},this.scte_35_pids={},this.smpte2038_pids={}},k=function(){},D=function(){},C=function(){this.slices=[],this.total_length=0,this.expected_length=0,this.file_position=0};!function(e){e[e.kUnspecified=0]="kUnspecified",e[e.kSliceNonIDR=1]="kSliceNonIDR",e[e.kSliceDPA=2]="kSliceDPA",e[e.kSliceDPB=3]="kSliceDPB",e[e.kSliceDPC=4]="kSliceDPC",e[e.kSliceIDR=5]="kSliceIDR",e[e.kSliceSEI=6]="kSliceSEI",e[e.kSliceSPS=7]="kSliceSPS",e[e.kSlicePPS=8]="kSlicePPS",e[e.kSliceAUD=9]="kSliceAUD",e[e.kEndOfSequence=10]="kEndOfSequence",e[e.kEndOfStream=11]="kEndOfStream",e[e.kFiller=12]="kFiller",e[e.kSPSExt=13]="kSPSExt",e[e.kReserved0=14]="kReserved0"}(L||(L={}));var B,I,O=function(){},P=function(e){var t=e.data.byteLength;this.type=e.type,this.data=new Uint8Array(4+t),new DataView(this.data.buffer).setUint32(0,t),this.data.set(e.data,4)},M=function(){function e(e){this.TAG="H264AnnexBParser",this.current_startcode_offset_=0,this.eof_flag_=!1,this.data_=e,this.current_startcode_offset_=this.findNextStartCodeOffset(0),this.eof_flag_&&r.a.e(this.TAG,"Could not find H264 startcode until payload end!")}return e.prototype.findNextStartCodeOffset=function(e){for(var t=e,i=this.data_;;){if(t+3>=i.byteLength)return this.eof_flag_=!0,i.byteLength;var n=i[t+0]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3],a=i[t+0]<<16|i[t+1]<<8|i[t+2];if(1===n||1===a)return t;t++}},e.prototype.readNextNaluPayload=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_startcode_offset_,n=31&e[i+=1===(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3])?4:3],a=(128&e[i])>>>7,r=this.findNextStartCodeOffset(i);if(this.current_startcode_offset_=r,!(n>=L.kReserved0)&&0===a){var s=e.subarray(i,r);(t=new O).type=n,t.data=s}}return t},e}(),x=function(){function e(e,t,i){var n=8+e.byteLength+1+2+t.byteLength,a=!1;66!==e[3]&&77!==e[3]&&88!==e[3]&&(a=!0,n+=4);var r=this.data=new Uint8Array(n);r[0]=1,r[1]=e[1],r[2]=e[2],r[3]=e[3],r[4]=255,r[5]=225;var s=e.byteLength;r[6]=s>>>8,r[7]=255&s;var o=8;r.set(e,8),r[o+=s]=1;var d=t.byteLength;r[o+1]=d>>>8,r[o+2]=255&d,r.set(t,o+3),o+=3+d,a&&(r[o]=252|i.chroma_format_idc,r[o+1]=248|i.bit_depth_luma-8,r[o+2]=248|i.bit_depth_chroma-8,r[o+3]=0,o+=4)}return e.prototype.getData=function(){return this.data},e}();!function(e){e[e.kNull=0]="kNull",e[e.kAACMain=1]="kAACMain",e[e.kAAC_LC=2]="kAAC_LC",e[e.kAAC_SSR=3]="kAAC_SSR",e[e.kAAC_LTP=4]="kAAC_LTP",e[e.kAAC_SBR=5]="kAAC_SBR",e[e.kAAC_Scalable=6]="kAAC_Scalable",e[e.kLayer1=32]="kLayer1",e[e.kLayer2=33]="kLayer2",e[e.kLayer3=34]="kLayer3"}(B||(B={})),function(e){e[e.k96000Hz=0]="k96000Hz",e[e.k88200Hz=1]="k88200Hz",e[e.k64000Hz=2]="k64000Hz",e[e.k48000Hz=3]="k48000Hz",e[e.k44100Hz=4]="k44100Hz",e[e.k32000Hz=5]="k32000Hz",e[e.k24000Hz=6]="k24000Hz",e[e.k22050Hz=7]="k22050Hz",e[e.k16000Hz=8]="k16000Hz",e[e.k12000Hz=9]="k12000Hz",e[e.k11025Hz=10]="k11025Hz",e[e.k8000Hz=11]="k8000Hz",e[e.k7350Hz=12]="k7350Hz"}(I||(I={}));var U,N,G=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],V=(U=function(e,t){return(U=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}U(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),F=function(){},j=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return V(t,e),t}(F),z=function(){function e(e){this.TAG="AACADTSParser",this.data_=e,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&r.a.e(this.TAG,"Could not found ADTS syncword until payload end")}return e.prototype.findNextSyncwordOffset=function(e){for(var t=e,i=this.data_;;){if(t+7>=i.byteLength)return this.eof_flag_=!0,i.byteLength;if(4095===(i[t+0]<<8|i[t+1])>>>4)return t;t++}},e.prototype.readNextAACFrame=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_syncword_offset_,n=(8&e[i+1])>>>3,a=(6&e[i+1])>>>1,r=1&e[i+1],s=(192&e[i+2])>>>6,o=(60&e[i+2])>>>2,d=(1&e[i+2])<<2|(192&e[i+3])>>>6,_=(3&e[i+3])<<11|e[i+4]<<3|(224&e[i+5])>>>5;e[i+6];if(i+_>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var h=1===r?7:9,c=_-h;i+=h;var u=this.findNextSyncwordOffset(i+c);if(this.current_syncword_offset_=u,(0===n||1===n)&&0===a){var l=e.subarray(i,i+c);(t=new F).audio_object_type=s+1,t.sampling_freq_index=o,t.sampling_frequency=G[o],t.channel_config=d,t.data=l}}return t},e.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},e.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},e}(),H=function(){function e(e){this.TAG="AACLOASParser",this.data_=e,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&r.a.e(this.TAG,"Could not found LOAS syncword until payload end")}return e.prototype.findNextSyncwordOffset=function(e){for(var t=e,i=this.data_;;){if(t+1>=i.byteLength)return this.eof_flag_=!0,i.byteLength;if(695===(i[t+0]<<3|i[t+1]>>>5))return t;t++}},e.prototype.getLATMValue=function(e){for(var t=e.readBits(2),i=0,n=0;n<=t;n++)i<<=8,i|=e.readByte();return i},e.prototype.readNextAACFrame=function(e){for(var t=this.data_,i=null;null==i&&!this.eof_flag_;){var n=this.current_syncword_offset_,a=(31&t[n+1])<<8|t[n+2];if(n+3+a>=this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var s=new f(t.subarray(n+3,n+3+a)),o=null;if(s.readBool()){if(null==e){r.a.w(this.TAG,"StreamMuxConfig Missing"),this.current_syncword_offset_=this.findNextSyncwordOffset(n+3+a),s.destroy();continue}o=e}else{var d=s.readBool();if(d&&s.readBool()){r.a.e(this.TAG,"audioMuxVersionA is Not Supported"),s.destroy();break}if(d&&this.getLATMValue(s),!s.readBool()){r.a.e(this.TAG,"allStreamsSameTimeFraming zero is Not Supported"),s.destroy();break}if(0!==s.readBits(6)){r.a.e(this.TAG,"more than 2 numSubFrames Not Supported"),s.destroy();break}if(0!==s.readBits(4)){r.a.e(this.TAG,"more than 2 numProgram Not Supported"),s.destroy();break}if(0!==s.readBits(3)){r.a.e(this.TAG,"more than 2 numLayer Not Supported"),s.destroy();break}var _=d?this.getLATMValue(s):0,h=s.readBits(5);_-=5;var c=s.readBits(4);_-=4;var u=s.readBits(4);_-=4,s.readBits(3),(_-=3)>0&&s.readBits(_);var l=s.readBits(3);if(0!==l){r.a.e(this.TAG,"frameLengthType = "+l+". Only frameLengthType = 0 Supported"),s.destroy();break}s.readByte();var p=s.readBool();if(p)if(d)this.getLATMValue(s);else{for(var m=0;;){m<<=8;var g=s.readBool();if(m+=s.readByte(),!g)break}console.log(m)}s.readBool()&&s.readByte(),(o=new j).audio_object_type=h,o.sampling_freq_index=c,o.sampling_frequency=G[o.sampling_freq_index],o.channel_config=u,o.other_data_present=p}for(var v=0;;){var y=s.readByte();if(v+=y,255!==y)break}for(var b=new Uint8Array(v),S=0;S=6?(n=5,t=new Array(4),s=a-3):(n=2,t=new Array(2),s=a):-1!==o.indexOf("android")?(n=2,t=new Array(2),s=a):(n=5,s=a,t=new Array(4),a>=6?s=a-3:1===r&&(n=2,t=new Array(2),s=a)),t[0]=n<<3,t[0]|=(15&a)>>>1,t[1]=(15&a)<<7,t[1]|=(15&r)<<3,5===n&&(t[1]|=(15&s)>>>1,t[2]=(1&s)<<7,t[2]|=8,t[3]=0),this.config=t,this.sampling_rate=G[a],this.channel_count=r,this.codec_mimetype="mp4a.40."+n,this.original_codec_mimetype="mp4a.40."+i},K=function(){},W=function(){};!function(e){e[e.kSpliceNull=0]="kSpliceNull",e[e.kSpliceSchedule=4]="kSpliceSchedule",e[e.kSpliceInsert=5]="kSpliceInsert",e[e.kTimeSignal=6]="kTimeSignal",e[e.kBandwidthReservation=7]="kBandwidthReservation",e[e.kPrivateCommand=255]="kPrivateCommand"}(N||(N={}));var X,Y=function(e){var t=e.readBool();return t?(e.readBits(6),{time_specified_flag:t,pts_time:4*e.readBits(31)+e.readBits(2)}):(e.readBits(7),{time_specified_flag:t})},J=function(e){var t=e.readBool();return e.readBits(6),{auto_return:t,duration:4*e.readBits(31)+e.readBits(2)}},Z=function(e,t){var i=t.readBits(8);return e?{component_tag:i}:{component_tag:i,splice_time:Y(t)}},Q=function(e){return{component_tag:e.readBits(8),utc_splice_time:e.readBits(32)}},$=function(e){var t=e.readBits(32),i=e.readBool();e.readBits(7);var n={splice_event_id:t,splice_event_cancel_indicator:i};if(i)return n;if(n.out_of_network_indicator=e.readBool(),n.program_splice_flag=e.readBool(),n.duration_flag=e.readBool(),e.readBits(5),n.program_splice_flag)n.utc_splice_time=e.readBits(32);else{n.component_count=e.readBits(8),n.components=[];for(var a=0;a=i.byteLength)return this.eof_flag_=!0,i.byteLength;var n=i[t+0]<<24|i[t+1]<<16|i[t+2]<<8|i[t+3],a=i[t+0]<<16|i[t+1]<<8|i[t+2];if(1===n||1===a)return t;t++}},e.prototype.readNextNaluPayload=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_startcode_offset_,n=e[i+=1===(e[i]<<24|e[i+1]<<16|e[i+2]<<8|e[i+3])?4:3]>>1&63,a=(128&e[i])>>>7,r=this.findNextStartCodeOffset(i);if(this.current_startcode_offset_=r,0===a){var s=e.subarray(i,r);(t=new de).type=n,t.data=s}}return t},e}(),ce=function(){function e(e,t,i,n){var a=23+(5+e.byteLength)+(5+t.byteLength)+(5+i.byteLength),r=this.data=new Uint8Array(a);r[0]=1,r[1]=(3&n.general_profile_space)<<6|(n.general_tier_flag?1:0)<<5|31&n.general_profile_idc,r[2]=n.general_profile_compatibility_flags_1,r[3]=n.general_profile_compatibility_flags_2,r[4]=n.general_profile_compatibility_flags_3,r[5]=n.general_profile_compatibility_flags_4,r[6]=n.general_constraint_indicator_flags_1,r[7]=n.general_constraint_indicator_flags_2,r[8]=n.general_constraint_indicator_flags_3,r[9]=n.general_constraint_indicator_flags_4,r[10]=n.general_constraint_indicator_flags_5,r[11]=n.general_constraint_indicator_flags_6,r[12]=n.general_level_idc,r[13]=240|(3840&n.min_spatial_segmentation_idc)>>8,r[14]=255&n.min_spatial_segmentation_idc,r[15]=252|3&n.parallelismType,r[16]=252|3&n.chroma_format_idc,r[17]=248|7&n.bit_depth_luma_minus8,r[18]=248|7&n.bit_depth_chroma_minus8,r[19]=0,r[20]=0,r[21]=(3&n.constant_frame_rate)<<6|(7&n.num_temporal_layers)<<3|(n.temporal_id_nested?1:0)<<2|3,r[22]=3,r[23]=128|X.kSliceVPS,r[24]=0,r[25]=1,r[26]=(65280&e.byteLength)>>8,r[27]=(255&e.byteLength)>>0,r.set(e,28),r[23+(5+e.byteLength)+0]=128|X.kSliceSPS,r[23+(5+e.byteLength)+1]=0,r[23+(5+e.byteLength)+2]=1,r[23+(5+e.byteLength)+3]=(65280&t.byteLength)>>8,r[23+(5+e.byteLength)+4]=(255&t.byteLength)>>0,r.set(t,23+(5+e.byteLength)+5),r[23+(5+e.byteLength+5+t.byteLength)+0]=128|X.kSlicePPS,r[23+(5+e.byteLength+5+t.byteLength)+1]=0,r[23+(5+e.byteLength+5+t.byteLength)+2]=1,r[23+(5+e.byteLength+5+t.byteLength)+3]=(65280&i.byteLength)>>8,r[23+(5+e.byteLength+5+t.byteLength)+4]=(255&i.byteLength)>>0,r.set(i,23+(5+e.byteLength+5+t.byteLength)+5)}return e.prototype.getData=function(){return this.data},e}(),ue=function(){},le=function(){},fe=function(){},pe=[[64,64,80,80,96,96,112,112,128,128,160,160,192,192,224,224,256,256,320,320,384,384,448,448,512,512,640,640,768,768,896,896,1024,1024,1152,1152,1280,1280],[69,70,87,88,104,105,121,122,139,140,174,175,208,209,243,244,278,279,348,349,417,418,487,488,557,558,696,697,835,836,975,976,1114,1115,1253,1254,1393,1394],[96,96,120,120,144,144,168,168,192,192,240,240,288,288,336,336,384,384,480,480,576,576,672,672,768,768,960,960,1152,1152,1344,1344,1536,1536,1728,1728,1920,1920]],me=function(){function e(e){this.TAG="AC3Parser",this.data_=e,this.current_syncword_offset_=this.findNextSyncwordOffset(0),this.eof_flag_&&r.a.e(this.TAG,"Could not found AC3 syncword until payload end")}return e.prototype.findNextSyncwordOffset=function(e){for(var t=e,i=this.data_;;){if(t+7>=i.byteLength)return this.eof_flag_=!0,i.byteLength;if(2935===(i[t+0]<<8|i[t+1]<<0))return t;t++}},e.prototype.readNextAC3Frame=function(){for(var e=this.data_,t=null;null==t&&!this.eof_flag_;){var i=this.current_syncword_offset_,n=e[i+4]>>6,a=[48e3,44200,33e3][n],r=63&e[i+4],s=2*pe[n][r];if(i+s>this.data_.byteLength){this.eof_flag_=!0,this.has_last_incomplete_data=!0;break}var o=this.findNextSyncwordOffset(i+s);this.current_syncword_offset_=o;var d=e[i+5]>>3,_=7&e[i+5],h=e[i+6]>>5,c=0;0!=(1&h)&&1!==h&&(c+=2),0!=(4&h)&&(c+=2),2===h&&(c+=2);var u=(e[i+6]<<8|e[i+7]<<0)>>12-c&1,l=[2,1,2,3,3,4,4,5][h]+u;(t=new fe).sampling_frequency=a,t.channel_count=l,t.channel_mode=h,t.bit_stream_identification=d,t.low_frequency_effects_channel_on=u,t.bit_stream_mode=_,t.frame_size_code=r,t.data=e.subarray(i,i+s)}return t},e.prototype.hasIncompleteData=function(){return this.has_last_incomplete_data},e.prototype.getIncompleteData=function(){return this.has_last_incomplete_data?this.data_.subarray(this.current_syncword_offset_):null},e}(),ge=function(e){var t;t=[e.sampling_rate_code<<6|e.bit_stream_identification<<1|e.bit_stream_mode>>2,(3&e.bit_stream_mode)<<6|e.channel_mode<<3|e.low_frequency_effects_channel_on<<2|e.frame_size_code>>4,e.frame_size_code<<4&224],this.config=t,this.sampling_rate=e.sampling_frequency,this.bit_stream_identification=e.bit_stream_identification,this.bit_stream_mode=e.bit_stream_mode,this.low_frequency_effects_channel_on=e.low_frequency_effects_channel_on,this.channel_count=e.channel_count,this.channel_mode=e.channel_mode,this.codec_mimetype="ac-3",this.original_codec_mimetype="ac-3"},ve=function(){var e=function(t,i){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(t,i)};return function(t,i){function n(){this.constructor=t}e(t,i),t.prototype=null===i?Object.create(i):(n.prototype=i.prototype,new n)}}(),ye=function(){return(ye=Object.assign||function(e){for(var t,i=1,n=arguments.length;i=4?(r.a.v("TSDemuxer","ts_packet_size = 192, m2ts mode"),i-=4):204===n&&r.a.v("TSDemuxer","ts_packet_size = 204, RS encoded MPEG2-TS stream"),{match:!0,consumed:0,ts_packet_size:n,sync_offset:i})},t.prototype.bindDataSource=function(e){return e.onDataArrival=this.parseChunks.bind(this),this},t.prototype.resetMediaInfo=function(){this.media_info_=new o.a},t.prototype.parseChunks=function(e,t){if(!(this.onError&&this.onMediaInfo&&this.onTrackMetadata&&this.onDataAvailable))throw new c.a("onError & onMediaInfo & onTrackMetadata & onDataAvailable callback must be specified");var i=0;for(this.first_parse_&&(this.first_parse_=!1,i=this.sync_offset_);i+this.ts_packet_size_<=e.byteLength;){var n=t+i;192===this.ts_packet_size_&&(i+=4);var a=new Uint8Array(e,i,188),s=a[0];if(71!==s){r.a.e(this.TAG,"sync_byte = "+s+", not 0x47");break}var o=(64&a[1])>>>6,d=(a[1],(31&a[1])<<8|a[2]),_=(48&a[3])>>>4,h=15&a[3],u={},l=4;if(2==_||3==_){var f=a[4];if(5+f===188){i+=188,204===this.ts_packet_size_&&(i+=16);continue}f>0&&(u=this.parseAdaptationField(e,i+4,1+f)),l=5+f}if(1==_||3==_)if(0===d||d===this.current_pmt_pid_||null!=this.pmt_&&this.pmt_.pid_stream_type[d]===E.kSCTE35){var p=188-l;this.handleSectionSlice(e,i+l,p,{pid:d,file_position:n,payload_unit_start_indicator:o,continuity_conunter:h,random_access_indicator:u.random_access_indicator})}else if(null!=this.pmt_&&null!=this.pmt_.pid_stream_type[d]){p=188-l;var m=this.pmt_.pid_stream_type[d];d!==this.pmt_.common_pids.h264&&d!==this.pmt_.common_pids.h265&&d!==this.pmt_.common_pids.adts_aac&&d!==this.pmt_.common_pids.loas_aac&&d!==this.pmt_.common_pids.ac3&&d!==this.pmt_.common_pids.opus&&d!==this.pmt_.common_pids.mp3&&!0!==this.pmt_.pes_private_data_pids[d]&&!0!==this.pmt_.timed_id3_pids[d]||this.handlePESSlice(e,i+l,p,{pid:d,stream_type:m,file_position:n,payload_unit_start_indicator:o,continuity_conunter:h,random_access_indicator:u.random_access_indicator})}i+=188,204===this.ts_packet_size_&&(i+=16)}return this.dispatchAudioVideoMediaSegment(),i},t.prototype.parseAdaptationField=function(e,t,i){var n=new Uint8Array(e,t,i),a=n[0];return a>0?a>183?(r.a.w(this.TAG,"Illegal adaptation_field_length: "+a),{}):{discontinuity_indicator:(128&n[1])>>>7,random_access_indicator:(64&n[1])>>>6,elementary_stream_priority_indicator:(32&n[1])>>>5}:{}},t.prototype.handleSectionSlice=function(e,t,i,n){var a=new Uint8Array(e,t,i),r=this.section_slice_queues_[n.pid];if(n.payload_unit_start_indicator){var s=a[0];if(null!=r&&0!==r.total_length){var o=new Uint8Array(e,t+1,Math.min(i,s));r.slices.push(o),r.total_length+=o.byteLength,r.total_length===r.expected_length?this.emitSectionSlices(r,n):this.clearSlices(r,n)}for(var d=1+s;d=r.expected_length&&this.clearSlices(r,n),d+=o.byteLength}}else if(null!=r&&0!==r.total_length){o=new Uint8Array(e,t,Math.min(i,r.expected_length-r.total_length));r.slices.push(o),r.total_length+=o.byteLength,r.total_length===r.expected_length?this.emitSectionSlices(r,n):r.total_length>=r.expected_length&&this.clearSlices(r,n)}},t.prototype.handlePESSlice=function(e,t,i,n){var a=new Uint8Array(e,t,i),s=a[0]<<16|a[1]<<8|a[2],o=(a[3],a[4]<<8|a[5]);if(n.payload_unit_start_indicator){if(1!==s)return void r.a.e(this.TAG,"handlePESSlice: packet_start_code_prefix should be 1 but with value "+s);var d=this.pes_slice_queues_[n.pid];d&&(0===d.expected_length||d.expected_length===d.total_length?this.emitPESSlices(d,n):this.clearSlices(d,n)),this.pes_slice_queues_[n.pid]=new C,this.pes_slice_queues_[n.pid].file_position=n.file_position,this.pes_slice_queues_[n.pid].random_access_indicator=n.random_access_indicator}if(null!=this.pes_slice_queues_[n.pid]){var _=this.pes_slice_queues_[n.pid];_.slices.push(a),n.payload_unit_start_indicator&&(_.expected_length=0===o?0:o+6),_.total_length+=a.byteLength,_.expected_length>0&&_.expected_length===_.total_length?this.emitPESSlices(_,n):_.expected_length>0&&_.expected_length<_.total_length&&this.clearSlices(_,n)}},t.prototype.emitSectionSlices=function(e,t){for(var i=new Uint8Array(e.total_length),n=0,a=0;n>>6,o=t[8],d=void 0,_=void 0;2!==s&&3!==s||(d=536870912*(14&t[9])+4194304*(255&t[10])+16384*(254&t[11])+128*(255&t[12])+(254&t[13])/2,_=3===s?536870912*(14&t[14])+4194304*(255&t[15])+16384*(254&t[16])+128*(255&t[17])+(254&t[18])/2:d);var h=9+o,c=void 0;if(0!==a){if(a<3+o)return void r.a.v(this.TAG,"Malformed PES: PES_packet_length < 3 + PES_header_data_length");c=a-3-o}else c=t.byteLength-h;var u=t.subarray(h,h+c);switch(e.stream_type){case E.kMPEG1Audio:case E.kMPEG2Audio:this.parseMP3Payload(u,d);break;case E.kPESPrivateData:this.pmt_.common_pids.opus===e.pid?this.parseOpusPayload(u,d):this.pmt_.common_pids.ac3===e.pid?this.parseAC3Payload(u,d):this.pmt_.smpte2038_pids[e.pid]?this.parseSMPTE2038MetadataPayload(u,d,_,e.pid,n):this.parsePESPrivateDataPayload(u,d,_,e.pid,n);break;case E.kADTSAAC:this.parseADTSAACPayload(u,d);break;case E.kLOASAAC:this.parseLOASAACPayload(u,d);break;case E.kAC3:this.parseAC3Payload(u,d);break;case E.kID3:this.parseTimedID3MetadataPayload(u,d,_,e.pid,n);break;case E.kH264:this.parseH264Payload(u,d,_,e.file_position,e.random_access_indicator);break;case E.kH265:this.parseH265Payload(u,d,_,e.file_position,e.random_access_indicator)}}else if((188===n||191===n||240===n||241===n||255===n||242===n||248===n)&&e.stream_type===E.kPESPrivateData){h=6,c=void 0;c=0!==a?a:t.byteLength-h;u=t.subarray(h,h+c);this.parsePESPrivateDataPayload(u,void 0,void 0,e.pid,n)}}else r.a.e(this.TAG,"parsePES: packet_start_code_prefix should be 1 but with value "+i)},t.prototype.parsePAT=function(e){var t=e[0];if(0===t){var i=(15&e[1])<<8|e[2],n=(e[3],e[4],(62&e[5])>>>1),a=1&e[5],s=e[6],o=(e[7],null);if(1===a&&0===s)(o=new T).version_number=n;else if(null==(o=this.pat_))return;for(var d=i-5-4,_=-1,h=-1,c=8;c<8+d;c+=4){var u=e[c]<<8|e[c+1],l=(31&e[c+2])<<8|e[c+3];0===u?o.network_pid=l:(o.program_pmt_pid[u]=l,-1===_&&(_=u),-1===h&&(h=l))}1===a&&0===s&&(null==this.pat_&&r.a.v(this.TAG,"Parsed first PAT: "+JSON.stringify(o)),this.pat_=o,this.current_program_=_,this.current_pmt_pid_=h)}else r.a.e(this.TAG,"parsePAT: table_id "+t+" is not corresponded to PAT!")},t.prototype.parsePMT=function(e){var t=e[0];if(2===t){var i=(15&e[1])<<8|e[2],n=e[3]<<8|e[4],a=(62&e[5])>>>1,s=1&e[5],o=e[6],d=(e[7],null);if(1===s&&0===o)(d=new w).program_number=n,d.version_number=a,this.program_pmt_map_[n]=d;else if(null==(d=this.program_pmt_map_[n]))return;e[8],e[9];for(var _=(15&e[10])<<8|e[11],h=12+_,c=i-9-_-4,u=h;u0){for(var v=u+5;v1&&(r.a.w(this.TAG,"AAC: Detected pts overlapped, expected: "+s+"ms, PES pts: "+a+"ms"),a=s)}}for(var o,d=new z(e),_=null,h=a;null!=(_=d.readNextAACFrame());){n=1024/_.sampling_frequency*1e3;var c={codec:"aac",data:_};0==this.audio_init_segment_dispatched_?(this.audio_metadata_={codec:"aac",audio_object_type:_.audio_object_type,sampling_freq_index:_.sampling_freq_index,sampling_frequency:_.sampling_frequency,channel_config:_.channel_config},this.dispatchAudioInitSegment(c)):this.detectAudioMetadataChange(c)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(c)),o=h;var u=Math.floor(h),l={unit:_.data,length:_.data.byteLength,pts:u,dts:u};this.audio_track_.samples.push(l),this.audio_track_.length+=_.data.byteLength,h+=n}d.hasIncompleteData()&&(this.aac_last_incomplete_data_=d.getIncompleteData()),o&&(this.aac_last_sample_pts_=o)}},t.prototype.parseLOASAACPayload=function(e,t){var i;if(!this.has_video_||this.video_init_segment_dispatched_){if(this.aac_last_incomplete_data_){var n=new Uint8Array(e.byteLength+this.aac_last_incomplete_data_.byteLength);n.set(this.aac_last_incomplete_data_,0),n.set(e,this.aac_last_incomplete_data_.byteLength),e=n}var a,s;if(null!=t&&(s=t/this.timescale_),"aac"===this.audio_metadata_.codec){if(null==t&&null!=this.aac_last_sample_pts_)a=1024/this.audio_metadata_.sampling_frequency*1e3,s=this.aac_last_sample_pts_+a;else if(null==t)return void r.a.w(this.TAG,"AAC: Unknown pts");if(this.aac_last_incomplete_data_&&this.aac_last_sample_pts_){a=1024/this.audio_metadata_.sampling_frequency*1e3;var o=this.aac_last_sample_pts_+a;Math.abs(o-s)>1&&(r.a.w(this.TAG,"AAC: Detected pts overlapped, expected: "+o+"ms, PES pts: "+s+"ms"),s=o)}}for(var d,_=new H(e),h=null,c=s;null!=(h=_.readNextAACFrame(null!==(i=this.loas_previous_frame)&&void 0!==i?i:void 0));){this.loas_previous_frame=h,a=1024/h.sampling_frequency*1e3;var u={codec:"aac",data:h};0==this.audio_init_segment_dispatched_?(this.audio_metadata_={codec:"aac",audio_object_type:h.audio_object_type,sampling_freq_index:h.sampling_freq_index,sampling_frequency:h.sampling_frequency,channel_config:h.channel_config},this.dispatchAudioInitSegment(u)):this.detectAudioMetadataChange(u)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(u)),d=c;var l=Math.floor(c),f={unit:h.data,length:h.data.byteLength,pts:l,dts:l};this.audio_track_.samples.push(f),this.audio_track_.length+=h.data.byteLength,c+=a}_.hasIncompleteData()&&(this.aac_last_incomplete_data_=_.getIncompleteData()),d&&(this.aac_last_sample_pts_=d)}},t.prototype.parseAC3Payload=function(e,t){if(!this.has_video_||this.video_init_segment_dispatched_){var i,n;if(null!=t&&(n=t/this.timescale_),"ac-3"===this.audio_metadata_.codec)if(null==t&&null!=this.aac_last_sample_pts_)i=1536/this.audio_metadata_.sampling_frequency*1e3,n=this.aac_last_sample_pts_+i;else if(null==t)return void r.a.w(this.TAG,"Opus: Unknown pts");for(var a,s=new me(e),o=null,d=n;null!=(o=s.readNextAC3Frame());){i=1536/o.sampling_frequency*1e3;var _={codec:"ac-3",data:o};0==this.audio_init_segment_dispatched_?(this.audio_metadata_={codec:"ac-3",sampling_frequency:o.sampling_frequency,bit_stream_identification:o.bit_stream_identification,bit_stream_mode:o.bit_stream_mode,low_frequency_effects_channel_on:o.low_frequency_effects_channel_on,channel_mode:o.channel_mode},console.log(JSON.stringify(this.audio_metadata_)),this.dispatchAudioInitSegment(_)):this.detectAudioMetadataChange(_)&&(this.dispatchAudioMediaSegment(),this.dispatchAudioInitSegment(_)),a=d;var h=Math.floor(d),c={unit:o.data,length:o.data.byteLength,pts:h,dts:h};this.audio_track_.samples.push(c),this.audio_track_.length+=o.data.byteLength,d+=i}a&&(this.aac_last_sample_pts_=a)}},t.prototype.parseOpusPayload=function(e,t){if(!this.has_video_||this.video_init_segment_dispatched_){var i,n;if(null!=t&&(n=t/this.timescale_),"opus"===this.audio_metadata_.codec)if(null==t&&null!=this.aac_last_sample_pts_)i=20,n=this.aac_last_sample_pts_+i;else if(null==t)return void r.a.w(this.TAG,"Opus: Unknown pts");for(var a,s=n,o=0;o>>3&3,s=(6&e[1])>>1,o=(240&e[2])>>>4,d=(12&e[2])>>>2,_=3!==(e[3]>>>6&3)?2:1,h=0,c=34;switch(r){case 0:h=[11025,12e3,8e3,0][d];break;case 2:h=[22050,24e3,16e3,0][d];break;case 3:h=[44100,48e3,32e3,0][d]}switch(s){case 1:c=34,o>>24&255,i[1]=t>>>16&255,i[2]=t>>>8&255,i[3]=255&t,i.set(e,4);var s=8;for(r=0;r>>24&255,t>>>16&255,t>>>8&255,255&t,i>>>24&255,i>>>16&255,i>>>8&255,255&i,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]))},e.trak=function(t){return e.box(e.types.trak,e.tkhd(t),e.mdia(t))},e.tkhd=function(t){var i=t.id,n=t.duration,a=t.presentWidth,r=t.presentHeight;return e.box(e.types.tkhd,new Uint8Array([0,0,0,7,0,0,0,0,0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i,0,0,0,0,n>>>24&255,n>>>16&255,n>>>8&255,255&n,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>>8&255,255&a,0,0,r>>>8&255,255&r,0,0]))},e.mdia=function(t){return e.box(e.types.mdia,e.mdhd(t),e.hdlr(t),e.minf(t))},e.mdhd=function(t){var i=t.timescale,n=t.duration;return e.box(e.types.mdhd,new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i,n>>>24&255,n>>>16&255,n>>>8&255,255&n,85,196,0,0]))},e.hdlr=function(t){var i=null;return i="audio"===t.type?e.constants.HDLR_AUDIO:e.constants.HDLR_VIDEO,e.box(e.types.hdlr,i)},e.minf=function(t){var i=null;return i="audio"===t.type?e.box(e.types.smhd,e.constants.SMHD):e.box(e.types.vmhd,e.constants.VMHD),e.box(e.types.minf,i,e.dinf(),e.stbl(t))},e.dinf=function(){return e.box(e.types.dinf,e.box(e.types.dref,e.constants.DREF))},e.stbl=function(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.constants.STTS),e.box(e.types.stsc,e.constants.STSC),e.box(e.types.stsz,e.constants.STSZ),e.box(e.types.stco,e.constants.STCO))},e.stsd=function(t){return"audio"===t.type?"mp3"===t.codec?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.mp3(t)):"ac-3"===t.codec?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.ac3(t)):"opus"===t.codec?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.Opus(t)):e.box(e.types.stsd,e.constants.STSD_PREFIX,e.mp4a(t)):"video"===t.type&&t.codec.startsWith("hvc1")?e.box(e.types.stsd,e.constants.STSD_PREFIX,e.hvc1(t)):e.box(e.types.stsd,e.constants.STSD_PREFIX,e.avc1(t))},e.mp3=function(t){var i=t.channelCount,n=t.audioSampleRate,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,i,0,16,0,0,0,0,n>>>8&255,255&n,0,0]);return e.box(e.types[".mp3"],a)},e.mp4a=function(t){var i=t.channelCount,n=t.audioSampleRate,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,i,0,16,0,0,0,0,n>>>8&255,255&n,0,0]);return e.box(e.types.mp4a,a,e.esds(t))},e.ac3=function(t){var i=t.channelCount,n=t.audioSampleRate,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,i,0,16,0,0,0,0,n>>>8&255,255&n,0,0]);return e.box(e.types["ac-3"],a,e.box(e.types.dac3,new Uint8Array(t.config)))},e.esds=function(t){var i=t.config||[],n=i.length,a=new Uint8Array([0,0,0,0,3,23+n,0,1,0,4,15+n,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([n]).concat(i).concat([6,1,2]));return e.box(e.types.esds,a)},e.Opus=function(t){var i=t.channelCount,n=t.audioSampleRate,a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,i,0,16,0,0,0,0,n>>>8&255,255&n,0,0]);return e.box(e.types.Opus,a,e.dOps(t))},e.dOps=function(t){var i=t.channelCount,n=t.channelConfigCode,a=t.audioSampleRate;if(t.config)return e.box(e.types.dOps,s);var r=[];switch(n){case 1:case 2:r=[0];break;case 0:r=[255,1,1,0,1];break;case 128:r=[255,2,0,0,1];break;case 3:r=[1,2,1,0,2,1];break;case 4:r=[1,2,2,0,1,2,3];break;case 5:r=[1,3,2,0,4,1,2,3];break;case 6:r=[1,4,2,0,4,1,2,3,5];break;case 7:r=[1,4,2,0,4,1,2,3,5,6];break;case 8:r=[1,5,3,0,6,1,2,3,4,5,7];break;case 130:r=[1,1,2,0,1];break;case 131:r=[1,1,3,0,1,2];break;case 132:r=[1,1,4,0,1,2,3];break;case 133:r=[1,1,5,0,1,2,3,4];break;case 134:r=[1,1,6,0,1,2,3,4,5];break;case 135:r=[1,1,7,0,1,2,3,4,5,6];break;case 136:r=[1,1,8,0,1,2,3,4,5,6,7]}var s=new Uint8Array(Se([0,i,0,0,a>>>24&255,a>>>17&255,a>>>8&255,a>>>0&255,0,0],r));return e.box(e.types.dOps,s)},e.avc1=function(t){var i=t.avcc,n=t.codecWidth,a=t.codecHeight,r=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,n>>>8&255,255&n,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return e.box(e.types.avc1,r,e.box(e.types.avcC,i))},e.hvc1=function(t){var i=t.hvcc,n=t.codecWidth,a=t.codecHeight,r=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,n>>>8&255,255&n,a>>>8&255,255&a,0,72,0,0,0,72,0,0,0,0,0,0,0,1,10,120,113,113,47,102,108,118,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,255,255]);return e.box(e.types.hvc1,r,e.box(e.types.hvcC,i))},e.mvex=function(t){return e.box(e.types.mvex,e.trex(t))},e.trex=function(t){var i=t.id,n=new Uint8Array([0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]);return e.box(e.types.trex,n)},e.moof=function(t,i){return e.box(e.types.moof,e.mfhd(t.sequenceNumber),e.traf(t,i))},e.mfhd=function(t){var i=new Uint8Array([0,0,0,0,t>>>24&255,t>>>16&255,t>>>8&255,255&t]);return e.box(e.types.mfhd,i)},e.traf=function(t,i){var n=t.id,a=e.box(e.types.tfhd,new Uint8Array([0,0,0,0,n>>>24&255,n>>>16&255,n>>>8&255,255&n])),r=e.box(e.types.tfdt,new Uint8Array([0,0,0,0,i>>>24&255,i>>>16&255,i>>>8&255,255&i])),s=e.sdtp(t),o=e.trun(t,s.byteLength+16+16+8+16+8+8);return e.box(e.types.traf,a,r,o,s)},e.sdtp=function(t){for(var i=t.samples||[],n=i.length,a=new Uint8Array(4+n),r=0;r>>24&255,a>>>16&255,a>>>8&255,255&a,i>>>24&255,i>>>16&255,i>>>8&255,255&i],0);for(var o=0;o>>24&255,d>>>16&255,d>>>8&255,255&d,_>>>24&255,_>>>16&255,_>>>8&255,255&_,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.isNonSync,0,0,c>>>24&255,c>>>16&255,c>>>8&255,255&c],12+16*o)}return e.box(e.types.trun,s)},e.mdat=function(t){return e.box(e.types.mdat,t)},e}();Ee.init();var Ae=Ee,Re=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])}return null},e}(),Te=i(7),Le=function(){function e(e){this.TAG="MP4Remuxer",this._config=e,this._isLive=!0===e.isLive,this._dtsBase=-1,this._dtsBaseInited=!1,this._audioDtsBase=1/0,this._videoDtsBase=1/0,this._audioNextDts=void 0,this._videoNextDts=void 0,this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList=new Te.c("audio"),this._videoSegmentInfoList=new Te.c("video"),this._onInitSegment=null,this._onMediaSegment=null,this._forceFirstIDR=!(!s.a.chrome||!(s.a.version.major<50||50===s.a.version.major&&s.a.version.build<2661)),this._fillSilentAfterSeek=s.a.msedge||s.a.msie,this._mp3UseMpegAudio=!s.a.firefox,this._fillAudioTimestampGap=this._config.fixAudioTimestampGap}return e.prototype.destroy=function(){this._dtsBase=-1,this._dtsBaseInited=!1,this._audioMeta=null,this._videoMeta=null,this._audioSegmentInfoList.clear(),this._audioSegmentInfoList=null,this._videoSegmentInfoList.clear(),this._videoSegmentInfoList=null,this._onInitSegment=null,this._onMediaSegment=null},e.prototype.bindDataSource=function(e){return e.onDataAvailable=this.remux.bind(this),e.onTrackMetadata=this._onTrackMetadataReceived.bind(this),this},Object.defineProperty(e.prototype,"onInitSegment",{get:function(){return this._onInitSegment},set:function(e){this._onInitSegment=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onMediaSegment",{get:function(){return this._onMediaSegment},set:function(e){this._onMediaSegment=e},enumerable:!1,configurable:!0}),e.prototype.insertDiscontinuity=function(){this._audioNextDts=this._videoNextDts=void 0},e.prototype.seek=function(e){this._audioStashedLastSample=null,this._videoStashedLastSample=null,this._videoSegmentInfoList.clear(),this._audioSegmentInfoList.clear()},e.prototype.remux=function(e,t){if(!this._onMediaSegment)throw new c.a("MP4Remuxer: onMediaSegment callback must be specificed!");this._dtsBaseInited||this._calculateDtsBase(e,t),t&&this._remuxVideo(t),e&&this._remuxAudio(e)},e.prototype._onTrackMetadataReceived=function(e,t){var i=null,n="mp4",a=t.codec;if("audio"===e)this._audioMeta=t,"mp3"===t.codec&&this._mp3UseMpegAudio?(n="mpeg",a="",i=new Uint8Array):i=Ae.generateInitSegment(t);else{if("video"!==e)return;this._videoMeta=t,i=Ae.generateInitSegment(t)}if(!this._onInitSegment)throw new c.a("MP4Remuxer: onInitSegment callback must be specified!");this._onInitSegment(e,{type:e,data:i.buffer,codec:a,container:e+"/"+n,mediaDuration:t.duration})},e.prototype._calculateDtsBase=function(e,t){this._dtsBaseInited||(e&&e.samples&&e.samples.length&&(this._audioDtsBase=e.samples[0].dts),t&&t.samples&&t.samples.length&&(this._videoDtsBase=t.samples[0].dts),this._dtsBase=Math.min(this._audioDtsBase,this._videoDtsBase),this._dtsBaseInited=!0)},e.prototype.getTimestampBase=function(){if(this._dtsBaseInited)return this._dtsBase},e.prototype.flushStashedSamples=function(){var e=this._videoStashedLastSample,t=this._audioStashedLastSample,i={type:"video",id:1,sequenceNumber:0,samples:[],length:0};null!=e&&(i.samples.push(e),i.length=e.length);var n={type:"audio",id:2,sequenceNumber:0,samples:[],length:0};null!=t&&(n.samples.push(t),n.length=t.length),this._videoStashedLastSample=null,this._audioStashedLastSample=null,this._remuxVideo(i,!0),this._remuxAudio(n,!0)},e.prototype._remuxAudio=function(e,t){if(null!=this._audioMeta){var i,n=e,a=n.samples,o=void 0,d=-1,_=this._audioMeta.refSampleDuration,h="mp3"===this._audioMeta.codec&&this._mp3UseMpegAudio,c=this._dtsBaseInited&&void 0===this._audioNextDts,u=!1;if(a&&0!==a.length&&(1!==a.length||t)){var l=0,f=null,p=0;h?(l=0,p=n.length):(l=8,p=8+n.length);var m=null;if(a.length>1&&(p-=(m=a.pop()).length),null!=this._audioStashedLastSample){var g=this._audioStashedLastSample;this._audioStashedLastSample=null,a.unshift(g),p+=g.length}null!=m&&(this._audioStashedLastSample=m);var v=a[0].dts-this._dtsBase;if(this._audioNextDts)o=v-this._audioNextDts;else if(this._audioSegmentInfoList.isEmpty())o=0,this._fillSilentAfterSeek&&!this._videoSegmentInfoList.isEmpty()&&"mp3"!==this._audioMeta.originalCodec&&(u=!0);else{var y=this._audioSegmentInfoList.getLastSampleBefore(v);if(null!=y){var b=v-(y.originalDts+y.duration);b<=3&&(b=0),o=v-(y.dts+y.duration+b)}else o=0}if(u){var S=v-o,E=this._videoSegmentInfoList.getLastSegmentBefore(v);if(null!=E&&E.beginDts=3*_&&this._fillAudioTimestampGap&&!s.a.safari){D=!0;var O,P=Math.floor(o/_);r.a.w(this.TAG,"Large audio timestamp gap detected, may cause AV sync to drift. Silent frames will be generated to avoid unsync.\noriginalDts: "+k+" ms, curRefDts: "+I+" ms, dtsCorrection: "+Math.round(o)+" ms, generate: "+P+" frames"),A=Math.floor(I),B=Math.floor(I+_)-A,null==(O=Re.getSilentFrame(this._audioMeta.originalCodec,this._audioMeta.channelCount))&&(r.a.w(this.TAG,"Unable to generate silent frame for "+this._audioMeta.originalCodec+" with "+this._audioMeta.channelCount+" channels, repeat last frame"),O=w),C=[];for(var M=0;M=1?T[T.length-1].duration:Math.floor(_);this._audioNextDts=A+B}-1===d&&(d=A),T.push({dts:A,pts:A,cts:0,unit:g.unit,size:g.unit.byteLength,duration:B,originalDts:k,flags:{isLeading:0,dependsOn:1,isDependedOn:0,hasRedundancy:0}}),D&&T.push.apply(T,C)}}if(0===T.length)return n.samples=[],void(n.length=0);h?f=new Uint8Array(p):((f=new Uint8Array(p))[0]=p>>>24&255,f[1]=p>>>16&255,f[2]=p>>>8&255,f[3]=255&p,f.set(Ae.types.mdat,4));for(L=0;L1&&(c-=(u=r.pop()).length),null!=this._videoStashedLastSample){var l=this._videoStashedLastSample;this._videoStashedLastSample=null,r.unshift(l),c+=l.length}null!=u&&(this._videoStashedLastSample=u);var f=r[0].dts-this._dtsBase;if(this._videoNextDts)s=f-this._videoNextDts;else if(this._videoSegmentInfoList.isEmpty())s=0;else{var p=this._videoSegmentInfoList.getLastSampleBefore(f);if(null!=p){var m=f-(p.originalDts+p.duration);m<=3&&(m=0),s=f-(p.dts+p.duration+m)}else s=0}for(var g=new Te.b,v=[],y=0;y=1?v[v.length-1].duration:Math.floor(this._videoMeta.refSampleDuration);if(S){var L=new Te.d(E,R,T,l.dts,!0);L.fileposition=l.fileposition,g.appendSyncPoint(L)}v.push({dts:E,pts:R,cts:A,units:l.units,size:l.length,isKeyframe:S,duration:T,originalDts:b,flags:{isLeading:0,dependsOn:S?2:1,isDependedOn:S?1:0,hasRedundancy:0,isNonSync:S?0:1}})}(h=new Uint8Array(c))[0]=c>>>24&255,h[1]=c>>>16&255,h[2]=c>>>8&255,h[3]=255&c,h.set(Ae.types.mdat,4);for(y=0;y0)this._demuxer.bindDataSource(this._ioctl),this._demuxer.timestampBase=this._mediaDataSource.segments[this._currentSegmentIndex].timestampBase,n=this._demuxer.parseChunks(e,t);else{var a=null;(a=A.probe(e)).match&&(this._setupFLVDemuxerRemuxer(a),n=this._demuxer.parseChunks(e,t)),a.match||a.needMoreData||(a=be.probe(e)).match&&(this._setupTSDemuxerRemuxer(a),n=this._demuxer.parseChunks(e,t)),a.match||a.needMoreData||(a=null,r.a.e(this.TAG,"Non MPEG-TS/FLV, Unsupported media type!"),Promise.resolve().then((function(){i._internalAbort()})),this._emitter.emit(ke.a.DEMUX_ERROR,m.a.FORMAT_UNSUPPORTED,"Non MPEG-TS/FLV, Unsupported media type!"))}return n},e.prototype._setupFLVDemuxerRemuxer=function(e){this._demuxer=new A(e,this._config),this._remuxer||(this._remuxer=new Le(this._config));var t=this._mediaDataSource;null==t.duration||isNaN(t.duration)||(this._demuxer.overridedDuration=t.duration),"boolean"==typeof t.hasAudio&&(this._demuxer.overridedHasAudio=t.hasAudio),"boolean"==typeof t.hasVideo&&(this._demuxer.overridedHasVideo=t.hasVideo),this._demuxer.timestampBase=t.segments[this._currentSegmentIndex].timestampBase,this._demuxer.onError=this._onDemuxException.bind(this),this._demuxer.onMediaInfo=this._onMediaInfo.bind(this),this._demuxer.onMetaDataArrived=this._onMetaDataArrived.bind(this),this._demuxer.onScriptDataArrived=this._onScriptDataArrived.bind(this),this._remuxer.bindDataSource(this._demuxer.bindDataSource(this._ioctl)),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},e.prototype._setupTSDemuxerRemuxer=function(e){var t=this._demuxer=new be(e,this._config);this._remuxer||(this._remuxer=new Le(this._config)),t.onError=this._onDemuxException.bind(this),t.onMediaInfo=this._onMediaInfo.bind(this),t.onMetaDataArrived=this._onMetaDataArrived.bind(this),t.onTimedID3Metadata=this._onTimedID3Metadata.bind(this),t.onSMPTE2038Metadata=this._onSMPTE2038Metadata.bind(this),t.onSCTE35Metadata=this._onSCTE35Metadata.bind(this),t.onPESPrivateDataDescriptor=this._onPESPrivateDataDescriptor.bind(this),t.onPESPrivateData=this._onPESPrivateData.bind(this),this._remuxer.bindDataSource(this._demuxer),this._demuxer.bindDataSource(this._ioctl),this._remuxer.onInitSegment=this._onRemuxerInitSegmentArrival.bind(this),this._remuxer.onMediaSegment=this._onRemuxerMediaSegmentArrival.bind(this)},e.prototype._onMediaInfo=function(e){var t=this;null==this._mediaInfo&&(this._mediaInfo=Object.assign({},e),this._mediaInfo.keyframesIndex=null,this._mediaInfo.segments=[],this._mediaInfo.segmentCount=this._mediaDataSource.segments.length,Object.setPrototypeOf(this._mediaInfo,o.a.prototype));var i=Object.assign({},e);Object.setPrototypeOf(i,o.a.prototype),this._mediaInfo.segments[this._currentSegmentIndex]=i,this._reportSegmentMediaInfo(this._currentSegmentIndex),null!=this._pendingSeekTime&&Promise.resolve().then((function(){var e=t._pendingSeekTime;t._pendingSeekTime=null,t.seek(e)}))},e.prototype._onMetaDataArrived=function(e){this._emitter.emit(ke.a.METADATA_ARRIVED,e)},e.prototype._onScriptDataArrived=function(e){this._emitter.emit(ke.a.SCRIPTDATA_ARRIVED,e)},e.prototype._onTimedID3Metadata=function(e){var t=this._remuxer.getTimestampBase();null!=t&&(null!=e.pts&&(e.pts-=t),null!=e.dts&&(e.dts-=t),this._emitter.emit(ke.a.TIMED_ID3_METADATA_ARRIVED,e))},e.prototype._onSMPTE2038Metadata=function(e){var t=this._remuxer.getTimestampBase();null!=t&&(null!=e.pts&&(e.pts-=t),null!=e.dts&&(e.dts-=t),null!=e.nearest_pts&&(e.nearest_pts-=t),this._emitter.emit(ke.a.SMPTE2038_METADATA_ARRIVED,e))},e.prototype._onSCTE35Metadata=function(e){var t=this._remuxer.getTimestampBase();null!=t&&(null!=e.pts&&(e.pts-=t),null!=e.nearest_pts&&(e.nearest_pts-=t),this._emitter.emit(ke.a.SCTE35_METADATA_ARRIVED,e))},e.prototype._onPESPrivateDataDescriptor=function(e){this._emitter.emit(ke.a.PES_PRIVATE_DATA_DESCRIPTOR,e)},e.prototype._onPESPrivateData=function(e){var t=this._remuxer.getTimestampBase();null!=t&&(null!=e.pts&&(e.pts-=t),null!=e.nearest_pts&&(e.nearest_pts-=t),null!=e.dts&&(e.dts-=t),this._emitter.emit(ke.a.PES_PRIVATE_DATA_ARRIVED,e))},e.prototype._onIOSeeked=function(){this._remuxer.insertDiscontinuity()},e.prototype._onIOComplete=function(e){var t=e+1;t0&&i[0].originalDts===n&&(n=i[0].pts),this._emitter.emit(ke.a.RECOMMEND_SEEKPOINT,n)}},e.prototype._enableStatisticsReporter=function(){null==this._statisticsReporter&&(this._statisticsReporter=self.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval))},e.prototype._disableStatisticsReporter=function(){this._statisticsReporter&&(self.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},e.prototype._reportSegmentMediaInfo=function(e){var t=this._mediaInfo.segments[e],i=Object.assign({},t);i.duration=this._mediaInfo.duration,i.segmentCount=this._mediaInfo.segmentCount,delete i.segments,delete i.keyframesIndex,this._emitter.emit(ke.a.MEDIA_INFO,i)},e.prototype._reportStatisticsInfo=function(){var e={};e.url=this._ioctl.currentURL,e.hasRedirect=this._ioctl.hasRedirect,e.hasRedirect&&(e.redirectedURL=this._ioctl.currentRedirectedURL),e.speed=this._ioctl.currentSpeed,e.loaderType=this._ioctl.loaderType,e.currentSegmentIndex=this._currentSegmentIndex,e.totalSegmentCount=this._mediaDataSource.segments.length,this._emitter.emit(ke.a.STATISTICS_INFO,e)},e}();t.a=De},function(e,t,i){"use strict";var n,a=i(0),r=function(){function e(){this._firstCheckpoint=0,this._lastCheckpoint=0,this._intervalBytes=0,this._totalBytes=0,this._lastSecondBytes=0,self.performance&&self.performance.now?this._now=self.performance.now.bind(self.performance):this._now=Date.now}return e.prototype.reset=function(){this._firstCheckpoint=this._lastCheckpoint=0,this._totalBytes=this._intervalBytes=0,this._lastSecondBytes=0},e.prototype.addBytes=function(e){0===this._firstCheckpoint?(this._firstCheckpoint=this._now(),this._lastCheckpoint=this._firstCheckpoint,this._intervalBytes+=e,this._totalBytes+=e):this._now()-this._lastCheckpoint<1e3?(this._intervalBytes+=e,this._totalBytes+=e):(this._lastSecondBytes=this._intervalBytes,this._intervalBytes=e,this._totalBytes+=e,this._lastCheckpoint=this._now())},Object.defineProperty(e.prototype,"currentKBps",{get:function(){this.addBytes(0);var e=(this._now()-this._lastCheckpoint)/1e3;return 0==e&&(e=1),this._intervalBytes/e/1024},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"lastSecondKBps",{get:function(){return this.addBytes(0),0!==this._lastSecondBytes?this._lastSecondBytes/1024:this._now()-this._lastCheckpoint>=500?this.currentKBps:0},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"averageKBps",{get:function(){var e=(this._now()-this._firstCheckpoint)/1e3;return this._totalBytes/e/1024},enumerable:!1,configurable:!0}),e}(),s=i(2),o=i(4),d=i(3),_=(n=function(e,t){return(n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var i in t)t.hasOwnProperty(i)&&(e[i]=t[i])})(e,t)},function(e,t){function i(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(i.prototype=t.prototype,new i)}),h=function(e){function t(t,i){var n=e.call(this,"fetch-stream-loader")||this;return n.TAG="FetchStreamLoader",n._seekHandler=t,n._config=i,n._needStash=!0,n._requestAbort=!1,n._abortController=null,n._contentLength=null,n._receivedLength=0,n}return _(t,e),t.isSupported=function(){try{var e=o.a.msedge&&o.a.version.minor>=15048,t=!o.a.msedge||e;return self.fetch&&self.ReadableStream&&t}catch(e){return!1}},t.prototype.destroy=function(){this.isWorking()&&this.abort(),e.prototype.destroy.call(this)},t.prototype.open=function(e,t){var i=this;this._dataSource=e,this._range=t;var n=e.url;this._config.reuseRedirectedURL&&null!=e.redirectedURL&&(n=e.redirectedURL);var a=this._seekHandler.getConfig(n,t),r=new self.Headers;if("object"==typeof a.headers){var o=a.headers;for(var _ in o)o.hasOwnProperty(_)&&r.append(_,o[_])}var h={method:"GET",headers:r,mode:"cors",cache:"default",referrerPolicy:"no-referrer-when-downgrade"};if("object"==typeof this._config.headers)for(var _ in this._config.headers)r.append(_,this._config.headers[_]);!1===e.cors&&(h.mode="same-origin"),e.withCredentials&&(h.credentials="include"),e.referrerPolicy&&(h.referrerPolicy=e.referrerPolicy),self.AbortController&&(this._abortController=new self.AbortController,h.signal=this._abortController.signal),this._status=s.c.kConnecting,self.fetch(a.url,h).then((function(e){if(i._requestAbort)return i._status=s.c.kIdle,void e.body.cancel();if(e.ok&&e.status>=200&&e.status<=299){if(e.url!==a.url&&i._onURLRedirect){var t=i._seekHandler.removeURLParameters(e.url);i._onURLRedirect(t)}var n=e.headers.get("Content-Length");return null!=n&&(i._contentLength=parseInt(n),0!==i._contentLength&&i._onContentLengthKnown&&i._onContentLengthKnown(i._contentLength)),i._pump.call(i,e.body.getReader())}if(i._status=s.c.kError,!i._onError)throw new d.d("FetchStreamLoader: Http code invalid, "+e.status+" "+e.statusText);i._onError(s.b.HTTP_STATUS_CODE_INVALID,{code:e.status,msg:e.statusText})})).catch((function(e){if(!i._abortController||!i._abortController.signal.aborted){if(i._status=s.c.kError,!i._onError)throw e;i._onError(s.b.EXCEPTION,{code:-1,msg:e.message})}}))},t.prototype.abort=function(){if(this._requestAbort=!0,(this._status!==s.c.kBuffering||!o.a.chrome)&&this._abortController)try{this._abortController.abort()}catch(e){}},t.prototype._pump=function(e){var t=this;return e.read().then((function(i){if(i.done)if(null!==t._contentLength&&t._receivedLength299)){if(this._status=s.c.kError,!this._onError)throw new d.d("MozChunkedLoader: Http code invalid, "+t.status+" "+t.statusText);this._onError(s.b.HTTP_STATUS_CODE_INVALID,{code:t.status,msg:t.statusText})}else this._status=s.c.kBuffering}},t.prototype._onProgress=function(e){if(this._status!==s.c.kError){null===this._contentLength&&null!==e.total&&0!==e.total&&(this._contentLength=e.total,this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength));var t=e.target.response,i=this._range.from+this._receivedLength;this._receivedLength+=t.byteLength,this._onDataArrival&&this._onDataArrival(t,i,this._receivedLength)}},t.prototype._onLoadEnd=function(e){!0!==this._requestAbort?this._status!==s.c.kError&&(this._status=s.c.kComplete,this._onComplete&&this._onComplete(this._range.from,this._range.from+this._receivedLength-1)):this._requestAbort=!1},t.prototype._onXhrError=function(e){this._status=s.c.kError;var t=0,i=null;if(this._contentLength&&e.loaded=this._contentLength&&(i=this._range.from+this._contentLength-1),this._currentRequestRange={from:t,to:i},this._internalOpen(this._dataSource,this._currentRequestRange)},t.prototype._internalOpen=function(e,t){this._lastTimeLoaded=0;var i=e.url;this._config.reuseRedirectedURL&&(null!=this._currentRedirectedURL?i=this._currentRedirectedURL:null!=e.redirectedURL&&(i=e.redirectedURL));var n=this._seekHandler.getConfig(i,t);this._currentRequestURL=n.url;var a=this._xhr=new XMLHttpRequest;if(a.open("GET",n.url,!0),a.responseType="arraybuffer",a.onreadystatechange=this._onReadyStateChange.bind(this),a.onprogress=this._onProgress.bind(this),a.onload=this._onLoad.bind(this),a.onerror=this._onXhrError.bind(this),e.withCredentials&&(a.withCredentials=!0),"object"==typeof n.headers){var r=n.headers;for(var s in r)r.hasOwnProperty(s)&&a.setRequestHeader(s,r[s])}if("object"==typeof this._config.headers){r=this._config.headers;for(var s in r)r.hasOwnProperty(s)&&a.setRequestHeader(s,r[s])}a.send()},t.prototype.abort=function(){this._requestAbort=!0,this._internalAbort(),this._status=s.c.kComplete},t.prototype._internalAbort=function(){this._xhr&&(this._xhr.onreadystatechange=null,this._xhr.onprogress=null,this._xhr.onload=null,this._xhr.onerror=null,this._xhr.abort(),this._xhr=null)},t.prototype._onReadyStateChange=function(e){var t=e.target;if(2===t.readyState){if(null!=t.responseURL){var i=this._seekHandler.removeURLParameters(t.responseURL);t.responseURL!==this._currentRequestURL&&i!==this._currentRedirectedURL&&(this._currentRedirectedURL=i,this._onURLRedirect&&this._onURLRedirect(i))}if(t.status>=200&&t.status<=299){if(this._waitForTotalLength)return;this._status=s.c.kBuffering}else{if(this._status=s.c.kError,!this._onError)throw new d.d("RangeLoader: Http code invalid, "+t.status+" "+t.statusText);this._onError(s.b.HTTP_STATUS_CODE_INVALID,{code:t.status,msg:t.statusText})}}},t.prototype._onProgress=function(e){if(this._status!==s.c.kError){if(null===this._contentLength){var t=!1;if(this._waitForTotalLength){this._waitForTotalLength=!1,this._totalLengthReceived=!0,t=!0;var i=e.total;this._internalAbort(),null!=i&0!==i&&(this._totalLength=i)}if(-1===this._range.to?this._contentLength=this._totalLength-this._range.from:this._contentLength=this._range.to-this._range.from+1,t)return void this._openSubRange();this._onContentLengthKnown&&this._onContentLengthKnown(this._contentLength)}var n=e.loaded-this._lastTimeLoaded;this._lastTimeLoaded=e.loaded,this._speedSampler.addBytes(n)}},t.prototype._normalizeSpeed=function(e){var t=this._chunkSizeKBList,i=t.length-1,n=0,a=0,r=i;if(e=t[n]&&e=3&&(t=this._speedSampler.currentKBps)),0!==t){var i=this._normalizeSpeed(t);this._currentSpeedNormalized!==i&&(this._currentSpeedNormalized=i,this._currentChunkSizeKB=i)}var n=e.target.response,a=this._range.from+this._receivedLength;this._receivedLength+=n.byteLength;var r=!1;null!=this._contentLength&&this._receivedLength0&&this._receivedLength0)for(var r=i.split("&"),s=0;s0;o[0]!==this._startName&&o[0]!==this._endName&&(d&&(a+="&"),a+=r[s])}return 0===a.length?t:t+"?"+a},e}(),y=function(){function e(e,t,i){this.TAG="IOController",this._config=t,this._extraData=i,this._stashInitialSize=65536,null!=t.stashInitialSize&&t.stashInitialSize>0&&(this._stashInitialSize=t.stashInitialSize),this._stashUsed=0,this._stashSize=this._stashInitialSize,this._bufferSize=3145728,this._stashBuffer=new ArrayBuffer(this._bufferSize),this._stashByteStart=0,this._enableStash=!0,!1===t.enableStashBuffer&&(this._enableStash=!1),this._loader=null,this._loaderClass=null,this._seekHandler=null,this._dataSource=e,this._isWebSocketURL=/wss?:\/\/(.+?)/.test(e.url),this._refTotalLength=e.filesize?e.filesize:null,this._totalLength=this._refTotalLength,this._fullRequestFlag=!1,this._currentRange=null,this._redirectedURL=null,this._speedNormalized=0,this._speedSampler=new r,this._speedNormalizeList=[32,64,96,128,192,256,384,512,768,1024,1536,2048,3072,4096],this._isEarlyEofReconnecting=!1,this._paused=!1,this._resumeFrom=0,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._selectSeekHandler(),this._selectLoader(),this._createLoader()}return e.prototype.destroy=function(){this._loader.isWorking()&&this._loader.abort(),this._loader.destroy(),this._loader=null,this._loaderClass=null,this._dataSource=null,this._stashBuffer=null,this._stashUsed=this._stashSize=this._bufferSize=this._stashByteStart=0,this._currentRange=null,this._speedSampler=null,this._isEarlyEofReconnecting=!1,this._onDataArrival=null,this._onSeeked=null,this._onError=null,this._onComplete=null,this._onRedirect=null,this._onRecoveredEarlyEof=null,this._extraData=null},e.prototype.isWorking=function(){return this._loader&&this._loader.isWorking()&&!this._paused},e.prototype.isPaused=function(){return this._paused},Object.defineProperty(e.prototype,"status",{get:function(){return this._loader.status},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"extraData",{get:function(){return this._extraData},set:function(e){this._extraData=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onDataArrival",{get:function(){return this._onDataArrival},set:function(e){this._onDataArrival=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onSeeked",{get:function(){return this._onSeeked},set:function(e){this._onSeeked=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onError",{get:function(){return this._onError},set:function(e){this._onError=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onComplete",{get:function(){return this._onComplete},set:function(e){this._onComplete=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onRedirect",{get:function(){return this._onRedirect},set:function(e){this._onRedirect=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"onRecoveredEarlyEof",{get:function(){return this._onRecoveredEarlyEof},set:function(e){this._onRecoveredEarlyEof=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentURL",{get:function(){return this._dataSource.url},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"hasRedirect",{get:function(){return null!=this._redirectedURL||null!=this._dataSource.redirectedURL},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentRedirectedURL",{get:function(){return this._redirectedURL||this._dataSource.redirectedURL},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentSpeed",{get:function(){return this._loaderClass===f?this._loader.currentSpeed:this._speedSampler.lastSecondKBps},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"loaderType",{get:function(){return this._loader.type},enumerable:!1,configurable:!0}),e.prototype._selectSeekHandler=function(){var e=this._config;if("range"===e.seekType)this._seekHandler=new g(this._config.rangeLoadZeroStart);else if("param"===e.seekType){var t=e.seekParamStart||"bstart",i=e.seekParamEnd||"bend";this._seekHandler=new v(t,i)}else{if("custom"!==e.seekType)throw new d.b("Invalid seekType in config: "+e.seekType);if("function"!=typeof e.customSeekHandler)throw new d.b("Custom seekType specified in config but invalid customSeekHandler!");this._seekHandler=new e.customSeekHandler}},e.prototype._selectLoader=function(){if(null!=this._config.customLoader)this._loaderClass=this._config.customLoader;else if(this._isWebSocketURL)this._loaderClass=m;else if(h.isSupported())this._loaderClass=h;else if(u.isSupported())this._loaderClass=u;else{if(!f.isSupported())throw new d.d("Your browser doesn't support xhr with arraybuffer responseType!");this._loaderClass=f}},e.prototype._createLoader=function(){this._loader=new this._loaderClass(this._seekHandler,this._config),!1===this._loader.needStashBuffer&&(this._enableStash=!1),this._loader.onContentLengthKnown=this._onContentLengthKnown.bind(this),this._loader.onURLRedirect=this._onURLRedirect.bind(this),this._loader.onDataArrival=this._onLoaderChunkArrival.bind(this),this._loader.onComplete=this._onLoaderComplete.bind(this),this._loader.onError=this._onLoaderError.bind(this)},e.prototype.open=function(e){this._currentRange={from:0,to:-1},e&&(this._currentRange.from=e),this._speedSampler.reset(),e||(this._fullRequestFlag=!0),this._loader.open(this._dataSource,Object.assign({},this._currentRange))},e.prototype.abort=function(){this._loader.abort(),this._paused&&(this._paused=!1,this._resumeFrom=0)},e.prototype.pause=function(){this.isWorking()&&(this._loader.abort(),0!==this._stashUsed?(this._resumeFrom=this._stashByteStart,this._currentRange.to=this._stashByteStart-1):this._resumeFrom=this._currentRange.to+1,this._stashUsed=0,this._stashByteStart=0,this._paused=!0)},e.prototype.resume=function(){if(this._paused){this._paused=!1;var e=this._resumeFrom;this._resumeFrom=0,this._internalSeek(e,!0)}},e.prototype.seek=function(e){this._paused=!1,this._stashUsed=0,this._stashByteStart=0,this._internalSeek(e,!0)},e.prototype._internalSeek=function(e,t){this._loader.isWorking()&&this._loader.abort(),this._flushStashBuffer(t),this._loader.destroy(),this._loader=null;var i={from:e,to:-1};this._currentRange={from:i.from,to:-1},this._speedSampler.reset(),this._stashSize=this._stashInitialSize,this._createLoader(),this._loader.open(this._dataSource,i),this._onSeeked&&this._onSeeked()},e.prototype.updateUrl=function(e){if(!e||"string"!=typeof e||0===e.length)throw new d.b("Url must be a non-empty string!");this._dataSource.url=e},e.prototype._expandBuffer=function(e){for(var t=this._stashSize;t+10485760){var n=new Uint8Array(this._stashBuffer,0,this._stashUsed);new Uint8Array(i,0,t).set(n,0)}this._stashBuffer=i,this._bufferSize=t}},e.prototype._normalizeSpeed=function(e){var t=this._speedNormalizeList,i=t.length-1,n=0,a=0,r=i;if(e=t[n]&&e=512&&e<=1024?Math.floor(1.5*e):2*e)>8192&&(t=8192);var i=1024*t+1048576;this._bufferSize0){var r=this._stashBuffer.slice(0,this._stashUsed);if((_=this._dispatchChunks(r,this._stashByteStart))0){h=new Uint8Array(r,_);o.set(h,0),this._stashUsed=h.byteLength,this._stashByteStart+=_}}else this._stashUsed=0,this._stashByteStart+=_;this._stashUsed+e.byteLength>this._bufferSize&&(this._expandBuffer(this._stashUsed+e.byteLength),o=new Uint8Array(this._stashBuffer,0,this._bufferSize)),o.set(new Uint8Array(e),this._stashUsed),this._stashUsed+=e.byteLength}else{if((_=this._dispatchChunks(e,t))this._bufferSize&&(this._expandBuffer(s),o=new Uint8Array(this._stashBuffer,0,this._bufferSize)),o.set(new Uint8Array(e,_),0),this._stashUsed+=s,this._stashByteStart=t+_}}else if(0===this._stashUsed){var s;if((_=this._dispatchChunks(e,t))this._bufferSize&&this._expandBuffer(s),(o=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(e,_),0),this._stashUsed+=s,this._stashByteStart=t+_}else{var o,_;if(this._stashUsed+e.byteLength>this._bufferSize&&this._expandBuffer(this._stashUsed+e.byteLength),(o=new Uint8Array(this._stashBuffer,0,this._bufferSize)).set(new Uint8Array(e),this._stashUsed),this._stashUsed+=e.byteLength,(_=this._dispatchChunks(this._stashBuffer.slice(0,this._stashUsed),this._stashByteStart))0){var h=new Uint8Array(this._stashBuffer,_);o.set(h,0)}this._stashUsed-=_,this._stashByteStart+=_}}},e.prototype._flushStashBuffer=function(e){if(this._stashUsed>0){var t=this._stashBuffer.slice(0,this._stashUsed),i=this._dispatchChunks(t,this._stashByteStart),n=t.byteLength-i;if(i0){var r=new Uint8Array(this._stashBuffer,0,this._bufferSize),s=new Uint8Array(t,i);r.set(s,0),this._stashUsed=s.byteLength,this._stashByteStart+=i}return 0}a.a.w(this.TAG,n+" bytes unconsumed data remain when flush buffer, dropped")}return this._stashUsed=0,this._stashByteStart=0,n}return 0},e.prototype._onLoaderComplete=function(e,t){this._flushStashBuffer(!0),this._onComplete&&this._onComplete(this._extraData)},e.prototype._onLoaderError=function(e,t){switch(a.a.e(this.TAG,"Loader error, code = "+t.code+", msg = "+t.msg),this._flushStashBuffer(!1),this._isEarlyEofReconnecting&&(this._isEarlyEofReconnecting=!1,e=s.b.UNRECOVERABLE_EARLY_EOF),e){case s.b.EARLY_EOF:if(!this._config.isLive&&this._totalLength){var i=this._currentRange.to+1;return void(i0}),!1)}e.exports=function(e,t){t=t||{};var a={main:i.m},o=t.all?{main:Object.keys(a.main)}:function(e,t){for(var i={main:[t]},n={main:[]},a={main:{}};s(i);)for(var o=Object.keys(i),d=0;d1)for(var i=1;i0&&(n+=";codecs="+i.codec);var a=!1;if(c.a.v(this.TAG,"Received Initialization Segment, mimeType: "+n),this._lastInitSegments[i.type]=i,n!==this._mimeTypes[i.type]){if(this._mimeTypes[i.type])c.a.v(this.TAG,"Notice: "+i.type+" mimeType changed, origin: "+this._mimeTypes[i.type]+", target: "+n);else{a=!0;try{var r=this._sourceBuffers[i.type]=this._mediaSource.addSourceBuffer(n);r.addEventListener("error",this.e.onSourceBufferError),r.addEventListener("updateend",this.e.onSourceBufferUpdateEnd)}catch(e){return c.a.e(this.TAG,e.message),void this._emitter.emit(S.ERROR,{code:e.code,msg:e.message})}}this._mimeTypes[i.type]=n}t||this._pendingSegments[i.type].push(i),a||this._sourceBuffers[i.type]&&!this._sourceBuffers[i.type].updating&&this._doAppendSegments(),u.a.safari&&"audio/mpeg"===i.container&&i.mediaDuration>0&&(this._requireSetMediaDuration=!0,this._pendingMediaDuration=i.mediaDuration/1e3,this._updateMediaSourceDuration())},e.prototype.appendMediaSegment=function(e){var t=e;this._pendingSegments[t.type].push(t),this._config.autoCleanupSourceBuffer&&this._needCleanupSourceBuffer()&&this._doCleanupSourceBuffer();var i=this._sourceBuffers[t.type];!i||i.updating||this._hasPendingRemoveRanges()||this._doAppendSegments()},e.prototype.seek=function(e){for(var t in this._sourceBuffers)if(this._sourceBuffers[t]){var i=this._sourceBuffers[t];if("open"===this._mediaSource.readyState)try{i.abort()}catch(e){c.a.e(this.TAG,e.message)}this._idrList.clear();var n=this._pendingSegments[t];if(n.splice(0,n.length),"closed"!==this._mediaSource.readyState){for(var a=0;a=1&&e-n.start(0)>=this._config.autoCleanupMaxBackwardDuration)return!0}}return!1},e.prototype._doCleanupSourceBuffer=function(){var e=this._mediaElement.currentTime;for(var t in this._sourceBuffers){var i=this._sourceBuffers[t];if(i){for(var n=i.buffered,a=!1,r=0;r=this._config.autoCleanupMaxBackwardDuration){a=!0;var d=e-this._config.autoCleanupMinBackwardDuration;this._pendingRemoveRanges[t].push({start:s,end:d})}}else o0&&(isNaN(t)||i>t)&&(c.a.v(this.TAG,"Update MediaSource duration from "+t+" to "+i),this._mediaSource.duration=i),this._requireSetMediaDuration=!1,this._pendingMediaDuration=0}},e.prototype._doRemoveRanges=function(){for(var e in this._pendingRemoveRanges)if(this._sourceBuffers[e]&&!this._sourceBuffers[e].updating)for(var t=this._sourceBuffers[e],i=this._pendingRemoveRanges[e];i.length&&!t.updating;){var n=i.shift();t.remove(n.start,n.end)}},e.prototype._doAppendSegments=function(){var e=this._pendingSegments;for(var t in e)if(this._sourceBuffers[t]&&!this._sourceBuffers[t].updating&&e[t].length>0){var i=e[t].shift();if(i.timestampOffset){var n=this._sourceBuffers[t].timestampOffset,a=i.timestampOffset/1e3;Math.abs(n-a)>.1&&(c.a.v(this.TAG,"Update MPEG audio timestampOffset from "+n+" to "+a),this._sourceBuffers[t].timestampOffset=a),delete i.timestampOffset}if(!i.data||0===i.data.byteLength)continue;try{this._sourceBuffers[t].appendBuffer(i.data),this._isBufferFull=!1,"video"===t&&i.hasOwnProperty("info")&&this._idrList.appendArray(i.info.syncPoints)}catch(e){this._pendingSegments[t].unshift(i),22===e.code?(this._isBufferFull||this._emitter.emit(S.BUFFER_FULL),this._isBufferFull=!0):(c.a.e(this.TAG,e.message),this._emitter.emit(S.ERROR,{code:e.code,msg:e.message}))}}},e.prototype._onSourceOpen=function(){if(c.a.v(this.TAG,"MediaSource onSourceOpen"),this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._pendingSourceBufferInit.length>0)for(var e=this._pendingSourceBufferInit;e.length;){var t=e.shift();this.appendInitSegment(t,!0)}this._hasPendingSegments()&&this._doAppendSegments(),this._emitter.emit(S.SOURCE_OPEN)},e.prototype._onSourceEnded=function(){c.a.v(this.TAG,"MediaSource onSourceEnded")},e.prototype._onSourceClose=function(){c.a.v(this.TAG,"MediaSource onSourceClose"),this._mediaSource&&null!=this.e&&(this._mediaSource.removeEventListener("sourceopen",this.e.onSourceOpen),this._mediaSource.removeEventListener("sourceended",this.e.onSourceEnded),this._mediaSource.removeEventListener("sourceclose",this.e.onSourceClose))},e.prototype._hasPendingSegments=function(){var e=this._pendingSegments;return e.video.length>0||e.audio.length>0},e.prototype._hasPendingRemoveRanges=function(){var e=this._pendingRemoveRanges;return e.video.length>0||e.audio.length>0},e.prototype._onSourceBufferUpdateEnd=function(){this._requireSetMediaDuration?this._updateMediaSourceDuration():this._hasPendingRemoveRanges()?this._doRemoveRanges():this._hasPendingSegments()?this._doAppendSegments():this._hasPendingEos&&this.endOfStream(),this._emitter.emit(S.UPDATE_END)},e.prototype._onSourceBufferError=function(e){c.a.e(this.TAG,"SourceBuffer Error: "+e)},e}(),T=i(5),L={NETWORK_ERROR:"NetworkError",MEDIA_ERROR:"MediaError",OTHER_ERROR:"OtherError"},w={NETWORK_EXCEPTION:d.b.EXCEPTION,NETWORK_STATUS_CODE_INVALID:d.b.HTTP_STATUS_CODE_INVALID,NETWORK_TIMEOUT:d.b.CONNECTING_TIMEOUT,NETWORK_UNRECOVERABLE_EARLY_EOF:d.b.UNRECOVERABLE_EARLY_EOF,MEDIA_MSE_ERROR:"MediaMSEError",MEDIA_FORMAT_ERROR:T.a.FORMAT_ERROR,MEDIA_FORMAT_UNSUPPORTED:T.a.FORMAT_UNSUPPORTED,MEDIA_CODEC_UNSUPPORTED:T.a.CODEC_UNSUPPORTED},k=function(){function e(e,t){this.TAG="MSEPlayer",this._type="MSEPlayer",this._emitter=new h.a,this._config=s(),"object"==typeof t&&Object.assign(this._config,t);var i=e.type.toLowerCase();if("mse"!==i&&"mpegts"!==i&&"m2ts"!==i&&"flv"!==i)throw new A.b("MSEPlayer requires an mpegts/m2ts/flv MediaDataSource input!");!0===e.isLive&&(this._config.isLive=!0),this.e={onvLoadedMetadata:this._onvLoadedMetadata.bind(this),onvSeeking:this._onvSeeking.bind(this),onvCanPlay:this._onvCanPlay.bind(this),onvStalled:this._onvStalled.bind(this),onvProgress:this._onvProgress.bind(this)},self.performance&&self.performance.now?this._now=self.performance.now.bind(self.performance):this._now=Date.now,this._pendingSeekTime=null,this._requestSetTime=!1,this._seekpointRecord=null,this._progressChecker=null,this._mediaDataSource=e,this._mediaElement=null,this._msectl=null,this._transmuxer=null,this._mseSourceOpened=!1,this._hasPendingLoad=!1,this._receivedCanPlay=!1,this._mediaInfo=null,this._statisticsInfo=null;var n=u.a.chrome&&(u.a.version.major<50||50===u.a.version.major&&u.a.version.build<2661);this._alwaysSeekKeyframe=!!(n||u.a.msedge||u.a.msie),this._alwaysSeekKeyframe&&(this._config.accurateSeek=!1)}return e.prototype.destroy=function(){null!=this._progressChecker&&(window.clearInterval(this._progressChecker),this._progressChecker=null),this._transmuxer&&this.unload(),this._mediaElement&&this.detachMediaElement(),this.e=null,this._mediaDataSource=null,this._emitter.removeAllListeners(),this._emitter=null},e.prototype.on=function(e,t){var i=this;e===l.MEDIA_INFO?null!=this._mediaInfo&&Promise.resolve().then((function(){i._emitter.emit(l.MEDIA_INFO,i.mediaInfo)})):e===l.STATISTICS_INFO&&null!=this._statisticsInfo&&Promise.resolve().then((function(){i._emitter.emit(l.STATISTICS_INFO,i.statisticsInfo)})),this._emitter.addListener(e,t)},e.prototype.off=function(e,t){this._emitter.removeListener(e,t)},e.prototype.attachMediaElement=function(e){var t=this;if(this._mediaElement=e,e.addEventListener("loadedmetadata",this.e.onvLoadedMetadata),e.addEventListener("seeking",this.e.onvSeeking),e.addEventListener("canplay",this.e.onvCanPlay),e.addEventListener("stalled",this.e.onvStalled),e.addEventListener("progress",this.e.onvProgress),this._msectl=new R(this._config),this._msectl.on(S.UPDATE_END,this._onmseUpdateEnd.bind(this)),this._msectl.on(S.BUFFER_FULL,this._onmseBufferFull.bind(this)),this._msectl.on(S.SOURCE_OPEN,(function(){t._mseSourceOpened=!0,t._hasPendingLoad&&(t._hasPendingLoad=!1,t.load())})),this._msectl.on(S.ERROR,(function(e){t._emitter.emit(l.ERROR,L.MEDIA_ERROR,w.MEDIA_MSE_ERROR,e)})),this._msectl.attachMediaElement(e),null!=this._pendingSeekTime)try{e.currentTime=this._pendingSeekTime,this._pendingSeekTime=null}catch(e){}},e.prototype.detachMediaElement=function(){this._mediaElement&&(this._msectl.detachMediaElement(),this._mediaElement.removeEventListener("loadedmetadata",this.e.onvLoadedMetadata),this._mediaElement.removeEventListener("seeking",this.e.onvSeeking),this._mediaElement.removeEventListener("canplay",this.e.onvCanPlay),this._mediaElement.removeEventListener("stalled",this.e.onvStalled),this._mediaElement.removeEventListener("progress",this.e.onvProgress),this._mediaElement=null),this._msectl&&(this._msectl.destroy(),this._msectl=null)},e.prototype.load=function(){var e=this;if(!this._mediaElement)throw new A.a("HTMLMediaElement must be attached before load()!");if(this._transmuxer)throw new A.a("MSEPlayer.load() has been called, please call unload() first!");this._hasPendingLoad||(this._config.deferLoadAfterSourceOpen&&!1===this._mseSourceOpened?this._hasPendingLoad=!0:(this._mediaElement.readyState>0&&(this._requestSetTime=!0,this._mediaElement.currentTime=0),this._transmuxer=new b(this._mediaDataSource,this._config),this._transmuxer.on(v.a.INIT_SEGMENT,(function(t,i){e._msectl.appendInitSegment(i)})),this._transmuxer.on(v.a.MEDIA_SEGMENT,(function(t,i){if(e._msectl.appendMediaSegment(i),e._config.lazyLoad&&!e._config.isLive){var n=e._mediaElement.currentTime;i.info.endDts>=1e3*(n+e._config.lazyLoadMaxDuration)&&null==e._progressChecker&&(c.a.v(e.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),e._suspendTransmuxer())}})),this._transmuxer.on(v.a.LOADING_COMPLETE,(function(){e._msectl.endOfStream(),e._emitter.emit(l.LOADING_COMPLETE)})),this._transmuxer.on(v.a.RECOVERED_EARLY_EOF,(function(){e._emitter.emit(l.RECOVERED_EARLY_EOF)})),this._transmuxer.on(v.a.IO_ERROR,(function(t,i){e._emitter.emit(l.ERROR,L.NETWORK_ERROR,t,i)})),this._transmuxer.on(v.a.DEMUX_ERROR,(function(t,i){e._emitter.emit(l.ERROR,L.MEDIA_ERROR,t,{code:-1,msg:i})})),this._transmuxer.on(v.a.MEDIA_INFO,(function(t){e._mediaInfo=t,e._emitter.emit(l.MEDIA_INFO,Object.assign({},t))})),this._transmuxer.on(v.a.METADATA_ARRIVED,(function(t){e._emitter.emit(l.METADATA_ARRIVED,t)})),this._transmuxer.on(v.a.SCRIPTDATA_ARRIVED,(function(t){e._emitter.emit(l.SCRIPTDATA_ARRIVED,t)})),this._transmuxer.on(v.a.TIMED_ID3_METADATA_ARRIVED,(function(t){e._emitter.emit(l.TIMED_ID3_METADATA_ARRIVED,t)})),this._transmuxer.on(v.a.SMPTE2038_METADATA_ARRIVED,(function(t){e._emitter.emit(l.SMPTE2038_METADATA_ARRIVED,t)})),this._transmuxer.on(v.a.SCTE35_METADATA_ARRIVED,(function(t){e._emitter.emit(l.SCTE35_METADATA_ARRIVED,t)})),this._transmuxer.on(v.a.PES_PRIVATE_DATA_DESCRIPTOR,(function(t){e._emitter.emit(l.PES_PRIVATE_DATA_DESCRIPTOR,t)})),this._transmuxer.on(v.a.PES_PRIVATE_DATA_ARRIVED,(function(t){e._emitter.emit(l.PES_PRIVATE_DATA_ARRIVED,t)})),this._transmuxer.on(v.a.STATISTICS_INFO,(function(t){e._statisticsInfo=e._fillStatisticsInfo(t),e._emitter.emit(l.STATISTICS_INFO,Object.assign({},e._statisticsInfo))})),this._transmuxer.on(v.a.RECOMMEND_SEEKPOINT,(function(t){e._mediaElement&&!e._config.accurateSeek&&(e._requestSetTime=!0,e._mediaElement.currentTime=t/1e3)})),this._transmuxer.open()))},e.prototype.unload=function(){this._mediaElement&&this._mediaElement.pause(),this._msectl&&this._msectl.seek(0),this._transmuxer&&(this._transmuxer.close(),this._transmuxer.destroy(),this._transmuxer=null)},e.prototype.play=function(){return this._mediaElement.play()},e.prototype.pause=function(){this._mediaElement.pause()},Object.defineProperty(e.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"buffered",{get:function(){return this._mediaElement.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"duration",{get:function(){return this._mediaElement.duration},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"volume",{get:function(){return this._mediaElement.volume},set:function(e){this._mediaElement.volume=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"muted",{get:function(){return this._mediaElement.muted},set:function(e){this._mediaElement.muted=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentTime",{get:function(){return this._mediaElement?this._mediaElement.currentTime:0},set:function(e){this._mediaElement?this._internalSeek(e):this._pendingSeekTime=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mediaInfo",{get:function(){return Object.assign({},this._mediaInfo)},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"statisticsInfo",{get:function(){return null==this._statisticsInfo&&(this._statisticsInfo={}),this._statisticsInfo=this._fillStatisticsInfo(this._statisticsInfo),Object.assign({},this._statisticsInfo)},enumerable:!1,configurable:!0}),e.prototype._fillStatisticsInfo=function(e){if(e.playerType=this._type,!(this._mediaElement instanceof HTMLVideoElement))return e;var t=!0,i=0,n=0;if(this._mediaElement.getVideoPlaybackQuality){var a=this._mediaElement.getVideoPlaybackQuality();i=a.totalVideoFrames,n=a.droppedVideoFrames}else null!=this._mediaElement.webkitDecodedFrameCount?(i=this._mediaElement.webkitDecodedFrameCount,n=this._mediaElement.webkitDroppedFrameCount):t=!1;return t&&(e.decodedFrames=i,e.droppedFrames=n),e},e.prototype._onmseUpdateEnd=function(){var e=this._mediaElement.buffered,t=this._mediaElement.currentTime;if(this._config.isLive&&this._config.liveBufferLatencyChasing&&e.length>0&&!this._mediaElement.paused){var i=e.end(e.length-1);if(i>this._config.liveBufferLatencyMaxLatency&&i-t>this._config.liveBufferLatencyMaxLatency){var n=i-this._config.liveBufferLatencyMinRemain;this.currentTime=n}}if(this._config.lazyLoad&&!this._config.isLive){for(var a=0,r=0;r=t+this._config.lazyLoadMaxDuration&&null==this._progressChecker&&(c.a.v(this.TAG,"Maximum buffering duration exceeded, suspend transmuxing task"),this._suspendTransmuxer())}},e.prototype._onmseBufferFull=function(){c.a.v(this.TAG,"MSE SourceBuffer is full, suspend transmuxing task"),null==this._progressChecker&&this._suspendTransmuxer()},e.prototype._suspendTransmuxer=function(){this._transmuxer&&(this._transmuxer.pause(),null==this._progressChecker&&(this._progressChecker=window.setInterval(this._checkProgressAndResume.bind(this),1e3)))},e.prototype._checkProgressAndResume=function(){for(var e=this._mediaElement.currentTime,t=this._mediaElement.buffered,i=!1,n=0;n=a&&e=r-this._config.lazyLoadRecoverDuration&&(i=!0);break}}i&&(window.clearInterval(this._progressChecker),this._progressChecker=null,i&&(c.a.v(this.TAG,"Continue loading from paused position"),this._transmuxer.resume()))},e.prototype._isTimepointBuffered=function(e){for(var t=this._mediaElement.buffered,i=0;i=n&&e0){var a=this._mediaElement.buffered.start(0);(a<1&&e0&&t.currentTime0){var n=i.start(0);if(n<1&&t0&&(this._mediaElement.currentTime=0),this._mediaElement.preload="auto",this._mediaElement.load(),this._statisticsReporter=window.setInterval(this._reportStatisticsInfo.bind(this),this._config.statisticsInfoReportInterval)},e.prototype.unload=function(){this._mediaElement&&(this._mediaElement.src="",this._mediaElement.removeAttribute("src")),null!=this._statisticsReporter&&(window.clearInterval(this._statisticsReporter),this._statisticsReporter=null)},e.prototype.play=function(){return this._mediaElement.play()},e.prototype.pause=function(){this._mediaElement.pause()},Object.defineProperty(e.prototype,"type",{get:function(){return this._type},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"buffered",{get:function(){return this._mediaElement.buffered},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"duration",{get:function(){return this._mediaElement.duration},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"volume",{get:function(){return this._mediaElement.volume},set:function(e){this._mediaElement.volume=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"muted",{get:function(){return this._mediaElement.muted},set:function(e){this._mediaElement.muted=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"currentTime",{get:function(){return this._mediaElement?this._mediaElement.currentTime:0},set:function(e){this._mediaElement?this._mediaElement.currentTime=e:this._pendingSeekTime=e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"mediaInfo",{get:function(){var e={mimeType:(this._mediaElement instanceof HTMLAudioElement?"audio/":"video/")+this._mediaDataSource.type};return this._mediaElement&&(e.duration=Math.floor(1e3*this._mediaElement.duration),this._mediaElement instanceof HTMLVideoElement&&(e.width=this._mediaElement.videoWidth,e.height=this._mediaElement.videoHeight)),e},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"statisticsInfo",{get:function(){var e={playerType:this._type,url:this._mediaDataSource.url};if(!(this._mediaElement instanceof HTMLVideoElement))return e;var t=!0,i=0,n=0;if(this._mediaElement.getVideoPlaybackQuality){var a=this._mediaElement.getVideoPlaybackQuality();i=a.totalVideoFrames,n=a.droppedVideoFrames}else null!=this._mediaElement.webkitDecodedFrameCount?(i=this._mediaElement.webkitDecodedFrameCount,n=this._mediaElement.webkitDroppedFrameCount):t=!1;return t&&(e.decodedFrames=i,e.droppedFrames=n),e},enumerable:!1,configurable:!0}),e.prototype._onvLoadedMetadata=function(e){null!=this._pendingSeekTime&&(this._mediaElement.currentTime=this._pendingSeekTime,this._pendingSeekTime=null),this._emitter.emit(l.MEDIA_INFO,this.mediaInfo)},e.prototype._reportStatisticsInfo=function(){this._emitter.emit(l.STATISTICS_INFO,this.statisticsInfo)},e}();n.a.install();var C={createPlayer:function(e,t){var i=e;if(null==i||"object"!=typeof i)throw new A.b("MediaDataSource must be an javascript object!");if(!i.hasOwnProperty("type"))throw new A.b("MediaDataSource must has type field to indicate video file type!");switch(i.type){case"mse":case"mpegts":case"m2ts":case"flv":return new k(i,t);default:return new D(i,t)}},isSupported:function(){return o.supportMSEH264Playback()},getFeatureList:function(){return o.getFeatureList()}};C.BaseLoader=d.a,C.LoaderStatus=d.c,C.LoaderErrors=d.b,C.Events=l,C.ErrorTypes=L,C.ErrorDetails=w,C.MSEPlayer=k,C.NativePlayer=D,C.LoggingControl=m.a,Object.defineProperty(C,"version",{enumerable:!0,get:function(){return"1.7.3"}});t.default=C}])})); -//# sourceMappingURL=mpegts.js.map \ No newline at end of file diff --git a/funasr/html/static/pcm.js b/funasr/html/static/pcm.js deleted file mode 100644 index 51c1efe..0000000 --- a/funasr/html/static/pcm.js +++ /dev/null @@ -1,96 +0,0 @@ -/* -pcm编码器+编码引擎 -https://github.com/xiangyuecn/Recorder - -编码原理:本编码器输出的pcm格式数据其实就是Recorder中的buffers原始数据(经过了重新采样),16位时为LE小端模式(Little Endian),并未经过任何编码处理 - -编码的代码和wav.js区别不大,pcm加上一个44字节wav头即成wav文件;所以要播放pcm就很简单了,直接转成wav文件来播放,已提供转换函数 Recorder.pcm2wav -*/ -(function(){ -"use strict"; - -Recorder.prototype.enc_pcm={ - stable:true - ,testmsg:"pcm为未封装的原始音频数据,pcm数据文件无法直接播放;支持位数8位、16位(填在比特率里面),采样率取值无限制" -}; -Recorder.prototype.pcm=function(res,True,False){ - var This=this,set=This.set - ,size=res.length - ,bitRate=set.bitRate==8?8:16; - - var buffer=new ArrayBuffer(size*(bitRate/8)); - var data=new DataView(buffer); - var offset=0; - - // 写入采样数据 - if(bitRate==8) { - for(var i=0;i>8)+128; - data.setInt8(offset,val,true); - }; - }else{ - for (var i=0;i=pcmSampleRate时不会进行任何处理,小于时会进行重新采样 -prevChunkInfo:{} 可选,上次调用时的返回值,用于连续转换,本次调用将从上次结束位置开始进行处理。或可自行定义一个ChunkInfo从pcmDatas指定的位置开始进行转换 -option:{ 可选,配置项 - frameSize:123456 帧大小,每帧的PCM Int16的数量,采样率转换后的pcm长度为frameSize的整数倍,用于连续转换。目前仅在mp3格式时才有用,frameSize取值为1152,这样编码出来的mp3时长和pcm的时长完全一致,否则会因为mp3最后一帧录音不够填满时添加填充数据导致mp3的时长变长。 - frameType:"" 帧类型,一般为rec.set.type,提供此参数时无需提供frameSize,会自动使用最佳的值给frameSize赋值,目前仅支持mp3=1152(MPEG1 Layer3的每帧采采样数),其他类型=1。 - 以上两个参数用于连续转换时使用,最多使用一个,不提供时不进行帧的特殊处理,提供时必须同时提供prevChunkInfo才有作用。最后一段数据处理时无需提供帧大小以便输出最后一丁点残留数据。 - } - -返回ChunkInfo:{ - //可定义,从指定位置开始转换到结尾 - index:0 pcmDatas已处理到的索引 - offset:0.0 已处理到的index对应的pcm中的偏移的下一个位置 - - //仅作为返回值 - frameNext:null||[Int16,...] 下一帧的部分数据,frameSize设置了的时候才可能会有 - sampleRate:16000 结果的采样率,<=newSampleRate - data:[Int16,...] 转换后的PCM结果;如果是连续转换,并且pcmDatas中并没有新数据时,data的长度可能为0 -} -*/ -Recorder.SampleData=function(pcmDatas,pcmSampleRate,newSampleRate,prevChunkInfo,option){ - prevChunkInfo||(prevChunkInfo={}); - var index=prevChunkInfo.index||0; - var offset=prevChunkInfo.offset||0; - - var frameNext=prevChunkInfo.frameNext||[]; - option||(option={}); - var frameSize=option.frameSize||1; - if(option.frameType){ - frameSize=option.frameType=="mp3"?1152:1; - }; - - var nLen=pcmDatas.length; - if(index>nLen+1){ - CLog("SampleData似乎传入了未重置chunk "+index+">"+nLen,3); - }; - var size=0; - for(var i=index;i1){//新采样低于录音采样,进行抽样 - size=Math.floor(size/step); - }else{//新采样高于录音采样不处理,省去了插值处理 - step=1; - newSampleRate=pcmSampleRate; - }; - - size+=frameNext.length; - var res=new Int16Array(size); - var idx=0; - //添加上一次不够一帧的剩余数据 - for(var i=0;i0){ - var u8Pos=(res.length-frameNextSize)*2; - frameNext=new Int16Array(res.buffer.slice(u8Pos)); - res=new Int16Array(res.buffer.slice(0,u8Pos)); - }; - - return { - index:index - ,offset:offset - - ,frameNext:frameNext - ,sampleRate:newSampleRate - ,data:res - }; -}; - - -/*计算音量百分比的一个方法 -pcmAbsSum: pcm Int16所有采样的绝对值的和 -pcmLength: pcm长度 -返回值:0-100,主要当做百分比用 -注意:这个不是分贝,因此没用volume当做名称*/ -Recorder.PowerLevel=function(pcmAbsSum,pcmLength){ - /*计算音量 https://blog.csdn.net/jody1989/article/details/73480259 - 更高灵敏度算法: - 限定最大感应值10000 - 线性曲线:低音量不友好 - power/10000*100 - 对数曲线:低音量友好,但需限定最低感应值 - (1+Math.log10(power/10000))*100 - */ - var power=(pcmAbsSum/pcmLength) || 0;//NaN - var level; - if(power<1251){//1250的结果10%,更小的音量采用线性取值 - level=Math.round(power/1250*10); - }else{ - level=Math.round(Math.min(100,Math.max(0,(1+Math.log(power/10000)/Math.log(10))*100))); - }; - return level; -}; - -/*计算音量,单位dBFS(满刻度相对电平) -maxSample: 为16位pcm采样的绝对值中最大的一个(计算峰值音量),或者为pcm中所有采样的绝对值的平局值 -返回值:-100~0 (最大值0dB,最小值-100代替-∞) -*/ -Recorder.PowerDBFS=function(maxSample){ - var val=Math.max(0.1, maxSample||0),Pref=0x7FFF; - val=Math.min(val,Pref); - //https://www.logiclocmusic.com/can-you-tell-the-decibel/ - //https://blog.csdn.net/qq_17256689/article/details/120442510 - val=20*Math.log(val/Pref)/Math.log(10); - return Math.max(-100,Math.round(val)); -}; - - - - -//带时间的日志输出,可设为一个空函数来屏蔽日志输出 -//CLog(msg,errOrLogMsg, logMsg...) err为数字时代表日志类型1:error 2:log默认 3:warn,否则当做内容输出,第一个参数不能是对象因为要拼接时间,后面可以接无数个输出参数 -Recorder.CLog=function(msg,err){ - var now=new Date(); - var t=("0"+now.getMinutes()).substr(-2) - +":"+("0"+now.getSeconds()).substr(-2) - +"."+("00"+now.getMilliseconds()).substr(-3); - var recID=this&&this.envIn&&this.envCheck&&this.id; - var arr=["["+t+" "+RecTxt+(recID?":"+recID:"")+"]"+msg]; - var a=arguments,console=window.console||{}; - var i=2,fn=console.log; - if(typeof(err)=="number"){ - fn=err==1?console.error:err==3?console.warn:fn; - }else{ - i=1; - }; - for(;i1?arr:""); - }else{ - fn.apply(console,arr); - }; -}; -var CLog=function(){ Recorder.CLog.apply(this,arguments); }; -var IsLoser=true;try{IsLoser=!console.log.apply;}catch(e){}; - - - - -var ID=0; -function initFn(set){ - this.id=++ID; - - //如果开启了流量统计,这里将发送一个图片请求 - Traffic(); - - - var o={ - type:"mp3" //输出类型:mp3,wav,wav输出文件尺寸超大不推荐使用,但mp3编码支持会导致js文件超大,如果不需支持mp3可以使js文件大幅减小 - ,bitRate:16 //比特率 wav:16或8位,MP3:8kbps 1k/s,8kbps 2k/s 录音文件很小 - - ,sampleRate:16000 //采样率,wav格式大小=sampleRate*时间;mp3此项对低比特率有影响,高比特率几乎无影响。 - //wav任意值,mp3取值范围:48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000 - //采样率参考https://www.cnblogs.com/devin87/p/mp3-recorder.html - - ,onProcess:NOOP //fn(buffers,powerLevel,bufferDuration,bufferSampleRate,newBufferIdx,asyncEnd) buffers=[[Int16,...],...]:缓冲的PCM数据,为从开始录音到现在的所有pcm片段;powerLevel:当前缓冲的音量级别0-100,bufferDuration:已缓冲时长,bufferSampleRate:缓冲使用的采样率(当type支持边录边转码(Worker)时,此采样率和设置的采样率相同,否则不一定相同);newBufferIdx:本次回调新增的buffer起始索引;asyncEnd:fn() 如果onProcess是异步的(返回值为true时),处理完成时需要调用此回调,如果不是异步的请忽略此参数,此方法回调时必须是真异步(不能真异步时需用setTimeout包裹)。onProcess返回值:如果返回true代表开启异步模式,在某些大量运算的场合异步是必须的,必须在异步处理完成时调用asyncEnd(不能真异步时需用setTimeout包裹),在onProcess执行后新增的buffer会全部替换成空数组,因此本回调开头应立即将newBufferIdx到本次回调结尾位置的buffer全部保存到另外一个数组内,处理完成后写回buffers中本次回调的结尾位置。 - - //*******高级设置****** - //,sourceStream:MediaStream Object - //可选直接提供一个媒体流,从这个流中录制、实时处理音频数据(当前Recorder实例独享此流);不提供时为普通的麦克风录音,由getUserMedia提供音频流(所有Recorder实例共享同一个流) - //比如:audio、video标签dom节点的captureStream方法(实验特性,不同浏览器支持程度不高)返回的流;WebRTC中的remote流;自己创建的流等 - //注意:流内必须至少存在一条音轨(Audio Track),比如audio标签必须等待到可以开始播放后才会有音轨,否则open会失败 - - //,audioTrackSet:{ deviceId:"",groupId:"", autoGainControl:true, echoCancellation:true, noiseSuppression:true } - //普通麦克风录音时getUserMedia方法的audio配置参数,比如指定设备id,回声消除、降噪开关;注意:提供的任何配置值都不一定会生效 - //由于麦克风是全局共享的,所以新配置后需要close掉以前的再重新open - //更多参考: https://developer.mozilla.org/en-US/docs/Web/API/MediaTrackConstraints - - //,disableEnvInFix:false 内部参数,禁用设备卡顿时音频输入丢失补偿功能 - - //,takeoffEncodeChunk:NOOP //fn(chunkBytes) chunkBytes=[Uint8,...]:实时编码环境下接管编码器输出,当编码器实时编码出一块有效的二进制音频数据时实时回调此方法;参数为二进制的Uint8Array,就是编码出来的音频数据片段,所有的chunkBytes拼接在一起即为完整音频。本实现的想法最初由QQ2543775048提出 - //当提供此回调方法时,将接管编码器的数据输出,编码器内部将放弃存储生成的音频数据;环境要求比较苛刻:如果当前环境不支持实时编码处理,将在open时直接走fail逻辑 - //因此提供此回调后调用stop方法将无法获得有效的音频数据,因为编码器内没有音频数据,因此stop时返回的blob将是一个字节长度为0的blob - //目前只有mp3格式实现了实时编码,在支持实时处理的环境中将会实时的将编码出来的mp3片段通过此方法回调,所有的chunkBytes拼接到一起即为完整的mp3,此种拼接的结果比mock方法实时生成的音质更加,因为天然避免了首尾的静默 - //目前除mp3外其他格式不可以提供此回调,提供了将在open时直接走fail逻辑 - }; - - for(var k in set){ - o[k]=set[k]; - }; - this.set=o; - - this._S=9;//stop同步锁,stop可以阻止open过程中还未运行的start - this.Sync={O:9,C:9};//和Recorder.Sync一致,只不过这个是非全局的,仅用来简化代码逻辑,无实际作用 -}; -//同步锁,控制对Stream的竞争;用于close时中断异步的open;一个对象open如果变化了都要阻止close,Stream的控制权交个新的对象 -Recorder.Sync={/*open*/O:9,/*close*/C:9}; - -Recorder.prototype=initFn.prototype={ - CLog:CLog - - //流相关的数据存储在哪个对象里面;如果提供了sourceStream,数据直接存储在当前对象中,否则存储在全局 - ,_streamStore:function(){ - if(this.set.sourceStream){ - return this; - }else{ - return Recorder; - } - } - - //打开录音资源True(),False(msg,isUserNotAllow),需要调用close。注意:此方法是异步的;一般使用时打开,用完立即关闭;可重复调用,可用来测试是否能录音 - ,open:function(True,False){ - var This=this,streamStore=This._streamStore(); - True=True||NOOP; - var failCall=function(errMsg,isUserNotAllow){ - isUserNotAllow=!!isUserNotAllow; - This.CLog("录音open失败:"+errMsg+",isUserNotAllow:"+isUserNotAllow,1); - False&&False(errMsg,isUserNotAllow); - }; - - var ok=function(){ - This.CLog("open ok id:"+This.id); - True(); - - This._SO=0;//解除stop对open中的start调用的阻止 - }; - - - //同步锁 - var Lock=streamStore.Sync; - var lockOpen=++Lock.O,lockClose=Lock.C; - This._O=This._O_=lockOpen;//记住当前的open,如果变化了要阻止close,这里假定了新对象已取代当前对象并且不再使用 - This._SO=This._S;//记住open过程中的stop,中途任何stop调用后都不能继续open中的start - var lockFail=function(){ - //允许多次open,但不允许任何一次close,或者自身已经调用了关闭 - if(lockClose!=Lock.C || !This._O){ - var err="open被取消"; - if(lockOpen==Lock.O){ - //无新的open,已经调用了close进行取消,此处应让上次的close明确生效 - This.close(); - }else{ - err="open被中断"; - }; - failCall(err); - return true; - }; - }; - - //环境配置检查 - var checkMsg=This.envCheck({envName:"H5",canProcess:true}); - if(checkMsg){ - failCall("不能录音:"+checkMsg); - return; - }; - - - //***********已直接提供了音频流************ - if(This.set.sourceStream){ - if(!Recorder.GetContext()){ - failCall("不支持此浏览器从流中获取录音"); - return; - }; - - Disconnect(streamStore);//可能已open过,直接先尝试断开 - This.Stream=This.set.sourceStream; - This.Stream._call={}; - - try{ - Connect(streamStore); - }catch(e){ - failCall("从流中打开录音失败:"+e.message); - return; - } - ok(); - return; - }; - - - //***********打开麦克风得到全局的音频流************ - var codeFail=function(code,msg){ - try{//跨域的优先检测一下 - window.top.a; - }catch(e){ - failCall('无权录音(跨域,请尝试给iframe添加麦克风访问策略,如allow="camera;microphone")'); - return; - }; - - if(/Permission|Allow/i.test(code)){ - failCall("用户拒绝了录音权限",true); - }else if(window.isSecureContext===false){ - failCall("浏览器禁止不安全页面录音,可开启https解决"); - }else if(/Found/i.test(code)){//可能是非安全环境导致的没有设备 - failCall(msg+",无可用麦克风"); - }else{ - failCall(msg); - }; - }; - - - //如果已打开并且有效就不要再打开了 - if(Recorder.IsOpen()){ - ok(); - return; - }; - if(!Recorder.Support()){ - codeFail("","此浏览器不支持录音"); - return; - }; - - //请求权限,如果从未授权,一般浏览器会弹出权限请求弹框 - var f1=function(stream){ - //https://github.com/xiangyuecn/Recorder/issues/14 获取到的track.readyState!="live",刚刚回调时可能是正常的,但过一下可能就被关掉了,原因不明。延迟一下保证真异步。对正常浏览器不影响 - setTimeout(function(){ - stream._call={}; - var oldStream=Recorder.Stream; - if(oldStream){ - Disconnect(); //直接断开已存在的,旧的Connect未完成会自动终止 - stream._call=oldStream._call; - }; - Recorder.Stream=stream; - if(lockFail())return; - - if(Recorder.IsOpen()){ - if(oldStream)This.CLog("发现同时多次调用open",1); - - Connect(streamStore,1); - ok(); - }else{ - failCall("录音功能无效:无音频流"); - }; - },100); - }; - var f2=function(e){ - var code=e.name||e.message||e.code+":"+e; - This.CLog("请求录音权限错误",1,e); - - codeFail(code,"无法录音:"+code); - }; - - var trackSet={ - noiseSuppression:false //默认禁用降噪,原声录制,免得移动端表现怪异(包括系统播放声音变小) - ,echoCancellation:false //回声消除 - }; - var trackSet2=This.set.audioTrackSet; - for(var k in trackSet2)trackSet[k]=trackSet2[k]; - trackSet.sampleRate=Recorder.Ctx.sampleRate;//必须指明采样率,不然手机上MediaRecorder采样率16k - - try{ - var pro=Recorder.Scope[getUserMediaTxt]({audio:trackSet},f1,f2); - }catch(e){//不能设置trackSet就算了 - This.CLog(getUserMediaTxt,3,e); - pro=Recorder.Scope[getUserMediaTxt]({audio:true},f1,f2); - }; - if(pro&&pro.then){ - pro.then(f1)[CatchTxt](f2); //fix 关键字,保证catch压缩时保持字符串形式 - }; - } - //关闭释放录音资源 - ,close:function(call){ - call=call||NOOP; - - var This=this,streamStore=This._streamStore(); - This._stop(); - - var Lock=streamStore.Sync; - This._O=0; - if(This._O_!=Lock.O){ - //唯一资源Stream的控制权已交给新对象,这里不能关闭。此处在每次都弹权限的浏览器内可能存在泄漏,新对象被拒绝权限可能不会调用close,忽略这种不处理 - This.CLog("close被忽略(因为同时open了多个rec,只有最后一个会真正close)",3); - call(); - return; - }; - Lock.C++;//获得控制权 - - Disconnect(streamStore); - - This.CLog("close"); - call(); - } - - - - - - /*模拟一段录音数据,后面可以调用stop进行编码,需提供pcm数据[1,2,3...],pcm的采样率*/ - ,mock:function(pcmData,pcmSampleRate){ - var This=this; - This._stop();//清理掉已有的资源 - - This.isMock=1; - This.mockEnvInfo=null; - This.buffers=[pcmData]; - This.recSize=pcmData.length; - This[srcSampleRateTxt]=pcmSampleRate; - return This; - } - ,envCheck:function(envInfo){//平台环境下的可用性检查,任何时候都可以调用检查,返回errMsg:""正常,"失败原因" - //envInfo={envName:"H5",canProcess:true} - var errMsg,This=this,set=This.set; - - //检测CPU的数字字节序,TypedArray字节序是个迷,直接拒绝罕见的大端模式,因为找不到这种CPU进行测试 - var tag="CPU_BE"; - if(!errMsg && !Recorder[tag] && window.Int8Array && !new Int8Array(new Int32Array([1]).buffer)[0]){ - Traffic(tag); //如果开启了流量统计,这里将发送一个图片请求 - errMsg="不支持"+tag+"架构"; - }; - - //编码器检查环境下配置是否可用 - if(!errMsg){ - var type=set.type; - if(This[type+"_envCheck"]){//编码器已实现环境检查 - errMsg=This[type+"_envCheck"](envInfo,set); - }else{//未实现检查的手动检查配置是否有效 - if(set.takeoffEncodeChunk){ - errMsg=type+"类型"+(This[type]?"":"(未加载编码器)")+"不支持设置takeoffEncodeChunk"; - }; - }; - }; - - return errMsg||""; - } - ,envStart:function(mockEnvInfo,sampleRate){//平台环境相关的start调用 - var This=this,set=This.set; - This.isMock=mockEnvInfo?1:0;//非H5环境需要启用mock,并提供envCheck需要的环境信息 - This.mockEnvInfo=mockEnvInfo; - This.buffers=[];//数据缓冲 - This.recSize=0;//数据大小 - - This.envInLast=0;//envIn接收到最后录音内容的时间 - This.envInFirst=0;//envIn接收到的首个录音内容的录制时间 - This.envInFix=0;//补偿的总时间 - This.envInFixTs=[];//补偿计数列表 - - //engineCtx需要提前确定最终的采样率 - var setSr=set[sampleRateTxt]; - if(setSr>sampleRate){ - set[sampleRateTxt]=sampleRate; - }else{ setSr=0 } - This[srcSampleRateTxt]=sampleRate; - This.CLog(srcSampleRateTxt+": "+sampleRate+" set."+sampleRateTxt+": "+set[sampleRateTxt]+(setSr?" 忽略"+setSr:""), setSr?3:0); - - This.engineCtx=0; - //此类型有边录边转码(Worker)支持 - if(This[set.type+"_start"]){ - var engineCtx=This.engineCtx=This[set.type+"_start"](set); - if(engineCtx){ - engineCtx.pcmDatas=[]; - engineCtx.pcmSize=0; - }; - }; - } - ,envResume:function(){//和平台环境无关的恢复录音 - //重新开始计数 - this.envInFixTs=[]; - } - ,envIn:function(pcm,sum){//和平台环境无关的pcm[Int16]输入 - var This=this,set=This.set,engineCtx=This.engineCtx; - var bufferSampleRate=This[srcSampleRateTxt]; - var size=pcm.length; - var powerLevel=Recorder.PowerLevel(sum,size); - - var buffers=This.buffers; - var bufferFirstIdx=buffers.length;//之前的buffer都是经过onProcess处理好的,不允许再修改 - buffers.push(pcm); - - //有engineCtx时会被覆盖,这里保存一份 - var buffersThis=buffers; - var bufferFirstIdxThis=bufferFirstIdx; - - //卡顿丢失补偿:因为设备很卡的时候导致H5接收到的数据量不够造成播放时候变速,结果比实际的时长要短,此处保证了不会变短,但不能修复丢失的音频数据造成音质变差。当前算法采用输入时间侦测下一帧是否需要添加补偿帧,需要(6次输入||超过1秒)以上才会开始侦测,如果滑动窗口内丢失超过1/3就会进行补偿 - var now=Date.now(); - var pcmTime=Math.round(size/bufferSampleRate*1000); - This.envInLast=now; - if(This.buffers.length==1){//记下首个录音数据的录制时间 - This.envInFirst=now-pcmTime; - }; - var envInFixTs=This.envInFixTs; - envInFixTs.splice(0,0,{t:now,d:pcmTime}); - //保留3秒的计数滑动窗口,另外超过3秒的停顿不补偿 - var tsInStart=now,tsPcm=0; - for(var i=0;i3000){ - envInFixTs.length=i; - break; - }; - tsInStart=o.t; - tsPcm+=o.d; - }; - //达到需要的数据量,开始侦测是否需要补偿 - var tsInPrev=envInFixTs[1]; - var tsIn=now-tsInStart; - var lost=tsIn-tsPcm; - if( lost>tsIn/3 && (tsInPrev&&tsIn>1000 || envInFixTs.length>=6) ){ - //丢失过多,开始执行补偿 - var addTime=now-tsInPrev.t-pcmTime;//距离上次输入丢失这么多ms - if(addTime>pcmTime/5){//丢失超过本帧的1/5 - var fixOpen=!set.disableEnvInFix; - This.CLog("["+now+"]"+(fixOpen?"":"未")+"补偿"+addTime+"ms",3); - This.envInFix+=addTime; - - //用静默进行补偿 - if(fixOpen){ - var addPcm=new Int16Array(addTime*bufferSampleRate/1000); - size+=addPcm.length; - buffers.push(addPcm); - }; - }; - }; - - - var sizeOld=This.recSize,addSize=size; - var bufferSize=sizeOld+addSize; - This.recSize=bufferSize;//此值在onProcess后需要修正,可能新数据被修改 - - - //此类型有边录边转码(Worker)支持,开启实时转码 - if(engineCtx){ - //转换成set的采样率 - var chunkInfo=Recorder.SampleData(buffers,bufferSampleRate,set[sampleRateTxt],engineCtx.chunkInfo); - engineCtx.chunkInfo=chunkInfo; - - sizeOld=engineCtx.pcmSize; - addSize=chunkInfo.data.length; - bufferSize=sizeOld+addSize; - engineCtx.pcmSize=bufferSize;//此值在onProcess后需要修正,可能新数据被修改 - - buffers=engineCtx.pcmDatas; - bufferFirstIdx=buffers.length; - buffers.push(chunkInfo.data); - bufferSampleRate=chunkInfo[sampleRateTxt]; - }; - - var duration=Math.round(bufferSize/bufferSampleRate*1000); - var bufferNextIdx=buffers.length; - var bufferNextIdxThis=buffersThis.length; - - //允许异步处理buffer数据 - var asyncEnd=function(){ - //重新计算size,异步的早已减去添加的,同步的需去掉本次添加的然后重新计算 - var num=asyncBegin?0:-addSize; - var hasClear=buffers[0]==null; - for(var i=bufferFirstIdx;i10 && This.envInFirst-now>1000){ //1秒后开始onProcess性能监测 - This.CLog(procTxt+"低性能,耗时"+slowT+"ms",3); - }; - - if(asyncBegin===true){ - //开启了异步模式,onProcess已接管buffers新数据,立即清空,避免出现未处理的数据 - var hasClear=0; - for(var i=bufferFirstIdx;i"+res.length+" 花:"+(Date.now()-t1)+"ms"); - - setTimeout(function(){ - t1=Date.now(); - This[set.type](res,function(blob){ - ok(blob,duration); - },function(msg){ - err(msg); - }); - }); - } - -}; - -if(window[RecTxt]){ - CLog("重复引入"+RecTxt,3); - window[RecTxt].Destroy(); -}; -window[RecTxt]=Recorder; - - - - -//=======从WebM字节流中提取pcm数据,提取成功返回Float32Array,失败返回null||-1===== -var WebM_Extract=function(inBytes, scope){ - if(!scope.pos){ - scope.pos=[0]; scope.tracks={}; scope.bytes=[]; - }; - var tracks=scope.tracks, position=[scope.pos[0]]; - var endPos=function(){ scope.pos[0]=position[0] }; - - var sBL=scope.bytes.length; - var bytes=new Uint8Array(sBL+inBytes.length); - bytes.set(scope.bytes); bytes.set(inBytes,sBL); - scope.bytes=bytes; - - //先读取文件头和Track信息 - if(!scope._ht){ - readMatroskaVInt(bytes, position);//EBML Header - readMatroskaBlock(bytes, position);//跳过EBML Header内容 - if(!BytesEq(readMatroskaVInt(bytes, position), [0x18,0x53,0x80,0x67])){ - return;//未识别到Segment - } - readMatroskaVInt(bytes, position);//跳过Segment长度值 - while(position[0]1){//多声道,提取一个声道 - var arr2=[]; - for(var i=0;i=arr.length)return; - var b0=arr[i],b2=("0000000"+b0.toString(2)).substr(-8); - var m=/^(0*1)(\d*)$/.exec(b2); - if(!m)return; - var len=m[1].length, val=[]; - if(i+len>arr.length)return; - for(var i2=0;i2arr.length)return; - for(var i2=0;i2>8)+128; - data.setInt8(offset,val,true); - }; - }else{ - for (var i=0;i