Files
xtremflow/web/player.html
T

442 lines
15 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>XtremFlow Player</title>
<!-- HLS.js and mpegts.js for MPEG-TS support -->
<script src="https://cdn.jsdelivr.net/npm/hls.js@1.4.12/dist/hls.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/mpegts.js@1.7.3/dist/mpegts.min.js"></script>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
background: #000;
width: 100%;
height: 100%;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
}
#player-container {
width: 100%;
height: 100%;
position: relative;
}
#video {
width: 100%;
height: 100%;
background: #000;
}
#error {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
text-align: center;
font-family: Arial, sans-serif;
}
#error-icon {
font-size: 64px;
color: #f44336;
margin-bottom: 16px;
}
#loading {
display: none;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: #fff;
text-align: center;
font-family: Arial, sans-serif;
}
.spinner {
width: 48px;
height: 48px;
border: 4px solid #fff;
border-top-color: transparent;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 16px;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
</style>
</head>
<body>
<div id="player-container">
<!-- No native controls - Flutter overlay handles controls -->
<video id="video" autoplay playsinline></video>
<div id="loading">
<div class="spinner"></div>
<div id="loading-text">Loading stream...</div>
</div>
<div id="error">
<div id="error-icon">⚠</div>
<div id="error-message">Failed to load stream</div>
</div>
</div>
<script>
const video = document.getElementById('video');
const loading = document.getElementById('loading');
const loadingText = document.getElementById('loading-text');
const error = document.getElementById('error');
const errorMessage = document.getElementById('error-message');
// Get parameters from query string
const urlParams = new URLSearchParams(window.location.search);
let streamUrl = urlParams.get('url');
const startTime = parseFloat(urlParams.get('t') || '0');
const streamType = urlParams.get('type') || ''; // 'live' or 'vod'
const injectedDuration = parseFloat(urlParams.get('duration') || '0'); // Fix for infinite HLS duration
function log(msg) {
console.log('[Player] ' + msg);
}
function showLoading(msg) {
loading.style.display = 'block';
loadingText.textContent = msg || 'Loading stream...';
error.style.display = 'none';
}
function hideLoading() {
loading.style.display = 'none';
}
function showError(message) {
hideLoading();
error.style.display = 'block';
errorMessage.textContent = message || 'Failed to load stream';
}
// Seek to startTime when video is ready
video.addEventListener('loadedmetadata', () => {
if (startTime > 0 && startTime < video.duration) {
video.currentTime = startTime;
log('Resuming from ' + Math.floor(startTime / 60) + 'm ' + Math.floor(startTime % 60) + 's');
}
});
// Report position to parent for resume feature
let lastReportedTime = 0;
function reportPosition() {
if (video.currentTime > 0 && !video.paused && video.readyState > 2) {
if (Math.abs(video.currentTime - lastReportedTime) >= 1) { // Report more frequently for smoother UI
lastReportedTime = video.currentTime;
let duration = video.duration;
// Priority: 1) HLS dynamic duration, 2) video.duration, 3) injectedDuration
const hlsDuration = window.currentHlsDuration || 0;
if (!isFinite(duration) || isNaN(duration) || duration < 1) {
duration = hlsDuration > 0 ? hlsDuration : (injectedDuration > 0 ? injectedDuration : 0);
} else if (hlsDuration > duration) {
duration = hlsDuration; // Use HLS duration if larger (growing playlist)
} else if (injectedDuration > 0 && duration < injectedDuration * 0.9) {
duration = injectedDuration; // Fallback to injected if significantly larger
}
window.parent.postMessage({
type: 'playback_position',
currentTime: video.currentTime,
duration: duration
}, '*');
}
}
}
setInterval(reportPosition, 5000);
// Report on pause and end
video.addEventListener('pause', () => {
let duration = video.duration;
if (!isFinite(duration) || isNaN(duration)) {
duration = injectedDuration > 0 ? injectedDuration : 0;
}
window.parent.postMessage({
type: 'playback_position',
currentTime: video.currentTime,
duration: duration
}, '*');
// Also report status
window.parent.postMessage({
type: 'playback_status',
status: 'paused'
}, '*');
});
video.addEventListener('ended', () => {
let duration = video.duration;
if (!isFinite(duration) || isNaN(duration)) {
duration = injectedDuration > 0 ? injectedDuration : 0;
}
window.parent.postMessage({
type: 'playback_ended',
duration: duration
}, '*');
});
video.addEventListener('playing', () => {
window.parent.postMessage({
type: 'playback_status',
status: 'playing'
}, '*');
});
// Report user activity (mouse movement or touch) to parent for auto-hide controls
let lastActivityTime = 0;
function reportActivity() {
const now = Date.now();
if (now - lastActivityTime > 100) { // Throttle to 100ms
lastActivityTime = now;
window.parent.postMessage({
type: 'user_activity'
}, '*');
}
}
document.addEventListener('mousemove', reportActivity);
document.addEventListener('touchstart', reportActivity);
document.addEventListener('touchmove', reportActivity);
document.addEventListener('click', reportActivity);
document.addEventListener('touchend', reportActivity);
// Handle commands from Flutter (Play, Pause, Seek, Volume)
window.addEventListener('message', (event) => {
const data = event.data;
if (!data) return;
switch (data.type) {
case 'play': video.play().catch(e => log('Play fail: ' + e)); break;
case 'pause': video.pause(); break;
case 'seek':
if (Number.isFinite(data.value)) video.currentTime = data.value;
break;
case 'set_volume':
video.volume = Math.max(0, Math.min(1, data.value));
break;
}
});
async function playWithHLS(url) {
log('Trying HLS.js with: ' + url);
showLoading('Loading HLS stream...');
if (!Hls.isSupported()) {
if (video.canPlayType('application/vnd.apple.mpegurl')) {
video.src = url;
video.addEventListener('canplay', () => {
hideLoading();
video.play().catch(e => log('Autoplay prevented: ' + e));
});
return true;
}
return false;
}
const hls = new Hls({
maxBufferLength: 30,
maxMaxBufferLength: 60,
enableWorker: true
});
window.hlsInstance = hls;
hls.loadSource(url);
hls.attachMedia(video);
hls.on(Hls.Events.MANIFEST_PARSED, () => {
log('HLS manifest parsed');
hideLoading();
video.play().catch(e => log('Autoplay prevented: ' + e));
});
// Track growing duration as more segments are added (for EVENT playlists)
hls.on(Hls.Events.LEVEL_LOADED, (event, data) => {
const levelDetails = data.details;
if (levelDetails && levelDetails.totalduration) {
const currentLevelDuration = levelDetails.totalduration;
log('Level loaded, current duration: ' + currentLevelDuration);
// Update injectedDuration if HLS gives us a better value
// This allows the progress bar to grow as transcoding progresses
if (currentLevelDuration > injectedDuration) {
window.currentHlsDuration = currentLevelDuration;
}
}
});
hls.on(Hls.Events.ERROR, (event, data) => {
log('HLS Error: ' + data.type + ' - ' + data.details);
if (data.fatal) {
if (data.type === Hls.ErrorTypes.NETWORK_ERROR) {
hls.startLoad();
} else if (data.type === Hls.ErrorTypes.MEDIA_ERROR) {
hls.recoverMediaError();
} else {
showError('HLS Error: ' + data.details);
hls.destroy();
}
}
});
return true;
}
async function playWithMpegTS(url, isLive = true) {
log('Trying mpegts.js with: ' + url + ' (isLive: ' + isLive + ')');
showLoading('Loading MPEG-TS stream...');
if (!mpegts.isSupported()) {
return false;
}
const playerConfig = {
enableWorker: true,
enableStashBuffer: true,
stashInitialSize: 1024 * 1024,
autoCleanupSourceBuffer: true,
};
let player = mpegts.createPlayer({
type: 'mpegts',
isLive: isLive,
url: url,
hasAudio: true,
hasVideo: true,
}, playerConfig);
player.attachMediaElement(video);
player.load();
player.play().catch(e => log('Autoplay prevented: ' + e));
player.on(mpegts.Events.ERROR, (errType, errDetail) => {
log('mpegts error: ' + errType + ' - ' + errDetail);
});
return true;
}
async function playDirect(url) {
log('Trying direct playback: ' + url);
showLoading('Loading video...');
video.src = url;
video.load();
return new Promise((resolve) => {
const onCanPlay = () => {
hideLoading();
video.play().catch(e => log('Autoplay prevented: ' + e));
resolve(true);
};
const onError = async () => {
// If direct fail, try HLS
if (await playWithHLS(url)) {
resolve(true);
} else {
showError('Format not supported.');
resolve(false);
}
};
video.addEventListener('canplay', onCanPlay, { once: true });
video.addEventListener('error', onError, { once: true });
});
}
async function initPlayer() {
if (!streamUrl) {
showError('No stream URL provided');
return;
}
log('Stream URL: ' + streamUrl);
log('Stream type: ' + streamType);
const lowerUrl = streamUrl.toLowerCase();
// LIVE TV
if (streamType === 'live') {
await playWithMpegTS(streamUrl, true);
return;
}
// VOD
if (streamType === 'vod') {
// If M3U8 -> HLS
if (lowerUrl.includes('.m3u8')) {
await playWithHLS(streamUrl);
} else {
// Try direct (MKV? wrapped in proxy?)
// If proxy returns M3U8 content for MKV url, playWithHLS handles it? No, hls.js needs .m3u8 extension usually or explicit config.
// But our VOD URL ends in /playlist.m3u8 so it enters the if above.
await playDirect(streamUrl);
}
return;
}
// Fallback auto-detect
if (lowerUrl.includes('.m3u8')) {
await playWithHLS(streamUrl);
} else {
await playDirect(streamUrl);
}
}
// Listen for messages from parent (Flutter)
window.addEventListener('message', (event) => {
const data = event.data;
if (!data) return;
log('Received message: ' + data.type);
switch (data.type) {
case 'play':
video.play().catch(e => log('Play failed: ' + e));
break;
case 'pause':
video.pause();
break;
case 'seek':
const time = parseFloat(data.value);
if (isFinite(time) && time >= 0) {
video.currentTime = time;
log('Seek to: ' + time);
}
break;
case 'set_volume':
const vol = parseFloat(data.value);
if (isFinite(vol) && vol >= 0 && vol <= 1) {
video.volume = vol;
video.muted = vol === 0;
}
break;
}
});
initPlayer();
</script>
</body>
</html>