Share page uses shared streaming player code
Shared video playback logic now lives in a single browser helper used by both the signed-in app preview and the public share page. This keeps Video.js buffering, VOD UI normalisation, track preference restore/save, and image subtitle overlay behaviour aligned automatically instead of maintaining two separate implementations. The share backend now exposes the same supporting stream lifecycle pieces the normal player expects: a subtitle-frame endpoint for bitmap subtitle rendering and an explicit session-release endpoint so share sessions are cleaned up on page close instead of waiting for idle expiry. Users opening a shared video can now access image subtitles the same way they can in the normal player, and future player fixes only need to be made once.
@@ -120,6 +120,8 @@
120
120
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
121
121
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
122
122
- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
123
- GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
124
- DELETE /api/share/video-stream/session/:sessionId - Public. Explicitly releases a shared HLS lease so the share page can clean up the backend stream session on close/unload instead of waiting for idle expiry.
123
125
- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
124
126
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
125
127
- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
@@ -151,10 +153,17 @@
151
153
- Standalone public share page served at /share/:token; no auth required.
152
154
- Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
153
155
- tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
154
- Share video preview - Uses the same Video.js playback behaviour as app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), and subtitle/audio track restore/save by matching track names when available.
156
- Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, and explicit backend session release on unload.
155
157
- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
156
158
- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
157
159
160
## public/shared-video-player.js
161
- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
162
- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
163
- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, and disables the track after the first hard failure.
164
- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
165
- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
166
158
167
## public/index.html
159
168
- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
160
169
- Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
@@ -120,6 +120,8 @@120
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
120
- GET /api/share/preview/:token - Public. Streams file content inline for preview (files only, max 50 MB); 400 for directories, 410 expired.
121
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
121
- GET /api/share/download/:token - Public. Downloads the file or a zip of the directory for a valid token; 410 expired.
122
- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
122
- GET /api/share/video-stream/:token - Public. Creates a short-lived HLS session for a shared video and returns playlistUrl, durationSeconds, subtitleTracks, imageSubtitleTracks, and subtitleSummary ({total, converted, imageBased, skipped}).
123
- GET /api/share/video-stream-subtitle-frame/:token - Public. Renders a PNG subtitle frame for shared-video bitmap subtitle tracks using the same cached PGS decode path as the authenticated player; returns 204 with X-Subtitle-Frame-Status when no frame is active or rendering fails.
124
- DELETE /api/share/video-stream/session/:sessionId - Public. Explicitly releases a shared HLS lease so the share page can clean up the backend stream session on close/unload instead of waiting for idle expiry.
123
- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
125
- buildShareOpenGraphPage(token, req) - Reads share.html, injects OG meta tags (<og:title>, <og:description>, <og:image> for image files, twitter:card) based on DB lookup of token, and returns the full HTML string. Handles expired and not-found tokens. Exported and used by the /share/:token route in server/index.js.
124
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
126
- buildZip(dirPath, cacheKey) - Creates (or returns cached) zip in zip-cache/; prunes stale zips before building; exported for reuse in files.js.
125
- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
127
- pruneZipCache() - Deletes zip files in zip-cache/ older than 1 day; called automatically before each zip build.
@@ -151,10 +153,17 @@151
- Standalone public share page served at /share/:token; no auth required.
153
- Standalone public share page served at /share/:token; no auth required.
152
- Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
154
- Timer bar - Live HH:MM:SS countdown showing remaining validity; turns red and disables download when expired.
153
- tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
155
- tryPreview(name, isDir) - Renders inline preview (img/video/audio/text pre); no-op for unsupported types or directories.
154
- Share video preview - Uses the same Video.js playback behaviour as app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), and subtitle/audio track restore/save by matching track names when available.
156
- Share video preview - Uses the shared browser video-player helper used by app previews: VOD UI enforcement, long forward buffer, forced caption overrides (text background opacity transparent + text edge style uniform), subtitle/audio track restore/save by matching track names, image-subtitle overlay support, and explicit backend session release on unload.
155
- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
157
- Fetches /api/share/info/:token on load; shows error state for 404/410 responses.
156
- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
158
- Download link points to /api/share/download/:token; labelled "Download als .zip" for directories.
157
159
160
## public/shared-video-player.js
161
- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
162
- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
163
- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, and disables the track after the first hard failure.
164
- configureVideoJsBuffering(videojs, opts) - Applies the long forward-buffer settings used for file playback when VHS exposes those knobs.
165
- ensureVideoPlaybackUi(player, durationSeconds) - Forces file streams into VOD UI mode, normalises the reported duration, stops live-tracker state, and hides the live badge when present.
166
158
## public/index.html
167
## public/index.html
159
- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
168
- Auth form - Login/setup form uses username plus mode-specific password autocomplete tokens so browser password managers behave correctly.
160
- Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
169
- Top bar - Places icon-only Refresh to the left of breadcrumb/Home, keeps search input with icon-only search button, and groups actions into Upload/User dropdown triggers.
@@ -370,697 +370,58 @@ function buildAuthHeaders ()
370
370
371
371
function applyUserVideoTextTrackPrefs ()
372
372
{
373
try
374
{
375
// Only override the two requested defaults and leave other settings at Video.js defaults.
376
localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW);
377
} catch
378
{
379
// Ignore localStorage failures.
380
}
381
}
382
383
function normaliseTrackName (name)
384
{
385
return String(name || '').trim().toLowerCase();
373
const shared = sharedVideoPlayer();
374
if (!shared || typeof shared.applyDefaultTextTrackPrefs !== 'function') return;
375
shared.applyDefaultTextTrackPrefs();
386
376
}
387
377
388
function getTrackName (track)
378
function sharedVideoPlayer ()
389
379
{
390
if (!track || typeof track !== 'object') return '';
391
const label = String(track.label || '').trim();
392
if (label) return label;
393
const name = String(track.name || '').trim();
394
if (name) return name;
395
const language = String(track.language || '').trim();
396
if (language) return language;
397
const id = String(track.id || '').trim();
398
if (id) return id;
399
return '';
400
}
401
402
function trackListToArray (trackList)
403
{
404
if (!trackList || typeof trackList.length !== 'number') return [];
405
const out = [];
406
for (let i = 0; i < trackList.length; i++)
407
{
408
const track = trackList[i] || (typeof trackList.item === 'function' ? trackList.item(i) : null);
409
if (track) out.push(track);
410
}
411
return out;
412
}
413
414
function subtitleTracksFromPlayer (player)
415
{
416
if (!player || typeof player.textTracks !== 'function') return [];
417
return trackListToArray(player.textTracks()).filter((track) =>
418
{
419
const kind = String(track.kind || '').toLowerCase();
420
return kind === 'subtitles' || kind === 'captions';
421
});
422
}
423
424
function audioTracksFromPlayer (player)
425
{
426
if (!player || typeof player.audioTracks !== 'function') return [];
427
return trackListToArray(player.audioTracks());
428
}
429
430
function applySavedSubtitleTrack (player, savedName)
431
{
432
if (typeof savedName !== 'string') return;
433
const tracks = subtitleTracksFromPlayer(player);
434
if (!tracks.length) return;
435
436
const wanted = normaliseTrackName(savedName);
437
if (!wanted)
438
{
439
for (const track of tracks) track.mode = 'disabled';
440
return;
441
}
442
443
const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted);
444
if (!match) return;
445
446
for (const track of tracks)
447
{
448
track.mode = track === match ? 'showing' : 'disabled';
449
}
450
}
451
452
function applySavedAudioTrack (player, savedName)
453
{
454
if (typeof savedName !== 'string') return;
455
const tracks = audioTracksFromPlayer(player);
456
if (!tracks.length) return;
457
458
const wanted = normaliseTrackName(savedName);
459
if (!wanted) return;
460
461
const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted);
462
if (!match) return;
463
464
for (const track of tracks)
465
{
466
track.enabled = track === match;
467
}
468
}
469
470
function getSelectedSubtitleTrackName (player)
471
{
472
const tracks = subtitleTracksFromPlayer(player);
473
if (!tracks.length) return null;
474
const active = tracks.find((track) => String(track.mode || '').toLowerCase() === 'showing');
475
return active ? getTrackName(active) : '';
476
}
477
478
function getSelectedAudioTrackName (player)
479
{
480
const tracks = audioTracksFromPlayer(player);
481
if (!tracks.length) return null;
482
const active = tracks.find((track) => !!track.enabled);
483
return active ? getTrackName(active) : '';
380
return window.FilemanagerSharedVideoPlayer || null;
484
381
}
485
382
486
383
function bindUserVideoTrackPrefs (player, prefs)
487
384
{
488
const applySavedTracks = () =>
489
{
490
applySavedSubtitleTrack(player, prefs.subtitleTrackName);
491
applySavedAudioTrack(player, prefs.audioTrackName);
492
};
493
494
const captureSelectedTracks = () =>
385
const shared = sharedVideoPlayer();
386
if (!shared || typeof shared.bindTrackPrefs !== 'function')
495
387
{
496
const subtitleTrackName = getSelectedSubtitleTrackName(player);
497
const audioTrackName = getSelectedAudioTrackName(player);
498
const patch = {};
499
500
if (subtitleTrackName !== null) patch.subtitleTrackName = subtitleTrackName;
501
if (audioTrackName !== null) patch.audioTrackName = audioTrackName;
502
503
if (Object.keys(patch).length) saveUserVideoPrefs(patch);
504
};
505
506
const textTrackList = typeof player.textTracks === 'function' ? player.textTracks() : null;
507
const audioTrackList = typeof player.audioTracks === 'function' ? player.audioTracks() : null;
508
const onTrackListChange = () => captureSelectedTracks();
509
510
if (textTrackList && typeof textTrackList.addEventListener === 'function')
511
{
512
textTrackList.addEventListener('change', onTrackListChange);
513
}
514
515
if (audioTrackList && typeof audioTrackList.addEventListener === 'function')
516
{
517
audioTrackList.addEventListener('change', onTrackListChange);
388
return {
389
applySavedTracks: () => {},
390
captureSelectedTracks: () => {},
391
detach: () => {},
392
};
518
393
}
519
520
return {
521
applySavedTracks,
522
captureSelectedTracks,
523
detach: () =>
524
{
525
if (textTrackList && typeof textTrackList.removeEventListener === 'function')
526
{
527
textTrackList.removeEventListener('change', onTrackListChange);
528
}
529
if (audioTrackList && typeof audioTrackList.removeEventListener === 'function')
530
{
531
audioTrackList.removeEventListener('change', onTrackListChange);
532
}
533
},
534
};
394
return shared.bindTrackPrefs(player, prefs, saveUserVideoPrefs);
535
395
}
536
396
537
397
function bindImageSubtitleOverlay (player, videojs, prefs, session, item)
538
398
{
539
const imageTracks = Array.isArray(session.imageSubtitleTracks)
540
? session.imageSubtitleTracks.map((track) => ({
541
label: String(track.label || '').trim() || `Subtitle ${Number(track.streamIndex || 0) + 1}`,
542
language: String(track.language || '').trim(),
543
isDefault: !!track.default,
544
streamIndex: Number(track.streamIndex),
545
})).filter((track) => Number.isInteger(track.streamIndex) && track.streamIndex >= 0)
546
: [];
547
548
if (!imageTracks.length) return null;
549
550
const trackByStreamIndex = new Map(imageTracks.map((track) => [track.streamIndex, track]));
551
let selectedStreamIndex = null;
552
let menuOpen = false;
553
let requestToken = 0;
554
let activeBucket = -1;
555
let activeObjectUrl = null;
556
let overlayEl = null;
557
let overlayImgEl = null;
558
let menuEl = null;
559
let buttonEl = null;
560
let trackDisabled = false;
561
let failureNotified = false;
562
563
const closeObjectUrl = () =>
564
{
565
if (activeObjectUrl)
566
{
567
URL.revokeObjectURL(activeObjectUrl);
568
activeObjectUrl = null;
569
}
570
};
571
572
const hideOverlay = () =>
573
{
574
if (overlayEl) overlayEl.style.display = 'none';
575
if (overlayImgEl) overlayImgEl.removeAttribute('src');
576
closeObjectUrl();
577
};
578
579
const updateButtonState = () =>
580
{
581
if (!buttonEl) return;
582
const track = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null;
583
buttonEl.setAttribute('title', track ? `Image subtitles: ${track.label}` : 'Image subtitles');
584
buttonEl.setAttribute('aria-pressed', selectedStreamIndex === null ? 'false' : 'true');
585
};
586
587
const updateMenuState = () =>
588
{
589
if (!menuEl) return;
590
const items = menuEl.querySelectorAll('[data-image-subtitle-stream-index]');
591
for (const itemEl of items)
592
{
593
const value = itemEl.getAttribute('data-image-subtitle-stream-index');
594
const isSelected = value === (selectedStreamIndex === null ? 'off' : String(selectedStreamIndex));
595
itemEl.classList.toggle('is-selected', isSelected);
596
itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false');
597
itemEl.style.background = isSelected ? 'rgba(90, 196, 255, 0.28)' : 'transparent';
598
itemEl.style.fontWeight = isSelected ? '600' : '400';
599
itemEl.style.boxShadow = isSelected ? 'inset 0 0 0 1px rgba(90, 196, 255, 0.55)' : 'none';
600
}
601
};
602
603
const closeMenu = () =>
604
{
605
menuOpen = false;
606
if (menuEl) menuEl.style.display = 'none';
607
};
608
609
const openMenu = () =>
610
{
611
menuOpen = true;
612
if (menuEl)
613
{
614
updateMenuState();
615
menuEl.style.display = 'block';
616
}
617
};
618
619
const toggleMenu = () =>
620
{
621
if (menuOpen) closeMenu();
622
else openMenu();
623
};
624
625
const saveSelection = () =>
626
{
627
const selectedTrack = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null;
628
saveUserVideoPrefs({
629
imageSubtitleTrackStreamIndex: selectedStreamIndex,
630
imageSubtitleTrackName: selectedTrack ? selectedTrack.label : null,
631
});
632
};
633
634
const disableTrack = () =>
635
{
636
trackDisabled = true;
637
selectedStreamIndex = null;
638
activeBucket = -1;
639
hideOverlay();
640
updateButtonState();
641
updateMenuState();
642
saveSelection();
643
644
if (!failureNotified)
645
{
646
failureNotified = true;
647
toast('Image subtitles could not be rendered for this file.', 'err');
648
}
649
};
650
651
const setSelectedStreamIndex = (streamIndex, { persist = true } = {}) =>
652
{
653
const nextStreamIndex = Number.isInteger(streamIndex) ? streamIndex : null;
654
if (nextStreamIndex !== null && !trackByStreamIndex.has(nextStreamIndex)) return;
655
656
trackDisabled = false;
657
failureNotified = false;
658
selectedStreamIndex = nextStreamIndex;
659
activeBucket = -1;
660
hideOverlay();
661
updateButtonState();
662
updateMenuState();
663
if (persist) saveSelection();
664
665
if (selectedStreamIndex !== null)
666
{
667
void refreshFrame(true);
668
}
669
};
670
671
const refreshFrame = async (force = false) =>
672
{
673
if (selectedStreamIndex === null) return;
674
if (!overlayEl || !overlayImgEl) return;
675
if (trackDisabled) return;
676
677
const currentTime = Number(player.currentTime());
678
if (!Number.isFinite(currentTime) || currentTime < 0) return;
679
680
const bucket = Math.floor(currentTime * 4);
681
if (!force && bucket === activeBucket) return;
682
activeBucket = bucket;
683
684
const token = ++requestToken;
685
const headers = buildAuthHeaders();
686
const url = `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${selectedStreamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`;
687
688
try
689
{
690
const res = await fetch(url, {
691
method: 'GET',
692
headers,
693
credentials: 'same-origin',
694
});
695
696
if (token !== requestToken) return;
697
698
if (res.status === 204)
699
{
700
const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase();
701
hideOverlay();
702
if (frameStatus === 'error') disableTrack();
703
return;
704
}
705
706
if (!res.ok)
707
{
708
disableTrack();
709
return;
710
}
711
712
const blob = await res.blob();
713
if (token !== requestToken) return;
714
715
if (!blob || blob.size === 0)
716
{
717
disableTrack();
718
return;
719
}
720
721
closeObjectUrl();
722
activeObjectUrl = URL.createObjectURL(blob);
723
overlayImgEl.src = activeObjectUrl;
724
725
// Apply placement from headers when available
726
const frameLeft = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Left') || ''), 10);
727
const frameTop = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Top') || ''), 10);
728
const frameWidth = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Width') || ''), 10);
729
const frameHeight = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Height') || ''), 10);
730
const canvasWidth = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Canvas-Width') || ''), 10);
731
const canvasHeight = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Canvas-Height') || ''), 10);
732
733
if (frameWidth > 0 && frameHeight > 0 && canvasWidth > 0 && canvasHeight > 0)
734
{
735
// Apply percentage-based sizing to scale the downscaled image properly
736
const widthPercent = (frameWidth / canvasWidth) * 100;
737
const heightPercent = (frameHeight / canvasHeight) * 100;
738
overlayImgEl.style.width = `${widthPercent}%`;
739
overlayImgEl.style.height = `${heightPercent}%`;
740
overlayImgEl.style.maxWidth = 'none';
741
overlayImgEl.style.maxHeight = 'none';
742
}
743
else
744
{
745
// Fallback: use auto sizing with max constraints
746
overlayImgEl.style.width = 'auto';
747
overlayImgEl.style.height = 'auto';
748
overlayImgEl.style.maxWidth = '100%';
749
overlayImgEl.style.maxHeight = '100%';
750
}
751
752
overlayEl.style.display = 'block';
753
overlayImgEl.style.display = 'block';
754
} catch
755
{
756
if (token === requestToken) disableTrack();
757
}
758
};
759
760
const dispose = () =>
761
{
762
requestToken++;
763
closeMenu();
764
hideOverlay();
765
if (overlayEl) overlayEl.remove();
766
if (menuEl) menuEl.remove();
767
player.imageSubtitleOverlayController = null;
768
buttonEl = null;
769
};
770
771
overlayEl = document.createElement('div');
772
overlayEl.className = 'video-subtitle-overlay';
773
overlayEl.style.position = 'absolute';
774
overlayEl.style.left = '0';
775
overlayEl.style.right = '0';
776
overlayEl.style.bottom = '3rem';
777
overlayEl.style.display = 'none';
778
overlayEl.style.zIndex = '3';
779
overlayEl.style.pointerEvents = 'none';
780
overlayEl.style.textAlign = 'center';
781
overlayEl.style.padding = '0 0.75rem';
782
overlayEl.style.maxHeight = '70%';
783
overlayEl.style.overflow = 'hidden';
784
785
overlayImgEl = document.createElement('img');
786
overlayImgEl.alt = 'Image subtitles';
787
overlayImgEl.style.display = 'none';
788
overlayImgEl.style.margin = '0 auto';
789
overlayImgEl.style.objectFit = 'contain';
790
overlayImgEl.style.filter = 'drop-shadow(0 2px 2px rgba(0, 0, 0, 0.7))';
791
overlayImgEl.style.maxWidth = '100%';
792
overlayImgEl.style.height = 'auto';
793
overlayEl.appendChild(overlayImgEl);
794
795
menuEl = document.createElement('div');
796
menuEl.className = 'video-subtitle-overlay-menu';
797
menuEl.style.position = 'absolute';
798
menuEl.style.right = '0.75rem';
799
menuEl.style.bottom = 'calc(3rem + 0.5rem)';
800
menuEl.style.minWidth = '14rem';
801
menuEl.style.maxWidth = '20rem';
802
menuEl.style.background = 'rgba(12, 12, 12, 0.96)';
803
menuEl.style.border = '1px solid rgba(255, 255, 255, 0.15)';
804
menuEl.style.borderRadius = '0.5rem';
805
menuEl.style.boxShadow = '0 12px 28px rgba(0, 0, 0, 0.35)';
806
menuEl.style.padding = '0.35rem';
807
menuEl.style.display = 'none';
808
menuEl.style.zIndex = '4';
809
810
const buildMenuItem = (label, streamIndex, isSelected) =>
811
{
812
const itemEl = document.createElement('button');
813
itemEl.type = 'button';
814
itemEl.className = 'video-subtitle-overlay-menu-item';
815
itemEl.setAttribute('data-image-subtitle-stream-index', streamIndex === null ? 'off' : String(streamIndex));
816
itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false');
817
itemEl.style.display = 'block';
818
itemEl.style.width = '100%';
819
itemEl.style.margin = '0';
820
itemEl.style.padding = '0.5rem 0.75rem';
821
itemEl.style.border = '0';
822
itemEl.style.borderRadius = '0.35rem';
823
itemEl.style.background = isSelected ? 'rgba(255, 255, 255, 0.18)' : 'transparent';
824
itemEl.style.color = '#fff';
825
itemEl.style.textAlign = 'left';
826
itemEl.style.cursor = 'pointer';
827
itemEl.textContent = label;
828
itemEl.addEventListener('click', () =>
829
{
830
setSelectedStreamIndex(streamIndex);
831
closeMenu();
832
});
833
return itemEl;
834
};
835
836
menuEl.appendChild(buildMenuItem('Off', null, false));
837
for (const track of imageTracks)
838
{
839
menuEl.appendChild(buildMenuItem(track.label, track.streamIndex, false));
840
}
841
842
const registerButton = () =>
843
{
844
if (!videojs || typeof videojs.getComponent !== 'function' || typeof videojs.registerComponent !== 'function') return;
845
if (videojs.getComponent('ImageSubtitleButton')) return;
846
847
const Button = videojs.getComponent('Button');
848
class ImageSubtitleButton extends Button
849
{
850
buildCSSClass ()
851
{
852
return `${super.buildCSSClass()} vjs-image-subtitle-button`;
853
}
854
855
createEl ()
856
{
857
const el = super.createEl();
858
el.type = 'button';
859
el.setAttribute('title', 'Image subtitles');
860
el.setAttribute('aria-label', 'Image subtitles');
861
el.innerHTML = '<span aria-hidden="true">IM</span>';
862
return el;
863
}
864
865
handleClick ()
866
{
867
const controller = this.player().imageSubtitleOverlayController;
868
if (controller) controller.toggleMenu();
869
}
870
}
871
872
videojs.registerComponent('ImageSubtitleButton', ImageSubtitleButton);
873
};
874
875
const attachUi = () =>
876
{
877
if (!player.el()) return;
878
registerButton();
879
if (overlayEl.parentElement !== player.el()) player.el().appendChild(overlayEl);
880
if (menuEl.parentElement !== player.el()) player.el().appendChild(menuEl);
881
const controlBar = typeof player.getChild === 'function' ? player.getChild('controlBar') : null;
882
if (controlBar && typeof controlBar.addChild === 'function' && !buttonEl)
883
{
884
const button = controlBar.addChild('ImageSubtitleButton', {});
885
buttonEl = button && typeof button.el === 'function' ? button.el() : null;
886
updateButtonState();
887
}
888
};
889
890
const applySavedTracks = () =>
891
{
892
const savedName = normaliseTrackName(prefs.imageSubtitleTrackName);
893
if (savedName)
894
{
895
const savedByName = imageTracks.find((track) => normaliseTrackName(track.label) === savedName) || null;
896
if (savedByName)
897
{
898
setSelectedStreamIndex(savedByName.streamIndex, { persist: false });
899
return;
900
}
901
}
902
903
const savedIndex = Number(prefs.imageSubtitleTrackStreamIndex);
904
if (Number.isInteger(savedIndex) && trackByStreamIndex.has(savedIndex))
905
{
906
setSelectedStreamIndex(savedIndex, { persist: false });
907
return;
908
}
909
910
const defaultTrack = imageTracks.find((track) => track.isDefault) || null;
911
if (defaultTrack)
912
{
913
setSelectedStreamIndex(defaultTrack.streamIndex, { persist: false });
914
return;
915
}
916
917
setSelectedStreamIndex(null, { persist: false });
918
};
919
920
player.imageSubtitleOverlayController = {
921
toggleMenu,
922
closeMenu,
923
applySavedTracks,
924
captureSelectedTracks: saveSelection,
925
detach: dispose,
926
};
927
928
player.on('timeupdate', () => { void refreshFrame(); });
929
player.on('seeking', () => { void refreshFrame(true); });
930
player.on('play', () => { void refreshFrame(true); });
931
player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });
932
player.on('dispose', dispose);
933
player.ready(() =>
934
{
935
attachUi();
936
updateMenuState();
937
updateButtonState();
938
applySavedTracks();
939
if (menuOpen) openMenu();
399
const shared = sharedVideoPlayer();
400
if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;
401
402
return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {
403
savePrefs: saveUserVideoPrefs,
404
buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({
405
url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,
406
headers: buildAuthHeaders(),
407
credentials: 'same-origin',
408
}),
409
onError: () => toast('Image subtitles could not be rendered for this file.', 'err'),
940
410
});
941
942
return player.imageSubtitleOverlayController;
943
411
}
944
412
945
413
function normaliseVideoDuration (player, durationSeconds)
946
414
{
947
const duration = Number(durationSeconds);
948
if (!player || !Number.isFinite(duration) || duration <= 0) return;
949
950
let originalDuration = null;
951
let durationWasChanged = false;
952
try
953
{
954
originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null;
955
installDurationFallback(player, originalDuration, duration);
956
if (player.__filemanagerDurationApplied) return;
957
958
const current = originalDuration ? Number(originalDuration()) : NaN;
959
const withinTolerance = Number.isFinite(current) && current >= duration * 0.95;
960
console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`);
961
if (withinTolerance)
962
{
963
player.__filemanagerDurationApplied = true;
964
return;
965
}
966
967
if (originalDuration)
968
{
969
durationWasChanged = true;
970
originalDuration(duration);
971
}
972
} catch
973
{
974
// Ignore players that do not support setting duration.
975
}
976
977
try
978
{
979
const updated = originalDuration ? Number(originalDuration()) : NaN;
980
if (Number.isFinite(updated) && updated >= duration * 0.95)
981
{
982
player.__filemanagerDurationApplied = true;
983
if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange');
984
return;
985
}
986
987
player.__filemanagerDurationApplied = true;
988
if (typeof player.trigger === 'function') player.trigger('durationchange');
989
} catch
990
{
991
// Ignore duration fallback failures.
992
}
993
}
994
995
function installDurationFallback (player, originalDuration, duration)
996
{
997
if (!player || !originalDuration || player.__filemanagerDurationFallback) return;
998
999
player.__filemanagerDurationFallback = true;
1000
player.duration = function durationWithFallback (...args)
1001
{
1002
if (args.length) return originalDuration(...args);
1003
const current = Number(originalDuration());
1004
return Number.isFinite(current) && current >= duration * 0.95 ? current : duration;
1005
};
1006
}
1007
1008
function formatDurationForDebug (seconds)
1009
{
1010
const value = Number(seconds);
1011
if (!Number.isFinite(value) || value < 0) return 'unknown';
1012
1013
const totalSeconds = Math.floor(value);
1014
const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');
1015
const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');
1016
const ss = String(totalSeconds % 60).padStart(2, '0');
1017
return `${hh}:${mm}:${ss}`;
415
const shared = sharedVideoPlayer();
416
if (!shared || typeof shared.normaliseVideoDuration !== 'function') return;
417
shared.normaliseVideoDuration(player, durationSeconds);
1018
418
}
1019
419
1020
420
function ensureVideoPlaybackUi (player, durationSeconds)
1021
421
{
1022
if (!player || typeof player.on !== 'function') return;
1023
1024
const forceVodUi = () =>
1025
{
1026
normaliseVideoDuration(player, durationSeconds);
1027
1028
try
1029
{
1030
if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')
1031
{
1032
player.liveTracker.stopTracking();
1033
}
1034
} catch
1035
{
1036
// Ignore live tracker availability issues.
1037
}
1038
1039
try
1040
{
1041
if (typeof player.removeClass === 'function')
1042
{
1043
player.removeClass('vjs-live');
1044
}
1045
} catch
1046
{
1047
// Ignore class update failures.
1048
}
1049
1050
try
1051
{
1052
const display = player.el() && player.el().querySelector('.vjs-live-display');
1053
if (display) display.style.display = 'none';
1054
} catch
1055
{
1056
// Ignore missing DOM.
1057
}
1058
};
1059
1060
player.ready(forceVodUi);
1061
player.on('loadedmetadata', forceVodUi);
1062
player.on('durationchange', forceVodUi);
1063
player.on('loadedplaylist', forceVodUi);
422
const shared = sharedVideoPlayer();
423
if (!shared || typeof shared.ensureVideoPlaybackUi !== 'function') return;
424
shared.ensureVideoPlaybackUi(player, durationSeconds);
1064
425
}
1065
426
1066
427
async function reportWatchProgress (filePath, progress)
@@ -4470,20 +3831,12 @@ async function ensureVideoJsLoaded ()
4470
3831
4471
3832
function configureVideoJsBuffering (videojs)
4472
3833
{
4473
if (!VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED)
4474
return;
4475
4476
if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return;
4477
videojs.__filemanagerBufferingConfigured = true;
4478
4479
try
4480
{
4481
videojs.Vhs.GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;
4482
videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;
4483
} catch
4484
{
4485
// Ignore builds that do not expose VHS buffer configuration.
4486
}
3834
const shared = sharedVideoPlayer();
3835
if (!shared || typeof shared.configureVideoJsBuffering !== 'function') return;
3836
shared.configureVideoJsBuffering(videojs, {
3837
enabled: VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED,
3838
seconds: VIDEO_FORWARD_BUFFER_SECONDS,
3839
});
4487
3840
}
4488
3841
4489
3842
async function createVideoStreamSessionForItem (item)
@@ -370,697 +370,58 @@ function buildAuthHeaders ()370
370
371
function applyUserVideoTextTrackPrefs ()371
function applyUserVideoTextTrackPrefs ()372
{372
{373
try373
const shared = sharedVideoPlayer();374
{374
if (!shared || typeof shared.applyDefaultTextTrackPrefs !== 'function') return;375
// Only override the two requested defaults and leave other settings at Video.js defaults.375
shared.applyDefaultTextTrackPrefs();376
localStorage.setItem(VIDEO_TEXT_TRACK_SETTINGS_KEY, VIDEO_TEXT_TRACK_OVERRIDE_SETTINGS_RAW);377
} catch378
{379
// Ignore localStorage failures.380
}381
}382
383
function normaliseTrackName (name)384
{385
return String(name || '').trim().toLowerCase();386
}376
}387
377
388
function getTrackName (track)378
function sharedVideoPlayer ()389
{379
{390
if (!track || typeof track !== 'object') return '';380
return window.FilemanagerSharedVideoPlayer || null;391
const label = String(track.label || '').trim();392
if (label) return label;393
const name = String(track.name || '').trim();394
if (name) return name;395
const language = String(track.language || '').trim();396
if (language) return language;397
const id = String(track.id || '').trim();398
if (id) return id;399
return '';400
}401
402
function trackListToArray (trackList)403
{404
if (!trackList || typeof trackList.length !== 'number') return [];405
const out = [];406
for (let i = 0; i < trackList.length; i++)407
{408
const track = trackList[i] || (typeof trackList.item === 'function' ? trackList.item(i) : null);409
if (track) out.push(track);410
}411
return out;412
}413
414
function subtitleTracksFromPlayer (player)415
{416
if (!player || typeof player.textTracks !== 'function') return [];417
return trackListToArray(player.textTracks()).filter((track) =>418
{419
const kind = String(track.kind || '').toLowerCase();420
return kind === 'subtitles' || kind === 'captions';421
});422
}423
424
function audioTracksFromPlayer (player)425
{426
if (!player || typeof player.audioTracks !== 'function') return [];427
return trackListToArray(player.audioTracks());428
}429
430
function applySavedSubtitleTrack (player, savedName)431
{432
if (typeof savedName !== 'string') return;433
const tracks = subtitleTracksFromPlayer(player);434
if (!tracks.length) return;435
436
const wanted = normaliseTrackName(savedName);437
if (!wanted)438
{439
for (const track of tracks) track.mode = 'disabled';440
return;441
}442
443
const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted);444
if (!match) return;445
446
for (const track of tracks)447
{448
track.mode = track === match ? 'showing' : 'disabled';449
}450
}451
452
function applySavedAudioTrack (player, savedName)453
{454
if (typeof savedName !== 'string') return;455
const tracks = audioTracksFromPlayer(player);456
if (!tracks.length) return;457
458
const wanted = normaliseTrackName(savedName);459
if (!wanted) return;460
461
const match = tracks.find((track) => normaliseTrackName(getTrackName(track)) === wanted);462
if (!match) return;463
464
for (const track of tracks)465
{466
track.enabled = track === match;467
}468
}469
470
function getSelectedSubtitleTrackName (player)471
{472
const tracks = subtitleTracksFromPlayer(player);473
if (!tracks.length) return null;474
const active = tracks.find((track) => String(track.mode || '').toLowerCase() === 'showing');475
return active ? getTrackName(active) : '';476
}477
478
function getSelectedAudioTrackName (player)479
{480
const tracks = audioTracksFromPlayer(player);481
if (!tracks.length) return null;482
const active = tracks.find((track) => !!track.enabled);483
return active ? getTrackName(active) : '';484
}381
}485
382
486
function bindUserVideoTrackPrefs (player, prefs)383
function bindUserVideoTrackPrefs (player, prefs)487
{384
{488
const applySavedTracks = () =>385
const shared = sharedVideoPlayer();489
{386
if (!shared || typeof shared.bindTrackPrefs !== 'function')490
applySavedSubtitleTrack(player, prefs.subtitleTrackName);491
applySavedAudioTrack(player, prefs.audioTrackName);492
};493
494
const captureSelectedTracks = () =>495
{387
{496
const subtitleTrackName = getSelectedSubtitleTrackName(player);388
return {497
const audioTrackName = getSelectedAudioTrackName(player);389
applySavedTracks: () => {},498
const patch = {};390
captureSelectedTracks: () => {},499
391
detach: () => {},500
if (subtitleTrackName !== null) patch.subtitleTrackName = subtitleTrackName;392
};501
if (audioTrackName !== null) patch.audioTrackName = audioTrackName;502
503
if (Object.keys(patch).length) saveUserVideoPrefs(patch);504
};505
506
const textTrackList = typeof player.textTracks === 'function' ? player.textTracks() : null;507
const audioTrackList = typeof player.audioTracks === 'function' ? player.audioTracks() : null;508
const onTrackListChange = () => captureSelectedTracks();509
510
if (textTrackList && typeof textTrackList.addEventListener === 'function')511
{512
textTrackList.addEventListener('change', onTrackListChange);513
}514
515
if (audioTrackList && typeof audioTrackList.addEventListener === 'function')516
{517
audioTrackList.addEventListener('change', onTrackListChange);518
}393
}519
394
return shared.bindTrackPrefs(player, prefs, saveUserVideoPrefs);520
return {521
applySavedTracks,522
captureSelectedTracks,523
detach: () =>524
{525
if (textTrackList && typeof textTrackList.removeEventListener === 'function')526
{527
textTrackList.removeEventListener('change', onTrackListChange);528
}529
if (audioTrackList && typeof audioTrackList.removeEventListener === 'function')530
{531
audioTrackList.removeEventListener('change', onTrackListChange);532
}533
},534
};535
}395
}536
396
537
function bindImageSubtitleOverlay (player, videojs, prefs, session, item)397
function bindImageSubtitleOverlay (player, videojs, prefs, session, item)538
{398
{539
const imageTracks = Array.isArray(session.imageSubtitleTracks)399
const shared = sharedVideoPlayer();540
? session.imageSubtitleTracks.map((track) => ({400
if (!shared || typeof shared.bindImageSubtitleOverlay !== 'function') return null;541
label: String(track.label || '').trim() || `Subtitle ${Number(track.streamIndex || 0) + 1}`,401
542
language: String(track.language || '').trim(),402
return shared.bindImageSubtitleOverlay(player, videojs, prefs, session, {543
isDefault: !!track.default,403
savePrefs: saveUserVideoPrefs,544
streamIndex: Number(track.streamIndex),404
buildFrameRequest: ({ currentTime, streamIndex, session: activeSession }) => ({545
})).filter((track) => Number.isInteger(track.streamIndex) && track.streamIndex >= 0)405
url: `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${streamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(activeSession.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(activeSession.videoHeight || ''))}`,546
: [];406
headers: buildAuthHeaders(),547
407
credentials: 'same-origin',548
if (!imageTracks.length) return null;408
}),549
409
onError: () => toast('Image subtitles could not be rendered for this file.', 'err'),550
const trackByStreamIndex = new Map(imageTracks.map((track) => [track.streamIndex, track]));551
let selectedStreamIndex = null;552
let menuOpen = false;553
let requestToken = 0;554
let activeBucket = -1;555
let activeObjectUrl = null;556
let overlayEl = null;557
let overlayImgEl = null;558
let menuEl = null;559
let buttonEl = null;560
let trackDisabled = false;561
let failureNotified = false;562
563
const closeObjectUrl = () =>564
{565
if (activeObjectUrl)566
{567
URL.revokeObjectURL(activeObjectUrl);568
activeObjectUrl = null;569
}570
};571
572
const hideOverlay = () =>573
{574
if (overlayEl) overlayEl.style.display = 'none';575
if (overlayImgEl) overlayImgEl.removeAttribute('src');576
closeObjectUrl();577
};578
579
const updateButtonState = () =>580
{581
if (!buttonEl) return;582
const track = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null;583
buttonEl.setAttribute('title', track ? `Image subtitles: ${track.label}` : 'Image subtitles');584
buttonEl.setAttribute('aria-pressed', selectedStreamIndex === null ? 'false' : 'true');585
};586
587
const updateMenuState = () =>588
{589
if (!menuEl) return;590
const items = menuEl.querySelectorAll('[data-image-subtitle-stream-index]');591
for (const itemEl of items)592
{593
const value = itemEl.getAttribute('data-image-subtitle-stream-index');594
const isSelected = value === (selectedStreamIndex === null ? 'off' : String(selectedStreamIndex));595
itemEl.classList.toggle('is-selected', isSelected);596
itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false');597
itemEl.style.background = isSelected ? 'rgba(90, 196, 255, 0.28)' : 'transparent';598
itemEl.style.fontWeight = isSelected ? '600' : '400';599
itemEl.style.boxShadow = isSelected ? 'inset 0 0 0 1px rgba(90, 196, 255, 0.55)' : 'none';600
}601
};602
603
const closeMenu = () =>604
{605
menuOpen = false;606
if (menuEl) menuEl.style.display = 'none';607
};608
609
const openMenu = () =>610
{611
menuOpen = true;612
if (menuEl)613
{614
updateMenuState();615
menuEl.style.display = 'block';616
}617
};618
619
const toggleMenu = () =>620
{621
if (menuOpen) closeMenu();622
else openMenu();623
};624
625
const saveSelection = () =>626
{627
const selectedTrack = selectedStreamIndex === null ? null : trackByStreamIndex.get(selectedStreamIndex) || null;628
saveUserVideoPrefs({629
imageSubtitleTrackStreamIndex: selectedStreamIndex,630
imageSubtitleTrackName: selectedTrack ? selectedTrack.label : null,631
});632
};633
634
const disableTrack = () =>635
{636
trackDisabled = true;637
selectedStreamIndex = null;638
activeBucket = -1;639
hideOverlay();640
updateButtonState();641
updateMenuState();642
saveSelection();643
644
if (!failureNotified)645
{646
failureNotified = true;647
toast('Image subtitles could not be rendered for this file.', 'err');648
}649
};650
651
const setSelectedStreamIndex = (streamIndex, { persist = true } = {}) =>652
{653
const nextStreamIndex = Number.isInteger(streamIndex) ? streamIndex : null;654
if (nextStreamIndex !== null && !trackByStreamIndex.has(nextStreamIndex)) return;655
656
trackDisabled = false;657
failureNotified = false;658
selectedStreamIndex = nextStreamIndex;659
activeBucket = -1;660
hideOverlay();661
updateButtonState();662
updateMenuState();663
if (persist) saveSelection();664
665
if (selectedStreamIndex !== null)666
{667
void refreshFrame(true);668
}669
};670
671
const refreshFrame = async (force = false) =>672
{673
if (selectedStreamIndex === null) return;674
if (!overlayEl || !overlayImgEl) return;675
if (trackDisabled) return;676
677
const currentTime = Number(player.currentTime());678
if (!Number.isFinite(currentTime) || currentTime < 0) return;679
680
const bucket = Math.floor(currentTime * 4);681
if (!force && bucket === activeBucket) return;682
activeBucket = bucket;683
684
const token = ++requestToken;685
const headers = buildAuthHeaders();686
const url = `/api/files/video-stream-subtitle-frame?filePath=${encodeURIComponent(item.path)}&streamIndex=${selectedStreamIndex}&timeSeconds=${encodeURIComponent(String(currentTime))}&videoWidth=${encodeURIComponent(String(session.videoWidth || ''))}&videoHeight=${encodeURIComponent(String(session.videoHeight || ''))}`;687
688
try689
{690
const res = await fetch(url, {691
method: 'GET',692
headers,693
credentials: 'same-origin',694
});695
696
if (token !== requestToken) return;697
698
if (res.status === 204)699
{700
const frameStatus = String(res.headers.get('X-Subtitle-Frame-Status') || '').toLowerCase();701
hideOverlay();702
if (frameStatus === 'error') disableTrack();703
return;704
}705
706
if (!res.ok)707
{708
disableTrack();709
return;710
}711
712
const blob = await res.blob();713
if (token !== requestToken) return;714
715
if (!blob || blob.size === 0)716
{717
disableTrack();718
return;719
}720
721
closeObjectUrl();722
activeObjectUrl = URL.createObjectURL(blob);723
overlayImgEl.src = activeObjectUrl;724
725
// Apply placement from headers when available726
const frameLeft = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Left') || ''), 10);727
const frameTop = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Top') || ''), 10);728
const frameWidth = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Width') || ''), 10);729
const frameHeight = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Height') || ''), 10);730
const canvasWidth = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Canvas-Width') || ''), 10);731
const canvasHeight = Number.parseInt(String(res.headers.get('X-Subtitle-Frame-Canvas-Height') || ''), 10);732
733
if (frameWidth > 0 && frameHeight > 0 && canvasWidth > 0 && canvasHeight > 0)734
{735
// Apply percentage-based sizing to scale the downscaled image properly736
const widthPercent = (frameWidth / canvasWidth) * 100;737
const heightPercent = (frameHeight / canvasHeight) * 100;738
overlayImgEl.style.width = `${widthPercent}%`;739
overlayImgEl.style.height = `${heightPercent}%`;740
overlayImgEl.style.maxWidth = 'none';741
overlayImgEl.style.maxHeight = 'none';742
}743
else744
{745
// Fallback: use auto sizing with max constraints746
overlayImgEl.style.width = 'auto';747
overlayImgEl.style.height = 'auto';748
overlayImgEl.style.maxWidth = '100%';749
overlayImgEl.style.maxHeight = '100%';750
}751
752
overlayEl.style.display = 'block';753
overlayImgEl.style.display = 'block';754
} catch755
{756
if (token === requestToken) disableTrack();757
}758
};759
760
const dispose = () =>761
{762
requestToken++;763
closeMenu();764
hideOverlay();765
if (overlayEl) overlayEl.remove();766
if (menuEl) menuEl.remove();767
player.imageSubtitleOverlayController = null;768
buttonEl = null;769
};770
771
overlayEl = document.createElement('div');772
overlayEl.className = 'video-subtitle-overlay';773
overlayEl.style.position = 'absolute';774
overlayEl.style.left = '0';775
overlayEl.style.right = '0';776
overlayEl.style.bottom = '3rem';777
overlayEl.style.display = 'none';778
overlayEl.style.zIndex = '3';779
overlayEl.style.pointerEvents = 'none';780
overlayEl.style.textAlign = 'center';781
overlayEl.style.padding = '0 0.75rem';782
overlayEl.style.maxHeight = '70%';783
overlayEl.style.overflow = 'hidden';784
785
overlayImgEl = document.createElement('img');786
overlayImgEl.alt = 'Image subtitles';787
overlayImgEl.style.display = 'none';788
overlayImgEl.style.margin = '0 auto';789
overlayImgEl.style.objectFit = 'contain';790
overlayImgEl.style.filter = 'drop-shadow(0 2px 2px rgba(0, 0, 0, 0.7))';791
overlayImgEl.style.maxWidth = '100%';792
overlayImgEl.style.height = 'auto';793
overlayEl.appendChild(overlayImgEl);794
795
menuEl = document.createElement('div');796
menuEl.className = 'video-subtitle-overlay-menu';797
menuEl.style.position = 'absolute';798
menuEl.style.right = '0.75rem';799
menuEl.style.bottom = 'calc(3rem + 0.5rem)';800
menuEl.style.minWidth = '14rem';801
menuEl.style.maxWidth = '20rem';802
menuEl.style.background = 'rgba(12, 12, 12, 0.96)';803
menuEl.style.border = '1px solid rgba(255, 255, 255, 0.15)';804
menuEl.style.borderRadius = '0.5rem';805
menuEl.style.boxShadow = '0 12px 28px rgba(0, 0, 0, 0.35)';806
menuEl.style.padding = '0.35rem';807
menuEl.style.display = 'none';808
menuEl.style.zIndex = '4';809
810
const buildMenuItem = (label, streamIndex, isSelected) =>811
{812
const itemEl = document.createElement('button');813
itemEl.type = 'button';814
itemEl.className = 'video-subtitle-overlay-menu-item';815
itemEl.setAttribute('data-image-subtitle-stream-index', streamIndex === null ? 'off' : String(streamIndex));816
itemEl.setAttribute('aria-checked', isSelected ? 'true' : 'false');817
itemEl.style.display = 'block';818
itemEl.style.width = '100%';819
itemEl.style.margin = '0';820
itemEl.style.padding = '0.5rem 0.75rem';821
itemEl.style.border = '0';822
itemEl.style.borderRadius = '0.35rem';823
itemEl.style.background = isSelected ? 'rgba(255, 255, 255, 0.18)' : 'transparent';824
itemEl.style.color = '#fff';825
itemEl.style.textAlign = 'left';826
itemEl.style.cursor = 'pointer';827
itemEl.textContent = label;828
itemEl.addEventListener('click', () =>829
{830
setSelectedStreamIndex(streamIndex);831
closeMenu();832
});833
return itemEl;834
};835
836
menuEl.appendChild(buildMenuItem('Off', null, false));837
for (const track of imageTracks)838
{839
menuEl.appendChild(buildMenuItem(track.label, track.streamIndex, false));840
}841
842
const registerButton = () =>843
{844
if (!videojs || typeof videojs.getComponent !== 'function' || typeof videojs.registerComponent !== 'function') return;845
if (videojs.getComponent('ImageSubtitleButton')) return;846
847
const Button = videojs.getComponent('Button');848
class ImageSubtitleButton extends Button849
{850
buildCSSClass ()851
{852
return `${super.buildCSSClass()} vjs-image-subtitle-button`;853
}854
855
createEl ()856
{857
const el = super.createEl();858
el.type = 'button';859
el.setAttribute('title', 'Image subtitles');860
el.setAttribute('aria-label', 'Image subtitles');861
el.innerHTML = '<span aria-hidden="true">IM</span>';862
return el;863
}864
865
handleClick ()866
{867
const controller = this.player().imageSubtitleOverlayController;868
if (controller) controller.toggleMenu();869
}870
}871
872
videojs.registerComponent('ImageSubtitleButton', ImageSubtitleButton);873
};874
875
const attachUi = () =>876
{877
if (!player.el()) return;878
registerButton();879
if (overlayEl.parentElement !== player.el()) player.el().appendChild(overlayEl);880
if (menuEl.parentElement !== player.el()) player.el().appendChild(menuEl);881
const controlBar = typeof player.getChild === 'function' ? player.getChild('controlBar') : null;882
if (controlBar && typeof controlBar.addChild === 'function' && !buttonEl)883
{884
const button = controlBar.addChild('ImageSubtitleButton', {});885
buttonEl = button && typeof button.el === 'function' ? button.el() : null;886
updateButtonState();887
}888
};889
890
const applySavedTracks = () =>891
{892
const savedName = normaliseTrackName(prefs.imageSubtitleTrackName);893
if (savedName)894
{895
const savedByName = imageTracks.find((track) => normaliseTrackName(track.label) === savedName) || null;896
if (savedByName)897
{898
setSelectedStreamIndex(savedByName.streamIndex, { persist: false });899
return;900
}901
}902
903
const savedIndex = Number(prefs.imageSubtitleTrackStreamIndex);904
if (Number.isInteger(savedIndex) && trackByStreamIndex.has(savedIndex))905
{906
setSelectedStreamIndex(savedIndex, { persist: false });907
return;908
}909
910
const defaultTrack = imageTracks.find((track) => track.isDefault) || null;911
if (defaultTrack)912
{913
setSelectedStreamIndex(defaultTrack.streamIndex, { persist: false });914
return;915
}916
917
setSelectedStreamIndex(null, { persist: false });918
};919
920
player.imageSubtitleOverlayController = {921
toggleMenu,922
closeMenu,923
applySavedTracks,924
captureSelectedTracks: saveSelection,925
detach: dispose,926
};927
928
player.on('timeupdate', () => { void refreshFrame(); });929
player.on('seeking', () => { void refreshFrame(true); });930
player.on('play', () => { void refreshFrame(true); });931
player.on('fullscreenchange', () => { closeMenu(); void refreshFrame(true); });932
player.on('dispose', dispose);933
player.ready(() =>934
{935
attachUi();936
updateMenuState();937
updateButtonState();938
applySavedTracks();939
if (menuOpen) openMenu();940
});410
});941
942
return player.imageSubtitleOverlayController;943
}411
}944
412
945
function normaliseVideoDuration (player, durationSeconds)413
function normaliseVideoDuration (player, durationSeconds)946
{414
{947
const duration = Number(durationSeconds);415
const shared = sharedVideoPlayer();948
if (!player || !Number.isFinite(duration) || duration <= 0) return;416
if (!shared || typeof shared.normaliseVideoDuration !== 'function') return;949
417
shared.normaliseVideoDuration(player, durationSeconds);950
let originalDuration = null;951
let durationWasChanged = false;952
try953
{954
originalDuration = typeof player.duration === 'function' ? player.duration.bind(player) : null;955
installDurationFallback(player, originalDuration, duration);956
if (player.__filemanagerDurationApplied) return;957
958
const current = originalDuration ? Number(originalDuration()) : NaN;959
const withinTolerance = Number.isFinite(current) && current >= duration * 0.95;960
console.log(`Current duration: ${formatDurationForDebug(current)}, Target time: ${formatDurationForDebug(duration)}, within 95%? ${withinTolerance ? 'yes' : 'no'}`);961
if (withinTolerance)962
{963
player.__filemanagerDurationApplied = true;964
return;965
}966
967
if (originalDuration)968
{969
durationWasChanged = true;970
originalDuration(duration);971
}972
} catch973
{974
// Ignore players that do not support setting duration.975
}976
977
try978
{979
const updated = originalDuration ? Number(originalDuration()) : NaN;980
if (Number.isFinite(updated) && updated >= duration * 0.95)981
{982
player.__filemanagerDurationApplied = true;983
if (durationWasChanged && typeof player.trigger === 'function') player.trigger('durationchange');984
return;985
}986
987
player.__filemanagerDurationApplied = true;988
if (typeof player.trigger === 'function') player.trigger('durationchange');989
} catch990
{991
// Ignore duration fallback failures.992
}993
}994
995
function installDurationFallback (player, originalDuration, duration)996
{997
if (!player || !originalDuration || player.__filemanagerDurationFallback) return;998
999
player.__filemanagerDurationFallback = true;1000
player.duration = function durationWithFallback (...args)1001
{1002
if (args.length) return originalDuration(...args);1003
const current = Number(originalDuration());1004
return Number.isFinite(current) && current >= duration * 0.95 ? current : duration;1005
};1006
}1007
1008
function formatDurationForDebug (seconds)1009
{1010
const value = Number(seconds);1011
if (!Number.isFinite(value) || value < 0) return 'unknown';1012
1013
const totalSeconds = Math.floor(value);1014
const hh = String(Math.floor(totalSeconds / 3600)).padStart(2, '0');1015
const mm = String(Math.floor((totalSeconds % 3600) / 60)).padStart(2, '0');1016
const ss = String(totalSeconds % 60).padStart(2, '0');1017
return `${hh}:${mm}:${ss}`;1018
}418
}1019
419
1020
function ensureVideoPlaybackUi (player, durationSeconds)420
function ensureVideoPlaybackUi (player, durationSeconds)1021
{421
{1022
if (!player || typeof player.on !== 'function') return;422
const shared = sharedVideoPlayer();1023
423
if (!shared || typeof shared.ensureVideoPlaybackUi !== 'function') return;1024
const forceVodUi = () =>424
shared.ensureVideoPlaybackUi(player, durationSeconds);1025
{1026
normaliseVideoDuration(player, durationSeconds);1027
1028
try1029
{1030
if (player.liveTracker && typeof player.liveTracker.stopTracking === 'function')1031
{1032
player.liveTracker.stopTracking();1033
}1034
} catch1035
{1036
// Ignore live tracker availability issues.1037
}1038
1039
try1040
{1041
if (typeof player.removeClass === 'function')1042
{1043
player.removeClass('vjs-live');1044
}1045
} catch1046
{1047
// Ignore class update failures.1048
}1049
1050
try1051
{1052
const display = player.el() && player.el().querySelector('.vjs-live-display');1053
if (display) display.style.display = 'none';1054
} catch1055
{1056
// Ignore missing DOM.1057
}1058
};1059
1060
player.ready(forceVodUi);1061
player.on('loadedmetadata', forceVodUi);1062
player.on('durationchange', forceVodUi);1063
player.on('loadedplaylist', forceVodUi);1064
}425
}1065
426
1066
async function reportWatchProgress (filePath, progress)427
async function reportWatchProgress (filePath, progress)@@ -4470,20 +3831,12 @@ async function ensureVideoJsLoaded ()4470
3831
4471
function configureVideoJsBuffering (videojs)3832
function configureVideoJsBuffering (videojs)4472
{3833
{4473
if (!VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED)3834
const shared = sharedVideoPlayer();4474
return;3835
if (!shared || typeof shared.configureVideoJsBuffering !== 'function') return;4475
3836
shared.configureVideoJsBuffering(videojs, {4476
if (!videojs || !videojs.Vhs || videojs.__filemanagerBufferingConfigured) return;3837
enabled: VIDEO_FORWARD_BUFFER_OVERRIDE_ENABLED,4477
videojs.__filemanagerBufferingConfigured = true;3838
seconds: VIDEO_FORWARD_BUFFER_SECONDS,4478
3839
});4479
try4480
{4481
videojs.Vhs.GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;4482
videojs.Vhs.MAX_GOAL_BUFFER_LENGTH = VIDEO_FORWARD_BUFFER_SECONDS;4483
} catch4484
{4485
// Ignore builds that do not expose VHS buffer configuration.4486
}4487
}3840
}4488
3841
4489
async function createVideoStreamSessionForItem (item)3842
async function createVideoStreamSessionForItem (item)@@ -433,6 +433,7 @@
433
433
}
434
434
</script>
435
435
<script src="drag-move.js"></script>
436
<script src="shared-video-player.js"></script>
436
437
<script src="app.js"></script>
437
438
</body>
438
439
@@ -433,6 +433,7 @@433
}433
}434
</script>434
</script>435
<script src="drag-move.js"></script>435
<script src="drag-move.js"></script>436
<script src="shared-video-player.js"></script>436
<script src="app.js"></script>437
<script src="app.js"></script>437
</body>438
</body>438
439