stremiok 2.3.6 → 2.3.8

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-subs.js CHANGED
@@ -230,9 +230,85 @@
230
230
  }
231
231
  // A file's cues: CUES_MAX at most, CUE_TEXT_MAX characters of text each (a broken or hostile
232
232
  // file can't hold the remote: the whole parse stays in time with the file's length).
233
+ // A cue: { start, end, text } (text: as read, plain), with runs when it has styling: [{ t, i, b,
234
+ // u, c }] (italic, bold, underline, a color '#rrggbb'), pieces drawn as text (drawCues).
235
+ // The format told by the file's content, whatever its name: ASS / SSA, SAMI, MicroDVD, MPL2,
236
+ // TMPlayer, else SRT / WebVTT.
233
237
  var CUES_MAX = 20000, CUE_TEXT_MAX = 1000;
234
238
  function parseCues(text) {
235
- text = ('' + text).replace(/\r/g, '');
239
+ text = ('' + text).replace(/\r/g, '').replace(/^/, '');
240
+ var head = text.slice(0, 4096), cues;
241
+ if (/^\s*\[script info\]/i.test(head) || /^\[v4\+? styles\]/im.test(head) || /^dialogue\s*:/im.test(head)) { cues = parseAss(text); }
242
+ else if (/<sami[\s>]/i.test(head)) { cues = parseSami(text); }
243
+ else if (/^\s*\{\d+\}\{\d*\}/.test(head)) { cues = parseFramed(text); }
244
+ else if (/^\s*\[\d+\]\[\d*\]/.test(head)) { cues = parseMpl2(text); }
245
+ else if (/^\s*\d{1,2}:\d{2}:\d{2}[:=]/.test(head) && head.indexOf('-->') === -1) { cues = parseTmp(text); }
246
+ else { cues = parseSrt(text); }
247
+ cues.sort(function (a, b) { return a.start - b.start; });
248
+ return cues;
249
+ }
250
+ // A cue from its runs: neighbours styled alike joined, the ends' spaces trimmed; runs kept only
251
+ // when one is styled; Skip lines with applied (a line taken out: the cue plain).
252
+ function makeCue(start, end, runs, skip) {
253
+ var out = [];
254
+ runs.forEach(function (r) {
255
+ if (!r.t) { return; }
256
+ var last = out[out.length - 1];
257
+ if (last && !!last.i === !!r.i && !!last.b === !!r.b && !!last.u === !!r.u && (last.c || '') === (r.c || '')) { last.t += r.t; return; }
258
+ out.push(runOf(r.t, r));
259
+ });
260
+ while (out.length && !/\S/.test(out[0].t)) { out.shift(); }
261
+ while (out.length && !/\S/.test(out[out.length - 1].t)) { out.pop(); }
262
+ if (!out.length) { return null; }
263
+ out[0].t = out[0].t.replace(/^\s+/, '');
264
+ out[out.length - 1].t = out[out.length - 1].t.replace(/\s+$/, '');
265
+ var plain = out.map(function (r) { return r.t; }).join('').slice(0, CUE_TEXT_MAX);
266
+ var txt = skip(plain);
267
+ if (!txt) { return null; }
268
+ var cue = { start: start, end: end, text: txt };
269
+ if (txt === plain && out.some(function (r) { return r.i || r.b || r.u || r.c; })) { cue.runs = out; }
270
+ return cue;
271
+ }
272
+ function runOf(t, st) {
273
+ var r = { t: t };
274
+ if (st.i) { r.i = true; } if (st.b) { r.b = true; } if (st.u) { r.u = true; } if (st.c) { r.c = st.c; }
275
+ return r;
276
+ }
277
+ // A color as '#rrggbb': #rgb / #rrggbb, or a plain color name (red); else none.
278
+ function cssColor(x) {
279
+ x = ('' + (x || '')).trim().toLowerCase().replace(/^["']|["']$/g, '');
280
+ var m = /^#?([0-9a-f]{6})$/.exec(x);
281
+ if (m) { return '#' + m[1]; }
282
+ m = /^#([0-9a-f])([0-9a-f])([0-9a-f])$/.exec(x);
283
+ if (m) { return '#' + m[1] + m[1] + m[2] + m[2] + m[3] + m[3]; }
284
+ return /^[a-z]{3,20}$/.test(x) ? x : '';
285
+ }
286
+ // HTML-like text (SRT, WebVTT, SAMI) as runs: <i> <b> <u> <font color> kept as styling, <br> a new
287
+ // line, other tags and a stray < left out (one pass, in time with the text's length), character
288
+ // codes read after (one written as &lt; is the file's own text: "<b>" shown as written).
289
+ function tagRuns(t) {
290
+ var runs = [], st = { i: 0, b: 0, u: 0 }, colors = [], i = 0, n = t.length;
291
+ function add(s) { if (s) { runs.push(runOf(charCodes(s), { i: st.i > 0, b: st.b > 0, u: st.u > 0, c: colors[colors.length - 1] })); } }
292
+ while (i < n) {
293
+ var lt = t.indexOf('<', i);
294
+ if (lt === -1) { add(t.slice(i)); break; }
295
+ add(t.slice(i, lt));
296
+ var gt = t.indexOf('>', lt + 1);
297
+ if (gt === -1) { add(t.slice(lt + 1).split('<').join('')); break; } // (no tag ends after it: the rest, its < gone)
298
+ var m = /^\s*(\/?)\s*([a-zA-Z]+)([\s\S]*)$/.exec(t.slice(lt + 1, gt));
299
+ i = gt + 1;
300
+ if (!m) { continue; }
301
+ var close = m[1] === '/', name = m[2].toLowerCase();
302
+ if (name === 'i' || name === 'b' || name === 'u') { st[name] = close ? Math.max(0, st[name] - 1) : st[name] + 1; }
303
+ else if (name === 'font') {
304
+ if (close) { colors.pop(); }
305
+ else { var cm = /color\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/i.exec(m[3]); colors.push(cm ? cssColor(cm[1]) : colors[colors.length - 1]); }
306
+ }
307
+ else if (name === 'br' && !close) { runs.push({ t: '\n' }); }
308
+ }
309
+ return runs;
310
+ }
311
+ function parseSrt(text) {
236
312
  var blocks = text.split(/\n\n+/);
237
313
  var cues = [], skip = skipper(); // (Skip lines with: your words)
238
314
  var re = /(?:(\d{1,3}):)?(\d{2}):(\d{2})[,.](\d{1,3})\s*-->\s*(?:(\d{1,3}):)?(\d{2}):(\d{2})[,.](\d{1,3})/;
@@ -247,40 +323,204 @@
247
323
  if (!m) { continue; }
248
324
  var start = (+(m[1] || 0)) * 3600 + (+m[2]) * 60 + (+m[3]) + ms(m[4]);
249
325
  var end = (+(m[5] || 0)) * 3600 + (+m[6]) * 60 + (+m[7]) + ms(m[8]);
250
- // (tags out, a stray < with them, in one pass; then entities read: one written as &lt; is the file's own text,
251
- // "<b>" shown as written. Never a tag: subtitles reach the screen as text only, textContent)
252
- var txt = skip(charCodes(noTags(lines.slice(ti + 1).join('\n').slice(0, CUE_TEXT_MAX)).replace(/\{[^}]+\}/g, '')).replace(/\s+$/, ''));
253
- if (txt) { cues.push({ start: start, end: end, text: txt }); }
326
+ var cue = makeCue(start, end, tagRuns(lines.slice(ti + 1).join('\n').slice(0, CUE_TEXT_MAX).replace(/\{\\[^}]*\}/g, '')), skip); // ({\an8}: an ASS position, not shown)
327
+ if (cue) { cues.push(cue); }
328
+ }
329
+ return cues;
330
+ }
331
+ // SAMI (.smi): <SYNC Start=ms> marks; a line shows until the next one (a blank one ends it).
332
+ function parseSami(text) {
333
+ var cues = [], skip = skipper(), re = /<sync[^>]*?start\s*=\s*["']?(\d+)[^>]*>/gi, marks = [], m;
334
+ while ((m = re.exec(text)) && marks.length < CUES_MAX) { marks.push({ at: +m[1] / 1000, from: re.lastIndex, to: text.length }); if (marks.length > 1) { marks[marks.length - 2].to = m.index; } }
335
+ for (var i = 0; i < marks.length; i++) {
336
+ var body = text.slice(marks[i].from, Math.min(marks[i].to, marks[i].from + CUE_TEXT_MAX * 4)).replace(/<\/(body|sami)>[\s\S]*$/i, '').replace(/\s*\n\s*/g, ' ');
337
+ var end = i + 1 < marks.length ? marks[i + 1].at : marks[i].at + 4;
338
+ var cue = makeCue(marks[i].at, end, tagRuns(body), skip);
339
+ if (cue) { cues.push(cue); }
340
+ }
341
+ return cues;
342
+ }
343
+ // A line's own styling in the frame-based formats: MicroDVD's {y:i} {y:b} {y:u} {c:$BBGGRR} at its
344
+ // start, a / starting a line for italics (MPL2, often MicroDVD); | between lines.
345
+ function slashRuns(body, st) {
346
+ var runs = [];
347
+ body.split('|').forEach(function (line, k) {
348
+ if (k) { runs.push({ t: '\n' }); }
349
+ var it = /^\s*\//.test(line);
350
+ runs.push(runOf(line.replace(/^\s*\//, '').replace(/\{[^}]*\}/g, ''), { i: st.i || it, b: st.b, u: st.u, c: st.c }));
351
+ });
352
+ return runs;
353
+ }
354
+ // MicroDVD (.sub, .txt): {start frame}{end frame}text, at the frame rate its first line gives
355
+ // ({1}{1}25.000), else 23.976.
356
+ function parseFramed(text) {
357
+ var lines = text.split('\n'), cues = [], skip = skipper(), fps = 23.976, re = /^\s*\{(\d+)\}\{(\d*)\}(.*)$/;
358
+ for (var i = 0; i < lines.length && cues.length < CUES_MAX; i++) {
359
+ var m = re.exec(lines[i]);
360
+ if (!m) { continue; }
361
+ var rate = /^\s*(\d{1,3}(?:\.\d+)?)\s*$/.exec(m[3]);
362
+ if (!cues.length && rate && +rate[1] >= 10 && +rate[1] <= 120 && +m[1] <= 1) { fps = +rate[1]; continue; }
363
+ var body = m[3].slice(0, CUE_TEXT_MAX), st = {}, code;
364
+ while ((code = /^\s*\{([a-zA-Z]):([^}]*)\}/.exec(body))) {
365
+ var k = code[1].toLowerCase(), v = code[2].toLowerCase();
366
+ if (k === 'y') { st.i = v.indexOf('i') !== -1; st.b = v.indexOf('b') !== -1; st.u = v.indexOf('u') !== -1; }
367
+ else if (k === 'c') { var hx = /\$?([0-9a-f]{6})/.exec(v); if (hx) { st.c = '#' + hx[1].slice(4, 6) + hx[1].slice(2, 4) + hx[1].slice(0, 2); } }
368
+ body = body.slice(code[0].length);
369
+ }
370
+ var start = +m[1] / fps, end = m[2] !== '' ? +m[2] / fps : start + 3;
371
+ var cue = makeCue(start, end, slashRuns(body, st), skip);
372
+ if (cue) { cues.push(cue); }
254
373
  }
255
- cues.sort(function (a, b) { return a.start - b.start; });
256
374
  return cues;
257
375
  }
376
+ // MPL2 (.txt): [start][end] in tenths of a second.
377
+ function parseMpl2(text) {
378
+ var lines = text.split('\n'), cues = [], skip = skipper(), re = /^\s*\[(\d+)\]\[(\d*)\](.*)$/;
379
+ for (var i = 0; i < lines.length && cues.length < CUES_MAX; i++) {
380
+ var m = re.exec(lines[i]);
381
+ if (!m) { continue; }
382
+ var start = +m[1] / 10, end = m[2] !== '' ? +m[2] / 10 : start + 3;
383
+ var cue = makeCue(start, end, slashRuns(m[3].slice(0, CUE_TEXT_MAX), {}), skip);
384
+ if (cue) { cues.push(cue); }
385
+ }
386
+ return cues;
387
+ }
388
+ // TMPlayer (.txt): hh:mm:ss:text, no end: each line until the next, TMP_MAX seconds at most.
389
+ var TMP_MAX = 5;
390
+ function parseTmp(text) {
391
+ var lines = text.split('\n'), marks = [], skip = skipper(), re = /^\s*(\d{1,2}):(\d{2}):(\d{2})[:=](.*)$/, cues = [];
392
+ for (var i = 0; i < lines.length && marks.length < CUES_MAX; i++) {
393
+ var m = re.exec(lines[i]);
394
+ if (m) { marks.push({ at: (+m[1]) * 3600 + (+m[2]) * 60 + (+m[3]), body: m[4].slice(0, CUE_TEXT_MAX) }); }
395
+ }
396
+ for (var j = 0; j < marks.length; j++) {
397
+ var next = j + 1 < marks.length ? marks[j + 1].at : Infinity;
398
+ var cue = makeCue(marks[j].at, Math.min(next, marks[j].at + TMP_MAX), slashRuns(marks[j].body, {}), skip);
399
+ if (cue) { cues.push(cue); }
400
+ }
401
+ return cues;
402
+ }
403
+ // ASS / SSA: its Dialogue lines, with each line's style (its color, bold, italic, underline) and
404
+ // the overrides in it ({\i1} {\b1} {\u1} {\c&HBBGGRR&} {\r}); drawings ({\p1}) and positions left out.
405
+ function assColor(x) {
406
+ x = ('' + (x || '')).trim();
407
+ var v = /^&h/i.test(x) ? parseInt(x.replace(/^&h/i, '').replace(/&$/, ''), 16) : parseInt(x, 10);
408
+ if (isNaN(v)) { return ''; }
409
+ var hex = function (n) { return ('0' + n.toString(16)).slice(-2); };
410
+ var c = '#' + hex(v & 0xFF) + hex((v >> 8) & 0xFF) + hex((v >> 16) & 0xFF);
411
+ return c === '#ffffff' ? '' : c; // (white: a file's usual color, yours shown instead)
412
+ }
413
+ function assTime(s) {
414
+ var m = /^\s*(\d+):(\d{2}):(\d{2})[.:](\d{1,3})\s*$/.exec(s || '');
415
+ return m ? (+m[1]) * 3600 + (+m[2]) * 60 + (+m[3]) + +((m[4] + '00').slice(0, 3)) / 1000 : null;
416
+ }
417
+ function parseAss(text) {
418
+ var lines = text.split('\n'), sect = '', sFmt = null, eFmt = null, styles = {}, cues = [], skip = skipper();
419
+ function on(v) { v = ('' + (v || '')).trim(); return v !== '' && v !== '0'; }
420
+ function fields(rest, fmt) {
421
+ var parts = rest.split(','), f = {}, n = fmt.length;
422
+ if (parts.length < n) { return null; }
423
+ for (var k = 0; k < n - 1; k++) { f[fmt[k]] = parts[k].trim(); }
424
+ f[fmt[n - 1]] = parts.slice(n - 1).join(',');
425
+ return f;
426
+ }
427
+ for (var i = 0; i < lines.length && cues.length < CUES_MAX; i++) {
428
+ var l = lines[i], h = /^\s*\[([^\]]+)\]\s*$/.exec(l), m;
429
+ if (h) { sect = h[1].toLowerCase(); continue; }
430
+ if ((m = /^\s*format\s*:\s*(.*)$/i.exec(l))) {
431
+ var fmt = m[1].split(',').map(function (x) { return x.trim().toLowerCase(); });
432
+ if (/styles/.test(sect)) { sFmt = fmt; } else if (sect === 'events') { eFmt = fmt; }
433
+ continue;
434
+ }
435
+ if ((m = /^\s*style\s*:\s*(.*)$/i.exec(l)) && sFmt) {
436
+ var s = fields(m[1], sFmt);
437
+ if (s) { styles[(s.name || '').toLowerCase()] = { i: on(s.italic), b: on(s.bold), u: on(s.underline), c: assColor(s.primarycolour || s.primarycolor) }; }
438
+ continue;
439
+ }
440
+ if (!(m = /^\s*dialogue\s*:\s*(.*)$/i.exec(l))) { continue; }
441
+ var f = fields(m[1], eFmt || ['layer', 'start', 'end', 'style', 'name', 'marginl', 'marginr', 'marginv', 'effect', 'text']);
442
+ if (!f) { continue; }
443
+ var start = assTime(f.start), end = assTime(f.end);
444
+ if (start === null || end === null) { continue; }
445
+ var cue = makeCue(start, end, assRuns(('' + (f.text || '')).slice(0, CUE_TEXT_MAX * 2), styles, (f.style || '').replace(/^\*/, '').toLowerCase()), skip);
446
+ if (cue) { cues.push(cue); }
447
+ }
448
+ return cues;
449
+ }
450
+ function assRuns(t, styles, name) {
451
+ var base = styles[name] || styles['default'] || {}, st = runOf('', base), runs = [], draw = false, i = 0, n = t.length;
452
+ function add(s) {
453
+ if (!s || draw) { return; }
454
+ runs.push(runOf(s.replace(/\\[Nn]/g, '\n').replace(/\\h/g, ' '), st));
455
+ }
456
+ while (i < n) {
457
+ var ob = t.indexOf('{', i);
458
+ if (ob === -1) { add(t.slice(i)); break; }
459
+ add(t.slice(i, ob));
460
+ var cb = t.indexOf('}', ob + 1);
461
+ if (cb === -1) { break; }
462
+ var block = t.slice(ob + 1, cb), re = /\\(1c|c|[ibu]|r|p)([^\\]*)/g, m;
463
+ i = cb + 1;
464
+ while ((m = re.exec(block))) {
465
+ var k = m[1], v = m[2].trim();
466
+ if (k === 'i' || k === 'u') { if (/^[01]$/.test(v)) { st[k] = v === '1'; } }
467
+ else if (k === 'b') { if (/^\d+$/.test(v)) { st.b = v === '1' || +v >= 600; } }
468
+ else if (k === 'c' || k === '1c') { var c = /^&?h([0-9a-f]{1,8})&?$/i.exec(v); if (c || !v) { st.c = c ? assColor('&H' + c[1]) : base.c; } } // (\c alone: the style's; \clip isn't a color)
469
+ else if (k === 'r') { var to = (v && styles[v.toLowerCase()]) || base; st = runOf('', to); }
470
+ else if (k === 'p') { draw = /^\d+$/.test(v) && +v > 0; }
471
+ }
472
+ }
473
+ return runs;
474
+ }
258
475
 
476
+ // Lines that overlap (dialogue and a sign) show together, up to SHOW_MAX, the earliest first.
477
+ var SHOW_MAX = 4;
259
478
  function renderSubs() {
260
479
  if (_embQueue.length) { flushEmbQueue(); }
261
480
  renderSecond();
262
481
  if (!_subOn || !_cues) { return; }
263
482
  var t = S.cur - _subDelay; // timing adjustment: + shows later, − earlier
264
- var show = '';
483
+ var show = [], key = '';
265
484
  // Skip the prefix of cues that already ended (they can't show again unless we go
266
- // back in time, which resets the index), then scan as before. Same cue as a full
485
+ // back in time, which resets the index), then scan as before. Same cues as a full
267
486
  // scan from 0, without walking the whole list late in a movie on every tick.
487
+ // (A long cue keeps the index at it: those after it that ended are passed over below.)
268
488
  if (t < _cueT) { _cueIdx = 0; }
269
489
  _cueT = t;
270
490
  while (_cueIdx < _cues.length && _cues[_cueIdx].end < t) { _cueIdx++; }
271
- for (var i = _cueIdx; i < _cues.length; i++) {
272
- if (_cues[i].start <= t && t <= _cues[i].end) { show = _cues[i].text; break; }
491
+ for (var i = _cueIdx; i < _cues.length && show.length < SHOW_MAX; i++) {
273
492
  if (_cues[i].start > t) { break; }
493
+ if (t <= _cues[i].end) { show.push(_cues[i]); key += i + ','; }
274
494
  }
275
- if (show) {
495
+ if (show.length) {
276
496
  S.subsEl.className = '';
277
497
  var span = S.subsEl.firstChild;
278
498
  if (!span) { span = document.createElement('span'); S.subsEl.appendChild(span); styleSpan(span); }
279
- if (span.textContent !== show) { span.textContent = show; }
499
+ key += P.subCfgVersion ? P.subCfgVersion() : '';
500
+ if (span.__cues !== key || span.__list !== _cues) { drawCues(span, show); span.__cues = key; span.__list = _cues; } // (drawn again only when what shows changes)
280
501
  } else {
281
502
  S.subsEl.className = 'hidden';
282
503
  }
283
504
  }
505
+ // The line's text, from its cues: each its own line; a styled cue's pieces each their own span,
506
+ // written as text (textContent: never markup). The file's colors only with Subtitles ›
507
+ // Appearance › The file's colors On (else yours: the line's own color).
508
+ function drawCues(span, cues) {
509
+ var colors = getSubCfg().fileColors === 'on';
510
+ U.clear(span);
511
+ cues.forEach(function (cue, k) {
512
+ var runs = (k ? [{ t: '\n' }] : []).concat(cue.runs || [{ t: cue.text }]); // (each cue its own line: the break unstyled)
513
+ runs.forEach(function (r) {
514
+ var piece = document.createElement('span');
515
+ piece.textContent = r.t;
516
+ if (r.i) { piece.style.fontStyle = 'italic'; }
517
+ if (r.b) { piece.style.fontWeight = 'bold'; }
518
+ if (r.u) { piece.style.textDecoration = 'underline'; }
519
+ if (r.c && colors) { piece.style.color = r.c; }
520
+ span.appendChild(piece);
521
+ });
522
+ });
523
+ }
284
524
 
285
525
  // Each choice (a track, Off, a built-in one) is a new one: a download still on its way
286
526
  // for an earlier choice is dropped when it comes, without a word (_subGen).
@@ -440,16 +680,25 @@
440
680
  var w = _embWant; _embWant = null;
441
681
  if (!w || _subOn) { return; } // an addon track was chosen meanwhile
442
682
  var tracks = getTextTracks(), pick = null, key = w.lang ? langKey(w.lang) : '';
683
+ // (of a language's tracks, by the file's header: a full one in text, then any in text — a
684
+ // picture one, PGS, shows nothing here — then a forced one)
685
+ var own = P.fileTracks ? P.fileTracks('subs', tracks) : null;
686
+ function best(match) {
687
+ var c = tracks.filter(match);
688
+ if (!own || c.length < 2) { return c[0] || null; }
689
+ var o = function (t) { return own[tracks.indexOf(t)] || {}; };
690
+ return c.filter(function (t) { return o(t).text !== false && !o(t).forced; })[0] || c.filter(function (t) { return o(t).text !== false; })[0] || c[0];
691
+ }
443
692
  if (w.index != null) {
444
693
  pick = tracks.find(function (t) { return t.index === w.index && (!key || langKey(textLang(t)) === key); }) || null;
445
694
  }
446
- if (!pick && key) { pick = tracks.find(function (t) { return langMatches(key, textLang(t)); }) || null; }
695
+ if (!pick && key) { pick = best(function (t) { return langMatches(key, textLang(t)); }); }
447
696
  if (!pick && w.nth != null && S.ctx && S.ctx._relayCc) { pick = tracks[w.nth] || null; } // (a live channel's closed captions: in the order asked for)
448
697
  if (!pick && w.lang2) { // nothing in the default language anywhere: the second choice, a track to download first
449
698
  var key2 = langKey(w.lang2);
450
699
  var dl = _subTracks.find(function (t) { return langMatches(key2, t.lang); });
451
700
  if (dl) { loadTrack(dl); return; }
452
- pick = tracks.find(function (t) { return langMatches(key2, textLang(t)); }) || null;
701
+ pick = best(function (t) { return langMatches(key2, textLang(t)); });
453
702
  }
454
703
  if (pick) { selectEmbeddedSub(pick); _embNudge = { index: pick.index, at: Date.now() + EMB_NUDGE_MS }; }
455
704
  }
@@ -512,7 +761,7 @@
512
761
  S.subsEl.className = '';
513
762
  var span = S.subsEl.firstChild;
514
763
  if (!span) { span = document.createElement('span'); S.subsEl.appendChild(span); styleSpan(span); }
515
- span.textContent = t;
764
+ span.textContent = t; span.__list = null;
516
765
  _embTimer = setTimeout(function () { S.subsEl.className = 'hidden'; }, Math.max(500, (+duration) || 3000));
517
766
  }
518
767
 
@@ -685,9 +934,10 @@
685
934
  run: function () { closeMenu(); rememberSub(S.ctx.id, { embedded: true, nth: x.n, lang: c.lang }); P.ccOn(c); } };
686
935
  }
687
936
  if (x.emb) {
688
- var tr = x.emb, l = textLang(tr);
937
+ var tr = x.emb, l = textLang(tr), own = P.fileTrack ? P.fileTrack('subs', getTextTracks(), x.n) : null;
689
938
  if (_embSub === tr.index) { idx = i; }
690
939
  return { label: (S.ctx && S.ctx._relayCc ? U.t('Closed captions') : U.t('Built into the file')) + (l ? ' (' + l + ')' : ' · ' + U.t('track {n}', { n: x.n + 1 })), sel: _embSub === tr.index,
940
+ detail: own && P.fileTrackNote ? P.fileTrackNote(own) || undefined : undefined, // (its own name and marks, from the file's header)
691
941
  run: function () {
692
942
  _embDelay = 0; _embQueue = []; _embNudge = null; selectEmbeddedSub(tr); rememberSub(S.ctx.id, { embedded: true, index: tr.index, lang: l });
693
943
  if (menuOpen()) { replaceTop(langTracksMenu(key, list)); }
@@ -770,7 +1020,7 @@
770
1020
  }
771
1021
  P.activeSub = activeSub;
772
1022
  P.subsKey = subsKey;
773
- P.fileHints = fileHints; P.parseCues = parseCues; P.loadTrack = loadTrack; P.subsOff = subsOff;
1023
+ P.fileHints = fileHints; P.parseCues = parseCues; P.drawCues = drawCues; P.loadTrack = loadTrack; P.subsOff = subsOff;
774
1024
  P.resetSubs = resetSubs; P.closeSubs = closeSubs; P.startSubtitles = startSubtitles;
775
1025
  P.subsBeforeOpen = subsBeforeOpen; P.subsOnTick = subsOnTick; P.subtitleSummary = subtitleSummary;
776
1026
  P.wantEmbedded = wantEmbedded;
package/js/plugins.js CHANGED
@@ -94,7 +94,7 @@ var Plugins = (function () {
94
94
  list = list.filter(function (x) { var k = idOf(x.id); if (seen[k]) { return false; } seen[k] = true; return true; });
95
95
  return Promise.all(list.map(function (x) {
96
96
  var types = (Array.isArray(x.supportedTypes) ? x.supportedTypes : ['movie', 'tv']).filter(function (t) { return t === 'movie' || t === 'tv'; });
97
- var p = { id: idOf(x.id), name: str(x.name, 80) || idOf(x.id), version: str(x.version, 20), file: resolve(url, x.filename), types: types, on: false };
97
+ var p = { id: idOf(x.id), name: str(x.name, 80) || idOf(x.id), version: str(x.version, 20), file: resolve(url, x.filename), types: types, on: false, authorOff: x.enabled === false };
98
98
  return U.getText(p.file, 20000, CODE_MAX).then(function (code) { p.code = '' + code; p.size = p.code.length; p.hash = hashOf(p.code); return p; },
99
99
  function (e) { p.error = U.problem(e); return p; });
100
100
  })).then(function (plugins) { return { name: str(m.name, 80) || url.replace(/^https?:\/\//, '').replace(/\/manifest\.json.*$/i, ''), plugins: plugins }; });
@@ -116,7 +116,7 @@ var Plugins = (function () {
116
116
  if (p.error) { failed++; return was || null; }
117
117
  if (!was) { added++; } else if (was.hash !== p.hash) { changed++; }
118
118
  writes.push(U.bigStore.set(CODE + rid + '.' + p.id, p.code));
119
- return { id: p.id, name: p.name, version: p.version, file: p.file, types: p.types, on: !!(was && was.on), size: p.size, hash: p.hash };
119
+ return { id: p.id, name: p.name, version: p.version, file: p.file, types: p.types, on: !!(was && was.on), size: p.size, hash: p.hash, authorOff: !!p.authorOff }; // (authorOff: its repository marks it off, often as broken)
120
120
  }).filter(Boolean);
121
121
  return Promise.all(writes).then(function () {
122
122
  if (old) { old.plugins.forEach(function (p) { if (!plugins.some(function (q) { return q.id === p.id; })) { U.bigStore.remove(CODE + rid + '.' + p.id); } }); }
@@ -224,30 +224,66 @@ var Plugins = (function () {
224
224
  if (!imdb || typeof Stremio === 'undefined' || !Stremio.tmdbFind) { return Promise.resolve(null); }
225
225
  return Stremio.tmdbFind(imdb[1], type === 'series' ? 'tv' : 'movie').then(function (n) { return n ? '' + n : null; });
226
226
  }
227
+ // A title's sources from the plugins that are on, within the time addons get (Settings ›
228
+ // Content › Addons › Wait for addons: a slower plugin is left out, the runtime started over so
229
+ // the next title doesn't wait behind it). The list carries _notes: [{ plugin, why }] for each
230
+ // that gave nothing (failed, too slow, no TMDB number), shown on No sources found.
231
+ function waitMs() {
232
+ var w = typeof Stremio !== 'undefined' && Stremio.getPrefs ? (+Stremio.getPrefs().addonWait || 0) * 1000 : 0;
233
+ return Math.max(w, 15000);
234
+ }
227
235
  function streams(type, id, meta) {
228
236
  if (!isEnabled()) { return Promise.resolve([]); }
229
237
  var kind = type === 'series' ? 'tv' : type === 'movie' ? 'movie' : '';
230
238
  var todo = enabledPlugins().filter(function (x) { return kind && x.p.types.indexOf(kind) !== -1; });
231
239
  if (!todo.length) { return Promise.resolve([]); }
232
240
  var ep = /:(\d+):(\d+)$/.exec(id || '');
241
+ function noted(list, notes) { list._notes = notes; return list; }
233
242
  return tmdbOf(type, id || '', meta).then(function (tmdb) {
234
- if (!tmdb) { U.log('plugins', 'No TMDB number for ' + id + ' (a TMDB key is needed: Settings › Content › Integrations)'); return []; }
243
+ if (!tmdb) {
244
+ U.log('plugins', 'No TMDB number for ' + id + ' (a TMDB key is needed: Settings › Content › Integrations)');
245
+ return noted([], todo.map(function (x) { return { plugin: x.p.name, why: U.t('no TMDB number for this title (a TMDB key is needed: Settings › Content › Integrations)') }; }));
246
+ }
235
247
  var args = [tmdb, kind, ep ? +ep[1] : null, ep ? +ep[2] : null];
236
248
  return YTPlay.pluginNet(lanAllowed()).then(function (net) {
237
- var out = [];
238
- return U.settleAll(todo.map(function (x) {
249
+ var out = [], notes = [], over = false, state = {};
250
+ var all = U.settleAll(todo.map(function (x) {
239
251
  return function () {
252
+ if (over) { return Promise.resolve(); }
253
+ state[x.p.id] = 'running';
240
254
  return U.bigStore.get(CODE + x.repo.id + '.' + x.p.id).then(function (code) {
241
255
  if (typeof code !== 'string' || !code) { throw new Error('its code isn’t on the TV: refresh its repository'); }
242
256
  return runOne(code, x.p, args, net);
243
257
  }).then(function (r) {
258
+ if (over) { return; }
244
259
  (r.logs || []).slice(0, 20).forEach(function (l) { U.log('plugins', x.p.name + ': ' + l); });
245
260
  if (r.type !== 'done') { throw new Error(r.why || 'failed'); }
246
261
  var list = (Array.isArray(r.streams) ? r.streams : []).slice(0, MAX_RESULTS).map(function (s, n) { return toSource(s, x.p, n); }).filter(Boolean);
262
+ state[x.p.id] = 'done';
263
+ if (!list.length) { notes.push({ plugin: x.p.name, why: U.t('no sources for this') }); }
247
264
  out = out.concat(list);
248
- }).then(null, function (e) { U.log('plugins', x.p.name + ' (' + args.slice(0, 2).join(' ') + '): ' + ((e && e.message) || e)); });
265
+ }).then(null, function (e) {
266
+ if (over) { return; }
267
+ var why = '' + ((e && e.message) || e);
268
+ state[x.p.id] = 'failed';
269
+ U.log('plugins', x.p.name + ' (' + args.slice(0, 2).join(' ') + '): ' + why);
270
+ notes.push({ plugin: x.p.name, why: why });
271
+ });
249
272
  };
250
- }), legacy() ? 1 : AT_ONCE).then(function () { return out; });
273
+ }), legacy() ? 1 : AT_ONCE);
274
+ return new Promise(function (resolve) {
275
+ var timer = setTimeout(function () {
276
+ over = true;
277
+ var late = todo.filter(function (x) { return state[x.p.id] !== 'done' && state[x.p.id] !== 'failed'; });
278
+ late.forEach(function (x) {
279
+ U.log('plugins', x.p.name + ' (' + args.slice(0, 2).join(' ') + '): too slow, left out after ' + Math.round(waitMs() / 1000) + ' s');
280
+ notes.push({ plugin: x.p.name, why: U.t('too slow: left out after {n} s (Wait for addons)', { n: Math.round(waitMs() / 1000) }) });
281
+ });
282
+ if (late.length) { fail('too slow'); } // (the runtime started over: the next title doesn't wait behind them)
283
+ resolve(noted(out, notes));
284
+ }, waitMs());
285
+ all.then(function () { if (over) { return; } over = true; clearTimeout(timer); resolve(noted(out, notes)); });
286
+ });
251
287
  }, function () { return []; });
252
288
  });
253
289
  }
package/js/stremio.js CHANGED
@@ -570,14 +570,16 @@ var Stremio = (function () {
570
570
  // The file import reads (parseSetupList): a line an addon link, playlist link or API key, what
571
571
  // any StremioK imports, and #!stremiok <kind> <JSON> lines, comments to an older one: playlist
572
572
  // (a playlist's name, guide link, off), stalker (a portal) and store (one of EXPORT_STORE, what
573
- // you chose in Settings: not caches, history, progress or your Trakt sign-in; integrations
574
- // without the three keys, which have their own lines, or Trakt's). Imported settings replace
575
- // yours, only those in EXPORT_STORE.
573
+ // you chose in Settings: not caches or your Trakt sign-in; integrations without the three keys,
574
+ // which have their own lines, or Trakt's) and history (one of HISTORY_STORE, when ticked: where
575
+ // you stopped, watched marks…). Imported settings and history replace yours, only those listed.
576
576
  var EXPORT_LINE = '#!stremiok ';
577
577
  var EXPORT_STORE = ['stremiok.prefs', 'stremiok.feeds', 'stremiok.searchfeeds', 'stremiok.sourcefeeds', 'stremiok.ranking', 'stremiok.server', 'stremiok.formats',
578
578
  'stremiok.resblock', 'stremiok.subcfg', 'stremiok.audiocfg', 'stremiok.playercfg', 'stremiok.private', 'stremiok.youtube', 'stremiok.appshortcuts',
579
579
  'stremiok.appsallowed', 'stremiok.aiomanager', 'stremiok.iptv.stalkerall', 'stremiok.iptv.stalkerkeep', 'stremiok.iptv.every', 'stremiok.local.matching', 'stremiok.local.hidden',
580
580
  'stremiok.addonsoff', 'stremiok.integrations'];
581
+ var HISTORY_STORE = ['stremiok.progress', 'stremiok.watched', 'stremiok.cworder', 'stremiok.subhist', 'stremiok.audiohist', 'stremiok.playedsrc', 'stremiok.seriessrc',
582
+ 'stremiok.unsuitable', 'stremiok.aspects', 'stremiok.iptv.favs', 'stremiok.local.matches', 'stremiok.local.fixes'];
581
583
  function plural(n, one) { return n + ' ' + one + (n === 1 ? '' : 's'); }
582
584
  function iptvLists() { return (_hasIptv && IPTV.getPlaylists) ? IPTV.getPlaylists() : []; }
583
585
  // What there is to export: [{ key, label }] (settings always).
@@ -590,6 +592,7 @@ var Stremio = (function () {
590
592
  if (st) { out.push({ key: 'stalker', label: U.tn(st, '{n} Stalker portal (their MAC addresses)', '{n} Stalker portals (their MAC addresses)') }); }
591
593
  if (keys.length) { out.push({ key: 'keys', label: U.t('API keys: {keys}', { keys: keys.join(', ') }) }); }
592
594
  out.push({ key: 'settings', label: U.t('Your settings: look, Home, playback, subtitles, sources, streaming server, YouTube…') });
595
+ if (HISTORY_STORE.some(function (k) { return U.store.get(k, null) != null; })) { out.push({ key: 'history', label: U.t('Your history: where you stopped, watched marks, Continue Watching…'), off: true }); }
593
596
  return out;
594
597
  }
595
598
  function settingsValue(key) {
@@ -634,11 +637,18 @@ var Stremio = (function () {
634
637
  if (v !== null && v !== undefined) { out.push(EXPORT_LINE + 'store ' + JSON.stringify({ k: key.replace(/^stremiok\./, ''), v: v })); }
635
638
  });
636
639
  }
640
+ if (want.history) {
641
+ out.push('');
642
+ HISTORY_STORE.forEach(function (key) {
643
+ var v = U.store.get(key, null);
644
+ if (v !== null && v !== undefined) { out.push(EXPORT_LINE + 'history ' + JSON.stringify({ k: key.replace(/^stremiok\./, ''), v: v })); }
645
+ });
646
+ }
637
647
  return out.join('\n') + '\n';
638
648
  }
639
649
  function parseSetupList(text) {
640
650
  var out = { items: [], ignored: 0 }, seen = {}, mine = getAddonUrls(), integ = getIntegrations();
641
- var have = iptvLists(), lists = have.map(function (x) { return x.url; }), details = {}, store = [];
651
+ var have = iptvLists(), lists = have.map(function (x) { return x.url; }), details = {}, store = [], hist = [];
642
652
  function push(it) { var k = it.kind + ' ' + it.value; if (seen[k]) { return; } seen[k] = 1; out.items.push(it); }
643
653
  function stremiokLine(rest) { // (an export's own lines: see exportSetup)
644
654
  var m = /^([a-z]+)\s+(\{[\s\S]*\})$/.exec(rest), o = null;
@@ -652,6 +662,7 @@ var Stremio = (function () {
652
662
  return;
653
663
  }
654
664
  if (m[1] === 'store' && typeof o.k === 'string' && EXPORT_STORE.indexOf('stremiok.' + o.k) !== -1 && o.v !== undefined && o.v !== null) { store.push(o); return; }
665
+ if (m[1] === 'history' && typeof o.k === 'string' && HISTORY_STORE.indexOf('stremiok.' + o.k) !== -1 && o.v !== undefined && o.v !== null) { hist.push(o); return; }
655
666
  out.ignored++;
656
667
  }
657
668
  ('' + (text || '')).split(/\r?\n/).forEach(function (line) {
@@ -678,6 +689,7 @@ var Stremio = (function () {
678
689
  if (d) { it.info = d; if (typeof d.name === 'string' && d.name) { it.label = U.t('IPTV playlist') + ' · ' + d.name.slice(0, 60); } }
679
690
  });
680
691
  if (store.length) { push({ kind: 'settings', value: 'settings', entries: store, label: U.tn(store.length, 'Your settings ({n} part)', 'Your settings ({n} parts)'), have: false, note: U.t('replaces yours') }); }
692
+ if (hist.length) { push({ kind: 'history', value: 'history', entries: hist, label: U.t('Your history and progress'), have: false, note: U.t('replaces yours') }); }
681
693
  return out;
682
694
  }
683
695
  function playlistDetails(id, d) {
@@ -687,7 +699,7 @@ var Stremio = (function () {
687
699
  }
688
700
  // Import the chosen lines (parseSetupList's items): what was added, as importSetupList says.
689
701
  function applySetupEntries(items) {
690
- var result = { addons: 0, playlists: 0, omdb: false, tmdb: false, mdblist: false, settings: false, ignored: 0 };
702
+ var result = { addons: 0, playlists: 0, omdb: false, tmdb: false, mdblist: false, settings: false, history: false, ignored: 0 };
691
703
  (items || []).forEach(function (it) {
692
704
  if (KEY_NAMES[it.kind]) { setIntegration(it.kind, it.value); result[it.kind] = true; }
693
705
  else if (it.kind === 'playlist') {
@@ -710,6 +722,9 @@ var Stremio = (function () {
710
722
  } else { U.store.set(key, o.v); }
711
723
  });
712
724
  result.settings = true;
725
+ } else if (it.kind === 'history') {
726
+ it.entries.forEach(function (o) { var key = 'stremiok.' + o.k; if (HISTORY_STORE.indexOf(key) !== -1) { U.store.set(key, o.v); } });
727
+ result.history = true;
713
728
  }
714
729
  else if (it.kind === 'addon') {
715
730
  var added = addAddon(it.value);
@@ -1171,6 +1186,10 @@ var Stremio = (function () {
1171
1186
  var ph = s.behaviorHints && s.behaviorHints.proxyHeaders, h = ph && ph.request ? U.sanitizeHeaders(ph.request) : null;
1172
1187
  if (h) { s._headers = h; }
1173
1188
  });
1189
+ // (StremioK's own source that says why parts of it gave nothing: Nuvio plugins, one line each)
1190
+ if (a.__impl && res.streams && Array.isArray(res.streams._notes)) {
1191
+ res.streams._notes.slice(0, 10).forEach(function (n) { notes.push({ addon: (a.manifest.name || U.t('Addon')) + ' · ' + ('' + n.plugin).slice(0, 60), title: ('' + n.why).replace(/\s+/g, ' ').slice(0, 160), text: '', rank: i }); });
1192
+ }
1174
1193
  slots[i] = arr; okCount++;
1175
1194
  if (!arr.length && notes.length === said) { note(a, i, U.t('no sources for this')); } // (its notices say why, when it sent any)
1176
1195
  }).then(function () { done(); }, function (err) {
@@ -2321,6 +2340,35 @@ var Stremio = (function () {
2321
2340
  if (info.container && info.container !== 'hls') { out.push(info.container.toUpperCase()); }
2322
2341
  return out.join(' · ');
2323
2342
  }
2343
+ // A source's details corrected by its file's header (the player's S.mi: see the service's
2344
+ // mediaInfo), where the header says: resolution (by width: a wide film is less tall), codec,
2345
+ // bit depth, HDR (Dolby Vision with or without a layer under it), the audio track that plays
2346
+ // first, the container. What the header doesn't say stays as the name had it.
2347
+ var FILE_AUDIO = { truehd: 'truehd', dts: 'dts', eac3: 'eac3', ac3: 'ac3', aac: 'aac', opus: 'opus', flac: 'flac' };
2348
+ function withFileInfo(info, mi) {
2349
+ var i = {};
2350
+ Object.keys(info || {}).forEach(function (k) { i[k] = info[k]; });
2351
+ i.audio = ((info && info.audio) || []).slice();
2352
+ if (!mi || typeof mi !== 'object') { return i; }
2353
+ var v = mi.video;
2354
+ if (v) {
2355
+ var w = +v.width || 0, h = +v.height || 0;
2356
+ if (w || h) { i.res = w >= 3200 || h >= 1800 ? 2160 : w >= 2400 || h >= 1300 ? 1440 : w >= 1700 || h >= 900 ? 1080 : w >= 1100 || h >= 650 ? 720 : 480; }
2357
+ if (/^(h264|hevc|av1)$/.test(v.codec || '')) { i.codec = v.codec; }
2358
+ if (v.bitDepth >= 10) { i.bits10 = true; } else if (v.bitDepth === 8) { i.bits10 = false; }
2359
+ if (v.dv) { i.hdr = (v.dv.compat === 1 || v.dv.compat === 6 || v.dv.compat === 4 || v.dv.compat === 2) ? 'dv' : 'dv-only'; }
2360
+ else if (v.hdr === 'hdr10' || v.hdr === 'hlg') { i.hdr = i.hdr === 'hdr10p' && v.hdr === 'hdr10' ? 'hdr10p' : 'hdr'; }
2361
+ }
2362
+ var tracks = mi.audio || [], first = tracks.filter(function (a) { return a.default; })[0] || tracks[0];
2363
+ if (first && FILE_AUDIO[first.codec]) {
2364
+ var a = FILE_AUDIO[first.codec];
2365
+ if (a === 'dts' && i.audio.indexOf('dtshd') !== -1) { a = 'dtshd'; } // (DTS-HD looks like DTS in a header: the name says which)
2366
+ i.audio = (i.audio.indexOf('atmos') !== -1 && (a === 'truehd' || a === 'eac3') ? ['atmos'] : []).concat([a]);
2367
+ }
2368
+ if (/^(mkv|mp4|webm)$/.test(mi.container || '')) { i.container = mi.container; } else if (mi.container === 'mov') { i.container = 'mp4'; }
2369
+ i.fromFile = true;
2370
+ return i;
2371
+ }
2324
2372
  function formatKeys(info) {
2325
2373
  var k = [], pk = profileKey(info);
2326
2374
  if (pk) { k.push(pk); }
@@ -2437,7 +2485,7 @@ var Stremio = (function () {
2437
2485
  isPlayable: isPlayable, youTubeSource: youTubeSource, torrentSource: torrentSource,
2438
2486
  keptSources: keptSources, torrentFile: torrentFile, server: server, setServer: setServer, testServer: testServer, convertUrl: convertUrl, serverAddressProblem: serverAddressProblem, streamLabel: streamLabel, streamName: streamName,
2439
2487
  streamSize: streamSize, streamDescription: streamDescription,
2440
- streamInfo: streamInfo, formatTags: formatTags, formatKeys: formatKeys, recordFormats: recordFormats, setFormat: setFormat,
2488
+ streamInfo: streamInfo, formatTags: formatTags, formatKeys: formatKeys, withFileInfo: withFileInfo, recordFormats: recordFormats, setFormat: setFormat,
2441
2489
  resetFormats: resetFormats, badFormats: badFormats, formatList: formatList,
2442
2490
  resList: resList, setResAllowed: setResAllowed, blockedRes: blockedRes,
2443
2491
  importSetupList: importSetupList, savedManifest: savedManifest, isAddonOff: isAddonOff, setAddonOff: setAddonOff, onIptvReady: onIptvReady, streamListenerCount: function (type, id) { var e = _streamCache[type + ':' + id]; return e ? e.listeners.length : 0; },
package/js/view-core.js CHANGED
@@ -144,7 +144,7 @@ var ViewParts = {};
144
144
  // that shows it to copy or download; kept open while the QR is on screen (asked every
145
145
  // GIVE_POLL_MS, which also says once the phone has it), closed with Done.
146
146
  var GIVE_POLL_MS = 3000;
147
- function phoneGive(title, text, note) {
147
+ function phoneGive(title, text, note, kind) { // (kind: 'logs' for the logs' own page; else a configuration)
148
148
  var existing = document.querySelector('.modal-overlay');
149
149
  if (existing) { existing.parentNode.removeChild(existing); }
150
150
  var overlay = U.el('div', 'modal-overlay'), box = U.el('div', 'modal-box qr-box');
@@ -171,7 +171,7 @@ var ViewParts = {};
171
171
  }, GIVE_POLL_MS);
172
172
  }
173
173
  if (typeof YTPlay === 'undefined' || !YTPlay.entryGive) { how.textContent = U.t('It needs StremioK’s service on the TV (not in a desktop browser).'); return; }
174
- YTPlay.entryGive(text).then(function (r) {
174
+ YTPlay.entryGive(text, kind).then(function (r) {
175
175
  if (over) { if (r && r.token) { YTPlay.entryClose(r.token); } return; }
176
176
  if (!r || !r.url) { throw new Error('no page'); }
177
177
  token = r.token;