stremiok 2.2.7 → 2.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/js/player-core.js CHANGED
@@ -48,7 +48,9 @@ var PlayerParts = {};
48
48
  function skipShown() { return P.skipShown.apply(null, arguments); } // controls
49
49
 
50
50
  var avplay = (window.webapis && webapis.avplay) ? webapis.avplay : null;
51
- var useAV = !!avplay;
51
+ // useAV: this playback is the TV's player's (everything but a ClearKey channel: see startShaka);
52
+ // the page's own <video> otherwise, and in a desktop browser. P.useAV says which, as it is now.
53
+ var hasAV = !!avplay, useAV = hasAV;
52
54
  P.avplay = avplay; P.useAV = useAV;
53
55
 
54
56
  // The playback session: read by every part, written here (and a few fields where noted).
@@ -394,7 +396,7 @@ var PlayerParts = {};
394
396
  // is what's learned from it (s.stream, through ctx.learnFor); the title, its episodes and
395
397
  // whether it's private stay.
396
398
  var SOURCE_FIELDS = ['url', 'variantUrl', 'initialQualityHeight', 'yt', 'ytLang', '_headers', 'localSubs', 'localFile', 'subExtra', 'sourceSubs', 'formatInfo', 'onStarted', 'onFailed', 'stream',
397
- '_reported', 'fromStart', 'resumeSec', 'switching'];
399
+ '_reported', 'fromStart', 'resumeSec', 'switching', 'viaService', '_relay', '_relayFor', '_relayCc'];
398
400
  // keep: a source that didn't start gives way to the next (nextSourceOnFail): the same place to
399
401
  // resume, and Play from the start as it was.
400
402
  function replaceSource(s, keep) {
@@ -434,6 +436,7 @@ var PlayerParts = {};
434
436
  S.active = true; S.cur = 0; S.dur = 0; _bg = null; S.actual = null;
435
437
  // Stremio "tv" and "radio" types are strong live hints; refined after prepare.
436
438
  S.isLive = !(ctx.stream && ctx.stream._vod) && ((ctx.type === 'tv' || ctx.type === 'radio') || /^iptv:/.test(ctx.id || '') || !!ctx.isLive); // (an IPTV channel: live, a sports one too; a film in a playlist isn't)
439
+ if (S.isLive) { vodCheck(ctx); } // (one whose manifest says it's a film: not live after all)
437
440
  formatStart(ctx);
438
441
  S.ctx.resumeSec = (ctx.trailer || ctx.fromStart) ? 0 : (ctx.resumeSec || getResume(ctx.type, ctx.id)); // (Play from start: 0:00)
439
442
 
@@ -455,6 +458,7 @@ var PlayerParts = {};
455
458
  renderOSD(); // show the NEW title immediately (not the previous item's)
456
459
  U.spinner(true, ctx.switching ? 'Switching source…' : ctx.initialQualityHeight ? 'Opening stream at ' + ctx.initialQualityHeight + 'p…' : 'Opening stream…');
457
460
 
461
+ engineFor(ctx); // (the TV's player, or a ClearKey channel's own: see startShaka)
458
462
  // (a TorrServer torrent that doesn't say which of its files: its file list asked for first)
459
463
  var go = function () { if (useAV) { startLive(ctx, settle); } else { startHTML5(ctx.url); } };
460
464
  if (ctx.stream && ctx.stream._pickFile && typeof Stremio !== 'undefined' && Stremio.torrentFile) {
@@ -580,8 +584,45 @@ var PlayerParts = {};
580
584
 
581
585
  // Decides live vs VOD from the reported duration (0 / non-finite = live).
582
586
  function markLiveFromDuration() {
583
- if (S.ctx && !(S.ctx.stream && S.ctx.stream._vod) && (S.ctx.type === 'tv' || S.ctx.type === 'radio' || /^iptv:/.test(S.ctx.id || ''))) { S.isLive = true; }
587
+ if (S.ctx && !(S.ctx.stream && S.ctx.stream._vod) && !S.ctx._vodManifest && (S.ctx.type === 'tv' || S.ctx.type === 'radio' || /^iptv:/.test(S.ctx.id || ''))) { S.isLive = true; }
584
588
  if (!S.dur || S.dur <= 0 || !isFinite(S.dur)) { S.isLive = true; }
589
+ else if (S.ctx && S.ctx._vodManifest) { S.isLive = false; } // (its manifest said it's a film before it was ready: see vodCheck)
590
+ }
591
+
592
+ // A playlist's entry whose link isn't a file's may still be a film: its manifest says so (DASH
593
+ // type="static", or none; HLS #EXT-X-ENDLIST or PLAYLIST-TYPE:VOD, a master playlist's first
594
+ // variant's). Read as it opens (with the channel's headers, through the service when it has
595
+ // some), not for an Xtream /live/ link; once known, it plays as a film (seeking, no ● LIVE).
596
+ var MANIFEST_LINK = /\.(mpd|m3u8?)(?:[?#]|$)/i, XT_LIVE_PATH = /\/live\/[^\/?#]+\/[^\/?#]+\/[^\/?#]+$/i;
597
+ function manifestText(url, h) {
598
+ if (!/\.mpd(?:[?#]|$)/i.test(url) && P.hlsMasterText) { return P.hlsMasterText(url, h); } // (HLS: read once, with the quality list)
599
+ if (h && (h.ua || h.ref || h.cookie) && typeof YTPlay !== 'undefined' && YTPlay.hlsMaster) { return YTPlay.hlsMaster(url, h); }
600
+ return U.getText(url, 8000, 524288, null, true);
601
+ }
602
+ function linkFrom(base, ref) {
603
+ if (/^https?:\/\//i.test(ref)) { return ref; }
604
+ var m = /^(https?:\/\/[^\/?#]+)([^?#]*)/i.exec(base);
605
+ if (!m) { return ''; }
606
+ return ref.charAt(0) === '/' ? m[1] + ref : m[1] + m[2].replace(/[^\/]*$/, '') + ref;
607
+ }
608
+ function manifestVod(url, h, inner) {
609
+ return manifestText(url, h).then(function (t) {
610
+ t = '' + t;
611
+ if (/<MPD[\s>]/i.test(t)) { return !/<MPD\b[^>]*\btype\s*=\s*["']dynamic["']/i.test(t); }
612
+ if (/#EXT-X-ENDLIST|#EXT-X-PLAYLIST-TYPE:\s*VOD/i.test(t)) { return true; }
613
+ var v = /#EXT-X-STREAM-INF[^\n]*\n\s*([^#\s][^\r\n]*)/i.exec(t), next = v ? linkFrom(url, v[1].trim()) : '';
614
+ return next && !inner ? manifestVod(next, h, true) : false;
615
+ });
616
+ }
617
+ function vodCheck(ctx) {
618
+ if (!ctx || ctx.yt || ctx.trailer || (ctx.stream && ctx.stream._vod) || !/^iptv:/.test(ctx.id || '')) { return; }
619
+ var url = ctx.url || '';
620
+ if (!MANIFEST_LINK.test(url) || XT_LIVE_PATH.test(url.replace(/[?#].*$/, '').replace(/\.[a-z0-9]+$/i, ''))) { return; }
621
+ manifestVod(url, U.sanitizeHeaders(ctx._headers)).then(function (vod) {
622
+ if (!vod || S.ctx !== ctx) { return; }
623
+ ctx._vodManifest = true;
624
+ if (S.active && S.playStarted && S.dur > 0 && isFinite(S.dur) && S.isLive) { S.isLive = false; U.log('player', 'A playlist entry that\'s a film (its manifest): seeking on'); renderOSD(); }
625
+ }, function () {});
585
626
  }
586
627
 
587
628
  // settle: a re-open of what's playing (a quality switch, or its retry). This TV's player
@@ -611,8 +652,57 @@ var PlayerParts = {};
611
652
  }
612
653
  openAV(url, token);
613
654
  }
655
+ // A DRM channel (its playlist's #KODIPROP lines, see IPTV's drmInto): set once the stream is
656
+ // open, before it's prepared (Samsung's order). PlayReady: the player asks its license server
657
+ // itself, with the playlist's headers. Widevine: the player hands over its license request
658
+ // (ondrmevent's Challenge), posted by StremioK's service (drmEvent), and the answer given back;
659
+ // Tizen 5 and later take its session in one call, earlier ones in three. ClearKey: Shaka's (see
660
+ // startShaka); one whose keys can't be read, or another system: said so, not opened.
661
+ function tizenMajor() { try { return parseInt(tizen.systeminfo.getCapability('http://tizen.org/feature/platform.version'), 10) || 0; } catch (e) { return 0; } }
662
+ function drmSetup(drm) {
663
+ try {
664
+ if (drm.sys === 'playready') {
665
+ var o = { DeleteLicenseAfterUse: true, LicenseServer: drm.url }, h = drm.h || {}, rest = [];
666
+ Object.keys(h).forEach(function (k) {
667
+ if (/^user-agent$/i.test(k)) { o.UserAgent = h[k]; } else if (/^cookie$/i.test(k)) { o.Cookie = h[k]; } else { rest.push(k + ': ' + h[k]); }
668
+ });
669
+ if (rest.length) { o.HttpHeader = rest.join('\r\n'); }
670
+ avplay.setDrm('PLAYREADY', 'SetProperties', JSON.stringify(o));
671
+ return;
672
+ }
673
+ var session = 'stremiok-' + Date.now(), v = tizenMajor();
674
+ if (!v || v >= 5) {
675
+ try { avplay.setDrm('WIDEVINE_CDM', 'SetProperties', JSON.stringify({ AppSession: session, DataType: 'MPEG-DASH' })); return; } catch (e5) { if (v) { throw e5; } } // (not known: the older calls next)
676
+ }
677
+ avplay.setDrm('WIDEVINE_CDM', 'Initialize', '');
678
+ avplay.setDrm('WIDEVINE_CDM', 'widevine_app_session', session);
679
+ avplay.setDrm('WIDEVINE_CDM', 'widevine_data_type', 'MPEG-DASH');
680
+ } catch (e) { U.log('player', 'DRM not set up (' + (e && (e.name || e.message || e)) + ')'); }
681
+ }
682
+ function drmEvent(drm, data, token) {
683
+ if (!drm || drm.sys !== 'widevine' || !data || data.name !== 'Challenge' || !data.challenge) { return; }
684
+ var ctx = S.ctx;
685
+ if (typeof YTPlay === 'undefined' || !YTPlay.drmLicense) { ctx._drmWhy = 'StremioK’s service isn’t there'; return; }
686
+ YTPlay.drmLicense(drm.url, drm.h, data.challenge, drm.b64).then(function (r) {
687
+ if (!S.active || token !== _playToken) { return; }
688
+ if (!r || !r.license) { throw new Error((r && r.why) || 'no answer'); }
689
+ avplay.setDrm('WIDEVINE_CDM', 'widevine_license_data', data.session_id + 'PARAM_START_POSITION' + r.license + 'PARAM_START_POSITION');
690
+ }).then(null, function (e) {
691
+ if (S.ctx !== ctx) { return; }
692
+ ctx._drmWhy = U.problem(e);
693
+ U.log('player', 'DRM: no license for this channel (' + ctx._drmWhy + ')');
694
+ });
695
+ }
696
+ function drmName(d) { return { clearkey: 'ClearKey', widevine: 'Widevine', playready: 'PlayReady' }[d.sys] || 'its DRM'; }
614
697
  var BUFFERS = { more: [8, 10], most: [15, 20] };
615
698
  function openAV(url, token) {
699
+ var drm = S.ctx && S.ctx.stream && S.ctx.stream._drm;
700
+ if (drm && !drm.ok) { // (ClearKey, or a license StremioK can't ask for)
701
+ U.log('player', 'Not played: ' + drmName(drm) + (drm.sys === 'clearkey' ? '' : ' without a license server StremioK can use') + ' (' + where(url) + ')');
702
+ U.spinner(false);
703
+ failedStart(drm.sys === 'clearkey' ? 'This ClearKey channel’s keys can’t be read (its playlist’s #KODIPROP lines)' : 'This channel’s DRM can’t be played on the TV (' + drmName(drm) + ')');
704
+ return;
705
+ }
616
706
  try {
617
707
  avplay.open(url);
618
708
  // Best-effort per-stream HTTP headers (some IPTV channels need a UA / Referer).
@@ -621,6 +711,7 @@ var PlayerParts = {};
621
711
  var h = U.sanitizeHeaders(S.ctx && S.ctx._headers);
622
712
  if (h && h.ua) { avplay.setStreamingProperty('USER_AGENT', h.ua); }
623
713
  if (h && h.ref) { avplay.setStreamingProperty('CUSTOM_MESSAGE', 'Referer:' + h.ref); }
714
+ if (h && h.cookie) { avplay.setStreamingProperty('COOKIE', h.cookie); }
624
715
  } catch (eh) {}
625
716
  // A bigger buffer (Settings › Playback › Seeking & buffering): seconds loaded before it
626
717
  // starts, and before it goes on after running dry (the TV's own when Normal)
@@ -661,6 +752,10 @@ var PlayerParts = {};
661
752
  if (!S.active || token !== _playToken) { return; }
662
753
  showEmbeddedText(text, duration);
663
754
  },
755
+ ondrmevent: function (type, data) {
756
+ if (!S.active || token !== _playToken) { return; }
757
+ drmEvent(drm, data, token);
758
+ },
664
759
  onerror: function (err) {
665
760
  // stop()/close() may emit a late NOT_SUPPORTED_FORMAT for an HLS
666
761
  // session that played successfully. Ignore callbacks after exit or
@@ -688,6 +783,7 @@ var PlayerParts = {};
688
783
  exitLater();
689
784
  }
690
785
  });
786
+ if (drm) { drmSetup(drm); }
691
787
  try { avplay.setStreamingProperty('ADAPTIVE_INFO', adaptiveInfo()); } catch (e0) {}
692
788
  _openedAt = Date.now();
693
789
  setTimeout(startCheck, startMs() + 500);
@@ -723,7 +819,7 @@ var PlayerParts = {};
723
819
  if (tryFallback()) { return; }
724
820
  U.log('player', 'Could not open: ' + (err && (err.name || err.message || err)) + ' (' + where(url) + ')');
725
821
  reportStart(false, err && (err.name || err.message || err));
726
- failedStart('Could not open stream');
822
+ failedStart(S.ctx && S.ctx._drmWhy ? 'No license for this channel: ' + S.ctx._drmWhy : 'Could not open stream');
727
823
  });
728
824
  } catch (e) {
729
825
  U.log('player', 'AVPlay failed: ' + (e && e.message));
@@ -757,18 +853,94 @@ var PlayerParts = {};
757
853
 
758
854
  // The desktop's <video> has no start timeout of its own (AVPlay's prepare does): a
759
855
  // stream the browser never gets going would leave the spinner up for good.
856
+ // A ClearKey channel (its playlist's #KODIPROP lines with keys or a key server, see IPTV's
857
+ // drmShaka): the TV's player has no ClearKey, so it alone plays in the page's own <video>
858
+ // through Shaka Player (js/vendor, Apache 2.0), loaded the first time one plays. Every other
859
+ // playback stays with the TV's player (engineFor: chosen as each starts, and after one, back).
860
+ var SHAKA_SRC = 'js/vendor/shaka-player.compiled.js', SHAKA_START_MS = 40000;
861
+ var _shakaPl = null, _shakaGone = null, _shakaLoad = null;
862
+ function shakaDrm(ctx) { var d = ctx && ctx.stream && ctx.stream._drm; return d && d.sys === 'clearkey' && d.shaka ? d : null; }
863
+ function loadShaka() {
864
+ if (typeof shaka !== 'undefined') { return Promise.resolve(); }
865
+ if (!_shakaLoad) {
866
+ _shakaLoad = U.loadScript(SHAKA_SRC).then(function () { if (typeof shaka !== 'undefined' && shaka.polyfill) { shaka.polyfill.installAll(); } });
867
+ _shakaLoad.then(null, function () { _shakaLoad = null; });
868
+ }
869
+ return _shakaLoad;
870
+ }
871
+ function shakaStop() { // (its player let go: the <video> free for the next)
872
+ var pl = _shakaPl;
873
+ _shakaPl = null;
874
+ if (pl) { _shakaGone = (_shakaGone || Promise.resolve()).then(function () { return pl.destroy(); }).then(null, function () {}); }
875
+ return _shakaGone || Promise.resolve();
876
+ }
877
+ function engineFor(ctx) {
878
+ var av = hasAV && !shakaDrm(ctx);
879
+ if (av === useAV) { return; }
880
+ if (useAV) { try { avplay.stop(); } catch (e0) {} try { avplay.close(); } catch (e1) {} objEl.className = ''; } // (the TV's player shut, for the page's)
881
+ else { shakaStop(); try { S.videoEl.pause(); S.videoEl.removeAttribute('src'); } catch (e2) {} S.videoEl.className = ''; }
882
+ useAV = av; P.useAV = av;
883
+ }
884
+ // A key server, and a DASH manifest naming only other systems (Widevine, PlayReady): Shaka asks
885
+ // a key server only for a system the manifest names (else its error 6012), so ClearKey is
886
+ // named after each group of them, its key ids the manifest's own (their default_KID). One
887
+ // naming it already (or its common key-id system), an HLS playlist: as they are.
888
+ var CK_URI = 'urn:uuid:e2719d58-a985-b3c9-781a-b030af78d30e';
889
+ var CP_RUN = /(?:<((?:[\w.-]+:)?)ContentProtection\b[^>]*?(?:\/>|>[\s\S]*?<\/(?:[\w.-]+:)?ContentProtection>)\s*)+/g;
890
+ var CK_NAMED = /e2719d58-a985-b3c9-781a-b030af78d30e|1077efec-c0b2-4d02-ace3-3c1e52e2fb4b/i;
891
+ function ckNamed(text) {
892
+ if (!/<(?:[\w.-]+:)?MPD\b/.test(text) || CK_NAMED.test(text)) { return text; }
893
+ return text.replace(CP_RUN, function (run, pre) { return run + '<' + pre + 'ContentProtection schemeIdUri="' + CK_URI + '" value="ClearKey1.0"/>'; });
894
+ }
895
+ function ckManifests(pl) {
896
+ var said = false, SU = shaka.util && shaka.util.StringUtils;
897
+ if (!SU) { return; }
898
+ pl.getNetworkingEngine().registerResponseFilter(function (type, resp) {
899
+ if (type !== shaka.net.NetworkingEngine.RequestType.MANIFEST || !resp || !resp.data) { return; }
900
+ var text = SU.fromUTF8(resp.data), out = ckNamed(text);
901
+ if (out === text) { return; }
902
+ resp.data = SU.toUTF8(out);
903
+ if (!said) { said = true; U.log('player', 'ClearKey named in the manifest beside its other DRM, for the playlist’s key server'); }
904
+ });
905
+ }
906
+ function shakaLoadInto(url, drm, token, fail) {
907
+ loadShaka().then(function () {
908
+ if (!S.active || token !== _playToken) { return; }
909
+ if (typeof shaka === 'undefined' || !shaka.Player.isBrowserSupported()) { throw new Error('this TV’s browser can’t play it'); }
910
+ return shakaStop().then(function () {
911
+ if (!S.active || token !== _playToken) { return; }
912
+ var pl = _shakaPl = new shaka.Player(), cfg = { streaming: { bufferingGoal: 10 } };
913
+ cfg.drm = drm.keys ? { clearKeys: drm.keys } : { servers: { 'org.w3.clearkey': drm.url } };
914
+ pl.configure(cfg);
915
+ if (!drm.keys) { ckManifests(pl); }
916
+ var h = drm.h || {};
917
+ if (!drm.keys && Object.keys(h).length) { // (the key server's own headers: those a page may send)
918
+ pl.getNetworkingEngine().registerRequestFilter(function (type, req) {
919
+ if (type === shaka.net.NetworkingEngine.RequestType.LICENSE) { Object.keys(h).forEach(function (k) { if (!/^(user-agent|referer|cookie|host|origin)$/i.test(k)) { req.headers[k] = h[k]; } }); }
920
+ });
921
+ }
922
+ pl.addEventListener('error', function (ev) { if (token === _playToken) { fail(shakaWhy(ev.detail)); } });
923
+ return pl.attach(S.videoEl).then(function () { return token === _playToken ? pl.load(url) : null; }).then(function () {
924
+ if (!S.active || token !== _playToken) { return; }
925
+ var p = S.videoEl.play();
926
+ if (p && p['catch']) { p['catch'](function () {}); }
927
+ });
928
+ });
929
+ }).then(null, function (e) { if (S.active && token === _playToken) { fail(shakaWhy(e)); } });
930
+ }
931
+ function shakaWhy(e) { return e && e.code ? 'Shaka error ' + e.code : (e && e.message) || 'it didn’t start'; }
760
932
  var HTML5_START_MS = 20000;
761
933
  function startHTML5(url) {
762
934
  url = opened(url);
763
- var token = ++_playToken, loaded = false;
935
+ var token = ++_playToken, loaded = false, drm = shakaDrm(S.ctx);
764
936
  S.videoEl.className = 'active';
765
- S.videoEl.src = url;
937
+ if (!drm) { S.videoEl.src = url; }
766
938
  setTimeout(function () {
767
939
  if (loaded || !S.active || token !== _playToken) { return; }
768
940
  reportStart(false, 'TIMEOUT');
769
941
  U.spinner(false);
770
942
  U.toast('This stream didn\'t start'); exitLater();
771
- }, HTML5_START_MS);
943
+ }, drm ? SHAKA_START_MS : HTML5_START_MS);
772
944
  S.videoEl.onloadedmetadata = function () {
773
945
  if (!S.active || token !== _playToken) { return; }
774
946
  loaded = true;
@@ -789,12 +961,21 @@ var PlayerParts = {};
789
961
  if (S.active && token === _playToken) { onEnded(); }
790
962
  };
791
963
  S.videoEl.onerror = function () {
792
- if (!S.active || token !== _playToken) { return; }
964
+ if (!S.active || token !== _playToken || drm) { return; } // (Shaka's own errors: see shakaLoadInto)
793
965
  reportStart(false, S.videoEl.error && S.videoEl.error.code === 2 ? 'NETWORK' : 'MEDIA_ERR');
794
966
  U.toast('Playback error'); exitLater();
795
967
  };
796
- var p = S.videoEl.play();
797
- if (p && p['catch']) { p['catch'](function () {}); }
968
+ if (drm) {
969
+ shakaLoadInto(url, drm, token, function (why) {
970
+ if (loaded) { U.log('player', 'ClearKey channel: ' + why); U.toast('Playback error: ' + why); exitLater(); return; }
971
+ U.log('player', 'ClearKey channel didn’t play (' + why + ')');
972
+ U.spinner(false);
973
+ failedStart('This ClearKey channel didn’t play (' + why + ')');
974
+ });
975
+ } else {
976
+ var p = S.videoEl.play();
977
+ if (p && p['catch']) { p['catch'](function () {}); }
978
+ }
798
979
  applyAspect(true);
799
980
  startTicker();
800
981
  }
@@ -1057,7 +1238,7 @@ var PlayerParts = {};
1057
1238
  // playback (the next sources aren't). Not a source that needs its own request headers.
1058
1239
  function convertOnFail() {
1059
1240
  var c = S.ctx;
1060
- if (!c || !S.active || S.playing || S.isLive || c.trailer || c.yt || c.localFile || !c.stream || c._converted || c._headers) { return false; }
1241
+ if (!c || !S.active || S.playing || S.isLive || c.trailer || c.yt || c.localFile || !c.stream || c._converted || c._headers || c.stream._drm) { return false; }
1061
1242
  var u = (typeof Stremio !== 'undefined' && Stremio.convertUrl) ? Stremio.convertUrl(c.url) : null;
1062
1243
  if (!u) { return false; }
1063
1244
  c._converted = true; c._convertedFrom = c.url; // (kept by what replaces it: Continue Watching saves its own link)
@@ -1150,7 +1331,7 @@ var PlayerParts = {};
1150
1331
  // needs repacking too.
1151
1332
  var LIVE_KEY = 'stremiok.livefix', LIVE_KEEP = 300, LIVE_DAYS = 14;
1152
1333
  function liveFixable(ctx) {
1153
- return useAV && S.isLive && !!ctx && !ctx.yt && !ctx.trailer && /^https?:\/\//i.test(ctx.url || '') &&
1334
+ return useAV && S.isLive && !!ctx && !ctx.yt && !ctx.trailer && !(ctx.stream && ctx.stream._drm) && /^https?:\/\//i.test(ctx.url || '') &&
1154
1335
  typeof YTPlay !== 'undefined' && !!YTPlay.liveOpen && YTPlay.installMode() !== 'browser';
1155
1336
  }
1156
1337
  function liveKnown(url) {
@@ -1187,7 +1368,32 @@ var PlayerParts = {};
1187
1368
  ctx._relay = r.url; ctx._relayFor = ctx.url; ctx._relayCc = cc || null; ctx._ccOffer = cc ? null : ctx._ccOffer;
1188
1369
  return true;
1189
1370
  }
1371
+ // HLS through StremioK's service (Settings › Playback › Seeking & buffering: 'off' | 'headers':
1372
+ // sources with their own User-Agent, Referer or Cookie | 'all'; or ctx.viaService, hold OK on a
1373
+ // source): the relay without the look, so every playlist and piece is fetched with the source's
1374
+ // headers (the TV's player can't always send them). A film's relay keeps every link (film=1).
1375
+ // Not YouTube, DRM, USB files or the service's own links; the service not answering: as it is.
1376
+ var HLS_LINK = /\.m3u8?(?:[?#]|$)/i;
1377
+ function viaService(ctx) {
1378
+ if (!useAV || !ctx || ctx.yt || ctx.trailer || ctx.localFile || (ctx.stream && ctx.stream._drm)) { return false; }
1379
+ if (typeof YTPlay === 'undefined' || !YTPlay.liveOpen || YTPlay.installMode() === 'browser') { return false; }
1380
+ var url = ctx.url || '';
1381
+ if (!/^https?:\/\//i.test(url) || /^http:\/\/(localhost|127\.0\.0\.1)[:\/]/i.test(url)) { return false; }
1382
+ if (!HLS_LINK.test(url) && !(ctx.formatInfo && ctx.formatInfo.container === 'hls')) { return false; }
1383
+ if (ctx.viaService) { return true; }
1384
+ var mode = P.playerCfg().hls;
1385
+ return mode === 'all' || (mode === 'headers' && !!U.sanitizeHeaders(ctx._headers));
1386
+ }
1387
+ function startViaService(ctx, settle) {
1388
+ var live = !!S.isLive, known = live && liveFixable(ctx) ? liveKnown(ctx.url) : null;
1389
+ YTPlay.liveOpen(ctx.url, ctx._headers, true, { fix: !!(known && known.fix), film: !live }).then(function (r) {
1390
+ if (S.ctx !== ctx || !S.active) { return; }
1391
+ relayed(ctx, r, null);
1392
+ startAV(ctx.url, settle);
1393
+ }, function () { if (S.ctx === ctx && S.active) { startAV(ctx.url, settle); } });
1394
+ }
1190
1395
  function startLive(ctx, settle) {
1396
+ if (!ctx._relay && viaService(ctx)) { startViaService(ctx, settle); return; }
1191
1397
  var known = liveFixable(ctx) ? liveKnown(ctx.url) : null, cc = ccOf(known);
1192
1398
  if (cc && cc.length) { ctx._ccOffer = cc; }
1193
1399
  var withCc = ccWanted(ctx, cc) ? cc : null;
@@ -1246,7 +1452,7 @@ var PlayerParts = {};
1246
1452
  // The relay didn't start (StremioK's service gone): the channel as it is.
1247
1453
  function relayFailed() {
1248
1454
  if (S.playStarted || !S.ctx || !S.ctx._relay) { return false; }
1249
- U.log('player', 'Live sound relay failed: playing the channel as it is');
1455
+ U.log('player', 'StremioK’s service relay didn’t start: playing the stream as it is');
1250
1456
  S.ctx._relay = null;
1251
1457
  startAV(S.ctx.url);
1252
1458
  return true;
@@ -1369,10 +1575,12 @@ var PlayerParts = {};
1369
1575
  try { avplay.close(); } catch (e2) {}
1370
1576
  objEl.className = '';
1371
1577
  } else {
1578
+ shakaStop();
1372
1579
  try { S.videoEl.pause(); } catch (e3) {}
1373
1580
  S.videoEl.removeAttribute('src');
1374
1581
  S.videoEl.className = '';
1375
1582
  }
1583
+ useAV = hasAV; P.useAV = hasAV; // (the next playback the TV's player's, unless it's ClearKey too)
1376
1584
  document.body.style.background = '';
1377
1585
  U.byId('app').className = '';
1378
1586
  U.spinner(false);
@@ -4,7 +4,6 @@
4
4
  (function (P) {
5
5
  'use strict';
6
6
  var S = P.S;
7
- var useAV = P.useAV;
8
7
 
9
8
  // ----- from the other parts -----
10
9
  function startAV() { return P.startAV.apply(null, arguments); } // core
@@ -119,7 +118,7 @@
119
118
  var v = variantByBw(bw);
120
119
  S.ctx.url = YTPlay.resolverUrl(S.ctx.yt, v ? v.h : 0, true, S.ctx.ytLang);
121
120
  }
122
- if (useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
121
+ if (P.useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
123
122
  }
124
123
 
125
124
  // YouTube re-opens fail on the FIRST attempt but succeed on the next (an AVPlay
@@ -137,7 +136,7 @@
137
136
  // Right after a switch this retry is routine: keep saying "Switching to …"
138
137
  U.spinner(true, _switchNote || ((retryHeight ? retryHeight + 'p' : 'The stream') + ' didn\'t start — retrying…'));
139
138
  _switchNote = null;
140
- if (useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
139
+ if (P.useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
141
140
  return true;
142
141
  }
143
142
 
@@ -165,7 +164,7 @@
165
164
  if (S.ctx.yt && typeof YTPlay !== 'undefined') { S.ctx.url = YTPlay.resolverUrl(S.ctx.yt, 0, true, S.ctx.ytLang); }
166
165
  _startNote = wasAuto ? '' : 'Playing with Auto quality';
167
166
  U.spinner(true, wasAuto ? 'Stream didn\'t start — retrying…' : 'Retrying with Auto quality…');
168
- if (useAV) { startAV(S.ctx.url); } else { startHTML5(S.ctx.url); }
167
+ if (P.useAV) { startAV(S.ctx.url); } else { startHTML5(S.ctx.url); }
169
168
  return true;
170
169
  }
171
170
 
@@ -191,13 +190,20 @@
191
190
  }
192
191
  // h: the stream's own User-Agent / Referer ({ ua, ref }): the list is then read through
193
192
  // StremioK's service, which can send them (as the TV's player does); a web page can't.
193
+ // (kept MASTER_MS: the player's look at whether a playlist's entry is a film reads it too, see vodCheck)
194
+ var _masters = U.lru(6), MASTER_MS = 15000;
194
195
  function getHlsMaster(url, h) {
195
- var viaService = !!(h && (h.ua || h.ref) && typeof YTPlay !== 'undefined' && YTPlay.hlsMaster && YTPlay.installMode && YTPlay.installMode() !== 'browser');
196
- return (viaService ? YTPlay.hlsMaster(url, h) : U.getText(url, 8000, HLS_MASTER_MAX)).then(function (text) {
196
+ var k = url + '|' + JSON.stringify(h || {}), kept = _masters.get(k);
197
+ if (kept && Date.now() - kept.at < MASTER_MS) { return kept.p; }
198
+ var viaService = !!(h && (h.ua || h.ref || h.cookie) && typeof YTPlay !== 'undefined' && YTPlay.hlsMaster && YTPlay.installMode && YTPlay.installMode() !== 'browser');
199
+ var p = (viaService ? YTPlay.hlsMaster(url, h) : U.getText(url, 8000, HLS_MASTER_MAX)).then(function (text) {
197
200
  var t = ('' + (text || '')).replace(/^\uFEFF/, '').replace(/^\s+/, '');
198
201
  if (t.indexOf('#EXTM3U') !== 0) { throw new Error('not an HLS playlist'); }
199
202
  return t;
200
203
  });
204
+ _masters.set(k, { at: Date.now(), p: p });
205
+ p.then(null, function () { var x = _masters.get(k); if (x && x.p === p) { _masters.set(k, null); } });
206
+ return p;
201
207
  }
202
208
  var _variantsToken = 0;
203
209
  // url: the master to read (a ctx's variantUrl), or a stream to read it from only when
@@ -286,7 +292,7 @@
286
292
  _switchNote = 'Switching to ' + ytLangLabel(a) + '…';
287
293
  _startNote = 'Audio: ' + ytLangLabel(a);
288
294
  U.spinner(true, _switchNote);
289
- if (useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
295
+ if (P.useAV) { startAV(S.ctx.url, true); } else { startHTML5(S.ctx.url); }
290
296
  }
291
297
  function ytLanguageMenu() {
292
298
  var cur = currentYtLanguage(), list = ytLanguages().slice();
@@ -321,7 +327,7 @@
321
327
  // ----- for the other parts (and js/player.js) -----
322
328
  P.resetQuality = resetQuality; P.qualityOnStart = qualityOnStart; P.clearStartNote = clearStartNote;
323
329
  P.qualityHeight = qualityHeight; P.qualityCount = qualityCount; P.hasQualities = hasQualities; P.qualityUnread = qualityUnread;
324
- P.adaptiveInfo = adaptiveInfo; P.tryFallback = tryFallback; P.switchSource = switchSource;
330
+ P.adaptiveInfo = adaptiveInfo; P.tryFallback = tryFallback; P.switchSource = switchSource; P.hlsMasterText = getHlsMaster;
325
331
  P.qualityLabel = qualityLabel; P.qualityMenu = qualityMenu;
326
332
  P.hasYtLanguages = hasYtLanguages; P.ytLanguageLabel = ytLanguageLabel; P.ytLanguageMenu = ytLanguageMenu;
327
333
  })(PlayerParts);
@@ -248,7 +248,8 @@
248
248
  return { aspect: d.aspect || 'fit', seek: SEEK_STEPS.indexOf(+d.seek) !== -1 ? +d.seek : 10,
249
249
  buffer: d.buffer === 'more' || d.buffer === 'most' ? d.buffer : 'normal',
250
250
  reconnect: d.reconnect === 'off' || d.reconnect === 'always' ? d.reconnect : 'few',
251
- phone: d.phone === 'infuse' || d.phone === 'link' ? d.phone : 'vlc' }; // (Continue on phone: what the QR opens)
251
+ phone: d.phone === 'infuse' || d.phone === 'link' ? d.phone : 'vlc', // (Continue on phone: what the QR opens)
252
+ hls: d.hls === 'headers' || d.hls === 'all' ? d.hls : 'off' }; // (HLS through StremioK's service: see player-core's viaService)
252
253
  }
253
254
  function setPlayerCfg(cfg) { // (what's given changes; the rest stays)
254
255
  var d = U.store.get(PLAYERCFG_KEY, {}) || {};
package/js/player-subs.js CHANGED
@@ -4,7 +4,7 @@
4
4
  (function (P) {
5
5
  'use strict';
6
6
  var S = P.S;
7
- var avplay = P.avplay, useAV = P.useAV;
7
+ var avplay = P.avplay; // (P.useAV: the TV's player's playback or the page's, as it is now: see player-core's engineFor)
8
8
 
9
9
  // ----- from the other parts -----
10
10
  function updateHint() { return P.updateHint.apply(null, arguments); } // core
@@ -426,7 +426,7 @@
426
426
  // StremioK draws it like an addon subtitle. Like audio, a track is only switched
427
427
  // once playback runs. Image-based tracks (PGS) produce no text and show nothing.
428
428
  function getTextTracks() {
429
- if (!useAV) { return []; }
429
+ if (!P.useAV) { return []; }
430
430
  try {
431
431
  var all = avplay.getTotalTrackInfo() || [], out = [];
432
432
  for (var i = 0; i < all.length; i++) { if (('' + all[i].type).toUpperCase() === 'TEXT') { out.push(all[i]); } }