From 928907086cb9080eadc9d14cdf033543512a3883 Mon Sep 17 00:00:00 2001 From: Adrian Lebioda Date: Mon, 10 May 2021 01:25:52 +0000 Subject: [PATCH] HLS video playback (#182) * HLS video playback Signed-off-by: Adrian Lebioda * Add LibreJS compliance * Locally host hls.js * Notification about HLS under videos that support it Signed-off-by: Adrian Lebioda * Use .contains() instead of .find() == None * Make list of preferences constant * Change headers_keys from Vector into Array * Fix incorrect detecting of # in paths * Remove trailing-slash-appending if statement * Change HLS notification styling Co-authored-by: spikecodes <19519553+spikecodes@users.noreply.github.com> --- src/client.rs | 20 +++++++++-- src/main.rs | 10 +++++- src/post.rs | 1 + src/search.rs | 4 +++ src/settings.rs | 45 +++++++++++++++++------ src/subreddit.rs | 4 +++ src/user.rs | 3 ++ src/utils.rs | 69 +++++++++++++++++++++++++++++------ static/hls.min.js | 5 +++ static/playHLSVideo.js | 77 ++++++++++++++++++++++++++++++++++++++++ static/style.css | 13 +++++++ templates/post.html | 10 ++++++ templates/settings.html | 12 +++++-- templates/subreddit.html | 4 +++ templates/utils.html | 16 ++++++++- 15 files changed, 265 insertions(+), 28 deletions(-) create mode 100644 static/hls.min.js create mode 100644 static/playHLSVideo.js diff --git a/src/client.rs b/src/client.rs index 784d1d8..9ec5215 100644 --- a/src/client.rs +++ b/src/client.rs @@ -13,10 +13,10 @@ pub async fn proxy(req: Request, format: &str) -> Result, S url = url.replace(&format!("{{{}}}", name), value); } - stream(&url).await + stream(&url, &req).await } -async fn stream(url: &str) -> Result, String> { +async fn stream(url: &str, req: &Request) -> Result, String> { // First parameter is target URL (mandatory). let url = Uri::from_str(url).map_err(|_| "Couldn't parse URL".to_string())?; @@ -26,8 +26,20 @@ async fn stream(url: &str) -> Result, String> { // Build the hyper client from the HTTPS connector. let client: client::Client<_, hyper::Body> = client::Client::builder().build(https); + let mut builder = Request::get(url); + + // Copy useful headers from original request + let headers = req.headers(); + for &key in &["Range", "If-Modified-Since", "Cache-Control"] { + if let Some(value) = headers.get(key) { + builder = builder.header(key, value); + } + } + + let stream_request = builder.body(Body::default()).expect("stream"); + client - .get(url) + .request(stream_request) .await .map(|mut res| { let mut rm = |key: &str| res.headers_mut().remove(key); @@ -40,6 +52,8 @@ async fn stream(url: &str) -> Result, String> { rm("x-cdn-client-region"); rm("x-cdn-name"); rm("x-cdn-server-region"); + rm("x-reddit-cdn"); + rm("x-reddit-video-features"); res }) diff --git a/src/main.rs b/src/main.rs index 1aa08d2..c26d093 100644 --- a/src/main.rs +++ b/src/main.rs @@ -139,7 +139,7 @@ async fn main() { "Referrer-Policy" => "no-referrer", "X-Content-Type-Options" => "nosniff", "X-Frame-Options" => "DENY", - "Content-Security-Policy" => "default-src 'none'; manifest-src 'self'; media-src 'self'; style-src 'self' 'unsafe-inline'; base-uri 'none'; img-src 'self' data:; form-action 'self'; frame-ancestors 'none';" + "Content-Security-Policy" => "default-src 'none'; script-src 'self' blob:; manifest-src 'self'; media-src 'self' data: blob: about:; style-src 'self' 'unsafe-inline'; base-uri 'none'; img-src 'self' data:; form-action 'self'; frame-ancestors 'none'; connect-src 'self'; worker-src blob:;" }; if let Some(expire_time) = hsts { @@ -158,9 +158,16 @@ async fn main() { app.at("/logo.png").get(|_| pwa_logo().boxed()); app.at("/touch-icon-iphone.png").get(|_| iphone_logo().boxed()); app.at("/apple-touch-icon.png").get(|_| iphone_logo().boxed()); + app + .at("/playHLSVideo.js") + .get(|_| resource(include_str!("../static/playHLSVideo.js"), "text/javascript", false).boxed()); + app + .at("/hls.min.js") + .get(|_| resource(include_str!("../static/hls.min.js"), "text/javascript", false).boxed()); // Proxy media through Libreddit app.at("/vid/:id/:size").get(|r| proxy(r, "https://v.redd.it/{id}/DASH_{size}").boxed()); + app.at("/hls/:id/*path").get(|r| proxy(r, "https://v.redd.it/{id}/{path}").boxed()); app.at("/img/:id").get(|r| proxy(r, "https://i.redd.it/{id}").boxed()); app.at("/thumb/:point/:id").get(|r| proxy(r, "https://{point}.thumbs.redditmedia.com/{id}").boxed()); app.at("/emoji/:id/:name").get(|r| proxy(r, "https://emoji.redditmedia.com/{id}/{name}").boxed()); @@ -184,6 +191,7 @@ async fn main() { // Configure settings app.at("/settings").get(|r| settings::get(r).boxed()).post(|r| settings::set(r).boxed()); app.at("/settings/restore").get(|r| settings::restore(r).boxed()); + app.at("/settings/update").get(|r| settings::update(r).boxed()); // Subreddit services app.at("/r/:sub").get(|r| subreddit::community(r).boxed()); diff --git a/src/post.rs b/src/post.rs index 0f06f8d..21005e8 100644 --- a/src/post.rs +++ b/src/post.rs @@ -106,6 +106,7 @@ async fn parse_post(json: &serde_json::Value) -> Post { media, thumbnail: Media { url: format_url(val(post, "thumbnail").as_str()), + alt_url: String::new(), width: post["data"]["thumbnail_width"].as_i64().unwrap_or_default(), height: post["data"]["thumbnail_height"].as_i64().unwrap_or_default(), poster: "".to_string(), diff --git a/src/search.rs b/src/search.rs index e18eb0c..74e4cc6 100644 --- a/src/search.rs +++ b/src/search.rs @@ -31,6 +31,7 @@ struct SearchTemplate { sub: String, params: SearchParams, prefs: Preferences, + url: String, } // SERVICES @@ -56,6 +57,8 @@ pub async fn find(req: Request) -> Result, String> { Vec::new() }; + let url = String::from(req.uri().path_and_query().map_or("", |val| val.as_str())); + match Post::fetch(&path, String::new()).await { Ok((posts, after)) => template(SearchTemplate { posts, @@ -70,6 +73,7 @@ pub async fn find(req: Request) -> Result, String> { restrict_sr: param(&path, "restrict_sr"), }, prefs: Preferences::new(req), + url, }), Err(msg) => error(req, msg).await, } diff --git a/src/settings.rs b/src/settings.rs index 5654be0..41b6404 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -16,6 +16,21 @@ struct SettingsTemplate { prefs: Preferences, } +// CONSTANTS + +const PREFS: [&str; 10] = [ + "theme", + "front_page", + "layout", + "wide", + "comment_sort", + "post_sort", + "show_nsfw", + "use_hls", + "hide_hls_notification", + "subscriptions", +]; + // FUNCTIONS // Retrieve cookies from request "Cookie" header @@ -50,9 +65,7 @@ pub async fn set(req: Request) -> Result, String> { let mut res = redirect("/settings".to_string()); - let names = vec!["theme", "front_page", "layout", "wide", "comment_sort", "post_sort", "show_nsfw"]; - - for name in names { + for &name in &PREFS { match form.get(name) { Some(value) => res.insert_cookie( Cookie::build(name.to_owned(), value.to_owned()) @@ -68,8 +81,7 @@ pub async fn set(req: Request) -> Result, String> { Ok(res) } -// Set cookies using response "Set-Cookie" header -pub async fn restore(req: Request) -> Result, String> { +fn set_cookies_method(req: Request, remove_cookies: bool) -> Response { // Split the body into parts let (parts, _) = req.into_parts(); @@ -85,16 +97,14 @@ pub async fn restore(req: Request) -> Result, String> { let form = url::form_urlencoded::parse(query).collect::>(); - let names = vec!["theme", "front_page", "layout", "wide", "comment_sort", "post_sort", "show_nsfw", "subscriptions"]; - let path = match form.get("redirect") { - Some(value) => format!("/{}/", value), + Some(value) => format!("/{}", value.replace("%26", "&").replace("%23", "#")), None => "/".to_string(), }; let mut res = redirect(path); - for name in names { + for &name in &PREFS { match form.get(name) { Some(value) => res.insert_cookie( Cookie::build(name.to_owned(), value.to_owned()) @@ -103,9 +113,22 @@ pub async fn restore(req: Request) -> Result, String> { .expires(OffsetDateTime::now_utc() + Duration::weeks(52)) .finish(), ), - None => res.remove_cookie(name.to_string()), + None => { + if remove_cookies { + res.remove_cookie(name.to_string()) + } + } }; } - Ok(res) + res +} + +// Set cookies using response "Set-Cookie" header +pub async fn restore(req: Request) -> Result, String> { + Ok(set_cookies_method(req, true)) +} + +pub async fn update(req: Request) -> Result, String> { + Ok(set_cookies_method(req, false)) } diff --git a/src/subreddit.rs b/src/subreddit.rs index d68eace..65804c1 100644 --- a/src/subreddit.rs +++ b/src/subreddit.rs @@ -16,6 +16,7 @@ struct SubredditTemplate { sort: (String, String), ends: (String, String), prefs: Preferences, + url: String, } #[derive(Template)] @@ -79,12 +80,15 @@ pub async fn community(req: Request) -> Result, String> { Subreddit::default() }; + let url = String::from(req.uri().path_and_query().map_or("", |val| val.as_str())); + template(SubredditTemplate { sub, posts, sort: (sort, param(&path, "t")), ends: (param(&path, "after"), after), prefs: Preferences::new(req), + url, }) } Err(msg) => match msg.as_str() { diff --git a/src/user.rs b/src/user.rs index 8f7910c..2ba024f 100644 --- a/src/user.rs +++ b/src/user.rs @@ -16,6 +16,7 @@ struct UserTemplate { sort: (String, String), ends: (String, String), prefs: Preferences, + url: String, } // FUNCTIONS @@ -33,6 +34,7 @@ pub async fn profile(req: Request) -> Result, String> { // Request user posts/comments from Reddit let posts = Post::fetch(&path, "Comment".to_string()).await; + let url = String::from(req.uri().path_and_query().map_or("", |val| val.as_str())); match posts { Ok((posts, after)) => { @@ -45,6 +47,7 @@ pub async fn profile(req: Request) -> Result, String> { sort: (sort, param(&path, "t")), ends: (param(&path, "after"), after), prefs: Preferences::new(req), + url, }) } // If there is an error show error page diff --git a/src/utils.rs b/src/utils.rs index dca2ad0..04e4723 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -75,6 +75,7 @@ pub struct Flags { pub struct Media { pub url: String, + pub alt_url: String, pub width: i64, pub height: i64, pub poster: String, @@ -85,12 +86,28 @@ impl Media { let mut gallery = Vec::new(); // If post is a video, return the video - let (post_type, url_val) = if data["preview"]["reddit_video_preview"]["fallback_url"].is_string() { + let (post_type, url_val, alt_url_val) = if data["preview"]["reddit_video_preview"]["fallback_url"].is_string() { // Return reddit video - ("video", &data["preview"]["reddit_video_preview"]["fallback_url"]) + ( + if data["preview"]["reddit_video_preview"]["is_gif"].as_bool().unwrap_or(false) { + "gif" + } else { + "video" + }, + &data["preview"]["reddit_video_preview"]["fallback_url"], + Some(&data["preview"]["reddit_video_preview"]["hls_url"]), + ) } else if data["secure_media"]["reddit_video"]["fallback_url"].is_string() { // Return reddit video - ("video", &data["secure_media"]["reddit_video"]["fallback_url"]) + ( + if data["preview"]["reddit_video_preview"]["is_gif"].as_bool().unwrap_or(false) { + "gif" + } else { + "video" + }, + &data["secure_media"]["reddit_video"]["fallback_url"], + Some(&data["secure_media"]["reddit_video"]["hls_url"]), + ) } else if data["post_hint"].as_str().unwrap_or("") == "image" { // Handle images, whether GIFs or pics let preview = &data["preview"]["images"][0]; @@ -98,26 +115,26 @@ impl Media { if mp4.is_object() { // Return the mp4 if the media is a gif - ("gif", &mp4["source"]["url"]) + ("gif", &mp4["source"]["url"], None) } else { // Return the picture if the media is an image if data["domain"] == "i.redd.it" { - ("image", &data["url"]) + ("image", &data["url"], None) } else { - ("image", &preview["source"]["url"]) + ("image", &preview["source"]["url"], None) } } } else if data["is_self"].as_bool().unwrap_or_default() { // If type is self, return permalink - ("self", &data["permalink"]) + ("self", &data["permalink"], None) } else if data["is_gallery"].as_bool().unwrap_or_default() { // If this post contains a gallery of images gallery = GalleryMedia::parse(&data["gallery_data"]["items"], &data["media_metadata"]); - ("gallery", &data["url"]) + ("gallery", &data["url"], None) } else { // If type can't be determined, return url - ("link", &data["url"]) + ("link", &data["url"], None) }; let source = &data["preview"]["images"][0]["source"]; @@ -128,10 +145,13 @@ impl Media { format_url(url_val.as_str().unwrap_or_default()) }; + let alt_url = alt_url_val.map_or(String::new(), |val| format_url(val.as_str().unwrap_or_default())); + ( post_type.to_string(), Self { url, + alt_url, width: source["width"].as_i64().unwrap_or_default(), height: source["height"].as_i64().unwrap_or_default(), poster: format_url(source["url"].as_str().unwrap_or_default()), @@ -259,6 +279,7 @@ impl Post { post_type, thumbnail: Media { url: format_url(val(post, "thumbnail").as_str()), + alt_url: String::new(), width: data["thumbnail_width"].as_i64().unwrap_or_default(), height: data["thumbnail_height"].as_i64().unwrap_or_default(), poster: "".to_string(), @@ -365,6 +386,8 @@ pub struct Preferences { pub layout: String, pub wide: String, pub show_nsfw: String, + pub hide_hls_notification: String, + pub use_hls: String, pub comment_sort: String, pub post_sort: String, pub subscriptions: Vec, @@ -379,6 +402,8 @@ impl Preferences { layout: cookie(&req, "layout"), wide: cookie(&req, "wide"), show_nsfw: cookie(&req, "show_nsfw"), + use_hls: cookie(&req, "use_hls"), + hide_hls_notification: cookie(&req, "hide_hls_notification"), comment_sort: cookie(&req, "comment_sort"), post_sort: cookie(&req, "post_sort"), subscriptions: cookie(&req, "subscriptions").split('+').map(String::from).filter(|s| !s.is_empty()).collect(), @@ -439,8 +464,32 @@ pub fn format_url(url: &str) -> String { .unwrap_or_default() }; + macro_rules! chain { + () => { + { + String::new() + } + }; + + ( $first_fn:expr, $($other_fns:expr), *) => { + { + let result = $first_fn; + if result.is_empty() { + chain!($($other_fns,)*) + } + else + { + result + } + } + }; + } + match domain { - "v.redd.it" => capture(r"https://v\.redd\.it/(.*)/DASH_([0-9]{2,4}(\.mp4|$))", "/vid/", 2), + "v.redd.it" => chain!( + capture(r"https://v\.redd\.it/(.*)/DASH_([0-9]{2,4}(\.mp4|$))", "/vid/", 2), + capture(r"https://v\.redd\.it/(.+)/(HLSPlaylist\.m3u8.*)$", "/hls/", 2) + ), "i.redd.it" => capture(r"https://i\.redd\.it/(.*)", "/img/", 1), "a.thumbs.redditmedia.com" => capture(r"https://a\.thumbs\.redditmedia\.com/(.*)", "/thumb/a/", 1), "b.thumbs.redditmedia.com" => capture(r"https://b\.thumbs\.redditmedia\.com/(.*)", "/thumb/b/", 1), diff --git a/static/hls.min.js b/static/hls.min.js new file mode 100644 index 0000000..a02b51e --- /dev/null +++ b/static/hls.min.js @@ -0,0 +1,5 @@ +// @license http://www.apache.org/licenses/LICENSE-2.0 Apache-2.0 +// @source https://github.com/video-dev/hls.js +"undefined"!=typeof window&&function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Hls=e():t.Hls=e()}(this,(function(){return function(t){var e={};function r(i){if(e[i])return e[i].exports;var a=e[i]={i:i,l:!1,exports:{}};return t[i].call(a.exports,a,a.exports,r),a.l=!0,a.exports}return r.m=t,r.c=e,r.d=function(t,e,i){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:i})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var i=Object.create(null);if(r.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var a in t)r.d(i,a,function(e){return t[e]}.bind(null,a));return i},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="/dist/",r(r.s=19)}([function(t,e,r){"use strict";var i;r.d(e,"a",(function(){return i})),function(t){t.MEDIA_ATTACHING="hlsMediaAttaching",t.MEDIA_ATTACHED="hlsMediaAttached",t.MEDIA_DETACHING="hlsMediaDetaching",t.MEDIA_DETACHED="hlsMediaDetached",t.BUFFER_RESET="hlsBufferReset",t.BUFFER_CODECS="hlsBufferCodecs",t.BUFFER_CREATED="hlsBufferCreated",t.BUFFER_APPENDING="hlsBufferAppending",t.BUFFER_APPENDED="hlsBufferAppended",t.BUFFER_EOS="hlsBufferEos",t.BUFFER_FLUSHING="hlsBufferFlushing",t.BUFFER_FLUSHED="hlsBufferFlushed",t.MANIFEST_LOADING="hlsManifestLoading",t.MANIFEST_LOADED="hlsManifestLoaded",t.MANIFEST_PARSED="hlsManifestParsed",t.LEVEL_SWITCHING="hlsLevelSwitching",t.LEVEL_SWITCHED="hlsLevelSwitched",t.LEVEL_LOADING="hlsLevelLoading",t.LEVEL_LOADED="hlsLevelLoaded",t.LEVEL_UPDATED="hlsLevelUpdated",t.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",t.LEVELS_UPDATED="hlsLevelsUpdated",t.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",t.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",t.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",t.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",t.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",t.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",t.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",t.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",t.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",t.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",t.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",t.CUES_PARSED="hlsCuesParsed",t.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",t.INIT_PTS_FOUND="hlsInitPtsFound",t.FRAG_LOADING="hlsFragLoading",t.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",t.FRAG_LOADED="hlsFragLoaded",t.FRAG_DECRYPTED="hlsFragDecrypted",t.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",t.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",t.FRAG_PARSING_METADATA="hlsFragParsingMetadata",t.FRAG_PARSED="hlsFragParsed",t.FRAG_BUFFERED="hlsFragBuffered",t.FRAG_CHANGED="hlsFragChanged",t.FPS_DROP="hlsFpsDrop",t.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",t.ERROR="hlsError",t.DESTROYING="hlsDestroying",t.KEY_LOADING="hlsKeyLoading",t.KEY_LOADED="hlsKeyLoaded",t.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",t.BACK_BUFFER_REACHED="hlsBackBufferReached"}(i||(i={}))},function(t,e,r){"use strict";r.d(e,"a",(function(){return o})),r.d(e,"b",(function(){return l}));var i=function(){},a={trace:i,debug:i,log:i,warn:i,info:i,error:i},n=a;function s(t){var e=self.console[t];return e?e.bind(self.console,"["+t+"] >"):i}function o(t){if(self.console&&!0===t||"object"==typeof t){!function(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i>8*(15-r)&255;return e},r.setDecryptDataFromLevelKey=function(t,e){var r=t;return"AES-128"===(null==t?void 0:t.method)&&t.uri&&!t.iv&&((r=o.a.fromURI(t.uri)).method=t.method,r.iv=this.createInitializationVector(e),r.keyFormat="identity"),r},r.setElementaryStreamInfo=function(t,e,r,i,a,n){void 0===n&&(n=!1);var s=this.elementaryStreams,o=s[t];o?(o.startPTS=Math.min(o.startPTS,e),o.endPTS=Math.max(o.endPTS,r),o.startDTS=Math.min(o.startDTS,i),o.endDTS=Math.max(o.endDTS,a)):s[t]={startPTS:e,endPTS:r,startDTS:i,endDTS:a,partial:n}},r.clearElementaryStreamInfo=function(){var t=this.elementaryStreams;t[i.AUDIO]=null,t[i.VIDEO]=null,t[i.AUDIOVIDEO]=null},c(e,[{key:"decryptdata",get:function(){if(!this.levelkey&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkey){var t=this.sn;"number"!=typeof t&&(this.levelkey&&"AES-128"===this.levelkey.method&&!this.levelkey.iv&&s.b.warn('missing IV for initialization segment with method="'+this.levelkey.method+'" - compliance issue'),t=0),this._decryptdata=this.setDecryptDataFromLevelKey(this.levelkey,t)}return this._decryptdata}},{key:"end",get:function(){return this.start+this.duration}},{key:"endProgramDateTime",get:function(){if(null===this.programDateTime)return null;if(!Object(a.a)(this.programDateTime))return null;var t=Object(a.a)(this.duration)?this.duration:0;return this.programDateTime+1e3*t}},{key:"encrypted",get:function(){var t;return!(null===(t=this.decryptdata)||void 0===t||!t.keyFormat||!this.decryptdata.uri)}}]),e}(f),v=function(t){function e(e,r,i,a,n){var s;(s=t.call(this,i)||this).fragOffset=0,s.duration=0,s.gap=!1,s.independent=!1,s.relurl=void 0,s.fragment=void 0,s.index=void 0,s.stats=new l.a,s.duration=e.decimalFloatingPoint("DURATION"),s.gap=e.bool("GAP"),s.independent=e.bool("INDEPENDENT"),s.relurl=e.enumeratedString("URI"),s.fragment=r,s.index=a;var o=e.enumeratedString("BYTERANGE");return o&&s.setByteRange(o,n),n&&(s.fragOffset=n.fragOffset+n.duration),s}return u(e,t),c(e,[{key:"start",get:function(){return this.fragment.start+this.fragOffset}},{key:"end",get:function(){return this.start+this.duration}},{key:"loaded",get:function(){var t=this.elementaryStreams;return!!(t.audio||t.video||t.audiovideo)}}]),e}(f)},function(t,e,r){"use strict";r.d(e,"b",(function(){return h})),r.d(e,"g",(function(){return d})),r.d(e,"f",(function(){return c})),r.d(e,"d",(function(){return f})),r.d(e,"c",(function(){return g})),r.d(e,"e",(function(){return p})),r.d(e,"h",(function(){return m})),r.d(e,"a",(function(){return y}));var i=r(8),a=r(4),n=Math.pow(2,32)-1,s=[].push;function o(t){return String.fromCharCode.apply(null,t)}function l(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<24|t[e+1]<<16|t[e+2]<<8|t[e+3];return r<0?4294967296+r:r}function u(t,e,r){"data"in t&&(e+=t.start,t=t.data),t[e]=r>>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=255&r}function h(t,e){var r,i,a,n=[];if(!e.length)return n;"data"in t?(r=t.data,i=t.start,a=t.end):(i=0,a=(r=t).byteLength);for(var u=i;u1?u+d:a;if(o(r.subarray(u+4,u+8))===e[0])if(1===e.length)n.push({data:r,start:u+8,end:c});else{var f=h({data:r,start:u+8,end:c},e.slice(1));f.length&&s.apply(n,f)}u=c}return n}function d(t){var e=h(t,["moov"])[0],r=e?e.end:null,i=h(t,["sidx"]);if(!i||!i[0])return null;var a=[],n=i[0],s=n.data[0],o=0===s?8:16,u=l(n,o);o+=4;o+=0===s?8:16,o+=2;var d=n.end+0,c=function(t,e){"data"in t&&(e+=t.start,t=t.data);var r=t[e]<<8|t[e+1];return r<0?65536+r:r}(n,o);o+=2;for(var f=0;f>>31)return console.warn("SIDX has hierarchical references (not supported)"),null;var m=l(n,g);g+=4,a.push({referenceSize:p,subsegmentDuration:m,info:{duration:m/u,start:d,end:d+p-1}}),d+=p,o=g+=4}return{earliestPresentationTime:0,timescale:u,version:s,referencesCount:c,references:a,moovEndOffset:r}}function c(t){for(var e=[],r=h(t,["moov","trak"]),i=0;i0)return t.subarray(r,r+i)},o=function(t,e){var r=0;return r=(127&t[e])<<21,r|=(127&t[e+1])<<14,r|=(127&t[e+2])<<7,r|=127&t[e+3]},l=function(t,e){return a(t,e)&&o(t,e+6)+10<=t.length-e},u=function(t){for(var e=c(t),r=0;r>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:u+=String.fromCharCode(n);break;case 12:case 13:s=t[h++],u+=String.fromCharCode((31&n)<<6|63&s);break;case 14:s=t[h++],o=t[h++],u+=String.fromCharCode((15&n)<<12|(63&s)<<6|(63&o)<<0)}}return u};function T(){return i||void 0===self.TextDecoder||(i=new self.TextDecoder("utf-8")),i}},function(t,e,r){"use strict";r.d(e,"c",(function(){return a})),r.d(e,"b",(function(){return n})),r.d(e,"a",(function(){return s}));function i(t,e,r,i){void 0===r&&(r=1),void 0===i&&(i=!1);var a=t*e*r;return i?Math.round(a):a}function a(t,e,r,a){return void 0===r&&(r=1),void 0===a&&(a=!1),i(t,e,1/r,a)}function n(t,e){return void 0===e&&(e=!1),i(t,1e3,1/9e4,e)}function s(t,e){return void 0===e&&(e=1),i(t,9e4,1/e)}},function(t,e,r){"use strict";function i(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}r.d(e,"a",(function(){return i}))},function(t,e,r){"use strict";r.d(e,"c",(function(){return lt})),r.d(e,"d",(function(){return ht})),r.d(e,"a",(function(){return dt})),r.d(e,"b",(function(){return ct}));var i=r(0),a=r(2),n=r(14),s=r(3),o=r(6);var l=r(5),u=r(8),h=function(){function t(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.initPTS=null}var e=t.prototype;return e.resetInitSegment=function(t,e,r){this._id3Track={type:"id3",id:0,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}},e.resetTimeStamp=function(){},e.resetContiguity=function(){},e.canParse=function(t,e){return!1},e.appendFrame=function(t,e,r){},e.demux=function(t,e){this.cachedData&&(t=Object(l.a)(this.cachedData,t),this.cachedData=null);var r,i,a=o.b(t,0),n=a?a.length:0,s=this._audioTrack,h=this._id3Track,c=a?o.d(a):void 0,f=t.length;for(0!==this.frameIndex&&null!==this.initPTS||(this.initPTS=d(c,e)),a&&a.length>0&&h.samples.push({pts:this.initPTS,dts:this.initPTS,data:a}),i=this.initPTS;n>>5}function m(t,e){return e+1=t.length)return!1;var i=p(t,e);if(i<=r)return!1;var a=e+i;return a===t.length||m(t,a)}return!1}function T(t,e,r,n,s){if(!t.samplerate){var o=function(t,e,r,n){var s,o,l,u,h=navigator.userAgent.toLowerCase(),d=n,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];s=1+((192&e[r+2])>>>6);var g=(60&e[r+2])>>>2;if(!(g>c.length-1))return l=(1&e[r+2])<<2,l|=(192&e[r+3])>>>6,f.b.log("manifest codec:"+n+", ADTS type:"+s+", samplingIndex:"+g),/firefox/i.test(h)?g>=6?(s=5,u=new Array(4),o=g-3):(s=2,u=new Array(2),o=g):-1!==h.indexOf("android")?(s=2,u=new Array(2),o=g):(s=5,u=new Array(4),n&&(-1!==n.indexOf("mp4a.40.29")||-1!==n.indexOf("mp4a.40.5"))||!n&&g>=6?o=g-3:((n&&-1!==n.indexOf("mp4a.40.2")&&(g>=6&&1===l||/vivaldi/i.test(h))||!n&&1===l)&&(s=2,u=new Array(2)),o=g)),u[0]=s<<3,u[0]|=(14&g)>>1,u[1]|=(1&g)<<7,u[1]|=l<<3,5===s&&(u[1]|=(14&o)>>1,u[2]=(1&o)<<7,u[2]|=8,u[3]=0),{config:u,samplerate:c[g],channelCount:l,codec:"mp4a.40."+s,manifestCodec:d};t.trigger(i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"invalid ADTS sampling index:"+g})}(e,r,n,s);if(!o)return;t.config=o.config,t.samplerate=o.samplerate,t.channelCount=o.channelCount,t.codec=o.codec,t.manifestCodec=o.manifestCodec,f.b.log("parsed codec:"+t.codec+", rate:"+o.samplerate+", channels:"+o.channelCount)}}function E(t){return 9216e4/t}function b(t,e,r,i,a){var n=function(t,e,r,i,a){var n=t.length,s=v(t,e),o=p(t,e);if((o-=s)>0&&e+s+o<=n)return{headerLength:s,frameLength:o,stamp:r+i*a}}(e,r,i,a,E(t.samplerate));if(n){var s=n.stamp,o=n.headerLength,l=n.frameLength,u={unit:e.subarray(r+o,r+o+l),pts:s,dts:s};return t.samples.push(u),{sample:u,length:l+o}}}function S(t,e){return(S=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}var L=function(t){var e,r;function i(e,r){var i;return(i=t.call(this)||this).observer=void 0,i.config=void 0,i.observer=e,i.config=r,i}r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,S(e,r);var a=i.prototype;return a.resetInitSegment=function(e,r,i){t.prototype.resetInitSegment.call(this,e,r,i),this._audioTrack={container:"audio/adts",type:"audio",id:0,pid:-1,sequenceNumber:0,isAAC:!0,samples:[],manifestCodec:e,duration:i,inputTimeScale:9e4,dropped:0}},i.probe=function(t){if(!t)return!1;for(var e=(o.b(t,0)||[]).length,r=t.length;e0},e.demux=function(t){var e=t,r={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};if(this.config.progressive){this.remainderData&&(e=Object(l.a)(this.remainderData,t));var i=Object(l.h)(e);this.remainderData=i.remainder,r.samples=i.valid||new Uint8Array}else r.samples=e;return{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:r,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.flush=function(){var t={type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0};return t.samples=this.remainderData||new Uint8Array,this.remainderData=null,{audioTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},avcTrack:t,id3Track:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0},textTrack:{type:"",id:-1,pid:-1,inputTimeScale:9e4,sequenceNumber:-1,samples:[],dropped:0}}},e.demuxSampleAes=function(t,e,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))},e.destroy=function(){},t}();R.minProbeByteLength=1024;var D=R,k=null,_=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],I=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],C=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],w=[0,1,1,4];function O(t,e,r,i,a){if(!(r+24>e.length)){var n=x(e,r);if(n&&r+n.frameLength<=e.length){var s=i+a*(9e4*n.samplesPerFrame/n.sampleRate),o={unit:e.subarray(r,r+n.frameLength),pts:s,dts:s};return t.config=[],t.channelCount=n.channelCount,t.samplerate=n.sampleRate,t.samples.push(o),{sample:o,length:n.frameLength}}}}function x(t,e){var r=t[e+1]>>3&3,i=t[e+1]>>1&3,a=t[e+2]>>4&15,n=t[e+2]>>2&3;if(1!==r&&0!==a&&15!==a&&3!==n){var s=t[e+2]>>1&1,o=t[e+3]>>6,l=1e3*_[14*(3===r?3-i:3===i?3:4)+a-1],u=I[3*(3===r?0:2===r?1:2)+n],h=3===o?1:2,d=C[r][i],c=w[i],f=8*d*c,g=Math.floor(d*l/u+s)*c;if(null===k){var v=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);k=v?parseInt(v[1]):0}return!!k&&k<=87&&2===i&&l>=224e3&&0===o&&(t[e+3]=128|t[e+3]),{sampleRate:u,channelCount:h,frameLength:g,samplesPerFrame:f}}}function P(t,e){return 255===t[e]&&224==(224&t[e+1])&&0!=(6&t[e+1])}function M(t,e){return e+1t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,t-=(e=t>>3)>>3,this.bytesAvailable-=e,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)},e.readBits=function(t){var e=Math.min(this.bitsAvailable,t),r=this.word>>>32-e;return t>32&&f.b.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=e,this.bitsAvailable>0?this.word<<=e:this.bytesAvailable>0&&this.loadWord(),(e=t-e)>0&&this.bitsAvailable?r<>>t))return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()},e.skipUEG=function(){this.skipBits(1+this.skipLZ())},e.skipEG=function(){this.skipBits(1+this.skipLZ())},e.readUEG=function(){var t=this.skipLZ();return this.readBits(t+1)-1},e.readEG=function(){var t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)},e.readBoolean=function(){return 1===this.readBits(1)},e.readUByte=function(){return this.readBits(8)},e.readUShort=function(){return this.readBits(16)},e.readUInt=function(){return this.readBits(32)},e.skipScalingList=function(t){for(var e=8,r=8,i=0;i=t.length)return void r();if(!(t[e].unit.length<32)){var i=this.decrypter.isSync();if(this.decryptAacSample(t,e,r,i),!i)return}}},e.getAvcEncryptedData=function(t){for(var e=16*Math.floor((t.length-48)/160)+16,r=new Int8Array(e),i=0,a=32;a<=t.length-16;a+=160,i+=16)r.set(t.subarray(a,a+16),i);return r},e.getAvcDecryptedUnit=function(t,e){for(var r=new Uint8Array(e),i=0,a=32;a<=t.length-16;a+=160,i+=16)t.set(r.subarray(i,i+16),a);return t},e.decryptAvcSample=function(t,e,r,i,a,n){var s=q(a.data),o=this.getAvcEncryptedData(s),l=this;this.decryptBuffer(o.buffer,(function(o){a.data=l.getAvcDecryptedUnit(s,o),n||l.decryptAvcSamples(t,e,r+1,i)}))},e.decryptAvcSamples=function(t,e,r,i){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;e++,r=0){if(e>=t.length)return void i();for(var a=t[e].units;!(r>=a.length);r++){var n=a[r];if(!(n.data.length<=48||1!==n.type&&5!==n.type)){var s=this.decrypter.isSync();if(this.decryptAvcSample(t,e,r,i,n,s),!s)return}}}},t}(),B={video:1,audio:2,id3:3,text:4},G=function(){function t(t,e,r){this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._duration=0,this.aacLastPTS=null,this._initPTS=null,this._initDTS=null,this._pmtId=-1,this._avcTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.avcSample=null,this.remainderData=null,this.observer=t,this.config=e,this.typeSupported=r}t.probe=function(e){var r=t.syncOffset(e);return!(r<0)&&(r&&f.b.warn("MPEG2-TS detected but first sync word found @ offset "+r+", junk ahead ?"),!0)},t.syncOffset=function(t){for(var e=Math.min(1e3,t.length-564),r=0;r>4>1){if((k=A+5+e[A+4])===A+188)continue}else k=A+4;switch(D){case c:R&&(g&&(o=V(g))&&this.parseAVCPES(o,!1),g={data:[],size:0}),g&&(g.data.push(e.subarray(k,A+188)),g.size+=A+188-k);break;case v:R&&(m&&(o=V(m))&&(h.isAAC?this.parseAACPES(o):this.parseMPEGPES(o)),m={data:[],size:0}),m&&(m.data.push(e.subarray(k,A+188)),m.size+=A+188-k);break;case p:R&&(y&&(o=V(y))&&this.parseID3PES(o),y={data:[],size:0}),y&&(y.data.push(e.subarray(k,A+188)),y.size+=A+188-k);break;case 0:R&&(k+=e[k]+1),b=this._pmtId=j(e,k);break;case b:R&&(k+=e[k]+1);var _=H(e,k,!0===this.typeSupported.mpeg||!0===this.typeSupported.mp3,n);(c=_.avc)>0&&(u.pid=c),(v=_.audio)>0&&(h.pid=v,h.isAAC=_.isAAC),(p=_.id3)>0&&(d.pid=p),T&&!E&&(f.b.log("reparse from beginning"),T=!1,A=L-188),E=this.pmtParsed=!0;break;case 17:case 8191:break;default:T=!0}}else this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!1,reason:"TS packet did not start with 0x47"});u.pesData=g,h.pesData=m,d.pesData=y;var I={audioTrack:h,avcTrack:u,id3Track:d,textTrack:this._txtTrack};return s&&this.extractRemainingSamples(I),I},e.flush=function(){var t,e=this.remainderData;return this.remainderData=null,t=e?this.demux(e,-1,!1,!0):{audioTrack:this._audioTrack,avcTrack:this._avcTrack,textTrack:this._txtTrack,id3Track:this._id3Track},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t},e.extractRemainingSamples=function(t){var e,r=t.audioTrack,i=t.avcTrack,a=t.id3Track,n=i.pesData,s=r.pesData,o=a.pesData;n&&(e=V(n))?(this.parseAVCPES(e,!0),i.pesData=null):i.pesData=n,s&&(e=V(s))?(r.isAAC?this.parseAACPES(e):this.parseMPEGPES(e),r.pesData=null):(null!=s&&s.size&&f.b.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=s),o&&(e=V(o))?(this.parseID3PES(e),a.pesData=null):a.pesData=o},e.demuxSampleAes=function(t,e,r){var i=this.demux(t,r,!0,!this.config.progressive),a=this.sampleAes=new U(this.observer,this.config,e);return this.decrypt(i,a)},e.decrypt=function(t,e){return new Promise((function(r){var i=t.audioTrack,a=t.avcTrack;i.samples&&i.isAAC?e.decryptAacSamples(i.samples,0,(function(){a.samples?e.decryptAvcSamples(a.samples,0,0,(function(){r(t)})):r(t)})):a.samples&&e.decryptAvcSamples(a.samples,0,0,(function(){r(t)}))}))},e.destroy=function(){this._initPTS=this._initDTS=null,this._duration=0},e.parseAVCPES=function(t,e){var r,i=this,a=this._avcTrack,n=this.parseAVCNALu(t.data),s=this.avcSample,l=!1;t.data=null,s&&n.length&&!a.audFound&&(W(s,a),s=this.avcSample=K(!1,t.pts,t.dts,"")),n.forEach((function(e){switch(e.type){case 1:r=!0,s||(s=i.avcSample=K(!0,t.pts,t.dts,"")),s.frame=!0;var n=e.data;if(l&&n.length>4){var u=new N(n).readSliceType();2!==u&&4!==u&&7!==u&&9!==u||(s.key=!0)}break;case 5:r=!0,s||(s=i.avcSample=K(!0,t.pts,t.dts,"")),s.key=!0,s.frame=!0;break;case 6:r=!0;var h=new N(q(e.data));h.readUByte();for(var d=0,c=0,f=!1,g=0;!f&&h.bytesAvailable>1;){d=0;do{d+=g=h.readUByte()}while(255===g);c=0;do{c+=g=h.readUByte()}while(255===g);if(4===d&&0!==h.bytesAvailable){if(f=!0,181===h.readUByte())if(49===h.readUShort())if(1195456820===h.readUInt())if(3===h.readUByte()){for(var v=h.readUByte(),p=31&v,m=[v,h.readUByte()],y=0;y16){for(var T=[],E=0;E<16;E++)T.push(h.readUByte().toString(16)),3!==E&&5!==E&&7!==E&&9!==E||T.push("-");for(var b=c-16,S=new Uint8Array(b),L=0;L=0){var d={data:t.subarray(u,l-n-1),type:h};o.push(d)}else{var c=this.getLastNalUnit();if(c&&(s&&l<=4-s&&c.state&&(c.data=c.data.subarray(0,c.data.byteLength-s)),(r=l-n-1)>0)){var f=new Uint8Array(c.data.byteLength+r);f.set(c.data,0),f.set(t.subarray(0,r),c.data.byteLength),c.data=f}}l=0&&n>=0){var g={data:t.subarray(u,i),type:h,state:n};o.push(g)}if(0===o.length){var v=this.getLastNalUnit();if(v){var p=new Uint8Array(v.data.byteLength+t.byteLength);p.set(v.data,0),p.set(t,v.data.byteLength),v.data=p}}return a.naluState=n,o},e.parseAACPES=function(t){var e,r,n,s,o=this._audioTrack,l=this.aacLastPTS,u=this.aacOverFlow,h=t.data;if(u){var d=new Uint8Array(u.byteLength+h.byteLength);d.set(u,0),d.set(h,u.byteLength),h=d}for(e=0,r=h.length;e1&&(f.b.log("[tsdemuxer]: AAC: align PTS for overlapping frames by "+Math.round((p-c)/90)),c=p)}for(var y=null;e1;){var l=new Uint8Array(o[0].length+o[1].length);l.set(o[0]),l.set(o[1],o[0].length),o[0]=l,o.splice(1,1)}if(1===((e=o[0])[0]<<16)+(e[1]<<8)+e[2]){if((r=(e[4]<<8)+e[5])&&r>t.size-6)return null;var u=e[7];192&u&&(a=536870912*(14&e[9])+4194304*(255&e[10])+16384*(254&e[11])+128*(255&e[12])+(254&e[13])/2,64&u?a-(n=536870912*(14&e[14])+4194304*(255&e[15])+16384*(254&e[16])+128*(255&e[17])+(254&e[18])/2)>54e5&&(f.b.warn(Math.round((a-n)/9e4)+"s delta between PTS and DTS, align them"),a=n):n=a);var h=(i=e[8])+9;if(t.size<=h)return null;t.size-=h;for(var d=new Uint8Array(t.size),c=0,g=o.length;cv){h-=v;continue}e=e.subarray(h),v-=h,h=0}d.set(e,s),s+=v}return r&&(r-=i+3),{data:d,pts:a,dts:n,len:r}}return null}function W(t,e){if(t.units.length&&t.frame){if(void 0===t.pts){var r=e.samples,i=r.length;if(!i)return void e.dropped++;var a=r[i-1];t.pts=a.pts,t.dts=a.dts}e.samples.push(t)}t.debug.length&&f.b.log(t.pts+"/"+t.dts+":"+t.debug)}function Y(t,e){var r=t.length;if(r>0){if(e.pts>=t[r-1].pts)t.push(e);else for(var i=r-1;i>=0;i--)if(e.pts0?this.lastEndDTS=p:(f.b.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());var m=!!c.audio,y=!!c.video,T="";m&&(T+="audio"),y&&(T+="video");var E={data1:h,startPTS:v,startDTS:v,endPTS:p,endDTS:p,type:T,hasAudio:m,hasVideo:y,nb:1,dropped:0};return u.audio="audio"===E.type?E:void 0,u.video="audio"!==E.type?E:void 0,u.text=i,u.id3=r,u.initSegment=d,u},t}(),et=function(t,e,r){return Object(l.d)(t,e)-r};function rt(t,e){var r=null==t?void 0:t.codec;return r&&r.length>4?r:"hvc1"===r?"hvc1.1.c.L120.90":"av01"===r?"av01.0.04M.08":"avc1"===r||e===Z.a.VIDEO?"avc1.42e01e":"mp4a.40.5"}var it,at=tt,nt=r(12);try{it=self.performance.now.bind(self.performance)}catch(t){f.b.debug("Unable to use Performance API on this environment"),it=self.Date.now}var st=[{demux:X,remux:J.a},{demux:D,remux:at},{demux:A,remux:J.a},{demux:$,remux:J.a}],ot=1024;st.forEach((function(t){var e=t.demux;ot=Math.max(ot,e.minProbeByteLength)}));var lt=function(){function t(t,e,r,i){this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.cache=new nt.a,this.observer=t,this.typeSupported=e,this.config=r,this.vendor=i}var e=t.prototype;return e.configure=function(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()},e.push=function(t,e,r,i){var a=this,n=r.transmuxing;n.executeStart=it();var s=new Uint8Array(t),o=this.cache,u=this.config,h=this.currentTransmuxState,d=this.transmuxConfig;i&&(this.currentTransmuxState=i);var c=function(t,e){var r=null;t.byteLength>0&&null!=e&&null!=e.key&&null!==e.iv&&null!=e.method&&(r=e);return r}(s,e);if(c&&"AES-128"===c.method){var f=this.getDecrypter();if(!u.enableSoftwareAES)return this.decryptionPromise=f.webCryptoDecrypt(s,c.key.buffer,c.iv.buffer).then((function(t){var e=a.push(t,null,r);return a.decryptionPromise=null,e})),this.decryptionPromise;var g=f.softwareDecrypt(s,c.key.buffer,c.iv.buffer);if(!g)return n.executeEnd=it(),ut(r);s=new Uint8Array(g)}var v=i||h,p=v.contiguous,m=v.discontinuity,y=v.trackSwitch,T=v.accurateTimeOffset,E=v.timeOffset,b=d.audioCodec,S=d.videoCodec,L=d.defaultInitPts,A=d.duration,R=d.initSegmentData;if((m||y)&&this.resetInitSegment(R,b,S,A),m&&this.resetInitialTimestamp(L),p||this.resetContiguity(),this.needsProbing(s,m,y)){if(o.dataLength){var D=o.flush();s=Object(l.a)(D,s)}this.configureTransmuxer(s,d)}var k=this.transmux(s,c,E,T,r),_=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,n.executeEnd=it(),k},e.flush=function(t){var e=this,r=t.transmuxing;r.executeStart=it();var n=this.decrypter,s=this.cache,o=this.currentTransmuxState,l=this.decryptionPromise;if(l)return l.then((function(){return e.flush(t)}));var u=[],h=o.timeOffset;if(n){var d=n.flush();d&&u.push(this.push(d,null,t))}var c=s.dataLength;s.reset();var f=this.demuxer,g=this.remuxer;if(!f||!g)return c>=ot&&this.observer.emit(i.a.ERROR,i.a.ERROR,{type:a.b.MEDIA_ERROR,details:a.a.FRAG_PARSING_ERROR,fatal:!0,reason:"no demux matching with content found"}),r.executeEnd=it(),[ut(t)];var v=f.flush(h);return ht(v)?v.then((function(r){return e.flushRemux(u,r,t),u})):(this.flushRemux(u,v,t),u)},e.flushRemux=function(t,e,r){var i=e.audioTrack,a=e.avcTrack,n=e.id3Track,s=e.textTrack,o=this.currentTransmuxState,l=o.accurateTimeOffset,u=o.timeOffset;f.b.log("[transmuxer.ts]: Flushed fragment "+r.sn+(r.part>-1?" p: "+r.part:"")+" of level "+r.level);var h=this.remuxer.remux(i,a,n,s,u,l,!0);t.push({remuxResult:h,chunkMeta:r}),r.transmuxing.executeEnd=it()},e.resetInitialTimestamp=function(t){var e=this.demuxer,r=this.remuxer;e&&r&&(e.resetTimeStamp(t),r.resetTimeStamp(t))},e.resetContiguity=function(){var t=this.demuxer,e=this.remuxer;t&&e&&(t.resetContiguity(),e.resetNextTimestamp())},e.resetInitSegment=function(t,e,r,i){var a=this.demuxer,n=this.remuxer;a&&n&&(a.resetInitSegment(e,r,i),n.resetInitSegment(t,e,r))},e.destroy=function(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)},e.transmux=function(t,e,r,i,a){return e&&"SAMPLE-AES"===e.method?this.transmuxSampleAes(t,e,r,i,a):this.transmuxUnencrypted(t,r,i,a)},e.transmuxUnencrypted=function(t,e,r,i){var a=this.demuxer.demux(t,e,!1,!this.config.progressive),n=a.audioTrack,s=a.avcTrack,o=a.id3Track,l=a.textTrack;return{remuxResult:this.remuxer.remux(n,s,o,l,e,r,!1),chunkMeta:i}},e.transmuxSampleAes=function(t,e,r,i,a){var n=this;return this.demuxer.demuxSampleAes(t,e,r).then((function(t){return{remuxResult:n.remuxer.remux(t.audioTrack,t.avcTrack,t.id3Track,t.textTrack,r,i,!1),chunkMeta:a}}))},e.configureTransmuxer=function(t,e){for(var r,i=this.config,a=this.observer,n=this.typeSupported,s=this.vendor,o=e.audioCodec,l=e.defaultInitPts,u=e.duration,h=e.initSegmentData,d=e.videoCodec,c=0,g=st.length;c>>8^255&p^99,t[f]=p,e[p]=f;var m=c[f],y=c[m],T=c[y],E=257*c[p]^16843008*p;i[f]=E<<24|E>>>8,a[f]=E<<16|E>>>16,n[f]=E<<8|E>>>24,s[f]=E,E=16843009*T^65537*y^257*m^16843008*f,l[p]=E<<24|E>>>8,u[p]=E<<16|E>>>16,h[p]=E<<8|E>>>24,d[p]=E,f?(f=m^c[c[c[T^m]]],g^=c[c[g]]):f=g=1}},e.expandKey=function(t){for(var e=this.uint8ArrayToUint32Array_(t),r=!0,i=0;i1?r-1:0),a=1;a>24&255,o[1]=e>>16&255,o[2]=e>>8&255,o[3]=255&e,o.set(t,4),n=0,e=8;n>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,85,196,0,0]))},t.mdia=function(e){return t.box(t.types.mdia,t.mdhd(e.timescale,e.duration),t.hdlr(e.type),t.minf(e))},t.mfhd=function(e){return t.box(t.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,255&e]))},t.minf=function(e){return"audio"===e.type?t.box(t.types.minf,t.box(t.types.smhd,t.SMHD),t.DINF,t.stbl(e)):t.box(t.types.minf,t.box(t.types.vmhd,t.VMHD),t.DINF,t.stbl(e))},t.moof=function(e,r,i){return t.box(t.types.moof,t.mfhd(e),t.traf(i,r))},t.moov=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trak(e[r]);return t.box.apply(null,[t.types.moov,t.mvhd(e[0].timescale,e[0].duration)].concat(i).concat(t.mvex(e)))},t.mvex=function(e){for(var r=e.length,i=[];r--;)i[r]=t.trex(e[r]);return t.box.apply(null,[t.types.mvex].concat(i))},t.mvhd=function(e,r){r*=e;var i=Math.floor(r/(n+1)),a=Math.floor(r%(n+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,255&e,i>>24,i>>16&255,i>>8&255,255&i,a>>24,a>>16&255,a>>8&255,255&a,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return t.box(t.types.mvhd,s)},t.sdtp=function(e){var r,i,a=e.samples||[],n=new Uint8Array(4+a.length);for(r=0;r>>8&255),n.push(255&a),n=n.concat(Array.prototype.slice.call(i));for(r=0;r>>8&255),s.push(255&a),s=s.concat(Array.prototype.slice.call(i));var o=t.box(t.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|e.sps.length].concat(n).concat([e.pps.length]).concat(s))),l=e.width,u=e.height,h=e.pixelRatio[0],d=e.pixelRatio[1];return t.box(t.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,255&l,u>>8&255,255&u,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,t.box(t.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),t.box(t.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,255&h,d>>24,d>>16&255,d>>8&255,255&d])))},t.esds=function(t){var e=t.config.length;return new Uint8Array([0,0,0,0,3,23+e,0,1,0,4,15+e,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([e]).concat(t.config).concat([6,1,2]))},t.mp4a=function(e){var r=e.samplerate;return t.box(t.types.mp4a,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]),t.box(t.types.esds,t.esds(e)))},t.mp3=function(e){var r=e.samplerate;return t.box(t.types[".mp3"],new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,255&r,0,0]))},t.stsd=function(e){return"audio"===e.type?e.isAAC||"mp3"!==e.codec?t.box(t.types.stsd,t.STSD,t.mp4a(e)):t.box(t.types.stsd,t.STSD,t.mp3(e)):t.box(t.types.stsd,t.STSD,t.avc1(e))},t.tkhd=function(e){var r=e.id,i=e.duration*e.timescale,a=e.width,s=e.height,o=Math.floor(i/(n+1)),l=Math.floor(i%(n+1));return t.box(t.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,255&r,0,0,0,0,o>>24,o>>16&255,o>>8&255,255&o,l>>24,l>>16&255,l>>8&255,255&l,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,s>>8&255,255&s,0,0]))},t.traf=function(e,r){var i=t.sdtp(e),a=e.id,s=Math.floor(r/(n+1)),o=Math.floor(r%(n+1));return t.box(t.types.traf,t.box(t.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,255&a])),t.box(t.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,255&s,o>>24,o>>16&255,o>>8&255,255&o])),t.trun(e,i.length+16+20+8+16+8+8),i)},t.trak=function(e){return e.duration=e.duration||4294967295,t.box(t.types.trak,t.tkhd(e),t.mdia(e))},t.trex=function(e){var r=e.id;return t.box(t.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,255&r,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))},t.trun=function(e,r){var i,a,n,s,o,l,u=e.samples||[],h=u.length,d=12+16*h,c=new Uint8Array(d);for(r+=8+d,c.set([0,0,15,1,h>>>24&255,h>>>16&255,h>>>8&255,255&h,r>>>24&255,r>>>16&255,r>>>8&255,255&r],0),i=0;i>>24&255,n>>>16&255,n>>>8&255,255&n,s>>>24&255,s>>>16&255,s>>>8&255,255&s,o.isLeading<<2|o.dependsOn,o.isDependedOn<<6|o.hasRedundancy<<4|o.paddingValue<<1|o.isNonSync,61440&o.degradPrio,15&o.degradPrio,l>>>24&255,l>>>16&255,l>>>8&255,255&l],12+16*i);return t.box(t.types.trun,c)},t.initSegment=function(e){t.types||t.init();var r=t.moov(e),i=new Uint8Array(t.FTYP.byteLength+r.byteLength);return i.set(t.FTYP),i.set(r,t.FTYP.byteLength),i},t}();s.types=void 0,s.HDLR_TYPES=void 0,s.STTS=void 0,s.STSC=void 0,s.STCO=void 0,s.STSZ=void 0,s.VMHD=void 0,s.SMHD=void 0,s.STSD=void 0,s.FTYP=void 0,s.DINF=void 0;var o=s,l=r(0),u=r(2),h=r(1),d=r(7);function c(){return(c=Object.assign||function(t){for(var e=1;e0?t:r.pts}),t[0].pts);return e&&h.b.debug("PTS rollover detected"),r},e.remux=function(t,e,r,i,a,n,s){var o,l,u,d,c,f,g=a,v=a,p=t.pid>-1,y=e.pid>-1,T=t.samples.length>0,E=e.samples.length>1;if((!p||T)&&(!y||E)||this.ISGenerated||s){this.ISGenerated||(u=this.generateIS(t,e,a));var b=this.isVideoContiguous;if(E&&!b&&this.config.forceKeyFrameOnDiscontinuity){var S=e.samples.length,L=function(t){for(var e=0;e0){h.b.warn("[mp4-remuxer]: Dropped "+L+" out of "+S+" video samples due to a missing keyframe");var A=this.getVideoStartPts(e.samples);e.samples=e.samples.slice(L),e.dropped+=L,v+=(e.samples[0].pts-A)/(e.timescale||9e4)}else-1===L&&(h.b.warn("[mp4-remuxer]: No keyframe found out of "+S+" video samples"),f=!1)}if(this.ISGenerated){if(T&&E){var R=this.getVideoStartPts(e.samples),D=(m(t.samples[0].pts,R)-R)/e.inputTimeScale;g+=Math.max(0,D),v+=Math.max(0,-D)}if(T){if(t.samplerate||(h.b.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),delete(u=this.generateIS(t,e,a)).video),l=this.remuxAudio(t,g,this.isAudioContiguous,n,E?v:void 0),E){var k=l?l.endPTS-l.startPTS:0;e.inputTimeScale||(h.b.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),u=this.generateIS(t,e,a)),o=this.remuxVideo(e,v,b,k)}}else E&&(o=this.remuxVideo(e,v,b,0));o&&void 0!==f&&(o.independent=f)}}return this.ISGenerated&&(r.samples.length&&(c=this.remuxID3(r,a)),i.samples.length&&(d=this.remuxText(i,a))),{audio:l,video:o,initSegment:u,independent:f,text:d,id3:c}},e.generateIS=function(t,e,r){var a,n,s,l=t.samples,u=e.samples,h=this.typeSupported,d={},c=!Object(i.a)(this._initPTS),f="audio/mp4";if(c&&(a=n=1/0),t.config&&l.length&&(t.timescale=t.samplerate,t.isAAC||(h.mpeg?(f="audio/mpeg",t.codec=""):h.mp3&&(t.codec="mp3")),d.audio={id:"audio",container:f,codec:t.codec,initSegment:!t.isAAC&&h.mpeg?new Uint8Array(0):o.initSegment([t]),metadata:{channelCount:t.channelCount}},c&&(s=t.inputTimeScale,a=n=l[0].pts-Math.round(s*r))),e.sps&&e.pps&&u.length&&(e.timescale=e.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:e.codec,initSegment:o.initSegment([e]),metadata:{width:e.width,height:e.height}},c)){s=e.inputTimeScale;var g=this.getVideoStartPts(u),v=Math.round(s*r);n=Math.min(n,m(u[0].dts,g)-v),a=Math.min(a,g-v)}if(Object.keys(d).length)return this.ISGenerated=!0,c&&(this._initPTS=a,this._initDTS=n),{tracks:d,initPTS:a,timescale:s}},e.remuxVideo=function(t,e,r,i){var a,n,s,g=t.inputTimeScale,p=t.samples,T=[],E=p.length,b=this._initPTS,S=this.nextAvcDts,L=8,A=Number.POSITIVE_INFINITY,R=Number.NEGATIVE_INFINITY,D=0,k=!1;r&&null!==S||(S=e*g-(p[0].pts-m(p[0].dts,p[0].pts)));for(var _=0;_I.pts){D=Math.max(Math.min(D,I.pts-I.dts),-18e3)}I.dts0?_-1:_].dts&&(k=!0)}k&&p.sort((function(t,e){var r=t.dts-e.dts,i=t.pts-e.pts;return r||i})),n=p[0].dts,s=p[p.length-1].dts;var C=Math.round((s-n)/(E-1));if(D<0){if(D<-2*C){h.b.warn("PTS < DTS detected in video samples, offsetting DTS from PTS by "+Object(d.b)(-C,!0)+" ms");for(var w=D,O=0;OC;if(M||P<-1){M?h.b.warn("AVC: "+Object(d.b)(P,!0)+" ms ("+P+"dts) hole between fragments detected, filling it"):h.b.warn("AVC: "+Object(d.b)(-P,!0)+" ms ("+P+"dts) overlapping between fragments detected"),n=S;var F=p[0].pts-P;p[0].dts=n,p[0].pts=F,h.b.log("Video: First PTS/DTS adjusted: "+Object(d.b)(F,!0)+"/"+Object(d.b)(n,!0)+", delta: "+Object(d.b)(P,!0)+" ms")}}v&&(n=Math.max(0,n));for(var N=0,U=0,B=0;B0?X-1:X].dts;if(it.stretchShortVideoTrack&&null!==this.nextAudioPts){var nt=Math.floor(it.maxBufferHole*g),st=(i?A+i*g:this.nextAudioPts)-z.pts;st>nt?((a=st-at)<0&&(a=at),h.b.log("[mp4-remuxer]: It is approximately "+st/90+" ms to the next segment; using duration "+a/90+" ms for the last video frame.")):a=at}else a=at}var ot=Math.round(z.pts-z.dts);T.push(new y(z.key,a,$,ot))}if(T.length&&f&&f<70){var lt=T[0].flags;lt.dependsOn=2,lt.isNonSync=0}this.nextAvcDts=S=s+a,this.isVideoContiguous=!0;var ut={data1:o.moof(t.sequenceNumber++,n,c({},t,{samples:T})),data2:W,startPTS:A/g,endPTS:(R+a)/g,startDTS:n/g,endDTS:S/g,type:"video",hasAudio:!1,hasVideo:!0,nb:T.length,dropped:t.dropped};return t.samples=[],t.dropped=0,ut},e.remuxAudio=function(t,e,r,i,n){var s,d=t.inputTimeScale,f=d/(t.samplerate?t.samplerate:d),g=t.isAAC?1024:1152,v=g*f,p=this._initPTS,T=!t.isAAC&&this.typeSupported.mpeg,E=[],b=t.samples,S=T?0:8,L=this.nextAudioPts||-1,A=e*d;if(this.isAudioContiguous=r=r||b.length&&L>0&&(i&&Math.abs(A-L)<9e3||Math.abs(m(b[0].pts-p,A)-L)<20*v),b.forEach((function(t){t.pts=t.dts=m(t.pts-p,A)})),!r||L<0){if(!(b=b.filter((function(t){return t.pts>=0}))).length)return;L=0===n?0:i?Math.max(0,A):b[0].pts}if(t.isAAC)for(var R=this.config.maxAudioFramesDrift,D=0,k=L;D0?(h.b.warn("[mp4-remuxer]: Dropping 1 audio frame @ "+(k/d).toFixed(3)+"s due to "+Math.round(w)+" ms overlap."),b.splice(D,1)):(h.b.warn("Audio frame @ "+(I/d).toFixed(3)+"s overlaps nextAudioPts by "+Math.round(1e3*C/d)+" ms."),k=I+v,D++);else if(C>=R*v&&w<1e4&&void 0!==n){var O=Math.floor(C/v);k=I-O*v,h.b.warn("[mp4-remuxer]: Injecting "+O+" audio frame @ "+(k/d).toFixed(3)+"s due to "+Math.round(1e3*C/d)+" ms gap.");for(var x=0;x0&&W<1e4)Y=Math.round((V-L)/v),h.b.log("[mp4-remuxer]: "+W+" ms hole between AAC samples detected,filling it"),Y>0&&((s=a.getSilentFrame(t.manifestCodec||t.codec,t.channelCount))||(s=H.subarray()),U+=Y*s.length);else if(W<-12){h.b.log("[mp4-remuxer]: drop overlapping AAC sample, expected/parsed/delta:"+(L/d).toFixed(3)+"s/"+(V/d).toFixed(3)+"s/"+-W+"ms"),U-=H.byteLength;continue}V=L}if(F=V,!(U>0))return;U+=S;try{M=new Uint8Array(U)}catch(t){return void this.observer.emit(l.a.ERROR,l.a.ERROR,{type:u.b.MUX_ERROR,details:u.a.REMUX_ALLOC_ERROR,fatal:!1,bytes:U,reason:"fail allocating audio mdat "+U})}T||(new DataView(M.buffer).setUint32(0,U),M.set(o.types.mdat,4));for(var q=0;q4294967296;)t+=r;return t}var y=function(t,e,r,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=e,this.size=r,this.cts=i,this.flags=new T(t)},T=function(t){this.isLeading=0,this.isDependedOn=0,this.hasRedundancy=0,this.degradPrio=0,this.dependsOn=1,this.isNonSync=1,this.dependsOn=t?2:1,this.isNonSync=t?0:1}},function(t,e,r){"use strict";r.d(e,"a",(function(){return n}));var i=r(10);function a(t,e){for(var r=0;r0}),!1)}t.exports=function(t,e){e=e||{};var a={main:r.m},o=e.all?{main:Object.keys(a.main)}:function(t,e){for(var r={main:[e]},i={main:[]},a={main:{}};s(r);)for(var o=Object.keys(r),l=0;lt.endSN||e>0||0===e&&r>0,this.updated||this.advanced?this.misses=Math.floor(.6*t.misses):this.misses=t.misses+1,this.availabilityDelay=t.availabilityDelay},e=t,(r=[{key:"hasProgramDateTime",get:function(){return!!this.fragments.length&&Object(a.a)(this.fragments[this.fragments.length-1].programDateTime)}},{key:"levelTargetDuration",get:function(){return this.averagetargetduration||this.targetduration||10}},{key:"drift",get:function(){var t=this.driftEndTime-this.driftStartTime;return t>0?1e3*(this.driftEnd-this.driftStart)/t:1}},{key:"edge",get:function(){return this.partEnd||this.fragmentEnd}},{key:"partEnd",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}},{key:"fragmentEnd",get:function(){var t;return null!==(t=this.fragments)&&void 0!==t&&t.length?this.fragments[this.fragments.length-1].end:0}},{key:"age",get:function(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}},{key:"lastPartIndex",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].index:-1}},{key:"lastPartSn",get:function(){var t;return null!==(t=this.partList)&&void 0!==t&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}])&&h(e.prototype,r),i&&h(e,i),t}(),c=r(16),f=/^(\d+)x(\d+)$/,g=/\s*(.+?)\s*=((?:\".*?\")|.*?)(?:,|$)/g,v=function(){function t(e){for(var r in"string"==typeof e&&(e=t.parseAttrList(e)),e)e.hasOwnProperty(r)&&(this[r]=e[r])}var e=t.prototype;return e.decimalInteger=function(t){var e=parseInt(this[t],10);return e>Number.MAX_SAFE_INTEGER?1/0:e},e.hexadecimalInteger=function(t){if(this[t]){var e=(this[t]||"0x").slice(2);e=(1&e.length?"0":"")+e;for(var r=new Uint8Array(e.length/2),i=0;iNumber.MAX_SAFE_INTEGER?1/0:e},e.decimalFloatingPoint=function(t){return parseFloat(this[t])},e.optionalFloat=function(t,e){var r=this[t];return r?parseFloat(r):e},e.enumeratedString=function(t){return this[t]},e.bool=function(t){return"YES"===this[t]},e.decimalResolution=function(t){var e=f.exec(this[t]);if(null!==e)return{width:parseInt(e[1],10),height:parseInt(e[2],10)}},t.parseAttrList=function(t){var e,r={};for(g.lastIndex=0;null!==(e=g.exec(t));){var i=e[2];0===i.indexOf('"')&&i.lastIndexOf('"')===i.length-1&&(i=i.slice(1,-1)),r[e[1]]=i}return r},t}(),p={audio:{a3ds:!0,"ac-3":!0,"ac-4":!0,alac:!0,alaw:!0,dra1:!0,"dts+":!0,"dts-":!0,dtsc:!0,dtse:!0,dtsh:!0,"ec-3":!0,enca:!0,g719:!0,g726:!0,m4ae:!0,mha1:!0,mha2:!0,mhm1:!0,mhm2:!0,mlpa:!0,mp4a:!0,"raw ":!0,Opus:!0,samr:!0,sawb:!0,sawp:!0,sevc:!0,sqcp:!0,ssmv:!0,twos:!0,ulaw:!0},video:{avc1:!0,avc2:!0,avc3:!0,avc4:!0,avcp:!0,av01:!0,drac:!0,dvav:!0,dvhe:!0,encv:!0,hev1:!0,hvc1:!0,mjp2:!0,mp4v:!0,mvc1:!0,mvc2:!0,mvc3:!0,mvc4:!0,resv:!0,rv60:!0,s263:!0,svc1:!0,svc2:!0,"vc-1":!0,vp08:!0,vp09:!0},text:{stpp:!0,wvtt:!0}};function m(t,e){return MediaSource.isTypeSupported((e||"video")+'/mp4;codecs="'+t+'"')}var y=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-SESSION-DATA:([^\r\n]*)[\r\n]+/g,T=/#EXT-X-MEDIA:(.*)/g,E=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[\S ]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),b=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(PLAYLIST-TYPE):(.+)/.source,/#EXT-X-(MEDIA-SEQUENCE): *(\d+)/.source,/#EXT-X-(SKIP):(.+)/.source,/#EXT-X-(TARGETDURATION): *(\d+)/.source,/#EXT-X-(KEY):(.+)/.source,/#EXT-X-(START):(.+)/.source,/#EXT-X-(ENDLIST)/.source,/#EXT-X-(DISCONTINUITY-SEQ)UENCE: *(\d+)/.source,/#EXT-X-(DIS)CONTINUITY/.source,/#EXT-X-(VERSION):(\d+)/.source,/#EXT-X-(MAP):(.+)/.source,/#EXT-X-(SERVER-CONTROL):(.+)/.source,/#EXT-X-(PART-INF):(.+)/.source,/#EXT-X-(GAP)/.source,/#EXT-X-(BITRATE):\s*(\d+)/.source,/#EXT-X-(PART):(.+)/.source,/#EXT-X-(PRELOAD-HINT):(.+)/.source,/#EXT-X-(RENDITION-REPORT):(.+)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),S=/\.(mp4|m4s|m4v|m4a)$/i;var L,A,R=function(){function t(){}return t.findGroup=function(t,e){for(var r=0;r2){var r=e.shift()+".";return r+=parseInt(e.shift()).toString(16),r+=("000"+parseInt(e.shift()).toString(16)).substr(-4)}return t},t.resolve=function(t,e){return i.buildAbsoluteURL(e,t,{alwaysNormalize:!0})},t.parseMasterPlaylist=function(e,r){var i,a=[],n={},s=!1;for(y.lastIndex=0;null!=(i=y.exec(e));)if(i[1]){var o=new v(i[1]),l={attrs:o,bitrate:o.decimalInteger("AVERAGE-BANDWIDTH")||o.decimalInteger("BANDWIDTH"),name:o.NAME,url:t.resolve(i[2],r)},u=o.decimalResolution("RESOLUTION");u&&(l.width=u.width,l.height=u.height),D((o.CODECS||"").split(/[ ,]+/).filter((function(t){return t})),l),l.videoCodec&&-1!==l.videoCodec.indexOf("avc1")&&(l.videoCodec=t.convertAVC1ToAVCOTI(l.videoCodec)),a.push(l)}else if(i[3]){var h=new v(i[3]);h["DATA-ID"]&&(s=!0,n[h["DATA-ID"]]=h)}return{levels:a,sessionData:s?n:null}},t.parseMasterPlaylistMedia=function(e,r,i,a){var n;void 0===a&&(a=[]);var s=[],o=0;for(T.lastIndex=0;null!==(n=T.exec(e));){var l=new v(n[1]);if(l.TYPE===i){var u={attrs:l,bitrate:0,id:o++,groupId:l["GROUP-ID"],instreamId:l["INSTREAM-ID"],name:l.NAME||l.LANGUAGE||"",type:i,default:l.bool("DEFAULT"),autoselect:l.bool("AUTOSELECT"),forced:l.bool("FORCED"),lang:l.LANGUAGE,url:l.URI?t.resolve(l.URI,r):""};if(a.length){var h=t.findGroup(a,u.groupId)||a[0];k(u,h,"audioCodec"),k(u,h,"textCodec")}s.push(u)}}return s},t.parseLevelPlaylist=function(t,e,r,n,s){var l,h,f,g=new d(e),p=g.fragments,m=0,y=0,T=0,L=0,A=null,R=new u.b(n,e),D=-1;for(E.lastIndex=0,g.m3u8=t;null!==(l=E.exec(t));){var k=l[1];if(k){R.duration=parseFloat(k);var I=(" "+l[2]).slice(1);R.title=I||null,R.tagList.push(I?["INF",k,I]:["INF",k])}else if(l[3])Object(a.a)(R.duration)&&(R.start=T,f&&(R.levelkey=f),R.sn=m,R.level=r,R.cc=L,R.urlId=s,p.push(R),R.relurl=(" "+l[3]).slice(1),_(R,A),A=R,T+=R.duration,m++,y=0,(R=new u.b(n,e)).start=T,R.sn=m,R.cc=L,R.level=r);else if(l[4]){var C=(" "+l[4]).slice(1);A?R.setByteRange(C,A):R.setByteRange(C)}else if(l[5])R.rawProgramDateTime=(" "+l[5]).slice(1),R.tagList.push(["PROGRAM-DATE-TIME",R.rawProgramDateTime]),-1===D&&(D=p.length);else{if(!(l=l[0].match(b))){o.b.warn("No matches on slow regex match for level playlist!");continue}for(h=1;h-1){o.b.warn("Keyformat "+W+" is not supported from the manifest");continue}if("identity"!==W)continue;G&&(f=c.a.fromURL(e,K),K&&["AES-128","SAMPLE-AES","SAMPLE-AES-CENC"].indexOf(G)>=0&&(f.method=G,f.keyFormat=W,V&&(f.keyID=V),H&&(f.keyFormatVersions=H),f.iv=j));break;case"START":var Y=new v(O).decimalFloatingPoint("TIME-OFFSET");Object(a.a)(Y)&&(g.startTimeOffset=Y);break;case"MAP":var q=new v(O);R.relurl=q.URI,q.BYTERANGE&&R.setByteRange(q.BYTERANGE),R.level=r,R.sn="initSegment",f&&(R.levelkey=f),g.initSegment=R,(R=new u.b(n,e)).rawProgramDateTime=g.initSegment.rawProgramDateTime;break;case"SERVER-CONTROL":var X=new v(O);g.canBlockReload=X.bool("CAN-BLOCK-RELOAD"),g.canSkipUntil=X.optionalFloat("CAN-SKIP-UNTIL",0),g.canSkipDateRanges=g.canSkipUntil>0&&X.bool("CAN-SKIP-DATERANGES"),g.partHoldBack=X.optionalFloat("PART-HOLD-BACK",0),g.holdBack=X.optionalFloat("HOLD-BACK",0);break;case"PART-INF":var z=new v(O);g.partTarget=z.decimalFloatingPoint("PART-TARGET");break;case"PART":var Q=g.partList;Q||(Q=g.partList=[]);var $=y>0?Q[Q.length-1]:void 0,J=y++,Z=new u.c(new v(O),R,e,J,$);Q.push(Z),R.duration+=Z.duration;break;case"PRELOAD-HINT":var tt=new v(O);g.preloadHint=tt;break;case"RENDITION-REPORT":var et=new v(O);g.renditionReports=g.renditionReports||[],g.renditionReports.push(et);break;default:o.b.warn("line parsed but not handled: "+l)}}}A&&!A.relurl?(p.pop(),T-=A.duration,g.partList&&(g.fragmentHint=A)):g.partList&&(_(R,A),R.cc=L,g.fragmentHint=R);var rt=p.length,it=p[0],at=p[rt-1];if((T+=g.skippedSegments*g.targetduration)>0&&rt&&at){g.averagetargetduration=T/rt;var nt=at.sn;g.endSN="initSegment"!==nt?nt:0,it&&(g.startCC=it.cc,g.initSegment||g.fragments.every((function(t){return t.relurl&&(e=t.relurl,S.test(null!=(r=null===(a=i.parseURL(e))||void 0===a?void 0:a.path)?r:""));var e,r,a}))&&(o.b.warn("MP4 fragments found but no init segment (probably no MAP, incomplete M3U8), trying to fetch SIDX"),(R=new u.b(n,e)).relurl=at.relurl,R.level=r,R.sn="initSegment",g.initSegment=R,g.needSidxRanges=!0))}else g.endSN=0,g.startCC=0;return g.fragmentHint&&(T+=g.fragmentHint.duration),g.totalduration=T,g.endCC=L,D>0&&function(t,e){for(var r=t[e],i=e;i--;){var a=t[i];if(!a)return;a.programDateTime=r.programDateTime-1e3*a.duration,r=a}}(p,D),g},t}();function D(t,e){["video","audio","text"].forEach((function(r){var i=t.filter((function(t){return function(t,e){var r=p[e];return!!r&&!0===r[t.slice(0,4)]}(t,r)}));if(i.length){var a=i.filter((function(t){return 0===t.lastIndexOf("avc1",0)||0===t.lastIndexOf("mp4a",0)}));e[r+"Codec"]=a.length>0?a[0]:i[0],t=t.filter((function(t){return-1===i.indexOf(t)}))}})),e.unknownCodecs=t}function k(t,e,r){var i=e[r];i&&(t[r]=i)}function _(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):null!=e&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),Object(a.a)(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function I(t,e){var r=t.url;return void 0!==r&&0!==r.indexOf("data:")||(r=e.url),r}!function(t){t.MANIFEST="manifest",t.LEVEL="level",t.AUDIO_TRACK="audioTrack",t.SUBTITLE_TRACK="subtitleTrack"}(L||(L={})),function(t){t.MAIN="main",t.AUDIO="audio",t.SUBTITLE="subtitle"}(A||(A={}));var C=function(){function t(t){this.hls=void 0,this.loaders=Object.create(null),this.hls=t,this.registerListeners()}var e=t.prototype;return e.registerListeners=function(){var t=this.hls;t.on(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.on(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.on(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MANIFEST_LOADING,this.onManifestLoading,this),t.off(n.a.LEVEL_LOADING,this.onLevelLoading,this),t.off(n.a.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(n.a.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)},e.createInternalLoader=function(t){var e=this.hls.config,r=e.pLoader,i=e.loader,a=new(r||i)(e);return t.loader=a,this.loaders[t.type]=a,a},e.getInternalLoader=function(t){return this.loaders[t.type]},e.resetInternalLoader=function(t){this.loaders[t]&&delete this.loaders[t]},e.destroyInternalLoaders=function(){for(var t in this.loaders){var e=this.loaders[t];e&&e.destroy(),this.resetInternalLoader(t)}},e.destroy=function(){this.unregisterListeners(),this.destroyInternalLoaders()},e.onManifestLoading=function(t,e){var r=e.url;this.load({id:null,groupId:null,level:0,responseType:"text",type:L.MANIFEST,url:r,deliveryDirectives:null})},e.onLevelLoading=function(t,e){var r=e.id,i=e.level,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:null,level:i,responseType:"text",type:L.LEVEL,url:a,deliveryDirectives:n})},e.onAudioTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:L.AUDIO_TRACK,url:a,deliveryDirectives:n})},e.onSubtitleTrackLoading=function(t,e){var r=e.id,i=e.groupId,a=e.url,n=e.deliveryDirectives;this.load({id:r,groupId:i,level:null,responseType:"text",type:L.SUBTITLE_TRACK,url:a,deliveryDirectives:n})},e.load=function(t){var e,r,i,a,n,s,l=this.hls.config,u=this.getInternalLoader(t);if(u){var h=u.context;if(h&&h.url===t.url)return void o.b.trace("[playlist-loader]: playlist request ongoing");o.b.log("[playlist-loader]: aborting previous loader for type: "+t.type),u.abort()}switch(t.type){case L.MANIFEST:r=l.manifestLoadingMaxRetry,i=l.manifestLoadingTimeOut,a=l.manifestLoadingRetryDelay,n=l.manifestLoadingMaxRetryTimeout;break;case L.LEVEL:case L.AUDIO_TRACK:case L.SUBTITLE_TRACK:r=0,i=l.levelLoadingTimeOut;break;default:r=l.levelLoadingMaxRetry,i=l.levelLoadingTimeOut,a=l.levelLoadingRetryDelay,n=l.levelLoadingMaxRetryTimeout}if((u=this.createInternalLoader(t),null!==(e=t.deliveryDirectives)&&void 0!==e&&e.part)&&(t.type===L.LEVEL&&null!==t.level?s=this.hls.levels[t.level].details:t.type===L.AUDIO_TRACK&&null!==t.id?s=this.hls.audioTracks[t.id].details:t.type===L.SUBTITLE_TRACK&&null!==t.id&&(s=this.hls.subtitleTracks[t.id].details),s)){var d=s.partTarget,c=s.targetduration;d&&c&&(i=Math.min(1e3*Math.max(3*d,.8*c),i))}var f={timeout:i,maxRetry:r,retryDelay:a,maxRetryDelay:n,highWaterMark:0},g={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};u.load(t,f,g)},e.loadsuccess=function(t,e,r,i){if(void 0===i&&(i=null),r.isSidxRequest)return this.handleSidxRequest(t,r),void this.handlePlaylistLoaded(t,e,r,i);this.resetInternalLoader(r.type);var a=t.data;0===a.indexOf("#EXTM3U")?(e.parsing.start=performance.now(),a.indexOf("#EXTINF:")>0||a.indexOf("#EXT-X-TARGETDURATION:")>0?this.handleTrackOrLevelPlaylist(t,e,r,i):this.handleMasterPlaylist(t,e,r,i)):this.handleManifestParsingError(t,r,"no EXTM3U delimiter",i)},e.loaderror=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!1,t)},e.loadtimeout=function(t,e,r){void 0===r&&(r=null),this.handleNetworkError(e,r,!0)},e.handleMasterPlaylist=function(t,e,r,i){var a=this.hls,s=t.data,l=I(t,r),u=R.parseMasterPlaylist(s,l),h=u.levels,d=u.sessionData;if(h.length){var c=h.map((function(t){return{id:t.attrs.AUDIO,audioCodec:t.audioCodec}})),f=h.map((function(t){return{id:t.attrs.SUBTITLES,textCodec:t.textCodec}})),g=R.parseMasterPlaylistMedia(s,l,"AUDIO",c),p=R.parseMasterPlaylistMedia(s,l,"SUBTITLES",f),m=R.parseMasterPlaylistMedia(s,l,"CLOSED-CAPTIONS");if(g.length)g.some((function(t){return!t.url}))||!h[0].audioCodec||h[0].attrs.AUDIO||(o.b.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),g.unshift({type:"main",name:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new v({}),bitrate:0,url:""}));a.trigger(n.a.MANIFEST_LOADED,{levels:h,audioTracks:g,subtitles:p,captions:m,url:l,stats:e,networkDetails:i,sessionData:d})}else this.handleManifestParsingError(t,r,"no level found in manifest",i)},e.handleTrackOrLevelPlaylist=function(t,e,r,i){var o=this.hls,l=r.id,u=r.level,h=r.type,d=I(t,r),c=Object(a.a)(l)?l:0,f=Object(a.a)(u)?u:c,g=function(t){switch(t.type){case L.AUDIO_TRACK:return A.AUDIO;case L.SUBTITLE_TRACK:return A.SUBTITLE;default:return A.MAIN}}(r),p=R.parseLevelPlaylist(t.data,d,f,g,c);if(p.fragments.length){if(h===L.MANIFEST){var m={attrs:new v({}),bitrate:0,details:p,name:"",url:d};o.trigger(n.a.MANIFEST_LOADED,{levels:[m],audioTracks:[],url:d,stats:e,networkDetails:i,sessionData:null})}if(e.parsing.end=performance.now(),p.needSidxRanges){var y=p.initSegment.url;this.load({url:y,isSidxRequest:!0,type:h,level:u,levelDetails:p,id:l,groupId:null,rangeStart:0,rangeEnd:2048,responseType:"arraybuffer",deliveryDirectives:null})}else r.levelDetails=p,this.handlePlaylistLoaded(t,e,r,i)}else o.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.LEVEL_EMPTY_ERROR,fatal:!1,url:d,reason:"no fragments found in level",level:"number"==typeof r.level?r.level:void 0})},e.handleSidxRequest=function(t,e){var r=Object(l.g)(new Uint8Array(t.data));if(r){var i=r.references,a=e.levelDetails;i.forEach((function(t,e){var r=t.info,i=a.fragments[e];0===i.byteRange.length&&i.setByteRange(String(1+r.end-r.start)+"@"+String(r.start))})),a.initSegment.setByteRange(String(r.moovEndOffset)+"@0")}},e.handleManifestParsingError=function(t,e,r,i){this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.MANIFEST_PARSING_ERROR,fatal:e.type===L.MANIFEST,url:t.url,reason:r,response:t,context:e,networkDetails:i})},e.handleNetworkError=function(t,e,r,i){void 0===r&&(r=!1),o.b.warn("[playlist-loader]: A network "+(r?"timeout":"error")+" occurred while loading "+t.type+" level: "+t.level+" id: "+t.id+' group-id: "'+t.groupId+'"');var a=s.a.UNKNOWN,l=!1,u=this.getInternalLoader(t);switch(t.type){case L.MANIFEST:a=r?s.a.MANIFEST_LOAD_TIMEOUT:s.a.MANIFEST_LOAD_ERROR,l=!0;break;case L.LEVEL:a=r?s.a.LEVEL_LOAD_TIMEOUT:s.a.LEVEL_LOAD_ERROR,l=!1;break;case L.AUDIO_TRACK:a=r?s.a.AUDIO_TRACK_LOAD_TIMEOUT:s.a.AUDIO_TRACK_LOAD_ERROR,l=!1;break;case L.SUBTITLE_TRACK:a=r?s.a.SUBTITLE_TRACK_LOAD_TIMEOUT:s.a.SUBTITLE_LOAD_ERROR,l=!1}u&&this.resetInternalLoader(t.type);var h={type:s.b.NETWORK_ERROR,details:a,fatal:l,url:t.url,loader:u,context:t,networkDetails:e};i&&(h.response=i),this.hls.trigger(n.a.ERROR,h)},e.handlePlaylistLoaded=function(t,e,r,i){var a=r.type,s=r.level,o=r.id,l=r.groupId,u=r.loader,h=r.levelDetails,d=r.deliveryDirectives;if(null!=h&&h.targetduration){if(u)switch(h.live&&(u.getCacheAge&&(h.ageHeader=u.getCacheAge()||0),u.getCacheAge&&!isNaN(h.ageHeader)||(h.ageHeader=0)),a){case L.MANIFEST:case L.LEVEL:this.hls.trigger(n.a.LEVEL_LOADED,{details:h,level:s||0,id:o||0,stats:e,networkDetails:i,deliveryDirectives:d});break;case L.AUDIO_TRACK:this.hls.trigger(n.a.AUDIO_TRACK_LOADED,{details:h,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:d});break;case L.SUBTITLE_TRACK:this.hls.trigger(n.a.SUBTITLE_TRACK_LOADED,{details:h,id:o||0,groupId:l||"",stats:e,networkDetails:i,deliveryDirectives:d})}}else this.handleManifestParsingError(t,r,"invalid target duration",i)},t}(),w=function(){function t(t){this.hls=void 0,this.loaders={},this.decryptkey=null,this.decrypturl=null,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){this.hls.on(n.a.KEY_LOADING,this.onKeyLoading,this)},e._unregisterListeners=function(){this.hls.off(n.a.KEY_LOADING,this.onKeyLoading)},e.destroy=function(){for(var t in this._unregisterListeners(),this.loaders){var e=this.loaders[t];e&&e.destroy()}this.loaders={}},e.onKeyLoading=function(t,e){var r=e.frag,i=r.type,a=this.loaders[i];if(r.decryptdata){var s=r.decryptdata.uri;if(s!==this.decrypturl||null===this.decryptkey){var l=this.hls.config;if(a&&(o.b.warn("abort previous key loader for type:"+i),a.abort()),!s)return void o.b.warn("key uri is falsy");var u=l.loader,h=r.loader=this.loaders[i]=new u(l);this.decrypturl=s,this.decryptkey=null;var d={url:s,frag:r,responseType:"arraybuffer"},c={timeout:l.fragLoadingTimeOut,maxRetry:0,retryDelay:l.fragLoadingRetryDelay,maxRetryDelay:l.fragLoadingMaxRetryTimeout,highWaterMark:0},f={onSuccess:this.loadsuccess.bind(this),onError:this.loaderror.bind(this),onTimeout:this.loadtimeout.bind(this)};h.load(d,c,f)}else this.decryptkey&&(r.decryptdata.key=this.decryptkey,this.hls.trigger(n.a.KEY_LOADED,{frag:r}))}else o.b.warn("Missing decryption data on fragment in onKeyLoading")},e.loadsuccess=function(t,e,r){var i=r.frag;i.decryptdata?(this.decryptkey=i.decryptdata.key=new Uint8Array(t.data),i.loader=null,delete this.loaders[i.type],this.hls.trigger(n.a.KEY_LOADED,{frag:i})):o.b.error("after key load, decryptdata unset")},e.loaderror=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_ERROR,fatal:!1,frag:r,response:t})},e.loadtimeout=function(t,e){var r=e.frag,i=r.loader;i&&i.abort(),delete this.loaders[r.type],this.hls.trigger(n.a.ERROR,{type:s.b.NETWORK_ERROR,details:s.a.KEY_LOAD_TIMEOUT,fatal:!1,frag:r})},t}();function O(t,e){var r;try{r=new Event("addtrack")}catch(t){(r=document.createEvent("Event")).initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function x(t,e){var r=t.mode;if("disabled"===r&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error("addCue is failed for: "+e)}catch(r){o.b.debug("[texttrack-utils]: "+r);var i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}"disabled"===r&&(t.mode=r)}function P(t){var e=t.mode;if("disabled"===e&&(t.mode="hidden"),t.cues){for(var r=t.cues.length;r--;)t.removeCue(t.cues[r]);"disabled"===e&&(t.mode=e)}}function M(t,e,r){var i=t.mode;if("disabled"===i&&(t.mode="hidden"),t.cues&&t.cues.length){for(var a=function(t,e,r){var i=[],a=function(t,e){if(et[r].endTime)return-1;var i=0,a=r;for(;i<=a;){var n=Math.floor((a+i)/2);if(et[n].startTime&&i-1)for(var n=a,s=t.length;n=e&&o.endTime<=r)i.push(o);else if(o.startTime>r)return i}return i}(t.cues,e,r),n=0;n.05&&this.forwardBufferLength>1){var u=Math.min(2,Math.max(1,n)),h=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;t.playbackRate=Math.min(u,Math.max(1,h))}else 1!==t.playbackRate&&0!==t.playbackRate&&(t.playbackRate=1)}}}}},a.estimateLiveEdge=function(){var t=this.levelDetails;return null===t?null:t.edge+t.age},a.computeLatency=function(){var t=this.estimateLiveEdge();return null===t?null:t-this.currentTime},e=t,(r=[{key:"latency",get:function(){return this._latency||0}},{key:"maxLatency",get:function(){var t=this.config,e=this.levelDetails;return void 0!==t.liveMaxLatencyDuration?t.liveMaxLatencyDuration:e?t.liveMaxLatencyDurationCount*e.targetduration:0}},{key:"targetLatency",get:function(){var t=this.levelDetails;if(null===t)return null;var e=t.holdBack,r=t.partHoldBack,i=t.targetduration,a=this.config,n=a.liveSyncDuration,s=a.liveSyncDurationCount,o=a.lowLatencyMode,l=this.hls.userConfig,u=o&&r||e;(l.liveSyncDuration||l.liveSyncDurationCount||0===u)&&(u=void 0!==n?n:s*i);var h=i;return u+Math.min(1*this.stallCount,h)}},{key:"liveSyncPosition",get:function(){var t=this.estimateLiveEdge(),e=this.targetLatency,r=this.levelDetails;if(null===t||null===e||null===r)return null;var i=r.edge,a=t-e-this.edgeStalled,n=i-r.totalduration,s=i-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(n,a),s)}},{key:"drift",get:function(){var t=this.levelDetails;return null===t?1:t.drift}},{key:"edgeStalled",get:function(){var t=this.levelDetails;if(null===t)return 0;var e=3*(this.config.lowLatencyMode&&t.partTarget||t.targetduration);return Math.max(t.age-e,0)}},{key:"forwardBufferLength",get:function(){var t=this.media,e=this.levelDetails;if(!t||!e)return 0;var r=t.buffered.length;return r?t.buffered.end(r-1):e.edge-this.currentTime}}])&&U(e.prototype,r),i&&U(e,i),t}();function K(t,e){for(var r=0;rt.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else if(e.sn>t.sn){t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration}else e.start=Math.max(t.start-e.duration,0)}function q(t,e,r,i,n,s){i-r<=0&&(o.b.warn("Fragment should have a positive duration",e),i=r+e.duration,s=n+e.duration);var l=r,u=i,h=e.startPTS,d=e.endPTS;if(Object(a.a)(h)){var c=Math.abs(h-r);Object(a.a)(e.deltaPTS)?e.deltaPTS=Math.max(c,e.deltaPTS):e.deltaPTS=c,l=Math.max(r,h),r=Math.min(r,h),n=Math.min(n,e.startDTS),u=Math.min(i,d),i=Math.max(i,d),s=Math.max(s,e.endDTS)}e.duration=i-r;var f=r-e.start;e.appendedPTS=i,e.start=e.startPTS=r,e.maxStartPTS=l,e.startDTS=n,e.endPTS=i,e.minEndPTS=u,e.endDTS=s;var g,v=e.sn;if(!t||vt.endSN)return 0;var p=v-t.startSN,m=t.fragments;for(m[p]=e,g=p;g>0;g--)Y(m[g],m[g-1]);for(g=p;g=i.length)){var n=i[r].start;if(n){for(var s=e.skippedSegments;se.partTarget&&(l+=1)}if(Object(a.a)(o))return new j(o,Object(a.a)(l)?l:void 0,B.No)}}},e.loadPlaylist=function(t){},e.shouldLoadTrack=function(t){return this.canLoad&&t&&!!t.url&&(!t.details||t.details.live)},e.playlistLoaded=function(t,e,r){var i=this,a=e.details,n=e.stats,s=n.loading.end?Math.max(0,self.performance.now()-n.loading.end):0;if(a.advancedDateTime=Date.now()-s,a.live||null!=r&&r.live){if(a.reloaded(r),r&&this.log("live playlist "+t+" "+(a.advanced?"REFRESHED "+a.lastPartSn+"-"+a.lastPartIndex:"MISSED")),r&&a.fragments.length>0&&X(r,a),!this.canLoad||!a.live)return;var o=void 0,l=void 0;if(a.canBlockReload&&a.endSN&&a.advanced){var u=this.hls.config.lowLatencyMode,h=a.lastPartIndex;u?(o=-1!==h?a.lastPartSn:a.endSN+1,l=-1!==h?h+1:void 0):(o=-1!==h?a.lastPartSn+1:a.endSN+1,l=-1!==h?0:void 0);var d=a.age,c=d+a.ageHeader,f=Math.min(c-a.partTarget,1.5*a.targetduration);if(f>0){if(r&&f>r.tuneInGoal)this.warn("CDN Tune-in goal increased from: "+r.tuneInGoal+" to: "+f+" with playlist age: "+a.age),f=0;else{var g=Math.floor(f/a.targetduration);if(o+=g,void 0!==l)l+=Math.round(f%a.targetduration/a.partTarget);this.log("CDN Tune-in age: "+a.ageHeader+"s last advanced "+d.toFixed(2)+"s goal: "+f+" skip sn "+g+" to part "+l)}a.tuneInGoal=f}var v=this.getDeliveryDirectives(a,e.deliveryDirectives,o,l);return void this.loadPlaylist(v)}var p=function(t,e){var r,i=1e3*t.levelTargetDuration,a=i/2,n=t.age,s=n>0&&n<3*i,o=e.loading.end-e.loading.start,l=t.availabilityDelay;if(!1===t.updated)if(s){var u=333*t.misses;r=Math.max(Math.min(a,2*o),u),t.availabilityDelay=(t.availabilityDelay||0)+r}else r=a;else s?(l=Math.min(l||i/2,n),t.availabilityDelay=l,r=l+i-n):r=i-o;return Math.round(r)}(a,n);this.log("reload live playlist "+t+" in "+Math.round(p)+" ms");var m=this.getDeliveryDirectives(a,e.deliveryDirectives,o,l);this.timer=self.setTimeout((function(){return i.loadPlaylist(m)}),p)}else this.clearTimer()},e.getDeliveryDirectives=function(t,e,r,i){var a=function(t,e){var r=t.canSkipUntil,i=t.canSkipDateRanges,a=t.endSN;return r&&(void 0!==e?e-a:0)-1&&null!==(e=t.context)&&void 0!==e&&e.deliveryDirectives)this.warn("retry playlist loading #"+this.retryCount+' after "'+t.details+'"'),this.loadPlaylist();else{var n=Math.min(Math.pow(2,this.retryCount)*i.levelLoadingRetryDelay,i.levelLoadingMaxRetryTimeout);this.timer=self.setTimeout((function(){return r.loadPlaylist()}),n),this.warn("retry playlist loading #"+this.retryCount+" in "+n+' ms after "'+t.details+'"')}else this.warn('cannot recover from error "'+t.details+'"'),this.clearTimer(),t.fatal=!0;return a},t}();function $(){return($=Object.assign||function(t){for(var e=1;e0){r=a[0].bitrate,a.sort((function(t,e){return t.bitrate-e.bitrate})),this._levels=a;for(var f=0;fthis.hls.config.fragLoadingMaxRetry&&(n=r.frag.level)):n=r.frag.level}break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:i&&(i.deliveryDirectives&&(l=!1),n=i.level),o=!0;break;case s.a.REMUX_ALLOC_ERROR:n=r.level,o=!0}void 0!==n&&this.recoverLevel(r,n,o,l)}}},u.recoverLevel=function(t,e,r,i){var a=t.details,n=this._levels[e];if(n.loadError++,r){if(!this.retryLoadingOrFail(t))return void(this.currentLevelIndex=-1);t.levelRetry=!0}if(i){var s=n.url.length;if(s>1&&n.loadError1){var i=(e.urlId+1)%r;this.warn("Switching to redundant URL-id "+i),this._levels.forEach((function(t){t.urlId=i})),this.level=t}},u.onFragLoaded=function(t,e){var r=e.frag;if(void 0!==r&&r.type===A.MAIN){var i=this._levels[r.level];void 0!==i&&(i.fragmentError=0,i.loadError=0)}},u.onLevelLoaded=function(t,e){var r,i,a=e.level,n=e.details,s=this._levels[a];if(!s)return this.warn("Invalid level index "+a),void(null!==(i=e.deliveryDirectives)&&void 0!==i&&i.skip&&(n.deltaUpdateFailed=!0));a===this.currentLevelIndex?(0===s.fragmentError&&(s.loadError=0,this.retryCount=0),this.playlistLoaded(a,e,s.details)):null!==(r=e.deliveryDirectives)&&void 0!==r&&r.skip&&(n.deltaUpdateFailed=!0)},u.onAudioTrackSwitched=function(t,e){var r=this.hls.levels[this.currentLevelIndex];if(r&&r.audioGroupIds){for(var i=-1,a=this.hls.audioTracks[e.id].groupId,n=0;n0){var i=r.urlId,a=r.url[i];if(t)try{a=t.addDirectives(a)}catch(t){this.warn("Could not construct new URL with HLS Delivery Directives: "+t)}this.log("Attempt loading level index "+e+(t?" at sn "+t.msn+" part "+t.part:"")+" with URL-id "+i+" "+a),this.clearTimer(),this.hls.trigger(n.a.LEVEL_LOADING,{url:a,level:e,id:i,deliveryDirectives:t||null})}},u.removeLevel=function(t,e){var r=function(t,r){return r!==e},i=this._levels.filter((function(i,a){return a!==t||i.url.length>1&&void 0!==e&&(i.url=i.url.filter(r),i.audioGroupIds&&(i.audioGroupIds=i.audioGroupIds.filter(r)),i.textGroupIds&&(i.textGroupIds=i.textGroupIds.filter(r)),i.urlId=0,!0)})).map((function(t,e){var r=t.details;return null!=r&&r.fragments&&r.fragments.forEach((function(t){t.level=e})),t}));this._levels=i,this.hls.trigger(n.a.LEVELS_UPDATED,{levels:i})},a=i,(o=[{key:"levels",get:function(){return 0===this._levels.length?null:this._levels}},{key:"level",get:function(){return this.currentLevelIndex},set:function(t){var e,r=this._levels;if(0!==r.length&&(this.currentLevelIndex!==t||null===(e=r[t])||void 0===e||!e.details)){if(t<0||t>=r.length){var i=t<0;if(this.hls.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.LEVEL_SWITCH_ERROR,level:t,fatal:i,reason:"invalid level idx"}),i)return;t=Math.min(t,r.length-1)}this.clearTimer();var a=this.currentLevelIndex,o=r[a],l=r[t];this.log("switching to level "+t+" from "+a),this.currentLevelIndex=t;var u=$({},l,{level:t,maxBitrate:l.maxBitrate,uri:l.uri,urlId:l.urlId});delete u._urlId,this.hls.trigger(n.a.LEVEL_SWITCHING,u);var h=l.details;if(!h||h.live){var d=this.switchParams(l.uri,null==o?void 0:o.details);this.loadPlaylist(d)}}}},{key:"manualLevel",get:function(){return this.manualLevelIndex},set:function(t){this.manualLevelIndex=t,void 0===this._startLevel&&(this._startLevel=t),-1!==t&&(this.level=t)}},{key:"firstLevel",get:function(){return this._firstLevel},set:function(t){this._firstLevel=t}},{key:"startLevel",get:function(){if(void 0===this._startLevel){var t=this.hls.config.startLevel;return void 0!==t?t:this._firstLevel}return this._startLevel},set:function(t){this._startLevel=t}},{key:"nextLoadLevel",get:function(){return-1!==this.manualLevelIndex?this.manualLevelIndex:this.hls.nextAutoLevel},set:function(t){this.level=t,-1===this.manualLevelIndex&&(this.hls.nextAutoLevel=t)}}])&&J(a.prototype,o),l&&J(a,l),i}(Q);!function(t){t.NOT_LOADED="NOT_LOADED",t.BACKTRACKED="BACKTRACKED",t.APPENDING="APPENDING",t.PARTIAL="PARTIAL",t.OK="OK"}(tt||(tt={}));var it=function(){function t(t){this.activeFragment=null,this.activeParts=null,this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hls=t,this._registerListeners()}var e=t.prototype;return e._registerListeners=function(){var t=this.hls;t.on(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.on(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.on(n.a.FRAG_LOADED,this.onFragLoaded,this)},e._unregisterListeners=function(){var t=this.hls;t.off(n.a.BUFFER_APPENDED,this.onBufferAppended,this),t.off(n.a.FRAG_BUFFERED,this.onFragBuffered,this),t.off(n.a.FRAG_LOADED,this.onFragLoaded,this)},e.destroy=function(){this._unregisterListeners(),this.fragments=this.timeRanges=null},e.getAppendedFrag=function(t,e){if(e===A.MAIN){var r=this.activeFragment,i=this.activeParts;if(!r)return null;if(i)for(var a=i.length;a--;){var n=i[a],s=n?n.end:r.appendedPTS;if(n.start<=t&&void 0!==s&&t<=s)return a>9&&(this.activeParts=i.slice(a-9)),n}else if(r.start<=t&&void 0!==r.appendedPTS&&t<=r.appendedPTS)return r}return this.getBufferedFrag(t,e)},e.getBufferedFrag=function(t,e){for(var r=this.fragments,i=Object.keys(r),a=i.length;a--;){var n=r[i[a]];if((null==n?void 0:n.body.type)===e&&n.buffered){var s=n.body;if(s.start<=t&&t<=s.end)return s}}return null},e.detectEvictedFragments=function(t,e){var r=this;Object.keys(this.fragments).forEach((function(i){var a=r.fragments[i];if(a&&a.buffered){var n=a.range[t];n&&n.time.some((function(t){var i=!r.isTimeBuffered(t.startPTS,t.endPTS,e);return i&&r.removeFragment(a.body),i}))}}))},e.detectPartialFragments=function(t){var e=this,r=this.timeRanges,i=t.frag,a=t.part;if(r&&"initSegment"!==i.sn){var n=nt(i),s=this.fragments[n];s&&(Object.keys(r).forEach((function(t){var n=i.elementaryStreams[t];if(n){var o=r[t],l=null!==a||!0===n.partial;s.range[t]=e.getBufferedTimes(i,a,l,o)}})),s.backtrack=s.loaded=null,Object.keys(s.range).length?s.buffered=!0:this.removeFragment(s.body))}},e.getBufferedTimes=function(t,e,r,i){for(var a={time:[],partial:r},n=e?e.start:t.start,s=e?e.end:t.end,o=t.minEndPTS||s,l=t.maxStartPTS||n,u=0;u=h&&o<=d){a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});break}if(nh)a.partial=!0,a.time.push({startPTS:Math.max(n,i.start(u)),endPTS:Math.min(s,i.end(u))});else if(s<=h)break}return a},e.getPartialFragment=function(t){var e,r,i,a=null,n=0,s=this.bufferPadding,o=this.fragments;return Object.keys(o).forEach((function(l){var u=o[l];u&&at(u)&&(r=u.body.start-s,i=u.body.end+s,t>=r&&t<=i&&(e=Math.min(t-r,i-t),n<=e&&(a=u.body,n=e)))})),a},e.getState=function(t){var e=nt(t),r=this.fragments[e];return r?r.buffered?at(r)?tt.PARTIAL:tt.OK:r.backtrack?tt.BACKTRACKED:tt.APPENDING:tt.NOT_LOADED},e.backtrack=function(t,e){var r=nt(t),i=this.fragments[r];if(!i||i.backtrack)return null;var a=i.backtrack=e||i.loaded;return i.loaded=null,a},e.getBacktrackData=function(t){var e=nt(t),r=this.fragments[e];if(r){var i,a=r.backtrack;if(null!=a&&null!==(i=a.payload)&&void 0!==i&&i.byteLength)return a;this.removeFragment(t)}return null},e.isTimeBuffered=function(t,e,r){for(var i,a,n=0;n=i&&e<=a)return!0;if(e<=i)return!1}return!1},e.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if("initSegment"!==r.sn&&!r.bitrateTest&&!i){var a=nt(r);this.fragments[a]={body:r,loaded:e,backtrack:null,buffered:!1,range:Object.create(null)}}},e.onBufferAppended=function(t,e){var r=this,i=e.frag,a=e.part,n=e.timeRanges;if(i.type===A.MAIN)if(this.activeFragment=i,a){var s=this.activeParts;s||(this.activeParts=s=[]),s.push(a)}else this.activeParts=null;this.timeRanges=n,Object.keys(n).forEach((function(t){var e=n[t];if(r.detectEvictedFragments(t,e),!a)for(var s=0;s1&&(this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)),this._tickCallCount=0)},e.doTick=function(){},t}(),ot={length:0,start:function(){return 0},end:function(){return 0}},lt=function(){function t(){}return t.isBuffered=function(e,r){try{if(e)for(var i=t.getBuffered(e),a=0;a=i.start(a)&&r<=i.end(a))return!0}catch(t){}return!1},t.bufferInfo=function(e,r,i){try{if(e){var a,n=t.getBuffered(e),s=[];for(a=0;as&&(i[n-1].end=t[a].end):i.push(t[a])}else i.push(t[a])}else i=t;for(var o,l=0,u=e,h=e,d=0;d=c&&er.startCC||t&&t.cc0)r=a+1;else{if(!(s<0))return n;i=a-1}}return null}};function vt(t,e,r){if(null===e||!Array.isArray(t)||!t.length||!Object(a.a)(e))return null;if(e<(t[0].programDateTime||0))return null;if(e>=(t[t.length-1].endProgramDateTime||0))return null;r=r||0;for(var i=0;it&&r.start?-1:0}function yt(t,e,r){var i=1e3*Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return(r.endProgramDateTime||0)-i>t}function Tt(t){var e="function"==typeof Map?new Map:void 0;return(Tt=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return Et(t,arguments,Lt(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),St(i,t)})(t)}function Et(t,e,r){return(Et=bt()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&St(a,r.prototype),a}).apply(null,arguments)}function bt(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function St(t,e){return(St=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function Lt(t){return(Lt=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var At=Math.pow(2,17),Rt=function(){function t(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}var e=t.prototype;return e.destroy=function(){this.loader&&(this.loader.destroy(),this.loader=null)},e.abort=function(){this.loader&&this.loader.abort()},e.load=function(t,e){var r=this,i=t.url;if(!i)return Promise.reject(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,networkDetails:null},"Fragment does not have a "+(i?"part list":"url")));this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(i,l){r.loader&&r.loader.destroy();var u=r.loader=t.loader=n?new n(a):new o(a),h=Dt(t),d={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:At};t.stats=u.stats,u.load(h,d,{onSuccess:function(e,a,n,s){r.resetLoader(t,u),i({frag:t,part:null,payload:e.data,networkDetails:s})},onError:function(e,i,a){r.resetLoader(t,u),l(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:e,networkDetails:a}))},onAbort:function(e,i,a){r.resetLoader(t,u),l(new kt({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,networkDetails:a}))},onTimeout:function(e,i,a){r.resetLoader(t,u),l(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,networkDetails:a}))},onProgress:function(r,i,a,n){e&&e({frag:t,part:null,payload:a,networkDetails:n})}})}))},e.loadPart=function(t,e,r){var i=this;this.abort();var a=this.config,n=a.fLoader,o=a.loader;return new Promise((function(l,u){i.loader&&i.loader.destroy();var h=i.loader=t.loader=n?new n(a):new o(a),d=Dt(t,e),c={timeout:a.fragLoadingTimeOut,maxRetry:0,retryDelay:0,maxRetryDelay:a.fragLoadingMaxRetryTimeout,highWaterMark:At};e.stats=h.stats,h.load(d,c,{onSuccess:function(a,n,s,o){i.resetLoader(t,h),i.updateStatsFromPart(t,e);var u={frag:t,part:e,payload:a.data,networkDetails:o};r(u),l(u)},onError:function(r,a,n){i.resetLoader(t,h),u(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:e,response:r,networkDetails:n}))},onAbort:function(r,a,n){t.stats.aborted=e.stats.aborted,i.resetLoader(t,h),u(new kt({type:s.b.NETWORK_ERROR,details:s.a.INTERNAL_ABORTED,fatal:!1,frag:t,part:e,networkDetails:n}))},onTimeout:function(r,a,n){i.resetLoader(t,h),u(new kt({type:s.b.NETWORK_ERROR,details:s.a.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:e,networkDetails:n}))}})}))},e.updateStatsFromPart=function(t,e){var r=t.stats,i=e.stats,a=i.total;if(r.loaded+=i.loaded,a){var n=Math.round(t.duration/e.duration),s=Math.min(Math.round(r.loaded/a),n),o=(n-s)*Math.round(r.loaded/s);r.total=r.loaded+o}else r.total=Math.max(r.loaded,r.total);var l=r.loading,u=i.loading;l.start?l.first+=u.first-u.start:(l.start=u.start,l.first=u.first),l.end=u.end},e.resetLoader=function(t,e){t.loader=null,this.loader===e&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),e.destroy()},t}();function Dt(t,e){void 0===e&&(e=null);var r=e||t,i={frag:t,part:e,responseType:"arraybuffer",url:r.url,rangeStart:0,rangeEnd:0},n=r.byteRangeStartOffset,s=r.byteRangeEndOffset;return Object(a.a)(n)&&Object(a.a)(s)&&(i.rangeStart=n,i.rangeEnd=s),i}var kt=function(t){var e,r;function i(e){for(var r,i=arguments.length,a=new Array(i>1?i-1:0),n=1;nh)&&(e.loader&&(this.log("seeking outside of buffer while fragment load in progress, cancel fragment load"),e.loader.abort()),this.resetLoadingState())}r&&(this.lastCurrentTime=s),this.loadedmetadata||o.len||(this.nextLoadPosition=this.startPosition=s),this.tick()},c.onMediaEnded=function(){this.startPosition=this.lastCurrentTime=0},c.onKeyLoaded=function(t,e){if(this.state===Pt&&this.levels){this.state=xt;var r=this.levels[e.frag.level].details;r&&this.loadFragment(e.frag,r,e.frag.start)}},c.onHandlerDestroying=function(){this.stopLoad(),t.prototype.onHandlerDestroying.call(this)},c.onHandlerDestroyed=function(){this.state=Ot,this.hls.off(n.a.KEY_LOADED,this.onKeyLoaded,this),this.fragmentLoader&&this.fragmentLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.fragmentLoader=this.fragmentTracker=null,t.prototype.onHandlerDestroyed.call(this)},c.loadFragment=function(t,e,r){this._loadFragForPlayback(t,e,r)},c._loadFragForPlayback=function(t,e,r){var i=this;this._doFragLoad(t,e,r,(function(e){if(i.fragContextChanged(t))return i.warn("Fragment "+t.sn+(e.part?" p: "+e.part.index:"")+" of level "+t.level+" was dropped during download."),void i.fragmentTracker.removeFragment(t);t.stats.chunkCount++,i._handleFragmentLoadProgress(e)})).then((function(e){if(e){i.fragLoadError=0;var r=i.state;if(!i.fragContextChanged(t))return"payload"in e&&(i.log("Loaded fragment "+t.sn+" of level "+t.level),i.hls.trigger(n.a.FRAG_LOADED,e),i.state===Gt)?(i.fragmentTracker.backtrack(t,e),void i.resetFragmentLoading(t)):void i._handleFragmentLoadComplete(e);(r===Mt||r===Gt||!i.fragCurrent&&r===Ut)&&(i.fragmentTracker.removeFragment(t),i.state=xt)}})).catch((function(e){i.warn(e),i.resetFragmentLoading(t)}))},c.flushMainBuffer=function(t,e,r){void 0===r&&(r=null);var i={startOffset:t,endOffset:e,type:r};this.fragLoadError=0,this.hls.trigger(n.a.BUFFER_FLUSHING,i)},c._loadInitSegment=function(t){var e=this;this._doFragLoad(t).then((function(r){if(!r||e.fragContextChanged(t)||!e.levels)throw new Error("init load aborted");return r})).then((function(r){var i=e.hls,a=r.payload,s=t.decryptdata;if(a&&a.byteLength>0&&s&&s.key&&s.iv&&"AES-128"===s.method){var o=self.performance.now();return e.decrypter.webCryptoDecrypt(new Uint8Array(a),s.key.buffer,s.iv.buffer).then((function(e){var a=self.performance.now();return i.trigger(n.a.FRAG_DECRYPTED,{frag:t,payload:e,stats:{tstart:o,tdecrypt:a}}),r.payload=e,r}))}return r})).then((function(r){var i=e.fragCurrent,a=e.hls,s=e.levels;if(!s)throw new Error("init load aborted, missing levels");var o=s[t.level].details.initSegment,l=t.stats;e.state=xt,e.fragLoadError=0,o.data=new Uint8Array(r.payload),l.parsing.start=l.buffering.start=self.performance.now(),l.parsing.end=l.buffering.end=self.performance.now(),r.frag===i&&a.trigger(n.a.FRAG_BUFFERED,{stats:l,frag:i,part:null,id:t.type}),e.tick()})).catch((function(r){e.warn(r),e.resetFragmentLoading(t)}))},c.fragContextChanged=function(t){var e=this.fragCurrent;return!t||!e||t.level!==e.level||t.sn!==e.sn||t.urlId!==e.urlId},c.fragBufferedComplete=function(t,e){var r=this.mediaBuffer?this.mediaBuffer:this.media;this.log("Buffered "+t.type+" sn: "+t.sn+(e?" part: "+e.index:"")+" of "+("[stream-controller]"===this.logPrefix?"level":"track")+" "+t.level+" "+It.toString(lt.getBuffered(r))),this.state=xt,this.tick()},c._handleFragmentLoadComplete=function(t){var e=this.transmuxer;if(e){var r=t.frag,i=t.part,a=t.partsLoaded,n=!a||0===a.length||a.some((function(t){return!t})),s=new ut(r.level,r.sn,r.stats.chunkCount+1,0,i?i.index:-1,!n);e.flush(s)}},c._handleFragmentLoadProgress=function(t){},c._doFragLoad=function(t,e,r,i){var s=this;if(void 0===r&&(r=null),!this.levels)throw new Error("frag load aborted, missing levels");if(r=Math.max(t.start,r||0),this.config.lowLatencyMode&&e){var o=e.partList;if(o&&i){r>t.end&&e.fragmentHint&&(t=e.fragmentHint);var l=this.getNextPart(o,t,r);if(l>-1){var u=o[l];return this.log("Loading part sn: "+t.sn+" p: "+u.index+" cc: "+t.cc+" of playlist ["+e.startSN+"-"+e.endSN+"] parts [0-"+l+"-"+(o.length-1)+"] "+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),this.nextLoadPosition=u.start+u.duration,this.state=Mt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,part:o[l],targetBufferTime:r}),this.doFragPartsLoad(t,o,l,i).catch((function(t){return s.handleFragLoadError(t)}))}if(!t.url||this.loadedEndOfParts(o,r))return Promise.resolve(null)}}return this.log("Loading fragment "+t.sn+" cc: "+t.cc+" "+(e?"of ["+e.startSN+"-"+e.endSN+"] ":"")+("[stream-controller]"===this.logPrefix?"level":"track")+": "+t.level+", target: "+parseFloat(r.toFixed(3))),Object(a.a)(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Mt,this.hls.trigger(n.a.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragmentLoader.load(t,i).catch((function(t){return s.handleFragLoadError(t)}))},c.doFragPartsLoad=function(t,e,r,i){var a=this;return new Promise((function(s,o){var l=[];!function r(u){var h=e[u];a.fragmentLoader.loadPart(t,h,i).then((function(i){l[h.index]=i;var o=i.part;a.hls.trigger(n.a.FRAG_LOADED,i);var d=e[u+1];if(!d||d.fragment!==t)return s({frag:t,part:o,partsLoaded:l});r(u+1)})).catch(o)}(r)}))},c.handleFragLoadError=function(t){var e=t.data;return e&&e.details===s.a.INTERNAL_ABORTED?this.handleFragLoadAborted(e.frag,e.part):this.hls.trigger(n.a.ERROR,e),null},c._handleTransmuxerFlush=function(t){var e=this.getCurrentContext(t);if(e&&this.state===Ut){var r=e.frag,i=e.part,a=e.level,n=self.performance.now();r.stats.parsing.end=n,i&&(i.stats.parsing.end=n),this.updateLevelTiming(r,i,a,t.partial)}else this.fragCurrent||(this.state=xt)},c.getCurrentContext=function(t){var e=this.levels,r=t.level,i=t.sn,a=t.part;if(!e||!e[r])return this.warn("Levels object was unset while buffering fragment "+i+" of level "+r+". The current chunk will not be buffered."),null;var n=e[r],s=a>-1?function(t,e,r){if(!t||!t.details)return null;var i=t.details.partList;if(i)for(var a=i.length;a--;){var n=i[a];if(n.index===r&&n.fragment.sn===e)return n}return null}(n,i,a):null,o=s?s.fragment:function(t,e){if(!t||!t.details)return null;var r=t.details,i=r.fragments[e-r.startSN];return i||((i=r.fragmentHint)&&i.sn===e?i:null)}(n,i);return o?{frag:o,part:s,level:n}:null},c.bufferFragmentData=function(t,e,r,i){if(t&&this.state===Ut){var a=t.data1,s=t.data2,o=a;if(a&&s&&(o=Object(l.a)(a,s)),o&&o.length){var u={type:t.type,frag:e,part:r,chunkMeta:i,parent:e.type,data:o};this.hls.trigger(n.a.BUFFER_APPENDING,u),t.dropped&&t.independent&&!r&&this.flushBufferGap(e)}}},c.flushBufferGap=function(t){var e=this.media;if(e)if(lt.isBuffered(e,e.currentTime)){var r=e.currentTime,i=lt.bufferInfo(e,r,0),a=t.duration,n=Math.min(2*this.config.maxFragLookUpTolerance,.25*a),s=Math.max(Math.min(t.start-n,i.end-n),r+n);t.start-s>n&&this.flushMainBuffer(s,t.start)}else this.flushMainBuffer(0,t.start)},c.reduceMaxBufferLength=function(t){var e=this.config,r=t||e.maxBufferLength;return e.maxMaxBufferLength>=r&&(e.maxMaxBufferLength/=2,this.warn("Reduce max buffer length to "+e.maxMaxBufferLength+"s"),!0)},c.getNextFragment=function(t,e){var r=e.fragments,i=r.length;if(!i)return null;var a,n=this.config,s=r[0].start;if(!e.initSegment||e.initSegment.data||this.bitrateTest)if(e.live){var o=n.initialLiveManifestSize;if(i-1&&rr.start&&r.loaded},c.getInitialLiveFragment=function(t,e){var r=this.fragPrevious,i=null;if(r){if(t.hasProgramDateTime&&(this.log("Live playlist, switching playlist, load frag with same PDT: "+r.programDateTime),i=vt(e,r.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){var a=r.sn+1;if(a>=t.startSN&&a<=t.endSN){var n=e[a-t.startSN];r.cc===n.cc&&(i=n,this.log("Live playlist, switching playlist, load frag with next SN: "+i.sn))}i||(i=function(t,e){return gt.search(t,(function(t){return t.cce?-1:0}))}(e,r.cc))&&this.log("Live playlist, switching playlist, load frag with same CC: "+i.sn)}}else{var s=this.hls.liveSyncPosition;null!==s&&(i=this.getFragmentAtPosition(s,this.bitrateTest?t.fragmentEnd:t.edge,t))}return i},c.getFragmentAtPosition=function(t,e,r){var i,a=this.config,n=this.fragPrevious,s=r.fragments,o=r.endSN,l=r.fragmentHint,u=a.maxFragLookUpTolerance,h=!!(a.lowLatencyMode&&r.partList&&l);(h&&l&&!this.bitrateTest&&(s=s.concat(l),o=l.sn),te-u?0:u):i=s[s.length-1];if(i){var d=i.sn-r.startSN,c=n&&i.level===n.level,f=s[d+1];if(this.fragmentTracker.getState(i)===tt.BACKTRACKED){i=null;for(var g=d;s[g]&&this.fragmentTracker.getState(s[g])===tt.BACKTRACKED;)i=n?s[g--]:s[--g];i||(i=f)}else n&&i.sn===n.sn&&!h&&c&&(i.sn=n-e.maxFragLookUpTolerance&&a<=s;if(null!==i&&r.duration>i&&(a0?(s=t.fragments[0].start,t.alignedSliding&&Object(a.a)(s)?this.log("Live playlist sliding:"+s.toFixed(3)):s||(this.warn("["+this.constructor.name+"] Live playlist - outdated PTS, unknown sliding"),ct(this.fragPrevious,n,t))):(this.log("Live playlist - first load, unknown sliding"),ct(this.fragPrevious,n,t)),s},c.waitForCdnTuneIn=function(t){return t.live&&t.canBlockReload&&t.tuneInGoal>Math.max(t.partHoldBack,3*t.partTarget)},c.setStartPosition=function(t,e){var r=this.startPosition;if(-1===this.startPosition||-1===this.lastCurrentTime){var i=t.startTimeOffset;Object(a.a)(i)?(i<0&&(this.log("Negative start time offset "+i+", count from end of last fragment"),i=e+t.totalduration+i),this.log("Start time offset found in playlist, adjust startPosition to "+i),this.startPosition=r=i):t.live?r=this.hls.liveSyncPosition||e:this.startPosition=r=0,this.lastCurrentTime=r}this.nextLoadPosition=r},c.getLoadPosition=function(){var t=this.media,e=0;return this.loadedmetadata?e=t.currentTime:this.nextLoadPosition&&(e=this.nextLoadPosition),e},c.handleFragLoadAborted=function(t,e){this.transmuxer&&"initSegment"!==t.sn&&(this.warn("Fragment "+t.sn+(e?" part"+e.index:"")+" of level "+t.level+" was aborted"),this.resetFragmentLoading(t))},c.resetFragmentLoading=function(t){this.fragCurrent&&this.fragContextChanged(t)||(this.state=xt)},c.onFragmentOrKeyLoadError=function(t,e){if(!e.fatal){var r=e.frag;if(r&&r.type===t){this.fragCurrent;var i=this.config;if(this.fragLoadError+1<=i.fragLoadingMaxRetry){if(this.resetLiveStartWhenNotLoaded(r.level))return;var a=Math.min(Math.pow(2,this.fragLoadError)*i.fragLoadingRetryDelay,i.fragLoadingMaxRetryTimeout);this.warn("Fragment "+r.sn+" of "+t+" "+r.level+" failed to load, retrying in "+a+"ms"),this.retryDate=self.performance.now()+a,this.fragLoadError++,this.state=Ft}else e.levelRetry?(t===A.AUDIO&&(this.fragCurrent=null),this.fragLoadError=0,this.state=xt):(o.b.error(e.details+" reaches max retry, redispatch as fatal ..."),e.fatal=!0,this.hls.stopLoad(),this.state=jt)}}},c.afterBufferFlushed=function(t,e){if(t){var r=lt.getBuffered(t);this.fragmentTracker.detectEvictedFragments(e,r),this.state===Kt&&this.resetLoadingState()}},c.resetLoadingState=function(){this.fragCurrent=null,this.fragPrevious=null,this.state=xt},c.resetLiveStartWhenNotLoaded=function(t){if(!this.loadedmetadata){this.startFragRequested=!1;var e=this.levels?this.levels[t].details:null;if(null!=e&&e.live)return this.startPosition=-1,this.setStartPosition(e,0),this.resetLoadingState(),!0;this.nextLoadPosition=this.startPosition}return!1},c.updateLevelTiming=function(t,e,r,i){var a=this,s=r.details;Object.keys(t.elementaryStreams).reduce((function(e,o){var l=t.elementaryStreams[o];if(l){var u=l.endPTS-l.startPTS;if(u<=0)return a.warn("Could not parse fragment "+t.sn+" "+o+" duration reliably ("+u+") resetting transmuxer to fallback to playlist timing"),a.resetTransmuxer(),e||!1;var h=i?0:q(s,t,l.startPTS,l.endPTS,l.startDTS,l.endDTS);return a.hls.trigger(n.a.LEVEL_PTS_UPDATED,{details:s,level:r,drift:h,type:o,frag:t,start:l.startPTS,end:l.endPTS}),!0}return e}),!1)?(this.state=Bt,this.hls.trigger(n.a.FRAG_PARSED,{frag:t,part:e})):this.resetLoadingState()},c.resetTransmuxer=function(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)},u=i,(h=[{key:"state",get:function(){return this._state},set:function(t){var e=this._state;e!==t&&(this._state=t,this.log(e+"->"+t))}}])&&Ct(u.prototype,h),d&&Ct(u,d),i}(st);function Yt(){return self.MediaSource||self.WebKitMediaSource}function qt(){return self.SourceBuffer||self.WebKitSourceBuffer}var Xt=r(17),zt=r(9),Qt=r(13),$t=Yt()||{isTypeSupported:function(){return!1}},Jt=function(){function t(t,e,r,i){var a=this;this.hls=void 0,this.id=void 0,this.observer=void 0,this.frag=null,this.part=null,this.worker=void 0,this.onwmsg=void 0,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.hls=t,this.id=e,this.onTransmuxComplete=r,this.onFlush=i;var l=t.config,u=function(e,r){(r=r||{}).frag=a.frag,r.id=a.id,t.trigger(e,r)};this.observer=new Qt.EventEmitter,this.observer.on(n.a.FRAG_DECRYPTED,u),this.observer.on(n.a.ERROR,u);var h={mp4:$t.isTypeSupported("video/mp4"),mpeg:$t.isTypeSupported("audio/mpeg"),mp3:$t.isTypeSupported('audio/mp4; codecs="mp3"')},d=navigator.vendor;if(l.enableWorker&&"undefined"!=typeof Worker){var c;o.b.log("demuxing in webworker");try{c=this.worker=Xt(18),this.onwmsg=this.onWorkerMessage.bind(this),c.addEventListener("message",this.onwmsg),c.onerror=function(e){t.trigger(n.a.ERROR,{type:s.b.OTHER_ERROR,details:s.a.INTERNAL_EXCEPTION,fatal:!0,event:"demuxerWorker",error:new Error(e.message+" ("+e.filename+":"+e.lineno+")")})},c.postMessage({cmd:"init",typeSupported:h,vendor:d,id:e,config:JSON.stringify(l)})}catch(t){o.b.warn("Error in worker:",t),o.b.error("Error while initializing DemuxerWorker, fallback to inline"),c&&self.URL.revokeObjectURL(c.objectURL),this.transmuxer=new zt.c(this.observer,h,l,d),this.worker=null}}else this.transmuxer=new zt.c(this.observer,h,l,d)}var e=t.prototype;return e.destroy=function(){var t=this.worker;if(t)t.removeEventListener("message",this.onwmsg),t.terminate(),this.worker=null;else{var e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}var r=this.observer;r&&r.removeAllListeners(),this.observer=null},e.push=function(t,e,r,i,a,n,s,l,u,h){var d=this;u.transmuxing.start=self.performance.now();var c=this.transmuxer,f=this.worker,g=n?n.start:a.start,v=a.decryptdata,p=this.frag,m=!(p&&a.cc===p.cc),y=!(p&&u.level===p.level),T=p?u.sn-p.sn:-1,E=this.part?u.part-this.part.index:1,b=!y&&(1===T||0===T&&1===E),S=self.performance.now();(y||T||0===a.stats.parsing.start)&&(a.stats.parsing.start=S),!n||!E&&b||(n.stats.parsing.start=S);var L=new zt.b(m,b,l,y,g);if(!b||m){o.b.log("[transmuxer-interface, "+a.type+"]: Starting new transmux session for sn: "+u.sn+" p: "+u.part+" level: "+u.level+" id: "+u.id+"\n discontinuity: "+m+"\n trackSwitch: "+y+"\n contiguous: "+b+"\n accurateTimeOffset: "+l+"\n timeOffset: "+g);var A=new zt.a(r,i,e,s,h);this.configureTransmuxer(A)}if(this.frag=a,this.part=n,f)f.postMessage({cmd:"demux",data:t,decryptdata:v,chunkMeta:u,state:L},t instanceof ArrayBuffer?[t]:[]);else if(c){var R=c.push(t,v,u,L);Object(zt.d)(R)?R.then((function(t){d.handleTransmuxComplete(t)})):this.handleTransmuxComplete(R)}},e.flush=function(t){var e=this;t.transmuxing.start=self.performance.now();var r=this.transmuxer,i=this.worker;if(i)i.postMessage({cmd:"flush",chunkMeta:t});else if(r){var a=r.flush(t);Object(zt.d)(a)?a.then((function(r){e.handleFlushResult(r,t)})):this.handleFlushResult(a,t)}},e.handleFlushResult=function(t,e){var r=this;t.forEach((function(t){r.handleTransmuxComplete(t)})),this.onFlush(e)},e.onWorkerMessage=function(t){var e=t.data,r=this.hls;switch(e.event){case"init":self.URL.revokeObjectURL(this.worker.objectURL);break;case"transmuxComplete":this.handleTransmuxComplete(e.data);break;case"flush":this.onFlush(e.data);break;default:e.data=e.data||{},e.data.frag=this.frag,e.data.id=this.id,r.trigger(e.event,e.data)}},e.configureTransmuxer=function(t){var e=this.worker,r=this.transmuxer;e?e.postMessage({cmd:"configure",config:t}):r&&r.configure(t)},e.handleTransmuxComplete=function(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)},t}(),Zt=function(){function t(t,e,r,i){this.config=void 0,this.media=void 0,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=t,this.media=e,this.fragmentTracker=r,this.hls=i}var e=t.prototype;return e.destroy=function(){this.hls=this.fragmentTracker=this.media=null},e.poll=function(t){var e=this.config,r=this.media,i=this.stalled,a=r.currentTime,n=r.seeking,s=this.seeking&&!n,l=!this.seeking&&n;if(this.seeking=n,a===t){if((l||s)&&(this.stalled=null),!r.paused&&!r.ended&&0!==r.playbackRate&<.getBuffered(r).length){var u=lt.bufferInfo(r,a,0),h=u.len>0,d=u.nextStart||0;if(h||d){if(n){var c=u.len>2,f=!d||d-a>2&&!this.fragmentTracker.getPartialFragment(a);if(c||f)return;this.moved=!1}if(!this.moved&&null!==this.stalled){var g,v=Math.max(d,u.start||0)-a,p=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,m=(null==p||null===(g=p.details)||void 0===g?void 0:g.live)?2*p.details.targetduration:2;if(v>0&&v<=m)return void this._trySkipBufferHole(null)}var y=self.performance.now();if(null!==i){var T=y-i;!n&&T>=250&&this._reportStall(u.len);var E=lt.bufferInfo(r,a,e.maxBufferHole);this._tryFixBufferStall(E,T)}else this.stalled=y}}}else if(this.moved=!0,null!==i){if(this.stallReported){var b=self.performance.now()-i;o.b.warn("playback not stuck anymore @"+a+", after "+Math.round(b)+"ms"),this.stallReported=!1}this.stalled=null,this.nudgeRetry=0}},e._tryFixBufferStall=function(t,e){var r=this.config,i=this.fragmentTracker,a=this.media.currentTime,n=i.getPartialFragment(a);if(n&&this._trySkipBufferHole(n))return;t.len>r.maxBufferHole&&e>1e3*r.highBufferWatchdogPeriod&&(o.b.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())},e._reportStall=function(t){var e=this.hls,r=this.media;this.stallReported||(this.stallReported=!0,o.b.warn("Playback stalling at @"+r.currentTime+" due to low buffer (buffer="+t+")"),e.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_STALLED_ERROR,fatal:!1,buffer:t}))},e._trySkipBufferHole=function(t){for(var e=this.config,r=this.hls,i=this.media,a=i.currentTime,l=0,u=lt.getBuffered(i),h=0;h=l&&a0&&-1===t&&(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),t=e),this.state=xt,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()}else this._forceStartLoad=!0,this.state=Ot},c.stopLoad=function(){this._forceStartLoad=!1,t.prototype.stopLoad.call(this)},c.doTick=function(){switch(this.state){case xt:this.doTickIdle();break;case Vt:var t,e=this.levels,r=this.level,i=null==e||null===(t=e[r])||void 0===t?void 0:t.details;if(i&&(!i.live||this.levelLastLoaded===this.level)){if(this.waitForCdnTuneIn(i))break;this.state=xt;break}break;case Ft:var a,n=self.performance.now(),s=this.retryDate;(!s||n>=s||null!==(a=this.media)&&void 0!==a&&a.seeking)&&(this.log("retryDate reached, switch back to IDLE state"),this.state=xt)}this.onTickEnd()},c.onTickEnd=function(){t.prototype.onTickEnd.call(this),this.checkBuffer(),this.checkFragmentChanged()},c.doTickIdle=function(){var t,e,r=this.hls,i=this.levelLastLoaded,s=this.levels,o=this.media,l=r.config,u=r.nextLoadLevel;if(null!==i&&(o||!this.startFragRequested&&l.startFragPrefetch)&&(!this.altAudio||!this.audioOnly)&&s&&s[u]){var h=s[u];this.level=r.nextLoadLevel=u;var d=h.details;if(!d||this.state===Vt||d.live&&this.levelLastLoaded!==u)this.state=Vt;else{var c=this.getLoadPosition();if(Object(a.a)(c)){var f=d.initSegment,g=0;if(!f||f.data||this.bitrateTest){var v,p=h.maxBitrate;v=p?Math.max(8*l.maxBufferSize/p,l.maxBufferLength):l.maxBufferLength,v=Math.min(v,l.maxMaxBufferLength);var m=c=v)return;if(this._streamEnded(y,d)){var T={};return this.altAudio&&(T.type="video"),this.hls.trigger(n.a.BUFFER_EOS,T),void(this.state=Kt)}if(g=y.end,(f=this.getNextFragment(g,d))&&this.fragmentTracker.getState(f)===tt.OK&&this.nextLoadPosition>g&&(f=this.getNextFragment(this.nextLoadPosition,d)),!f)return}"identity"!==(null===(t=f.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=f.decryptdata)&&void 0!==e&&e.key?this.loadFragment(f,d,g):(this.log("Loading key for "+f.sn+" of ["+d.startSN+"-"+d.endSN+"], level "+u),this.loadKey(f))}}}},c.loadKey=function(t){this.state=Pt,this.hls.trigger(n.a.KEY_LOADING,{frag:t})},c.loadFragment=function(e,r,i){var a,n=this.fragmentTracker.getState(e);if(this.fragCurrent=e,n===tt.BACKTRACKED){var s=this.fragmentTracker.getBacktrackData(e);if(s)return this._handleFragmentLoadProgress(s),void this._handleFragmentLoadComplete(s);n=tt.NOT_LOADED}n===tt.NOT_LOADED||n===tt.PARTIAL?"initSegment"===e.sn?this._loadInitSegment(e):this.bitrateTest?(e.bitrateTest=!0,this.log("Fragment "+e.sn+" of level "+e.level+" is being downloaded to test bitrate and will not be buffered"),this._loadBitrateTestFrag(e)):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)):n===tt.APPENDING?this.reduceMaxBufferLength(e.duration)&&this.fragmentTracker.removeFragment(e):0===(null===(a=this.media)||void 0===a?void 0:a.buffered.length)&&this.fragmentTracker.removeAllFragments()},c.getAppendedFrag=function(t){var e=this.fragmentTracker.getAppendedFrag(t,A.MAIN);return e&&"fragment"in e?e.fragment:e},c.getBufferedFrag=function(t){return this.fragmentTracker.getBufferedFrag(t,A.MAIN)},c.followingBufferedFrag=function(t){return t?this.getBufferedFrag(t.end+.5):null},c.immediateLevelSwitch=function(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)},c.nextLevelSwitch=function(){var t=this.levels,e=this.media;if(null!=e&&e.readyState){var r,i=this.getAppendedFrag(e.currentTime);if(i&&i.start>1&&this.flushMainBuffer(0,i.start-1),!e.paused&&t){var a=t[this.hls.nextLoadLevel],n=this.fragLastKbps;r=n&&this.fragCurrent?this.fragCurrent.duration*a.maxBitrate/(1e3*n)+1:0}else r=0;var s=this.getBufferedFrag(e.currentTime+r);if(s){var o=this.followingBufferedFrag(s);if(o){this.abortCurrentFrag();var l=o.maxStartPTS?o.maxStartPTS:o.start,u=o.duration,h=Math.max(s.end,l+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,.5*u),.75*u));this.flushMainBuffer(h,Number.POSITIVE_INFINITY)}}}},c.abortCurrentFrag=function(){var t=this.fragCurrent;this.fragCurrent=null,null!=t&&t.loader&&t.loader.abort(),this.nextLoadPosition=this.getLoadPosition()},c.flushMainBuffer=function(e,r){t.prototype.flushMainBuffer.call(this,e,r,this.altAudio?"video":null)},c.onMediaAttached=function(e,r){t.prototype.onMediaAttached.call(this,e,r);var i=r.media;this.onvplaying=this.onMediaPlaying.bind(this),this.onvseeked=this.onMediaSeeked.bind(this),i.addEventListener("playing",this.onvplaying),i.addEventListener("seeked",this.onvseeked),this.gapController=new Zt(this.config,i,this.fragmentTracker,this.hls)},c.onMediaDetaching=function(){var e=this.media;e&&(e.removeEventListener("playing",this.onvplaying),e.removeEventListener("seeked",this.onvseeked),this.onvplaying=this.onvseeked=null,this.videoBuffer=null),this.fragPlaying=null,this.gapController&&(this.gapController.destroy(),this.gapController=null),t.prototype.onMediaDetaching.call(this)},c.onMediaPlaying=function(){this.tick()},c.onMediaSeeked=function(){var t=this.media,e=t?t.currentTime:null;Object(a.a)(e)&&this.log("Media seeked to "+e.toFixed(3)),this.tick()},c.onManifestLoading=function(){this.log("Trigger BUFFER_RESET"),this.hls.trigger(n.a.BUFFER_RESET,void 0),this.fragmentTracker.removeAllFragments(),this.stalled=!1,this.startPosition=this.lastCurrentTime=0,this.fragPlaying=null},c.onManifestParsed=function(t,e){var r,i,a,n=!1,s=!1;e.levels.forEach((function(t){(r=t.audioCodec)&&(-1!==r.indexOf("mp4a.40.2")&&(n=!0),-1!==r.indexOf("mp4a.40.5")&&(s=!0))})),this.audioCodecSwitch=n&&s&&!("function"==typeof(null==(a=qt())||null===(i=a.prototype)||void 0===i?void 0:i.changeType)),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=e.levels,this.startFragRequested=!1},c.onLevelLoading=function(t,e){var r=this.levels;if(r&&this.state===xt){var i=r[e.level];(!i.details||i.details.live&&this.levelLastLoaded!==e.level||this.waitForCdnTuneIn(i.details))&&(this.state=Vt)}},c.onLevelLoaded=function(t,e){var r,i=this.levels,a=e.level,s=e.details,o=s.totalduration;if(i){this.log("Level "+a+" loaded ["+s.startSN+","+s.endSN+"], cc ["+s.startCC+", "+s.endCC+"] duration:"+o);var l=this.fragCurrent;!l||this.state!==Mt&&this.state!==Ft||l.level!==e.level&&l.loader&&(this.state=xt,l.loader.abort());var u=i[a],h=0;if(s.live||null!==(r=u.details)&&void 0!==r&&r.live){if(s.fragments[0]||(s.deltaUpdateFailed=!0),s.deltaUpdateFailed)return;h=this.alignPlaylists(s,u.details)}if(u.details=s,this.levelLastLoaded=a,this.hls.trigger(n.a.LEVEL_UPDATED,{details:s,level:a}),this.state===Vt){if(this.waitForCdnTuneIn(s))return;this.state=xt}this.startFragRequested?s.live&&this.synchronizeToLiveEdge(s):this.setStartPosition(s,h),this.tick()}else this.warn("Levels were reset while loading level "+a)},c._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,a=t.payload,n=this.levels;if(n){var s=n[r.level],o=s.details;if(o){var l=s.videoCodec,u=o.PTSKnown||!o.live,h=null===(e=o.initSegment)||void 0===e?void 0:e.data,d=this._getAudioCodec(s),c=this.transmuxer=this.transmuxer||new Jt(this.hls,A.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=i?i.index:-1,g=-1!==f,v=new ut(r.level,r.sn,r.stats.chunkCount,a.byteLength,f,g),p=this.initPTS[r.cc];c.push(a,h,d,l,r,i,o.totalduration,u,v,p)}else this.warn("Dropping fragment "+r.sn+" of level "+r.level+" after level details were reset")}else this.warn("Levels were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},c.onAudioTrackSwitching=function(t,e){var r=this.altAudio,i=!!e.url,a=e.id;if(!i){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;var s=this.fragCurrent;null!=s&&s.loader&&(this.log("Switching to main audio track, cancel main fragment load"),s.loader.abort()),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();var o=this.hls;r&&o.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:"audio"}),o.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:a})}},c.onAudioTrackSwitched=function(t,e){var r=e.id,i=!!this.hls.audioTracks[r].url;if(i){var a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=i,this.tick()},c.onBufferCreated=function(t,e){var r,i,a=e.tracks,n=!1;for(var s in a){var o=a[s];if("main"===o.id){if(i=s,r=o,"video"===s){var l=a[s];l&&(this.videoBuffer=l.buffer)}}else n=!0}n&&r?(this.log("Alternate track found, use "+i+".buffered to schedule main fragment loading"),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media},c.onFragBuffered=function(t,e){var r=e.frag,i=e.part;if(!r||r.type===A.MAIN){if(this.fragContextChanged(r))return this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state),void(this.state===Bt&&(this.state=xt));var a=i?i.stats:r.stats;this.fragLastKbps=Math.round(8*a.total/(a.buffering.end-a.loading.first)),"initSegment"!==r.sn&&(this.fragPrevious=r),this.fragBufferedComplete(r,i)}},c.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(A.MAIN,e);break;case s.a.LEVEL_LOAD_ERROR:case s.a.LEVEL_LOAD_TIMEOUT:this.state!==jt&&(e.fatal?(this.warn(""+e.details),this.state=jt):e.levelRetry||this.state!==Vt||(this.state=xt));break;case s.a.BUFFER_FULL_ERROR:if("main"===e.parent&&(this.state===Ut||this.state===Bt))!!this.media&<.isBuffered(this.media,this.media.currentTime)&<.isBuffered(this.media,this.media.currentTime+.5)?(this.reduceMaxBufferLength(),this.state=xt):(this.warn("buffer full error also media.currentTime is not buffered, flush everything"),this.immediateLevelSwitch())}},c.checkBuffer=function(){var t=this.media,e=this.gapController;if(t&&e&&t.readyState){var r=lt.getBuffered(t);!this.loadedmetadata&&r.length?(this.loadedmetadata=!0,this.seekToStartPos()):e.poll(this.lastCurrentTime),this.lastCurrentTime=t.currentTime}},c.onFragLoadEmergencyAborted=function(){this.state=xt,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tick()},c.onBufferFlushed=function(t,e){var r=e.type;if(r!==u.a.AUDIO||this.audioOnly&&!this.altAudio){var i=(r===u.a.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(i,r)}},c.onLevelsUpdated=function(t,e){this.levels=e.levels},c.swapAudioCodec=function(){this.audioCodecSwap=!this.audioCodecSwap},c.seekToStartPos=function(){var t=this.media,e=t.currentTime,r=this.startPosition;if(r>=0&&e0&&a1&&!1===t.seeking){var r=t.currentTime;if(lt.isBuffered(t,r)?e=this.getAppendedFrag(r):lt.isBuffered(t,r+.1)&&(e=this.getAppendedFrag(r+.1)),e){var i=this.fragPlaying,a=e.level;i&&e.sn===i.sn&&i.level===a&&e.urlId===i.urlId||(this.hls.trigger(n.a.FRAG_CHANGED,{frag:e}),i&&i.level===a||this.hls.trigger(n.a.LEVEL_SWITCHED,{level:a}),this.fragPlaying=e)}}},l=i,(h=[{key:"nextLevel",get:function(){var t=this.nextBufferedFrag;return t?t.level:-1}},{key:"currentLevel",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);if(e)return e.level}return-1}},{key:"nextBufferedFrag",get:function(){var t=this.media;if(t){var e=this.getAppendedFrag(t.currentTime);return this.followingBufferedFrag(e)}return null}},{key:"forceStartLoad",get:function(){return this._forceStartLoad}}])&&te(l.prototype,h),d&&te(l,d),i}(Wt),ie=function(){function t(t,e,r){void 0===e&&(e=0),void 0===r&&(r=0),this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=e,this.totalWeight_=r}var e=t.prototype;return e.sample=function(t,e){var r=Math.pow(this.alpha_,t);this.estimate_=e*(1-r)+r*this.estimate_,this.totalWeight_+=t},e.getTotalWeight=function(){return this.totalWeight_},e.getEstimate=function(){if(this.alpha_){var t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_},t}(),ae=function(){function t(t,e,r){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new ie(t),this.fast_=new ie(e)}var e=t.prototype;return e.update=function(t,e){var r=this.slow_,i=this.fast_;this.slow_.halfLife!==t&&(this.slow_=new ie(t,r.getEstimate(),r.getTotalWeight())),this.fast_.halfLife!==e&&(this.fast_=new ie(e,i.getEstimate(),i.getTotalWeight()))},e.sample=function(t,e){var r=(t=Math.max(t,this.minDelayMs_))/1e3,i=8*e/r;this.fast_.sample(r,i),this.slow_.sample(r,i)},e.canEstimate=function(){var t=this.fast_;return t&&t.getTotalWeight()>=this.minWeight_},e.getEstimate=function(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_},e.destroy=function(){},t}();function ne(t,e){for(var r=0;r=2*h/c||y<=E)){var b,S=Number.POSITIVE_INFINITY;for(b=t.level-1;b>g;b--){if((S=h*f[b].maxBitrate/(6.4*m))=y)){var L=this.bwEstimator.getEstimate();o.b.warn("Fragment "+t.sn+(e?" part "+e.index:"")+" of level "+t.level+" is loading too slowly and will cause an underbuffer; aborting and switching to level "+b+"\n Current BW estimate: "+(Object(a.a)(L)?(L/1024).toFixed(3):"Unknown")+" Kb/s\n Estimated load time for current fragment: "+y.toFixed(3)+" s\n Estimated load time for the next fragment: "+S.toFixed(3)+" s\n Time to underbuffer: "+E.toFixed(3)+" s"),r.nextLoadLevel=b,this.bwEstimator.sample(d,u.loaded),this.clearTimer(),t.loader&&(this.fragCurrent=this.partCurrent=null,t.loader.abort()),r.trigger(n.a.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:e,stats:u})}}}}}},l.onFragLoaded=function(t,e){var r=e.frag,i=e.part;if(r.type===A.MAIN&&Object(a.a)(r.sn)){var s=i?i.stats:r.stats,o=i?i.duration:r.duration;if(this.clearTimer(),this.lastLoadedFragLevel=r.level,this._nextAutoLevel=-1,this.hls.config.abrMaxWithRealBitrate){var l=this.hls.levels[r.level],u=(l.loaded?l.loaded.bytes:0)+s.loaded,h=(l.loaded?l.loaded.duration:0)+o;l.loaded={bytes:u,duration:h},l.realBitrate=Math.round(8*u/h)}if(r.bitrateTest){var d={stats:s,frag:r,part:i,id:r.type};this.onFragBuffered(n.a.FRAG_BUFFERED,d),r.bitrateTest=!1}}},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part,a=i?i.stats:r.stats;if(!a.aborted&&r.type===A.MAIN&&"initSegment"!==r.sn){var n=a.parsing.end-a.loading.start;this.bwEstimator.sample(n,a.loaded),a.bwEstimate=this.bwEstimator.getEstimate(),r.bitrateTest?this.bitrateTestDelay=n/1e3:this.bitrateTestDelay=0}},l.onError=function(t,e){switch(e.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:this.clearTimer()}},l.clearTimer=function(){self.clearInterval(this.timer),this.timer=void 0},l.getNextABRAutoLevel=function(){var t=this.fragCurrent,e=this.partCurrent,r=this.hls,i=r.maxAutoLevel,a=r.config,n=r.minAutoLevel,s=r.media,l=e?e.duration:t?t.duration:0,u=s?s.currentTime:0,h=s&&0!==s.playbackRate?Math.abs(s.playbackRate):1,d=this.bwEstimator?this.bwEstimator.getEstimate():a.abrEwmaDefaultEstimate,c=(lt.bufferInfo(s,u,a.maxBufferHole).end-u)/h,f=this.findBestLevel(d,n,i,c,a.abrBandWidthFactor,a.abrBandWidthUpFactor);if(f>=0)return f;o.b.trace((c?"rebuffering expected":"buffer is empty")+", finding optimal quality level");var g=l?Math.min(l,a.maxStarvationDelay):a.maxStarvationDelay,v=a.abrBandWidthFactor,p=a.abrBandWidthUpFactor;if(!c){var m=this.bitrateTestDelay;if(m)g=(l?Math.min(l,a.maxLoadingDelay):a.maxLoadingDelay)-m,o.b.trace("bitrate test took "+Math.round(1e3*m)+"ms, set first fragment max fetchDuration to "+Math.round(1e3*g)+" ms"),v=p=1}return f=this.findBestLevel(d,n,i,c+g,v,p),Math.max(f,0)},l.findBestLevel=function(t,e,r,i,a,n){for(var s,l=this.fragCurrent,u=this.partCurrent,h=this.lastLoadedFragLevel,d=this.hls.levels,c=d[h],f=!(null==c||null===(s=c.details)||void 0===s||!s.live),g=null==c?void 0:c.codecSet,v=u?u.duration:l?l.duration:0,p=r;p>=e;p--){var m=d[p];if(m&&(!g||m.codecSet===g)){var y=m.details,T=(u?null==y?void 0:y.partTarget:null==y?void 0:y.averagetargetduration)||v,E=void 0;E=p<=h?a*t:n*t;var b=d[p].maxBitrate,S=b*T/E;if(o.b.trace("level/adjustedbw/bitrate/avgDuration/maxFetchDuration/fetchDuration: "+p+"/"+Math.round(E)+"/"+b+"/"+T+"/"+i+"/"+S),E>b&&(!S||f&&!this.bitrateTestDelay||S0&&-1===t?(this.log("Override startPosition with lastCurrentTime @"+e.toFixed(3)),this.state=xt):(this.loadedmetadata=!1,this.state=Nt),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=t,this.tick()},l.doTick=function(){switch(this.state){case xt:this.doTickIdle();break;case Nt:var e,r=this.levels,i=this.trackId,a=null==r||null===(e=r[i])||void 0===e?void 0:e.details;if(a){if(this.waitForCdnTuneIn(a))break;this.state=Ht}break;case Ft:var n,s=performance.now(),l=this.retryDate;(!l||s>=l||null!==(n=this.media)&&void 0!==n&&n.seeking)&&(this.log("RetryDate reached, switch back to IDLE state"),this.state=xt);break;case Ht:var u=this.waitingData;if(u){var h=u.frag,d=u.part,c=u.cache,f=u.complete;if(void 0!==this.initPTS[h.cc]){this.waitingData=null,this.state=Mt;var g={frag:h,part:d,payload:c.flush(),networkDetails:null};this._handleFragmentLoadProgress(g),f&&t.prototype._handleFragmentLoadComplete.call(this,g)}else if(this.videoTrackCC!==this.waitingVideoCC)o.b.log("Waiting fragment cc ("+h.cc+") cancelled because video is at cc "+this.videoTrackCC),this.clearWaitingFragment();else{var v=lt.bufferInfo(this.mediaBuffer,this.media.currentTime,this.config.maxBufferHole);mt(v.end,this.config.maxFragLookUpTolerance,h)<0&&(o.b.log("Waiting fragment cc ("+h.cc+") @ "+h.start+" cancelled because another fragment at "+v.end+" is needed"),this.clearWaitingFragment())}}else this.state=xt}this.onTickEnd()},l.clearWaitingFragment=function(){var t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=xt)},l.onTickEnd=function(){var t=this.media;if(t&&t.readyState){var e=(this.mediaBuffer?this.mediaBuffer:t).buffered;!this.loadedmetadata&&e.length&&(this.loadedmetadata=!0),this.lastCurrentTime=t.currentTime}},l.doTickIdle=function(){var t,e,r=this.hls,i=this.levels,s=this.media,o=this.trackId,l=r.config;if(i&&i[o]&&(s||!this.startFragRequested&&l.startFragPrefetch)){var u=this.getLoadPosition();if(Object(a.a)(u)){var h=i[o].details;if(!h||h.live&&this.levelLastLoaded!==o||this.waitForCdnTuneIn(h))this.state=Nt;else{var d=h.initSegment,c=0;if(!d||d.data){var f=this.mediaBuffer?this.mediaBuffer:this.media,g=this.videoBuffer?this.videoBuffer:this.media,v=u=E&&!b)return;if(!b&&this._streamEnded(p,h))return r.trigger(n.a.BUFFER_EOS,{type:"audio"}),void(this.state=Kt);var S=h.fragments[0].start;if(c=p.end,b&&(c=u,h.PTSKnown&&uS||p.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),s.currentTime=S+.05)),!(d=this.getNextFragment(c,h)))return}"identity"!==(null===(t=d.decryptdata)||void 0===t?void 0:t.keyFormat)||null!==(e=d.decryptdata)&&void 0!==e&&e.key?this.loadFragment(d,h,c):(this.log("Loading key for "+d.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+o),this.state=Pt,r.trigger(n.a.KEY_LOADING,{frag:d}))}}}},l.onMediaDetaching=function(){this.videoBuffer=null,t.prototype.onMediaDetaching.call(this)},l.onAudioTracksUpdated=function(t,e){var r=e.audioTracks;this.resetTransmuxer(),this.levels=r.map((function(t){return new H(t)}))},l.onAudioTrackSwitching=function(t,e){var r=!!e.url;this.trackId=e.id;var i=this.fragCurrent;null!=i&&i.loader&&i.loader.abort(),this.fragCurrent=null,this.clearWaitingFragment(),r?this.setInterval(100):this.resetTransmuxer(),r?(this.audioSwitch=!0,this.state=xt):this.state=Ot,this.tick()},l.onManifestLoading=function(){this.mainDetails=null,this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0},l.onLevelLoaded=function(t,e){if(null===this.mainDetails){var r=this.mainDetails=e.details,i=this.levelLastLoaded;if(null!==i&&this.levels&&-1===this.startPosition&&r.live){var a=this.levels[i];if(!a.details||!a.details.fragments[0])return;ft(a.details,r),this.setStartPosition(a.details,a.details.fragments[0].start)}}},l.onAudioTrackLoaded=function(t,e){var r,i=this.levels,a=e.details,n=e.id;if(i){this.log("Track "+n+" loaded ["+a.startSN+","+a.endSN+"],duration:"+a.totalduration);var s=i[n],o=0;if(a.live||null!==(r=s.details)&&void 0!==r&&r.live){var l;if(a.fragments[0]||(a.deltaUpdateFailed=!0),a.deltaUpdateFailed)return;!s.details&&null!==(l=this.mainDetails)&&void 0!==l&&l.hasProgramDateTime&&a.hasProgramDateTime?(ft(a,this.mainDetails),o=a.fragments[0].start):o=this.alignPlaylists(a,s.details)}s.details=a,this.levelLastLoaded=n,this.startFragRequested||!this.mainDetails&&a.live||this.setStartPosition(s.details,o),this.state!==Nt||this.waitForCdnTuneIn(a)||(this.state=xt),this.tick()}else this.warn("Audio tracks were reset while loading level "+n)},l._handleFragmentLoadProgress=function(t){var e,r=t.frag,i=t.part,a=t.payload,n=this.config,s=this.trackId,l=this.levels;if(l){var u=l[s],h=u.details,d=n.defaultAudioCodec||u.audioCodec||"mp4a.40.2",c=this.transmuxer;c||(c=this.transmuxer=new Jt(this.hls,A.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));var f=this.initPTS[r.cc],g=null===(e=h.initSegment)||void 0===e?void 0:e.data;if(void 0!==f){var v=i?i.index:-1,p=-1!==v,m=new ut(r.level,r.sn,r.stats.chunkCount,a.byteLength,v,p);c.push(a,g,d,"",r,i,h.totalduration,!1,m,f)}else{o.b.log("Unknown video PTS for cc "+r.cc+", waiting for video PTS before demuxing audio frag "+r.sn+" of ["+h.startSN+" ,"+h.endSN+"],track "+s),(this.waitingData=this.waitingData||{frag:r,part:i,cache:new oe.a,complete:!1}).cache.push(new Uint8Array(a)),this.waitingVideoCC=this.videoTrackCC,this.state=Ht}}else this.warn("Audio tracks were reset while fragment load was in progress. Fragment "+r.sn+" of level "+r.level+" will not be buffered")},l._handleFragmentLoadComplete=function(e){this.waitingData?this.waitingData.complete=!0:t.prototype._handleFragmentLoadComplete.call(this,e)},l.onBufferReset=function(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1},l.onBufferCreated=function(t,e){var r=e.tracks.audio;r&&(this.mediaBuffer=r.buffer),e.tracks.video&&(this.videoBuffer=e.tracks.video.buffer)},l.onFragBuffered=function(t,e){var r=e.frag,i=e.part;r.type===A.AUDIO&&(this.fragContextChanged(r)?this.warn("Fragment "+r.sn+(i?" p: "+i.index:"")+" of level "+r.level+" finished buffering, but was aborted. state: "+this.state+", audioSwitch: "+this.audioSwitch):("initSegment"!==r.sn&&(this.fragPrevious=r,this.audioSwitch&&(this.audioSwitch=!1,this.hls.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:this.trackId}))),this.fragBufferedComplete(r,i)))},l.onError=function(e,r){switch(r.details){case s.a.FRAG_LOAD_ERROR:case s.a.FRAG_LOAD_TIMEOUT:case s.a.KEY_LOAD_ERROR:case s.a.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(A.AUDIO,r);break;case s.a.AUDIO_TRACK_LOAD_ERROR:case s.a.AUDIO_TRACK_LOAD_TIMEOUT:this.state!==jt&&this.state!==Ot&&(this.state=r.fatal?jt:xt,this.warn(r.details+" while loading frag, switching to "+this.state+" state"));break;case s.a.BUFFER_FULL_ERROR:if("audio"===r.parent&&(this.state===Ut||this.state===Bt)){var i=this.mediaBuffer,a=this.media.currentTime;i&<.isBuffered(i,a)&<.isBuffered(i,a+.5)?(this.reduceMaxBufferLength(),this.state=xt):(this.warn("Buffer full error also media.currentTime is not buffered, flush audio buffer"),this.fragCurrent=null,t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio"))}}},l.onBufferFlushed=function(t,e){var r=e.type;if(r===u.a.AUDIO){var i=this.mediaBuffer?this.mediaBuffer:this.media;this.afterBufferFlushed(i,r)}},l._handleTransmuxComplete=function(t){var e,r="audio",i=this.hls,a=t.remuxResult,s=t.chunkMeta,o=this.getCurrentContext(s);if(!o)return this.warn("The loading context changed while buffering fragment "+s.sn+" of level "+s.level+". This chunk will not be buffered."),void this.resetLiveStartWhenNotLoaded(s.level);var l=o.frag,h=o.part,d=a.audio,c=a.text,f=a.id3,g=a.initSegment;if(!this.fragContextChanged(l)){if(this.state=Ut,this.audioSwitch&&d&&this.completeAudioSwitch(),null!=g&&g.tracks&&(this._bufferInitSegment(g.tracks,l,s),i.trigger(n.a.FRAG_PARSING_INIT_SEGMENT,{frag:l,id:r,tracks:g.tracks})),d){var v=d.startPTS,p=d.endPTS,m=d.startDTS,y=d.endDTS;h&&(h.elementaryStreams[u.a.AUDIO]={startPTS:v,endPTS:p,startDTS:m,endDTS:y}),l.setElementaryStreamInfo(u.a.AUDIO,v,p,m,y),this.bufferFragmentData(d,l,h,s)}if(null!=f&&null!==(e=f.samples)&&void 0!==e&&e.length){var T=le({frag:l,id:r},f);i.trigger(n.a.FRAG_PARSING_METADATA,T)}if(c){var E=le({frag:l,id:r},c);i.trigger(n.a.FRAG_PARSING_USERDATA,E)}}},l._bufferInitSegment=function(t,e,r){if(this.state===Ut){t.video&&delete t.video;var i=t.audio;if(i){i.levelCodec=i.codec,i.id="audio",this.log("Init audio buffer, container:"+i.container+", codecs[parsed]=["+i.codec+"]"),this.hls.trigger(n.a.BUFFER_CODECS,t);var a=i.initSegment;if(null!=a&&a.byteLength){var s={type:"audio",frag:e,part:null,chunkMeta:r,parent:e.type,data:a};this.hls.trigger(n.a.BUFFER_APPENDING,s)}this.tick()}}},l.loadFragment=function(e,r,i){var n=this.fragmentTracker.getState(e);this.fragCurrent=e,(this.audioSwitch||n===tt.NOT_LOADED||n===tt.PARTIAL)&&("initSegment"===e.sn?this._loadInitSegment(e):r.live&&!Object(a.a)(this.initPTS[e.cc])?(this.log("Waiting for video PTS in continuity counter "+e.cc+" of live stream before loading audio fragment "+e.sn+" of level "+this.trackId),this.state=Ht):(this.startFragRequested=!0,t.prototype.loadFragment.call(this,e,r,i)))},l.completeAudioSwitch=function(){var e=this.hls,r=this.media,i=this.trackId;r&&(this.log("Switching audio track : flushing all audio"),t.prototype.flushMainBuffer.call(this,0,Number.POSITIVE_INFINITY,"audio")),this.audioSwitch=!1,e.trigger(n.a.AUDIO_TRACK_SWITCHED,{id:i})},i}(Wt);function de(t,e){for(var r=0;r=e.length)this.warn("Invalid id passed to audio-track controller");else{this.clearTimer();var r=e[this.trackId];this.log("Now switching to audio-track index "+t);var i=e[t],a=i.id,s=i.groupId,o=void 0===s?"":s,l=i.name,u=i.type,h=i.url;if(this.trackId=t,this.trackName=l,this.selectDefaultTrack=!1,this.hls.trigger(n.a.AUDIO_TRACK_SWITCHING,{id:a,groupId:o,name:l,type:u,url:h}),!i.details||i.details.live){var d=this.switchParams(i.url,null==r?void 0:r.details);this.loadPlaylist(d)}}},u.selectInitialTrack=function(){this.tracksInGroup;var t=this.trackName,e=this.findTrackId(t)||this.findTrackId();-1!==e?this.setAudioTrack(e):(this.warn("No track found for running audio group-ID: "+this.groupId),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.AUDIO_TRACK_LOAD_ERROR,fatal:!0}))},u.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=a[o].start&&s<=a[o].end){n=a[o];break}var l=r.start+r.duration;n?n.end=l:(n={start:s,end:l},a.push(n))}}},u.onMediaAttached=function(t,e){var r=e.media;this.media=r,this.state=xt},u.onMediaDetaching=function(){var t=this;this.media&&(this.fragmentTracker.removeAllFragments(),this.fragPrevious=null,this.currentTrackId=-1,this.levels.forEach((function(e){t.tracksBuffered[e.id]=[]})),this.media=null,this.mediaBuffer=null,this.state=Ot)},u.onError=function(t,e){var r,i=e.frag;i&&i.type===A.SUBTITLE&&(null!==(r=this.fragCurrent)&&void 0!==r&&r.loader&&this.fragCurrent.loader.abort(),this.state=xt)},u.onSubtitleTracksUpdated=function(t,e){var r=this,i=e.subtitleTracks;this.tracksBuffered=[],this.levels=i.map((function(t){return new H(t)})),this.fragmentTracker.removeAllFragments(),this.fragPrevious=null,this.levels.forEach((function(t){r.tracksBuffered[t.id]=[]})),this.mediaBuffer=null},u.onSubtitleTrackSwitch=function(t,e){if(this.currentTrackId=e.id,this.levels.length&&-1!==this.currentTrackId){var r=this.levels[this.currentTrackId];null!=r&&r.details?(this.mediaBuffer=this.mediaBufferTimeRanges,this.setInterval(500)):this.mediaBuffer=null}else this.clearInterval()},u.onSubtitleTrackLoaded=function(t,e){var r,i=e.id,a=e.details,n=this.currentTrackId,s=this.levels;if(s.length&&a){var o=s[n];if(!(i>=s.length||i!==n)&&o){if(this.mediaBuffer=this.mediaBufferTimeRanges,a.live||null!==(r=o.details)&&void 0!==r&&r.live){if(a.deltaUpdateFailed)return;this.alignPlaylists(a,o.details)}o.details=a,this.levelLastLoaded=i,this.setInterval(500)}}},u._handleFragmentLoadComplete=function(t){var e=t.frag,r=t.payload,i=e.decryptdata,a=this.hls;if(!this.fragContextChanged(e)&&r&&r.byteLength>0&&i&&i.key&&i.iv&&"AES-128"===i.method){var s=performance.now();this.decrypter.webCryptoDecrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer).then((function(t){var r=performance.now();a.trigger(n.a.FRAG_DECRYPTED,{frag:e,payload:t,stats:{tstart:s,tdecrypt:r}})}))}},u.doTick=function(){if(this.media){if(this.state===xt){var t,e=this.config,r=this.currentTrackId,i=this.fragmentTracker,a=this.media,s=this.levels;if(!s.length||!s[r]||!s[r].details)return;var l=e.maxBufferHole,u=e.maxFragLookUpTolerance,h=Math.min(e.maxBufferLength,e.maxMaxBufferLength),d=lt.bufferedInfo(this.mediaBufferTimeRanges,a.currentTime,l),c=d.end;if(d.len>h)return;var f,g=s[r].details,v=g.fragments,p=v.length,m=v[p-1].start+v[p-1].duration,y=this.fragPrevious;c-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?(self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval((function(){r.trackChangeListener()}),500)):this.media.textTracks.addEventListener("change",this.trackChangeListener))},l.onMediaDetaching=function(){this.media&&(this.useTextTrackPolling?self.clearInterval(this.subtitlePollingInterval):this.media.textTracks.removeEventListener("change",this.trackChangeListener),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Te(this.media.textTracks).forEach((function(t){P(t)})),this.subtitleTrack=-1,this.media=null)},l.onManifestLoading=function(){this.tracks=[],this.groupId=null,this.tracksInGroup=[],this.trackId=-1,this.selectDefaultTrack=!0},l.onManifestParsed=function(t,e){this.tracks=e.subtitleTracks},l.onSubtitleTrackLoaded=function(t,e){var r=e.id,i=e.details,a=this.trackId,n=this.tracksInGroup[a];if(n){var s=n.details;n.details=e.details,this.log("subtitle track "+r+" loaded ["+i.startSN+"-"+i.endSN+"]"),r===this.trackId&&(this.retryCount=0,this.playlistLoaded(r,e,s))}else this.warn("Invalid subtitle track id "+r)},l.onLevelLoading=function(t,e){this.switchLevel(e.level)},l.onLevelSwitching=function(t,e){this.switchLevel(e.level)},l.switchLevel=function(t){var e=this.hls.levels[t];if(null!=e&&e.textGroupIds){var r=e.textGroupIds[e.urlId];if(this.groupId!==r){var i=this.tracksInGroup?this.tracksInGroup[this.trackId]:void 0,a=this.findTrackId(null==i?void 0:i.name)||this.findTrackId(),s=this.tracks.filter((function(t){return!r||t.groupId===r}));this.groupId=r,this.tracksInGroup=s;var o={subtitleTracks:s};this.log("Updating subtitle tracks, "+s.length+' track(s) found in "'+r+'" group-id'),this.hls.trigger(n.a.SUBTITLE_TRACKS_UPDATED,o),-1!==a&&this.setSubtitleTrack(a,i)}}},l.findTrackId=function(t){for(var e=this.tracksInGroup,r=0;r=i.length)){this.clearTimer();var a=i[t];if(this.log("Switching to subtitle track "+t),this.trackId=t,a){var s=a.id,o=a.groupId,l=void 0===o?"":o,u=a.name,h=a.type,d=a.url;this.hls.trigger(n.a.SUBTITLE_TRACK_SWITCH,{id:s,groupId:l,name:u,type:h,url:d});var c=this.switchParams(a.url,null==e?void 0:e.details);this.loadPlaylist(c)}else this.hls.trigger(n.a.SUBTITLE_TRACK_SWITCH,{id:t})}}else this.queuedDefaultTrack=t},l.onTextTracksChanged=function(){if(this.media&&this.hls.config.renderTextTracksNatively){for(var t=-1,e=Te(this.media.textTracks),r=0;r0||Object.keys(this.pendingTracks).length>0},e.destroy=function(){this.unregisterListeners(),this.details=null},e.registerListeners=function(){var t=this.hls;t.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.on(n.a.BUFFER_RESET,this.onBufferReset,this),t.on(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.on(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.on(n.a.BUFFER_EOS,this.onBufferEos,this),t.on(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(n.a.FRAG_PARSED,this.onFragParsed,this),t.on(n.a.FRAG_CHANGED,this.onFragChanged,this)},e.unregisterListeners=function(){var t=this.hls;t.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(n.a.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(n.a.MANIFEST_PARSED,this.onManifestParsed,this),t.off(n.a.BUFFER_RESET,this.onBufferReset,this),t.off(n.a.BUFFER_APPENDING,this.onBufferAppending,this),t.off(n.a.BUFFER_CODECS,this.onBufferCodecs,this),t.off(n.a.BUFFER_EOS,this.onBufferEos,this),t.off(n.a.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(n.a.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(n.a.FRAG_PARSED,this.onFragParsed,this),t.off(n.a.FRAG_CHANGED,this.onFragChanged,this)},e._initSourceBuffer=function(){this.sourceBuffer={},this.operationQueue=new Se(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]}},e.onManifestParsed=function(t,e){var r=2;(e.audio&&!e.video||!e.altAudio)&&(r=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=r,this.details=null,o.b.log(this.bufferCodecEventsExpected+" bufferCodec event(s) expected")},e.onMediaAttaching=function(t,e){var r=this.media=e.media;if(r&&Le){var i=this.mediaSource=new Le;i.addEventListener("sourceopen",this._onMediaSourceOpen),i.addEventListener("sourceended",this._onMediaSourceEnded),i.addEventListener("sourceclose",this._onMediaSourceClose),r.src=self.URL.createObjectURL(i),this._objectUrl=r.src}},e.onMediaDetaching=function(){var t=this.media,e=this.mediaSource,r=this._objectUrl;if(e){if(o.b.log("[buffer-controller]: media source detaching"),"open"===e.readyState)try{e.endOfStream()}catch(t){o.b.warn("[buffer-controller]: onMediaDetaching: "+t.message+" while calling endOfStream")}this.onBufferReset(),e.removeEventListener("sourceopen",this._onMediaSourceOpen),e.removeEventListener("sourceended",this._onMediaSourceEnded),e.removeEventListener("sourceclose",this._onMediaSourceClose),t&&(r&&self.URL.revokeObjectURL(r),t.src===r?(t.removeAttribute("src"),t.load()):o.b.warn("[buffer-controller]: media.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(n.a.MEDIA_DETACHED,void 0)},e.onBufferReset=function(){var t=this,e=this.sourceBuffer;this.getSourceBufferTypes().forEach((function(r){var i=e[r];try{i&&(t.removeBufferListeners(r),t.mediaSource&&t.mediaSource.removeSourceBuffer(i),e[r]=void 0)}catch(t){o.b.warn("[buffer-controller]: Failed to reset the "+r+" buffer",t)}})),this._initSourceBuffer()},e.onBufferCodecs=function(t,e){var r=this,i=Object.keys(this.sourceBuffer).length;Object.keys(e).forEach((function(t){if(i){var a=r.tracks[t];if(a&&"function"==typeof a.buffer.changeType){var n=e[t],s=n.codec,o=n.levelCodec,l=n.container;if((a.levelCodec||a.codec).replace(Ae,"$1")!==(o||s).replace(Ae,"$1")){var u=l+";codecs="+(o||s);r.appendChangeType(t,u)}}}else r.pendingTracks[t]=e[t]})),i||(this.bufferCodecEventsExpected=Math.max(this.bufferCodecEventsExpected-1,0),this.mediaSource&&"open"===this.mediaSource.readyState&&this.checkPendingTracks())},e.appendChangeType=function(t,e){var r=this,i=this.operationQueue,a={execute:function(){var a=r.sourceBuffer[t];a&&(o.b.log("[buffer-controller]: changing "+t+" sourceBuffer type to "+e),a.changeType(e)),i.shiftAndExecuteNext(t)},onStart:function(){},onComplete:function(){},onError:function(e){o.b.warn("[buffer-controller]: Failed to change "+t+" SourceBuffer type",e)}};i.append(a,t)},e.onBufferAppending=function(t,e){var r=this,i=this.hls,a=this.operationQueue,l=this.tracks,u=e.data,h=e.type,d=e.frag,c=e.part,f=e.chunkMeta,g=f.buffering[h],v=self.performance.now();g.start=v;var p=d.stats.buffering,m=c?c.stats.buffering:null;0===p.start&&(p.start=v),m&&0===m.start&&(m.start=v);var y=l.audio,T="audio"===h&&1===f.id&&"audio/mpeg"===(null==y?void 0:y.container),E={execute:function(){if(g.executeStart=self.performance.now(),T){var t=r.sourceBuffer[h];if(t){var e=d.start-t.timestampOffset;Math.abs(e)>=.1&&(o.b.log("[buffer-controller]: Updating audio SourceBuffer timestampOffset to "+d.start+" (delta: "+e+") sn: "+d.sn+")"),t.timestampOffset=d.start)}}r.appendExecutor(u,h)},onStart:function(){},onComplete:function(){var t=self.performance.now();g.executeEnd=g.end=t,0===p.first&&(p.first=t),m&&0===m.first&&(m.first=t);var e=r.sourceBuffer,i={};for(var a in e)i[a]=lt.getBuffered(e[a]);r.appendError=0,r.hls.trigger(n.a.BUFFER_APPENDED,{type:h,frag:d,part:c,chunkMeta:f,parent:d.type,timeRanges:i})},onError:function(t){o.b.error("[buffer-controller]: Error encountered while trying to append to the "+h+" SourceBuffer",t);var e={type:s.b.MEDIA_ERROR,parent:d.type,details:s.a.BUFFER_APPEND_ERROR,err:t,fatal:!1};t.code===DOMException.QUOTA_EXCEEDED_ERR?e.details=s.a.BUFFER_FULL_ERROR:(r.appendError++,e.details=s.a.BUFFER_APPEND_ERROR,r.appendError>i.config.appendErrorMaxRetry&&(o.b.error("[buffer-controller]: Failed "+i.config.appendErrorMaxRetry+" times to append segment in sourceBuffer"),e.fatal=!0)),i.trigger(n.a.ERROR,e)}};a.append(E,h)},e.onBufferFlushing=function(t,e){var r=this,i=this.operationQueue,a=function(t){return{execute:r.removeExecutor.bind(r,t,e.startOffset,e.endOffset),onStart:function(){},onComplete:function(){r.hls.trigger(n.a.BUFFER_FLUSHED,{type:t})},onError:function(e){o.b.warn("[buffer-controller]: Failed to remove from "+t+" SourceBuffer",e)}}};e.type?i.append(a(e.type),e.type):(i.append(a("audio"),"audio"),i.append(a("video"),"video"))},e.onFragParsed=function(t,e){var r=this,i=e.frag,a=e.part,s=[],l=a?a.elementaryStreams:i.elementaryStreams;l[u.a.AUDIOVIDEO]?s.push("audiovideo"):(l[u.a.AUDIO]&&s.push("audio"),l[u.a.VIDEO]&&s.push("video"));0===s.length&&o.b.warn("Fragments must have at least one ElementaryStreamType set. type: "+i.type+" level: "+i.level+" sn: "+i.sn),this.blockBuffers((function(){var t=self.performance.now();i.stats.buffering.end=t,a&&(a.stats.buffering.end=t);var e=a?a.stats:i.stats;r.hls.trigger(n.a.FRAG_BUFFERED,{frag:i,part:a,stats:e,id:i.type})}),s)},e.onFragChanged=function(t,e){this.flushBackBuffer()},e.onBufferEos=function(t,e){var r=this;this.getSourceBufferTypes().reduce((function(t,i){var a=r.sourceBuffer[i];return e.type&&e.type!==i||a&&!a.ended&&(a.ended=!0,o.b.log("[buffer-controller]: "+i+" sourceBuffer now EOS")),t&&!(a&&!a.ended)}),!0)&&this.blockBuffers((function(){var t=r.mediaSource;t&&"open"===t.readyState&&t.endOfStream()}))},e.onLevelUpdated=function(t,e){var r=e.details;r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())},e.flushBackBuffer=function(){var t=this.hls,e=this.details,r=this.media,i=this.sourceBuffer;if(r&&null!==e){var s=this.getSourceBufferTypes();if(s.length){var o=e.live&&null!==t.config.liveBackBufferLength?t.config.liveBackBufferLength:t.config.backBufferLength;if(Object(a.a)(o)&&!(o<0)){var l=r.currentTime,u=e.levelTargetDuration,h=Math.max(o,u),d=Math.floor(l/u)*u-h;s.forEach((function(r){var a=i[r];if(a){var s=lt.getBuffered(a);s.length>0&&d>s.start(0)&&(t.trigger(n.a.BACK_BUFFER_REACHED,{bufferEnd:d}),e.live&&t.trigger(n.a.LIVE_BACK_BUFFER_REACHED,{bufferEnd:d}),t.trigger(n.a.BUFFER_FLUSHING,{startOffset:0,endOffset:d,type:r}))}}))}}}},e.updateMediaElementDuration=function(){if(this.details&&this.media&&this.mediaSource&&"open"===this.mediaSource.readyState){var t=this.details,e=this.hls,r=this.media,i=this.mediaSource,n=t.fragments[0].start+t.totalduration,s=r.duration,l=Object(a.a)(i.duration)?i.duration:0;t.live&&e.config.liveDurationInfinity?(o.b.log("[buffer-controller]: Media Source duration is set to Infinity"),i.duration=1/0,this.updateSeekableRange(t)):(n>l&&n>s||!Object(a.a)(s))&&(o.b.log("[buffer-controller]: Updating Media Source duration to "+n.toFixed(3)),i.duration=n)}},e.updateSeekableRange=function(t){var e=this.mediaSource,r=t.fragments;if(r.length&&t.live&&null!=e&&e.setLiveSeekableRange){var i=Math.max(0,r[0].start),a=Math.max(i,i+t.totalduration);e.setLiveSeekableRange(i,a)}},e.checkPendingTracks=function(){var t=this.bufferCodecEventsExpected,e=this.operationQueue,r=this.pendingTracks,i=Object.keys(r).length;if(i&&!t||2===i){this.createSourceBuffers(r),this.pendingTracks={};var a=Object.keys(this.sourceBuffer);if(0===a.length)return void this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,reason:"could not create source buffer for media codec(s)"});a.forEach((function(t){e.executeNext(t)}))}},e.createSourceBuffers=function(t){var e=this.sourceBuffer,r=this.mediaSource;if(!r)throw Error("createSourceBuffers called when mediaSource was null");var i=0;for(var a in t)if(!e[a]){var l=t[a];if(!l)throw Error("source buffer exists for track "+a+", however track does not");var u=l.levelCodec||l.codec,h=l.container+";codecs="+u;o.b.log("[buffer-controller]: creating sourceBuffer("+h+")");try{var d=e[a]=r.addSourceBuffer(h),c=a;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.tracks[a]={buffer:d,codec:u,container:l.container,levelCodec:l.levelCodec,id:l.id},i++}catch(t){o.b.error("[buffer-controller]: error while trying to add sourceBuffer: "+t.message),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:t,mimeType:h})}}i&&this.hls.trigger(n.a.BUFFER_CREATED,{tracks:this.tracks})},e._onSBUpdateStart=function(t){this.operationQueue.current(t).onStart()},e._onSBUpdateEnd=function(t){var e=this.operationQueue;e.current(t).onComplete(),e.shiftAndExecuteNext(t)},e._onSBUpdateError=function(t,e){o.b.error("[buffer-controller]: "+t+" SourceBuffer error",e),this.hls.trigger(n.a.ERROR,{type:s.b.MEDIA_ERROR,details:s.a.BUFFER_APPENDING_ERROR,fatal:!1});var r=this.operationQueue.current(t);r&&r.onError(e)},e.removeExecutor=function(t,e,r){var i=this.media,n=this.mediaSource,s=this.operationQueue,l=this.sourceBuffer[t];if(!i||!n||!l)return o.b.warn("[buffer-controller]: Attempting to remove from the "+t+" SourceBuffer, but it does not exist"),void s.shiftAndExecuteNext(t);var u=Object(a.a)(i.duration)?i.duration:1/0,h=Object(a.a)(n.duration)?n.duration:1/0,d=Math.max(0,e),c=Math.min(r,u,h);c>d?(o.b.log("[buffer-controller]: Removing ["+d+","+c+"] from the "+t+" SourceBuffer"),l.remove(d,c)):s.shiftAndExecuteNext(t)},e.appendExecutor=function(t,e){var r=this.operationQueue,i=this.sourceBuffer[e];if(!i)return o.b.warn("[buffer-controller]: Attempting to append to the "+e+" SourceBuffer, but it does not exist"),void r.shiftAndExecuteNext(e);i.ended=!1,i.appendBuffer(t)},e.blockBuffers=function(t,e){var r=this;if(void 0===e&&(e=this.getSourceBufferTypes()),!e.length)return o.b.log("[buffer-controller]: Blocking operation requested, but no SourceBuffers exist"),void Promise.resolve(t);var i=this.operationQueue,a=e.map((function(t){return i.appendBlocker(t)}));Promise.all(a).then((function(){t(),e.forEach((function(t){var e=r.sourceBuffer[t];e&&e.updating||i.shiftAndExecuteNext(t)}))}))},e.getSourceBufferTypes=function(){return Object.keys(this.sourceBuffer)},e.addBufferListener=function(t,e,r){var i=this.sourceBuffer[t];if(i){var a=r.bind(this,t);this.listeners[t].push({event:e,listener:a}),i.addEventListener(e,a)}},e.removeBufferListeners=function(t){var e=this.sourceBuffer[t];e&&this.listeners[t].forEach((function(t){e.removeEventListener(t.event,t.listener)}))},t}(),De={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},ke=function(t){var e=t;return De.hasOwnProperty(t)&&(e=De[t]),String.fromCharCode(e)},_e={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Ie={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Ce={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},we={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Oe=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];!function(t){t[t.ERROR=0]="ERROR",t[t.TEXT=1]="TEXT",t[t.WARNING=2]="WARNING",t[t.INFO=2]="INFO",t[t.DEBUG=3]="DEBUG",t[t.DATA=3]="DATA"}(Ee||(Ee={}));var xe=function(){function t(){this.time=null,this.verboseLevel=Ee.ERROR}return t.prototype.log=function(t,e){this.verboseLevel>=t&&o.b.log(this.time+" ["+t+"] "+e)},t}(),Pe=function(t){for(var e=[],r=0;r100&&(this.logger.log(Ee.DEBUG,"Too large cursor position "+this.pos),this.pos=100)},e.moveCursor=function(t){var e=this.pos+t;if(t>1)for(var r=this.pos+1;r=144&&this.backSpace();var e=ke(t);this.pos>=100?this.logger.log(Ee.ERROR,"Cannot insert "+t.toString(16)+" ("+e+") at position "+this.pos+". Skipping it!"):(this.chars[this.pos].setChar(e,this.currPenState),this.moveCursor(1))},e.clearFromPos=function(t){var e;for(e=t;e<100;e++)this.chars[e].reset()},e.clear=function(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()},e.clearToEndOfRow=function(){this.clearFromPos(this.pos)},e.getTextString=function(){for(var t=[],e=!0,r=0;r<100;r++){var i=this.chars[r].uchar;" "!==i&&(e=!1),t.push(i)}return e?"":t.join("")},e.setPenStyles=function(t){this.currPenState.setStyles(t),this.chars[this.pos].setPenState(this.currPenState)},t}(),Ue=function(){function t(t){this.rows=void 0,this.currRow=void 0,this.nrRollUpRows=void 0,this.lastOutputScreen=void 0,this.logger=void 0,this.rows=[];for(var e=0;e<15;e++)this.rows.push(new Ne(t));this.logger=t,this.currRow=14,this.nrRollUpRows=null,this.lastOutputScreen=null,this.reset()}var e=t.prototype;return e.reset=function(){for(var t=0;t<15;t++)this.rows[t].clear();this.currRow=14},e.equals=function(t){for(var e=!0,r=0;r<15;r++)if(!this.rows[r].equals(t.rows[r])){e=!1;break}return e},e.copy=function(t){for(var e=0;e<15;e++)this.rows[e].copy(t.rows[e])},e.isEmpty=function(){for(var t=!0,e=0;e<15;e++)if(!this.rows[e].isEmpty()){t=!1;break}return t},e.backSpace=function(){this.rows[this.currRow].backSpace()},e.clearToEndOfRow=function(){this.rows[this.currRow].clearToEndOfRow()},e.insertChar=function(t){this.rows[this.currRow].insertChar(t)},e.setPen=function(t){this.rows[this.currRow].setPenStyles(t)},e.moveCursor=function(t){this.rows[this.currRow].moveCursor(t)},e.setCursor=function(t){this.logger.log(Ee.INFO,"setCursor: "+t),this.rows[this.currRow].setCursor(t)},e.setPAC=function(t){this.logger.log(Ee.INFO,"pacData = "+JSON.stringify(t));var e=t.row-1;if(this.nrRollUpRows&&e0&&(r=t?"["+e.join(" | ")+"]":e.join("\n")),r},e.getTextAndFormat=function(){return this.rows},t}(),Be=function(){function t(t,e,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=e,this.mode=null,this.verbose=0,this.displayedMemory=new Ue(r),this.nonDisplayedMemory=new Ue(r),this.lastOutputScreen=new Ue(r),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}var e=t.prototype;return e.reset=function(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[14],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null},e.getHandler=function(){return this.outputFilter},e.setHandler=function(t){this.outputFilter=t},e.setPAC=function(t){this.writeScreen.setPAC(t)},e.setBkgData=function(t){this.writeScreen.setBkgData(t)},e.setMode=function(t){t!==this.mode&&(this.mode=t,this.logger.log(Ee.INFO,"MODE="+t),"MODE_POP-ON"===this.mode?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),"MODE_ROLL-UP"!==this.mode&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)},e.insertChars=function(t){for(var e=0;e=46,e.italics)e.foreground="white";else{var r=Math.floor(t/2)-16;e.foreground=["white","green","blue","cyan","red","yellow","magenta"][r]}this.logger.log(Ee.INFO,"MIDROW: "+JSON.stringify(e)),this.writeScreen.setPen(e)},e.outputDataUpdate=function(t){void 0===t&&(t=!1);var e=this.logger.time;null!==e&&this.outputFilter&&(null!==this.cueStartTime||this.displayedMemory.isEmpty()?this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,e,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:e):this.cueStartTime=e,this.lastOutputScreen.copy(this.displayedMemory))},e.cueSplitAtTime=function(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))},t}();function Ge(t,e,r){r.a=t,r.b=e}function Ke(t,e,r){return r.a===t&&r.b===e}var je=function(){function t(t,e,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=void 0,this.logger=void 0;var i=new xe;this.channels=[null,new Be(t,e,i),new Be(t+1,r,i)],this.cmdHistory={a:null,b:null},this.logger=i}var e=t.prototype;return e.getHandler=function(t){return this.channels[t].getHandler()},e.setHandler=function(t,e){this.channels[t].setHandler(e)},e.addData=function(t,e){var r,i,a,n=!1;this.logger.time=t;for(var s=0;s ("+Pe([i,a])+")"),(r=this.parseCmd(i,a))||(r=this.parseMidrow(i,a)),r||(r=this.parsePAC(i,a)),r||(r=this.parseBackgroundAttributes(i,a)),!r&&(n=this.parseChars(i,a))){var o=this.currentChannel;if(o&&o>0)this.channels[o].insertChars(n);else this.logger.log(Ee.WARNING,"No channel found yet. TEXT-MODE?")}r||n||this.logger.log(Ee.WARNING,"Couldn't parse cleaned data "+Pe([i,a])+" orig: "+Pe([e[s],e[s+1]]))}},e.parseCmd=function(t,e){var r=this.cmdHistory;if(!((20===t||28===t||21===t||29===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=33&&e<=35))return!1;if(Ke(t,e,r))return Ge(null,null,r),this.logger.log(Ee.DEBUG,"Repeated command ("+Pe([t,e])+") is dropped"),!0;var i=20===t||21===t||23===t?1:2,a=this.channels[i];return 20===t||21===t||28===t||29===t?32===e?a.ccRCL():33===e?a.ccBS():34===e?a.ccAOF():35===e?a.ccAON():36===e?a.ccDER():37===e?a.ccRU(2):38===e?a.ccRU(3):39===e?a.ccRU(4):40===e?a.ccFON():41===e?a.ccRDC():42===e?a.ccTR():43===e?a.ccRTD():44===e?a.ccEDM():45===e?a.ccCR():46===e?a.ccENM():47===e&&a.ccEOC():a.ccTO(e-32),Ge(t,e,r),this.currentChannel=i,!0},e.parseMidrow=function(t,e){var r=0;if((17===t||25===t)&&e>=32&&e<=47){if((r=17===t?1:2)!==this.currentChannel)return this.logger.log(Ee.ERROR,"Mismatch channel in midrow parsing"),!1;var i=this.channels[r];return!!i&&(i.ccMIDROW(e),this.logger.log(Ee.DEBUG,"MIDROW ("+Pe([t,e])+")"),!0)}return!1},e.parsePAC=function(t,e){var r,i=this.cmdHistory;if(!((t>=17&&t<=23||t>=25&&t<=31)&&e>=64&&e<=127)&&!((16===t||24===t)&&e>=64&&e<=95))return!1;if(Ke(t,e,i))return Ge(null,null,i),!0;var a=t<=23?1:2;r=e>=64&&e<=95?1===a?_e[t]:Ce[t]:1===a?Ie[t]:we[t];var n=this.channels[a];return!!n&&(n.setPAC(this.interpretPAC(r,e)),Ge(t,e,i),this.currentChannel=a,!0)},e.interpretPAC=function(t,e){var r,i={color:null,italics:!1,indent:null,underline:!1,row:t};return r=e>95?e-96:e-64,i.underline=1==(1&r),r<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(i.italics=!0,i.color="white"):i.indent=4*Math.floor((r-16)/2),i},e.parseChars=function(t,e){var r,i,a=null,n=null;(t>=25?(r=2,n=t-8):(r=1,n=t),n>=17&&n<=19)?(i=17===n?e+80:18===n?e+112:e+144,this.logger.log(Ee.INFO,"Special char '"+ke(i)+"' in channel "+r),a=[i]):t>=32&&t<=127&&(a=0===e?[t]:[t,e]);if(a){var s=Pe(a);this.logger.log(Ee.DEBUG,"Char codes = "+s.join(",")),Ge(t,e,this.cmdHistory)}return a},e.parseBackgroundAttributes=function(t,e){var r;if(!((16===t||24===t)&&e>=32&&e<=47)&&!((23===t||31===t)&&e>=45&&e<=47))return!1;var i={};16===t||24===t?(r=Math.floor((e-32)/2),i.background=Oe[r],e%2==1&&(i.background=i.background+"_semi")):45===e?i.background="transparent":(i.foreground="black",47===e&&(i.underline=!0));var a=t<=23?1:2;return this.channels[a].setBkgData(i),Ge(t,e,this.cmdHistory),!0},e.reset=function(){for(var t=0;tt)&&(this.startTime=t),this.endTime=e,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)},e.reset=function(){this.cueRanges=[]},t}(),Ve=function(){if("undefined"!=typeof self&&self.VTTCue)return self.VTTCue;var t=["","lr","rl"],e=["start","middle","end","left","right"];function r(t,e){if("string"!=typeof e)return!1;if(!Array.isArray(t))return!1;var r=e.toLowerCase();return!!~t.indexOf(r)&&r}function i(t){return r(e,t)}function a(t){for(var e=arguments.length,r=new Array(e>1?e-1:0),i=1;i100)throw new Error("Position must be between 0 and 100.");T=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",a({},l,{get:function(){return E},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");E=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",a({},l,{get:function(){return b},set:function(t){if(t<0||t>100)throw new Error("Size must be between 0 and 100.");b=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",a({},l,{get:function(){return S},set:function(t){var e=i(t);if(!e)throw new SyntaxError("An invalid or illegal string was specified.");S=e,this.hasBeenReset=!0}})),o.displayState=void 0}return n.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},n}(),We=function(){function t(){}return t.prototype.decode=function(t,e){if(!t)return"";if("string"!=typeof t)throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))},t}();function Ye(t){function e(t,e,r,i){return 3600*(0|t)+60*(0|e)+(0|r)+parseFloat(i||0)}var r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}var qe=function(){function t(){this.values=Object.create(null)}var e=t.prototype;return e.set=function(t,e){this.get(t)||""===e||(this.values[t]=e)},e.get=function(t,e,r){return r?this.has(t)?this.values[t]:e[r]:this.has(t)?this.values[t]:e},e.has=function(t){return t in this.values},e.alt=function(t,e,r){for(var i=0;i=0&&r<=100)return this.set(t,r),!0}return!1},t}();function Xe(t,e,r,i){var a=i?t.split(i):[t];for(var n in a)if("string"==typeof a[n]){var s=a[n].split(r);if(2===s.length)e(s[0],s[1])}}var ze=new Ve(0,0,""),Qe="middle"===ze.align?"middle":"center";function $e(t,e,r){var i=t;function a(){var e=Ye(t);if(null===e)throw new Error("Malformed timestamp: "+i);return t=t.replace(/^[^\sa-zA-Z-]+/,""),e}function n(){t=t.replace(/^\s+/,"")}if(n(),e.startTime=a(),n(),"--\x3e"!==t.substr(0,3))throw new Error("Malformed time stamp (time stamps must be separated by '--\x3e'): "+i);t=t.substr(3),n(),e.endTime=a(),n(),function(t,e){var i=new qe;Xe(t,(function(t,e){var a;switch(t){case"region":for(var n=r.length-1;n>=0;n--)if(r[n].id===e){i.set(t,r[n].region);break}break;case"vertical":i.alt(t,e,["rl","lr"]);break;case"line":a=e.split(","),i.integer(t,a[0]),i.percent(t,a[0])&&i.set("snapToLines",!1),i.alt(t,a[0],["auto"]),2===a.length&&i.alt("lineAlign",a[1],["start",Qe,"end"]);break;case"position":a=e.split(","),i.percent(t,a[0]),2===a.length&&i.alt("positionAlign",a[1],["start",Qe,"end","line-left","line-right","auto"]);break;case"size":i.percent(t,e);break;case"align":i.alt(t,e,["start",Qe,"end","left","right"])}}),/:/,/\s/),e.region=i.get("region",null),e.vertical=i.get("vertical","");var a=i.get("line","auto");"auto"===a&&-1===ze.line&&(a=-1),e.line=a,e.lineAlign=i.get("lineAlign","start"),e.snapToLines=i.get("snapToLines",!0),e.size=i.get("size",100),e.align=i.get("align",Qe);var n=i.get("position","auto");"auto"===n&&50===ze.position&&(n="start"===e.align||"left"===e.align?0:"end"===e.align||"right"===e.align?100:50),e.position=n}(t,e)}function Je(t){return t.replace(//gi,"\n")}var Ze=function(){function t(){this.state="INITIAL",this.buffer="",this.decoder=new We,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}var e=t.prototype;return e.parse=function(t){var e=this;function r(){var t=e.buffer,r=0;for(t=Je(t);r>>0).toString()};function nr(t,e,r){return ar(t.toString())+ar(e.toString())+ar(r)}function sr(t,e,r,i,n,s,o,l){var u,h=new Ze,d=Object(F.f)(new Uint8Array(t)).trim().replace(rr,"\n").split("\n"),c=[],f=Object(tr.a)(e,r),g="00:00.000",v=0,p=0,m=!0,y=!1;h.oncue=function(t){var e=i[n],r=i.ccOffset,a=(v-f)/9e4;if(null!=e&&e.new&&(void 0!==p?r=i.ccOffset=e.start:function(t,e,r){var i=t[e],a=t[i.prevCC];if(!a||!a.new&&i.new)return t.ccOffset=t.presentationOffset=i.start,void(i.new=!1);for(;null!==(n=a)&&void 0!==n&&n.new;){var n;t.ccOffset+=i.start-a.start,i.new=!1,a=t[(i=a).prevCC]}t.presentationOffset=r}(i,n,a)),a&&(r=a-i.presentationOffset),y){var o=t.endTime-t.startTime,l=Object(er.b)(9e4*(t.startTime+r-p),9e4*s)/9e4;t.startTime=l,t.endTime=l+o}var u=t.text.trim();t.text=decodeURIComponent(encodeURIComponent(u)),t.id||(t.id=nr(t.startTime,t.endTime,u)),t.endTime>0&&c.push(t)},h.onparsingerror=function(t){u=t},h.onflush=function(){u?l(u):o(c)},d.forEach((function(t){if(m){if(ir(t,"X-TIMESTAMP-MAP=")){m=!1,y=!0,t.substr(16).split(",").forEach((function(t){ir(t,"LOCAL:")?g=t.substr(6):ir(t,"MPEGTS:")&&(v=parseInt(t.substr(7)))}));try{p=function(t){var e=parseInt(t.substr(-3)),r=parseInt(t.substr(-6,2)),i=parseInt(t.substr(-9,2)),n=t.length>9?parseInt(t.substr(0,t.indexOf(":"))):0;if(!(Object(a.a)(e)&&Object(a.a)(r)&&Object(a.a)(i)&&Object(a.a)(n)))throw Error("Malformed X-TIMESTAMP-MAP: Local:"+t);return e+=1e3*r,e+=6e4*i,e+=36e5*n}(g)/1e3}catch(t){y=!1,u=t}return}""===t&&(m=!1)}h.parse(t+"\n")})),h.flush()}function or(){return(or=Object.assign||function(t){for(var e=1;e=0&&(c[0]=Math.min(c[0],e),c[1]=Math.max(c[1],r),h=!0,f/(r-e)>.5))return}if(h||a.push([e,r]),this.config.renderTextTracksNatively){var g=this.captionsTracks[t];this.Cues.newCue(g,e,r,i)}else{var v=this.Cues.newCue(null,e,r,i);this.hls.trigger(n.a.CUES_PARSED,{type:"captions",cues:v,track:t})}},e.onInitPtsFound=function(t,e){var r=this,i=e.frag,a=e.id,s=e.initPTS,o=e.timescale,l=this.unparsedVttFrags;"main"===a&&(this.initPTS[i.cc]=s,this.timescale[i.cc]=o),l.length&&(this.unparsedVttFrags=[],l.forEach((function(t){r.onFragLoaded(n.a.FRAG_LOADED,t)})))},e.getExistingTrack=function(t){var e=this.media;if(e)for(var r=0;r0&&this.mediaWidth>0){var t=this.hls.levels;if(t.length){var e=this.hls;e.autoLevelCapping=this.getMaxLevel(t.length-1),e.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=e.autoLevelCapping}}},a.getMaxLevel=function(e){var r=this,i=this.hls.levels;if(!i.length)return-1;var a=i.filter((function(i,a){return t.isLevelAllowed(a,r.restrictedLevels)&&a<=e}));return this.clientRect=null,t.getMaxLevelByMediaSize(a,this.mediaWidth,this.mediaHeight)},a.startCapping=function(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,this.hls.firstLevel=this.getMaxLevel(this.firstLevel),self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())},a.stopCapping=function(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)},a.getDimensions=function(){if(this.clientRect)return this.clientRect;var t=this.media,e={width:0,height:0};if(t){var r=t.getBoundingClientRect();e.width=r.width,e.height=r.height,e.width||e.height||(e.width=r.right-r.left||t.width||0,e.height=r.bottom-r.top||t.height||0)}return this.clientRect=e,e},t.isLevelAllowed=function(t,e){return void 0===e&&(e=[]),-1===e.indexOf(t)},t.getMaxLevelByMediaSize=function(t,e,r){if(!t||!t.length)return-1;for(var i,a,n=t.length-1,s=0;s=e||o.height>=r)&&(i=o,!(a=t[s+1])||i.width!==a.width||i.height!==a.height)){n=s;break}}return n},e=t,i=[{key:"contentScaleFactor",get:function(){var t=1;try{t=self.devicePixelRatio}catch(t){}return t}}],(r=[{key:"mediaWidth",get:function(){return this.getDimensions().width*t.contentScaleFactor}},{key:"mediaHeight",get:function(){return this.getDimensions().height*t.contentScaleFactor}}])&&Tr(e.prototype,r),i&&Tr(e,i),t}(),Sr=function(){function t(t){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=t,this.registerListeners()}var e=t.prototype;return e.setStreamController=function(t){this.streamController=t},e.registerListeners=function(){this.hls.on(n.a.MEDIA_ATTACHING,this.onMediaAttaching,this)},e.unregisterListeners=function(){this.hls.off(n.a.MEDIA_ATTACHING,this.onMediaAttaching)},e.destroy=function(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null},e.onMediaAttaching=function(t,e){var r=this.hls.config;if(r.capLevelOnFPSDrop){var i=e.media instanceof self.HTMLVideoElement?e.media:null;this.media=i,i&&"function"==typeof i.getVideoPlaybackQuality&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setTimeout(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}},e.checkFPS=function(t,e,r){var i=performance.now();if(e){if(this.lastTime){var a=i-this.lastTime,s=r-this.lastDroppedFrames,l=e-this.lastDecodedFrames,u=1e3*s/a,h=this.hls;if(h.trigger(n.a.FPS_DROP,{currentDropped:s,currentDecoded:l,totalDroppedFrames:r}),u>0&&s>h.config.fpsDroppedMonitoringThreshold*l){var d=h.currentLevel;o.b.warn("drop FPS ratio greater than max allowed value for currentLevel: "+d),d>0&&(-1===h.autoLevelCapping||h.autoLevelCapping>=d)&&(d-=1,h.trigger(n.a.FPS_DROP_LEVEL_CAPPING,{level:d,droppedLevel:h.currentLevel}),h.autoLevelCapping=d,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=r,this.lastDecodedFrames=e}},e.checkFPSInterval=function(){var t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){var e=t.getVideoPlaybackQuality();this.checkFPS(t,e.totalVideoFrames,e.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)},t}();!function(t){t.WIDEVINE="com.widevine.alpha",t.PLAYREADY="com.microsoft.playready"}(Er||(Er={}));var Lr="undefined"!=typeof self&&self.navigator&&self.navigator.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null;function Ar(t,e){for(var r=0;r3)return void this.hls.trigger(n.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0});var u=3-this._requestLicenseFailureCount+1;o.b.warn("Retrying license request, "+u+" attempts left"),this._requestLicense(r,i)}}},a._generateLicenseRequestChallenge=function(t,e){switch(t.mediaKeySystemDomain){case Er.WIDEVINE:return e}throw new Error("unsupported key-system: "+t.mediaKeySystemDomain)},a._requestLicense=function(t,e){o.b.log("Requesting content license for key-system");var r=this._mediaKeysList[0];if(!r)return o.b.error("Fatal error: Media is encrypted but no key-system access has been obtained yet"),void this.hls.trigger(n.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_NO_ACCESS,fatal:!0});try{var i=this.getLicenseServerUrl(r.mediaKeySystemDomain),a=this._createLicenseXhr(i,t,e);o.b.log("Sending license request to URL: "+i);var l=this._generateLicenseRequestChallenge(r,t);a.send(l)}catch(t){o.b.error("Failure requesting DRM license: "+t),this.hls.trigger(n.a.ERROR,{type:s.b.KEY_SYSTEM_ERROR,details:s.a.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0})}},a.onMediaAttached=function(t,e){if(this._emeEnabled){var r=e.media;this._media=r,r.addEventListener("encrypted",this._onMediaEncrypted)}},a.onMediaDetached=function(){var t=this._media,e=this._mediaKeysList;t&&(t.removeEventListener("encrypted",this._onMediaEncrypted),this._media=null,this._mediaKeysList=[],Promise.all(e.map((function(t){if(t.mediaKeysSession)return t.mediaKeysSession.close().catch((function(){}))}))).then((function(){return t.setMediaKeys(null)})).catch((function(){})))},a.onManifestParsed=function(t,e){if(this._emeEnabled){var r=e.levels.map((function(t){return t.audioCodec})).filter((function(t){return!!t})),i=e.levels.map((function(t){return t.videoCodec})).filter((function(t){return!!t}));this._attemptKeySystemAccess(Er.WIDEVINE,r,i)}},e=t,(r=[{key:"requestMediaKeySystemAccess",get:function(){if(!this._requestMediaKeySystemAccess)throw new Error("No requestMediaKeySystemAccess function configured");return this._requestMediaKeySystemAccess}}])&&Ar(e.prototype,r),i&&Ar(e,i),t}(),Dr=r(11),kr=/^age:\s*[\d.]+\s*$/m,_r=function(){function t(t){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=void 0,this.loader=null,this.stats=void 0,this.xhrSetup=t?t.xhrSetup:null,this.stats=new Dr.a,this.retryDelay=0}var e=t.prototype;return e.destroy=function(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null},e.abortInternal=function(){var t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,4!==t.readyState&&(this.stats.aborted=!0,t.abort()))},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)},e.load=function(t,e,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=e,this.callbacks=r,this.retryDelay=e.retryDelay,this.loadInternal()},e.loadInternal=function(){var t=this.config,e=this.context;if(t){var r=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0;var a=this.xhrSetup;try{if(a)try{a(r,e.url)}catch(t){r.open("GET",e.url,!0),a(r,e.url)}r.readyState||r.open("GET",e.url,!0)}catch(t){return void this.callbacks.onError({code:r.status,text:t.message},e,r)}e.rangeEnd&&r.setRequestHeader("Range","bytes="+e.rangeStart+"-"+(e.rangeEnd-1)),r.onreadystatechange=this.readystatechange.bind(this),r.onprogress=this.loadprogress.bind(this),r.responseType=e.responseType,self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),t.timeout),r.send()}},e.readystatechange=function(){var t=this.context,e=this.loader,r=this.stats;if(t&&e){var i=e.readyState,a=this.config;if(!r.aborted&&i>=2)if(self.clearTimeout(this.requestTimeout),0===r.loading.first&&(r.loading.first=Math.max(self.performance.now(),r.loading.start)),4===i){e.onreadystatechange=null,e.onprogress=null;var n=e.status;if(n>=200&&n<300){var s,l;if(r.loading.end=Math.max(self.performance.now(),r.loading.first),l="arraybuffer"===t.responseType?(s=e.response).byteLength:(s=e.responseText).length,r.loaded=r.total=l,!this.callbacks)return;var u=this.callbacks.onProgress;if(u&&u(r,t,s,e),!this.callbacks)return;var h={url:e.responseURL,data:s};this.callbacks.onSuccess(h,r,t,e)}else r.retry>=a.maxRetry||n>=400&&n<499?(o.b.error(n+" while loading "+t.url),this.callbacks.onError({code:n,text:e.statusText},t,e)):(o.b.warn(n+" while loading "+t.url+", retrying in "+this.retryDelay+"..."),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay),this.retryDelay=Math.min(2*this.retryDelay,a.maxRetryDelay),r.retry++)}else self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),a.timeout)}},e.loadtimeout=function(){o.b.warn("timeout while loading "+this.context.url);var t=this.callbacks;t&&(this.abortInternal(),t.onTimeout(this.stats,this.context,this.loader))},e.loadprogress=function(t){var e=this.stats;e.loaded=t.loaded,t.lengthComputable&&(e.total=t.total)},e.getCacheAge=function(){var t=null;if(this.loader&&kr.test(this.loader.getAllResponseHeaders())){var e=this.loader.getResponseHeader("age");t=e?parseFloat(e):null}return t},t}();function Ir(t){var e="function"==typeof Map?new Map:void 0;return(Ir=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,i)}function i(){return Cr(t,arguments,xr(this).constructor)}return i.prototype=Object.create(t.prototype,{constructor:{value:i,enumerable:!1,writable:!0,configurable:!0}}),Or(i,t)})(t)}function Cr(t,e,r){return(Cr=wr()?Reflect.construct:function(t,e,r){var i=[null];i.push.apply(i,e);var a=new(Function.bind.apply(t,i));return r&&Or(a,r.prototype),a}).apply(null,arguments)}function wr(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function Or(t,e){return(Or=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function xr(t){return(xr=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}var Pr=function(){function t(t){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=void 0,this.response=void 0,this.controller=void 0,this.context=void 0,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=t.fetchSetup||Mr,this.controller=new self.AbortController,this.stats=new Dr.a}var e=t.prototype;return e.destroy=function(){this.loader=this.callbacks=null,this.abortInternal()},e.abortInternal=function(){this.stats.aborted=!0,this.controller.abort()},e.abort=function(){var t;this.abortInternal(),null!==(t=this.callbacks)&&void 0!==t&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)},e.load=function(t,e,r){var i=this,n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();var s=function(t,e){var r={method:"GET",mode:"cors",credentials:"same-origin",signal:e};t.rangeEnd&&(r.headers=new self.Headers({Range:"bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)}));return r}(t,this.controller.signal),o=r.onProgress,l="arraybuffer"===t.responseType,u=l?"byteLength":"length";this.context=t,this.config=e,this.callbacks=r,this.request=this.fetchSetup(t,s),self.clearTimeout(this.requestTimeout),this.requestTimeout=self.setTimeout((function(){i.abortInternal(),r.onTimeout(n,t,i.response)}),e.timeout),self.fetch(this.request).then((function(r){if(i.response=i.loader=r,!r.ok){var s=r.status,u=r.statusText;throw new Fr(u||"fetch, bad network response",s,r)}return n.loading.first=Math.max(self.performance.now(),n.loading.start),n.total=parseInt(r.headers.get("Content-Length")||"0"),o&&Object(a.a)(e.highWaterMark)?i.loadProgressively(r,n,t,e.highWaterMark,o):l?r.arrayBuffer():r.text()})).then((function(s){var l=i.response;self.clearTimeout(i.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first),n.loaded=n.total=s[u];var h={url:l.url,data:s};o&&!Object(a.a)(e.highWaterMark)&&o(n,t,s,l),r.onSuccess(h,n,t,l)})).catch((function(e){if(self.clearTimeout(i.requestTimeout),!n.aborted){var a=e.code||0;r.onError({code:a,text:e.message},t,e.details)}}))},e.getCacheAge=function(){var t=null;if(this.response){var e=this.response.headers.get("age");t=e?parseFloat(e):null}return t},e.loadProgressively=function(t,e,r,i,a){void 0===i&&(i=0);var n=new oe.a,s=t.body.getReader();return function o(){return s.read().then((function(s){if(s.done)return n.dataLength&&a(e,r,n.flush(),t),Promise.resolve(new ArrayBuffer(0));var l=s.value,u=l.length;return e.loaded+=u,u=i&&a(e,r,n.flush(),t)):a(e,r,l,t),o()})).catch((function(){return Promise.reject()}))}()},t}();function Mr(t,e){return new self.Request(t.url,e)}var Fr=function(t){var e,r;function i(e,r,i){var a;return(a=t.call(this,e)||this).code=void 0,a.details=void 0,a.code=r,a.details=i,a}return r=t,(e=i).prototype=Object.create(r.prototype),e.prototype.constructor=e,Or(e,r),i}(Ir(Error)),Nr=Pr,Ur=/\s/;function Br(){return(Br=Object.assign||function(t){for(var e=1;e=16?o--:o++;var f=Je(l.trim()),g=nr(e,r,f);t&&t.cues&&t.cues.getCueById(g)||((n=new h(e,r,f)).id=g,n.line=d+1,n.align="left",n.position=10+Math.min(80,10*Math.floor(8*o/32)),u.push(n))}return t&&u.length&&(u.sort((function(t,e){return"auto"===t.line||"auto"===e.line?0:t.line>8&&e.line>8?e.line-t.line:t.line-e.line})),u.forEach((function(e){return x(t,e)}))),u}},enableCEA708Captions:!0,enableWebVTT:!0,enableIMSC1:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}),{},{subtitleStreamController:pe,subtitleTrackController:be,timelineController:mr,audioStreamController:he,audioTrackController:fe,emeController:Rr});function Vr(t){var e=t.loader;e!==Nr&&e!==_r?(o.b.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):function(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch(t){}return!1}()&&(t.loader=Nr,t.progressive=!0,t.enableSoftwareAES=!0,o.b.log("[config]: Progressive streaming enabled, using FetchLoader"))}function Wr(t,e){for(var r=0;re)return i;return 0}},{key:"maxAutoLevel",get:function(){var t=this.levels,e=this.autoLevelCapping;return-1===e&&t&&t.length?t.length-1:e}},{key:"nextAutoLevel",get:function(){return Math.min(Math.max(this.abrController.nextAutoLevel,this.minAutoLevel),this.maxAutoLevel)},set:function(t){this.abrController.nextAutoLevel=Math.max(this.minAutoLevel,t)}},{key:"audioTracks",get:function(){var t=this.audioTrackController;return t?t.audioTracks:[]}},{key:"audioTrack",get:function(){var t=this.audioTrackController;return t?t.audioTrack:-1},set:function(t){var e=this.audioTrackController;e&&(e.audioTrack=t)}},{key:"subtitleTracks",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTracks:[]}},{key:"subtitleTrack",get:function(){var t=this.subtitleTrackController;return t?t.subtitleTrack:-1},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleTrack=t)}},{key:"media",get:function(){return this._media}},{key:"subtitleDisplay",get:function(){var t=this.subtitleTrackController;return!!t&&t.subtitleDisplay},set:function(t){var e=this.subtitleTrackController;e&&(e.subtitleDisplay=t)}},{key:"lowLatencyMode",get:function(){return this.config.lowLatencyMode},set:function(t){this.config.lowLatencyMode=t}},{key:"liveSyncPosition",get:function(){return this.latencyController.liveSyncPosition}},{key:"latency",get:function(){return this.latencyController.latency}},{key:"maxLatency",get:function(){return this.latencyController.maxLatency}},{key:"targetLatency",get:function(){return this.latencyController.targetLatency}},{key:"drift",get:function(){return this.latencyController.drift}},{key:"forceStartLoad",get:function(){return this.streamController.forceStartLoad}}])&&Wr(e.prototype,r),a&&Wr(e,a),t}();Yr.defaultConfig=void 0}]).default})); +//# sourceMappingURL=hls.min.js.map +// @license-end \ No newline at end of file diff --git a/static/playHLSVideo.js b/static/playHLSVideo.js new file mode 100644 index 0000000..bb6ebeb --- /dev/null +++ b/static/playHLSVideo.js @@ -0,0 +1,77 @@ +// @license http://www.gnu.org/licenses/agpl-3.0.html AGPL-3.0 +(function () { + if (Hls.isSupported()) { + var videoSources = document.querySelectorAll("video source[type='application/vnd.apple.mpegurl']"); + videoSources.forEach(function (source) { + var playlist = source.src; + + var oldVideo = source.parentNode; + var autoplay = oldVideo.classList.contains("hls_autoplay"); + + // If HLS is supported natively then don't use hls.js + if (oldVideo.canPlayType(source.type)) { + if (autoplay) { + oldVideo.play(); + } + return; + } + + // Replace video with copy that will have all "source" elements removed + var newVideo = oldVideo.cloneNode(true); + var allSources = newVideo.querySelectorAll("source"); + allSources.forEach(function (source) { + source.remove(); + }); + + // Empty source to enable play event + newVideo.src = "about:blank"; + + oldVideo.parentNode.replaceChild(newVideo, oldVideo); + + function initializeHls() { + newVideo.removeEventListener('play', initializeHls); + + var hls = new Hls({ autoStartLoad: false }); + hls.loadSource(playlist); + hls.attachMedia(newVideo); + hls.on(Hls.Events.MANIFEST_PARSED, function () { + hls.loadLevel = hls.levels.length - 1; + hls.startLoad(); + newVideo.play(); + }); + + hls.on(Hls.Events.ERROR, function (event, data) { + var errorType = data.type; + var errorFatal = data.fatal; + if (errorFatal) { + switch (errorType) { + case Hls.ErrorType.NETWORK_ERROR: + hls.startLoad(); + break; + case Hls.ErrorType.MEDIA_ERROR: + hls.recoverMediaError(); + break; + default: + hls.destroy(); + break; + } + } + + console.error("HLS error", data); + }); + } + + newVideo.addEventListener('play', initializeHls); + + if (autoplay) { + newVideo.play(); + } + }); + } else { + var videos = document.querySelectorAll("video.hls_autoplay"); + videos.forEach(function (video) { + video.setAttribute("autoplay", ""); + }); + } +})(); +// @license-end \ No newline at end of file diff --git a/static/style.css b/static/style.css index 4690d17..2a54241 100644 --- a/static/style.css +++ b/static/style.css @@ -664,6 +664,7 @@ a.search_subreddit:hover { "post_score post_title post_thumbnail" 1fr "post_score post_media post_thumbnail" auto "post_score post_body post_thumbnail" auto + "post_score post_notification post_thumbnail" auto "post_score post_footer post_thumbnail" auto / minmax(40px, auto) minmax(0, 1fr) fit-content(min(20%, 152px)); } @@ -706,6 +707,17 @@ a.search_subreddit:hover { grid-area: post_title; } +.post_notification { + grid-area: post_notification; + margin: 5px 15px; + text-align: center; + font-size: 12px; +} + +.post_notification a { + text-decoration: underline; +} + .post_flair { background: var(--accent); color: var(--background); @@ -1256,6 +1268,7 @@ td, th { "post_title post_title post_thumbnail" 1fr "post_media post_media post_thumbnail" auto "post_body post_body post_thumbnail" auto + "post_notification post_notification post_thumbnail" auto "post_score post_footer post_thumbnail" auto / auto 1fr fit-content(min(20%, 152px)); } diff --git a/templates/post.html b/templates/post.html index 479134e..761af06 100644 --- a/templates/post.html +++ b/templates/post.html @@ -68,7 +68,17 @@ {% else if post.post_type == "video" || post.post_type == "gif" %} + {% if prefs.use_hls == "on" && !post.media.alt_url.is_empty() %} + + + + {% else %} + {% call utils::render_hls_notification(post.permalink[1..]) %} + {% endif %} {% else if post.post_type == "gallery" %} +
+ + +
+
+ + +
@@ -68,10 +76,10 @@ {% endfor %} {% endif %} - +

Note: settings and subscriptions are saved in browser cookies. Clearing your cookies will reset them.


-

You can restore your current settings and subscriptions after clearing your cookies using this link.

+

You can restore your current settings and subscriptions after clearing your cookies using this link.

diff --git a/templates/subreddit.html b/templates/subreddit.html index ff9dbff..bae969b 100644 --- a/templates/subreddit.html +++ b/templates/subreddit.html @@ -52,6 +52,10 @@ {% call utils::post_in_list(post) %} {% endif %} {% endfor %} + {% if prefs.use_hls == "on" %} + + + {% endif %}