允许拉取进度条

This commit is contained in:
CN-JS-HuiBai
2026-04-02 22:05:30 +08:00
parent fd199fdde7
commit 504d02c0fa
3 changed files with 202 additions and 15 deletions

View File

@@ -120,6 +120,21 @@
</div> </div>
</div> </div>
<video id="video-player" controls preload="auto" class="hidden"></video> <video id="video-player" controls preload="auto" class="hidden"></video>
<div id="seeking-overlay" class="seeking-overlay hidden">
<div class="spinner"></div>
<span>跳转中...</span>
</div>
</div>
<div id="custom-seek-container" class="custom-seek-container hidden">
<div id="seek-bar" class="seek-bar">
<div id="seek-bar-progress" class="seek-bar-progress"></div>
<div id="seek-bar-handle" class="seek-bar-handle"></div>
</div>
<div class="seek-time-display">
<span id="seek-current-time">00:00:00</span>
<span class="seek-separator">/</span>
<span id="seek-total-time">00:00:00</span>
</div>
</div> </div>
<div id="now-playing" class="now-playing hidden"> <div id="now-playing" class="now-playing hidden">
<h3>Now Playing</h3> <h3>Now Playing</h3>

View File

@@ -38,6 +38,15 @@ document.addEventListener('DOMContentLoaded', () => {
const statBitrate = document.getElementById('stat-bitrate'); const statBitrate = document.getElementById('stat-bitrate');
const statTime = document.getElementById('stat-time'); const statTime = document.getElementById('stat-time');
// Custom seek bar elements
const customSeekContainer = document.getElementById('custom-seek-container');
const seekBar = document.getElementById('seek-bar');
const seekBarProgress = document.getElementById('seek-bar-progress');
const seekBarHandle = document.getElementById('seek-bar-handle');
const seekCurrentTime = document.getElementById('seek-current-time');
const seekTotalTime = document.getElementById('seek-total-time');
const seekingOverlay = document.getElementById('seeking-overlay');
let currentPollInterval = null; let currentPollInterval = null;
let selectedBucket = null; let selectedBucket = null;
let selectedKey = null; let selectedKey = null;
@@ -49,6 +58,12 @@ document.addEventListener('DOMContentLoaded', () => {
let s3Password = ''; let s3Password = '';
let s3AuthHeaders = {}; let s3AuthHeaders = {};
// Seek state
let videoDuration = 0;
let seekOffset = 0;
let isDraggingSeek = false;
let isStreamActive = false;
const formatBytes = (bytes) => { const formatBytes = (bytes) => {
if (!bytes || bytes === 0) return '0 B'; if (!bytes || bytes === 0) return '0 B';
const units = ['B', 'KB', 'MB', 'GB', 'TB']; const units = ['B', 'KB', 'MB', 'GB', 'TB'];
@@ -57,6 +72,14 @@ document.addEventListener('DOMContentLoaded', () => {
return (bytes / Math.pow(k, i)).toFixed(i > 0 ? 2 : 0) + ' ' + units[i]; return (bytes / Math.pow(k, i)).toFixed(i > 0 ? 2 : 0) + ' ' + units[i];
}; };
const formatTime = (seconds) => {
if (!seconds || !isFinite(seconds) || seconds < 0) return '00:00:00';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
};
const sendWsMessage = (message) => { const sendWsMessage = (message) => {
if (ws && ws.readyState === WebSocket.OPEN) { if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(message)); ws.send(JSON.stringify(message));
@@ -73,10 +96,16 @@ document.addEventListener('DOMContentLoaded', () => {
const handleWsMessage = (event) => { const handleWsMessage = (event) => {
try { try {
const message = JSON.parse(event.data); const message = JSON.parse(event.data);
if (message.type === 'progress' && message.key === currentVideoKey) { if (message.key !== currentVideoKey) return;
if (message.type === 'duration' && message.duration) {
videoDuration = message.duration;
if (seekTotalTime) seekTotalTime.textContent = formatTime(videoDuration);
}
if (message.type === 'progress') {
handleProgress(message.progress); handleProgress(message.progress);
} }
if (message.type === 'ready' && message.key === currentVideoKey) { if (message.type === 'ready') {
handleProgress({ status: 'finished', percent: 100, details: 'Ready to play' }); handleProgress({ status: 'finished', percent: 100, details: 'Ready to play' });
playMp4Stream(message.mp4Url); playMp4Stream(message.mp4Url);
} }
@@ -104,7 +133,6 @@ document.addEventListener('DOMContentLoaded', () => {
downloadSizeText.textContent = `${downloaded} / ${total} — 下载完成`; downloadSizeText.textContent = `${downloaded} / ${total} — 下载完成`;
downloadProgressText.textContent = '100%'; downloadProgressText.textContent = '100%';
downloadProgressFill.style.width = '100%'; downloadProgressFill.style.width = '100%';
// Brief pause then transition to transcode phase
setTimeout(() => { setTimeout(() => {
showTranscodePhase(); showTranscodePhase();
}, 600); }, 600);
@@ -115,7 +143,6 @@ document.addEventListener('DOMContentLoaded', () => {
transcodeProgressFill.style.width = `${percent}%`; transcodeProgressFill.style.width = `${percent}%`;
transcodeDetailText.textContent = progress.details || 'FFmpeg 转码中...'; transcodeDetailText.textContent = progress.details || 'FFmpeg 转码中...';
// Show stats
if (progress.fps || progress.bitrate || progress.timemark) { if (progress.fps || progress.bitrate || progress.timemark) {
transcodeStats.classList.remove('hidden'); transcodeStats.classList.remove('hidden');
statFps.textContent = progress.fps ? `${progress.fps} fps` : ''; statFps.textContent = progress.fps ? `${progress.fps} fps` : '';
@@ -147,13 +174,11 @@ document.addEventListener('DOMContentLoaded', () => {
}; };
const resetPhases = () => { const resetPhases = () => {
// Reset download phase
if (downloadPhase) downloadPhase.classList.remove('hidden'); if (downloadPhase) downloadPhase.classList.remove('hidden');
if (downloadSizeText) downloadSizeText.textContent = '准备下载...'; if (downloadSizeText) downloadSizeText.textContent = '准备下载...';
if (downloadProgressText) downloadProgressText.textContent = '0%'; if (downloadProgressText) downloadProgressText.textContent = '0%';
if (downloadProgressFill) downloadProgressFill.style.width = '0%'; if (downloadProgressFill) downloadProgressFill.style.width = '0%';
// Reset transcode phase
if (transcodePhase) transcodePhase.classList.add('hidden'); if (transcodePhase) transcodePhase.classList.add('hidden');
if (transcodeDetailText) transcodeDetailText.textContent = 'FFmpeg 转码中...'; if (transcodeDetailText) transcodeDetailText.textContent = 'FFmpeg 转码中...';
if (transcodeProgressText) transcodeProgressText.textContent = '0%'; if (transcodeProgressText) transcodeProgressText.textContent = '0%';
@@ -166,7 +191,6 @@ document.addEventListener('DOMContentLoaded', () => {
if (statBitrate) statBitrate.textContent = ''; if (statBitrate) statBitrate.textContent = '';
if (statTime) statTime.textContent = ''; if (statTime) statTime.textContent = '';
// Reset buttons
if (stopTranscodeBtn) { if (stopTranscodeBtn) {
stopTranscodeBtn.classList.add('hidden'); stopTranscodeBtn.classList.add('hidden');
stopTranscodeBtn.disabled = false; stopTranscodeBtn.disabled = false;
@@ -174,6 +198,122 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}; };
// --- Custom seek bar ---
const showSeekBar = () => {
if (customSeekContainer && videoDuration > 0) {
customSeekContainer.classList.remove('hidden');
}
};
const hideSeekBar = () => {
if (customSeekContainer) customSeekContainer.classList.add('hidden');
};
const updateSeekBarPosition = (absoluteTime) => {
if (!seekBar || videoDuration <= 0) return;
const ratio = Math.max(0, Math.min(1, absoluteTime / videoDuration));
seekBarProgress.style.width = `${ratio * 100}%`;
seekBarHandle.style.left = `${ratio * 100}%`;
seekCurrentTime.textContent = formatTime(absoluteTime);
};
// Track playback position in the custom seek bar
videoPlayer.addEventListener('timeupdate', () => {
if (isDraggingSeek || !isStreamActive) return;
const absoluteTime = seekOffset + videoPlayer.currentTime;
updateSeekBarPosition(absoluteTime);
});
// Seek bar interaction: click or drag
const getSeekRatio = (e) => {
const rect = seekBar.getBoundingClientRect();
return Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
};
const handleSeekStart = (e) => {
if (!isStreamActive || videoDuration <= 0) return;
e.preventDefault();
isDraggingSeek = true;
seekBar.classList.add('seeking');
const ratio = getSeekRatio(e);
const targetTime = ratio * videoDuration;
updateSeekBarPosition(targetTime);
};
const handleSeekMove = (e) => {
if (!isDraggingSeek) return;
e.preventDefault();
const ratio = getSeekRatio(e);
const targetTime = ratio * videoDuration;
updateSeekBarPosition(targetTime);
};
const handleSeekEnd = (e) => {
if (!isDraggingSeek) return;
isDraggingSeek = false;
seekBar.classList.remove('seeking');
const ratio = getSeekRatio(e);
const targetTime = ratio * videoDuration;
seekToTime(targetTime);
};
if (seekBar) {
seekBar.addEventListener('mousedown', handleSeekStart);
document.addEventListener('mousemove', handleSeekMove);
document.addEventListener('mouseup', handleSeekEnd);
// Touch support
seekBar.addEventListener('touchstart', (e) => {
const touch = e.touches[0];
handleSeekStart({ clientX: touch.clientX, preventDefault: () => e.preventDefault() });
});
document.addEventListener('touchmove', (e) => {
if (!isDraggingSeek) return;
const touch = e.touches[0];
handleSeekMove({ clientX: touch.clientX, preventDefault: () => e.preventDefault() });
});
document.addEventListener('touchend', (e) => {
if (!isDraggingSeek) return;
const touch = e.changedTouches[0];
handleSeekEnd({ clientX: touch.clientX });
});
}
const seekToTime = (targetSeconds) => {
if (!selectedKey || !selectedBucket || videoDuration <= 0) return;
targetSeconds = Math.max(0, Math.min(targetSeconds, videoDuration - 0.5));
seekOffset = targetSeconds;
// Show seeking indicator
if (seekingOverlay) seekingOverlay.classList.remove('hidden');
// Build new stream URL with ss parameter
const codec = codecSelect?.value || 'h264';
const encoder = encoderSelect?.value || 'software';
let streamUrl = `/api/stream?bucket=${encodeURIComponent(selectedBucket)}&key=${encodeURIComponent(selectedKey)}&codec=${encodeURIComponent(codec)}&encoder=${encodeURIComponent(encoder)}&ss=${targetSeconds}`;
if (s3Username) streamUrl += `&username=${encodeURIComponent(s3Username)}`;
if (s3Password) streamUrl += `&password=${encodeURIComponent(s3Password)}`;
// Changing src automatically aborts the previous HTTP request,
// which triggers res.on('close') on the server, killing the old ffmpeg process
videoPlayer.src = streamUrl;
videoPlayer.load();
const onCanPlay = () => {
if (seekingOverlay) seekingOverlay.classList.add('hidden');
videoPlayer.play().catch(() => {});
videoPlayer.removeEventListener('canplay', onCanPlay);
};
videoPlayer.addEventListener('canplay', onCanPlay);
// Timeout fallback: hide seeking overlay after 8s even if canplay doesn't fire
setTimeout(() => {
if (seekingOverlay) seekingOverlay.classList.add('hidden');
}, 8000);
};
// --- End custom seek bar ---
const loadConfig = async () => { const loadConfig = async () => {
if (!topBanner) return; if (!topBanner) return;
try { try {
@@ -353,7 +493,7 @@ document.addEventListener('DOMContentLoaded', () => {
return; return;
} }
// Build a tree structure from S3 keys, preserving original object storage directories // Build a tree structure from S3 keys
const tree = {}; const tree = {};
data.videos.forEach(key => { data.videos.forEach(key => {
const parts = key.split('/'); const parts = key.split('/');
@@ -362,11 +502,9 @@ document.addEventListener('DOMContentLoaded', () => {
if (!current[part]) { if (!current[part]) {
current[part] = {}; current[part] = {};
} }
if (index === parts.length - 1) { if (index === parts.length - 1) {
current[part].__file = key; current[part].__file = key;
} }
current = current[part]; current = current[part];
}); });
}); });
@@ -391,7 +529,6 @@ document.addEventListener('DOMContentLoaded', () => {
return li; return li;
}; };
// Recursive function to render the tree
const renderTree = (node, container) => { const renderTree = (node, container) => {
for (const [name, value] of Object.entries(node)) { for (const [name, value] of Object.entries(node)) {
if (name === '__file') continue; if (name === '__file') continue;
@@ -445,17 +582,20 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}; };
// Handle video selection and trigger transcode // Handle video selection
const selectVideo = (key, listItemNode) => { const selectVideo = (key, listItemNode) => {
// Update UI
document.querySelectorAll('.video-item').forEach(n => n.classList.remove('active')); document.querySelectorAll('.video-item').forEach(n => n.classList.remove('active'));
listItemNode.classList.add('active'); listItemNode.classList.add('active');
// Reset player UI
stopPolling(); stopPolling();
playerOverlay.classList.add('hidden'); playerOverlay.classList.add('hidden');
videoPlayer.classList.add('hidden'); videoPlayer.classList.add('hidden');
videoPlayer.pause(); videoPlayer.pause();
isStreamActive = false;
videoDuration = 0;
seekOffset = 0;
hideSeekBar();
if (transcodeBtn) { if (transcodeBtn) {
transcodeBtn.disabled = false; transcodeBtn.disabled = false;
transcodeBtn.textContent = 'Start Transcode'; transcodeBtn.textContent = 'Start Transcode';
@@ -492,6 +632,10 @@ document.addEventListener('DOMContentLoaded', () => {
} }
stopPolling(); stopPolling();
resetPhases(); resetPhases();
seekOffset = 0;
videoDuration = 0;
isStreamActive = false;
hideSeekBar();
transcodingOverlay.classList.remove('hidden'); transcodingOverlay.classList.remove('hidden');
try { try {
@@ -506,6 +650,8 @@ document.addEventListener('DOMContentLoaded', () => {
videoPlayer.addEventListener('loadedmetadata', () => { videoPlayer.addEventListener('loadedmetadata', () => {
transcodingOverlay.classList.add('hidden'); transcodingOverlay.classList.add('hidden');
videoPlayer.classList.remove('hidden'); videoPlayer.classList.remove('hidden');
isStreamActive = true;
showSeekBar();
if (playBtn) { if (playBtn) {
playBtn.disabled = false; playBtn.disabled = false;
playBtn.textContent = 'Play'; playBtn.textContent = 'Play';
@@ -533,6 +679,8 @@ document.addEventListener('DOMContentLoaded', () => {
if (!res.ok) throw new Error(data.error || 'Failed to stop transcode'); if (!res.ok) throw new Error(data.error || 'Failed to stop transcode');
handleProgress({ status: 'cancelled', percent: 0, details: 'Transcode stopped' }); handleProgress({ status: 'cancelled', percent: 0, details: 'Transcode stopped' });
isStreamActive = false;
hideSeekBar();
if (transcodeBtn) { if (transcodeBtn) {
transcodeBtn.disabled = false; transcodeBtn.disabled = false;
transcodeBtn.textContent = 'Start Transcode'; transcodeBtn.textContent = 'Start Transcode';
@@ -557,7 +705,6 @@ document.addEventListener('DOMContentLoaded', () => {
} }
}; };
// Initialize MP4 Player
const playMp4Stream = (url) => { const playMp4Stream = (url) => {
transcodingOverlay.classList.add('hidden'); transcodingOverlay.classList.add('hidden');
videoPlayer.classList.remove('hidden'); videoPlayer.classList.remove('hidden');
@@ -569,6 +716,8 @@ document.addEventListener('DOMContentLoaded', () => {
videoPlayer.src = url; videoPlayer.src = url;
videoPlayer.load(); videoPlayer.load();
isStreamActive = true;
showSeekBar();
videoPlayer.addEventListener('loadedmetadata', () => { videoPlayer.addEventListener('loadedmetadata', () => {
if (playBtn) { if (playBtn) {
playBtn.disabled = false; playBtn.disabled = false;

View File

@@ -111,6 +111,15 @@ const shouldRetryWithSoftware = (message) => {
return /Cannot load libcuda\.so\.1|Could not open encoder before EOF|Error while opening encoder|Operation not permitted|Invalid argument/i.test(message); return /Cannot load libcuda\.so\.1|Could not open encoder before EOF|Error while opening encoder|Operation not permitted|Invalid argument/i.test(message);
}; };
const probeFile = (filePath) => {
return new Promise((resolve, reject) => {
ffmpeg.ffprobe(filePath, (err, metadata) => {
if (err) reject(err);
else resolve(metadata);
});
});
};
const extractS3Credentials = (req) => { const extractS3Credentials = (req) => {
const query = req.query || {}; const query = req.query || {};
const username = req.headers['x-s3-username'] || req.body?.username || query.username || query.accessKeyId || ''; const username = req.headers['x-s3-username'] || req.body?.username || query.username || query.accessKeyId || '';
@@ -284,6 +293,7 @@ app.get('/api/stream', async (req, res) => {
const key = req.query.key; const key = req.query.key;
const codec = req.query.codec; const codec = req.query.codec;
const encoder = req.query.encoder; const encoder = req.query.encoder;
const startSeconds = parseFloat(req.query.ss) || 0;
if (!bucket) { if (!bucket) {
return res.status(400).json({ error: 'Bucket name is required' }); return res.status(400).json({ error: 'Bucket name is required' });
@@ -378,6 +388,15 @@ app.get('/api/stream', async (req, res) => {
broadcastWs(progressKey, { type: 'progress', key, progress: progressMap[progressKey] }); broadcastWs(progressKey, { type: 'progress', key, progress: progressMap[progressKey] });
} }
// Probe file for duration and broadcast to clients
try {
const metadata = await probeFile(tmpInputPath);
const duration = metadata.format?.duration || 0;
broadcastWs(progressKey, { type: 'duration', key, duration: parseFloat(duration) });
} catch (probeErr) {
console.error('Probe failed:', probeErr);
}
res.setHeader('Content-Type', 'video/mp4'); res.setHeader('Content-Type', 'video/mp4');
res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive'); res.setHeader('Connection', 'keep-alive');
@@ -392,6 +411,10 @@ app.get('/api/stream', async (req, res) => {
.outputOptions(streamingOptions) .outputOptions(streamingOptions)
.format('mp4'); .format('mp4');
if (startSeconds > 0) {
ffmpegCommand.inputOptions(['-ss', startSeconds.toString()]);
}
if (/_vaapi$/.test(encoderName)) { if (/_vaapi$/.test(encoderName)) {
ffmpegCommand ffmpegCommand
.inputOptions(['-vaapi_device', '/dev/dri/renderD128']) .inputOptions(['-vaapi_device', '/dev/dri/renderD128'])