From 52c8466ddda5e8e542da719a49108d9c9a99d7db Mon Sep 17 00:00:00 2001 From: CN-JS-HuiBai Date: Thu, 2 Apr 2026 22:54:46 +0800 Subject: [PATCH] =?UTF-8?q?FIXA-=E6=87=92=E5=BE=97=E5=86=99=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- public/css/style.css | 16 +++++++--- public/js/main.js | 25 ++++++++++----- server.js | 76 ++++++++++++++++++++++++++++++++++---------- 3 files changed, 89 insertions(+), 28 deletions(-) diff --git a/public/css/style.css b/public/css/style.css index a36acab..cadddd2 100644 --- a/public/css/style.css +++ b/public/css/style.css @@ -579,6 +579,10 @@ header p { transition: opacity 0.3s ease; } +.player-section { + position: relative; +} + .player-overlay h3 { margin-bottom: 0.5rem; font-weight: 600; @@ -590,7 +594,7 @@ header p { } .now-playing { - margin-top: 1.5rem; + margin-top: 2.5rem; padding-top: 1.5rem; border-top: 1px solid var(--panel-border); } @@ -609,11 +613,14 @@ header p { } .custom-controls { - margin-top: 0.9rem; + position: relative; + z-index: 12; + margin: -5.75rem 1rem 0; padding: 0.9rem 1rem; border-radius: 14px; border: 1px solid var(--panel-border); - background: rgba(15, 23, 42, 0.72); + background: linear-gradient(180deg, rgba(15, 23, 42, 0.18), rgba(15, 23, 42, 0.86)); + backdrop-filter: blur(10px); display: flex; align-items: center; justify-content: space-between; @@ -627,7 +634,7 @@ header p { .custom-controls.controls-faded, .custom-seek-container.controls-faded { opacity: 0; - transform: translateY(8px); + transform: translateY(12px); pointer-events: none; } @@ -989,6 +996,7 @@ header p { .custom-controls { align-items: center; + margin: -6.25rem 0.75rem 0; } .controls-left, diff --git a/public/js/main.js b/public/js/main.js index 4cd26e6..8c0aeb2 100644 --- a/public/js/main.js +++ b/public/js/main.js @@ -110,6 +110,21 @@ document.addEventListener('DOMContentLoaded', () => { } }; + const createStreamSessionId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + + const buildStreamUrl = (targetSeconds = null) => { + const codec = codecSelect?.value || 'h264'; + const encoder = encoderSelect?.value || 'software'; + const streamSessionId = createStreamSessionId(); + let streamUrl = `/api/stream?bucket=${encodeURIComponent(selectedBucket)}&key=${encodeURIComponent(selectedKey)}&codec=${encodeURIComponent(codec)}&encoder=${encodeURIComponent(encoder)}&streamSessionId=${encodeURIComponent(streamSessionId)}`; + if (typeof targetSeconds === 'number' && Number.isFinite(targetSeconds) && targetSeconds > 0) { + streamUrl += `&ss=${targetSeconds}`; + } + if (s3Username) streamUrl += `&username=${encodeURIComponent(s3Username)}`; + if (s3Password) streamUrl += `&password=${encodeURIComponent(s3Password)}`; + return streamUrl; + }; + const updatePlayControls = () => { if (controlPlayToggle) { controlPlayToggle.textContent = videoPlayer.paused ? 'Play' : 'Pause'; @@ -510,11 +525,7 @@ document.addEventListener('DOMContentLoaded', () => { } // 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)}`; + const streamUrl = buildStreamUrl(targetSeconds); // Changing src automatically aborts the previous HTTP request, // which triggers res.on('close') on the server, killing the old ffmpeg process @@ -876,9 +887,7 @@ document.addEventListener('DOMContentLoaded', () => { const codec = codecSelect?.value || 'h264'; const encoder = encoderSelect?.value || 'software'; if (!selectedBucket) throw new Error('No bucket selected'); - let streamUrl = `/api/stream?bucket=${encodeURIComponent(selectedBucket)}&key=${encodeURIComponent(selectedKey)}&codec=${encodeURIComponent(codec)}&encoder=${encodeURIComponent(encoder)}`; - if (s3Username) streamUrl += `&username=${encodeURIComponent(s3Username)}`; - if (s3Password) streamUrl += `&password=${encodeURIComponent(s3Password)}`; + const streamUrl = buildStreamUrl(); videoPlayer.src = streamUrl; videoPlayer.load(); videoPlayer.addEventListener('loadedmetadata', () => { diff --git a/server.js b/server.js index 74eb636..f5a5417 100644 --- a/server.js +++ b/server.js @@ -64,6 +64,8 @@ const wsSubscriptions = new Map(); const getProgressKey = (key) => key.split('/').map(segment => segment.replace(/[^a-zA-Z0-9_\-]/g, '_')).join('/'); +const createStreamSessionId = () => `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`; + const addWsClient = (progressKey, ws) => { if (!wsSubscriptions.has(progressKey)) { wsSubscriptions.set(progressKey, new Set()); @@ -187,26 +189,28 @@ const parseTimemarkToSeconds = (timemark) => { }; const stopActiveTranscode = (progressKey) => { - const activeCommand = transcodeProcesses.get(progressKey); - if (!activeCommand) { - return; + const activeProcess = transcodeProcesses.get(progressKey); + if (!activeProcess?.command) { + return false; } try { - if (typeof activeCommand.removeAllListeners === 'function') { - activeCommand.removeAllListeners('progress'); - activeCommand.removeAllListeners('stderr'); - activeCommand.removeAllListeners('end'); - activeCommand.removeAllListeners('error'); + if (typeof activeProcess.command.removeAllListeners === 'function') { + activeProcess.command.removeAllListeners('progress'); + activeProcess.command.removeAllListeners('stderr'); + activeProcess.command.removeAllListeners('end'); + activeProcess.command.removeAllListeners('error'); } - if (typeof activeCommand.kill === 'function') { - activeCommand.kill('SIGKILL'); + if (typeof activeProcess.command.kill === 'function') { + activeProcess.command.kill('SIGKILL'); } } catch (killError) { console.warn(`Failed to kill transcode process for ${progressKey}:`, killError); } finally { transcodeProcesses.delete(progressKey); } + + return true; }; const extractS3Credentials = (req) => { @@ -376,6 +380,9 @@ app.get('/api/stream', async (req, res) => { const codec = req.query.codec; const encoder = req.query.encoder; const startSeconds = parseFloat(req.query.ss) || 0; + const streamSessionId = typeof req.query.streamSessionId === 'string' && req.query.streamSessionId.trim() + ? req.query.streamSessionId.trim() + : createStreamSessionId(); if (!bucket) { return res.status(400).json({ error: 'Bucket name is required' }); @@ -405,7 +412,19 @@ app.get('/api/stream', async (req, res) => { const s3Client = createS3Client(auth); try { - stopActiveTranscode(progressKey); + const replacedExistingStream = stopActiveTranscode(progressKey); + if (replacedExistingStream && startSeconds > 0) { + progressMap[progressKey] = { + ...(progressMap[progressKey] || {}), + status: 'transcoding', + percent: Math.min(Math.max(Math.round((startSeconds / Math.max(progressMap[progressKey]?.duration || startSeconds || 1, 1)) * 100), 0), 100), + startSeconds, + streamSessionId, + details: `Restarting transcode from ${startSeconds.toFixed(2)}s`, + mp4Url: null + }; + broadcastWs(progressKey, { type: 'progress', key, progress: progressMap[progressKey] }); + } let totalBytes = 0; let downloadedBytes = 0; @@ -421,6 +440,7 @@ app.get('/api/stream', async (req, res) => { percent: 0, downloadedBytes: 0, totalBytes, + streamSessionId, details: 'Downloading full source before streaming...', mp4Url: null }; @@ -436,6 +456,7 @@ app.get('/api/stream', async (req, res) => { percent, downloadedBytes, totalBytes, + streamSessionId, details: totalBytes ? `Downloading source ${percent}%` : 'Downloading source...', mp4Url: null }; @@ -453,6 +474,7 @@ app.get('/api/stream', async (req, res) => { percent: 100, downloadedBytes, totalBytes, + streamSessionId, details: 'Source download complete, starting real-time transcode...', mp4Url: null }; @@ -466,6 +488,7 @@ app.get('/api/stream', async (req, res) => { percent: 100, downloadedBytes, totalBytes, + streamSessionId, details: 'Source already downloaded locally, starting real-time transcode...', mp4Url: null }; @@ -480,7 +503,8 @@ app.get('/api/stream', async (req, res) => { const duration = metadata.format?.duration || 0; progressMap[progressKey] = { ...(progressMap[progressKey] || {}), - duration: parseFloat(duration) || 0 + duration: parseFloat(duration) || 0, + streamSessionId }; broadcastWs(progressKey, { type: 'duration', key, duration: parseFloat(duration) }); } catch (probeErr) { @@ -495,14 +519,19 @@ app.get('/api/stream', async (req, res) => { const startStream = (encoderName) => { const streamingOptions = createFfmpegOptions(encoderName).concat(getSeekFriendlyOutputOptions(encoderName, sourceMetadata)); - ffmpegCommand = ffmpeg(tmpInputPath) + ffmpegCommand = ffmpeg() + .input(tmpInputPath) .videoCodec(encoderName) .audioCodec('aac') .outputOptions(streamingOptions) .format('mp4'); if (startSeconds > 0) { - ffmpegCommand.inputOptions(['-ss', startSeconds.toString()]); + if (typeof ffmpegCommand.seekInput === 'function') { + ffmpegCommand.seekInput(startSeconds); + } else { + ffmpegCommand.inputOptions(['-ss', startSeconds.toString()]); + } } if (/_vaapi$/.test(encoderName)) { @@ -511,10 +540,13 @@ app.get('/api/stream', async (req, res) => { .videoFilters('format=nv12,hwupload'); } - transcodeProcesses.set(progressKey, ffmpegCommand); + transcodeProcesses.set(progressKey, { command: ffmpegCommand, streamSessionId }); ffmpegCommand .on('progress', (progress) => { + if (transcodeProcesses.get(progressKey)?.streamSessionId !== streamSessionId) { + return; + } const effectiveDuration = Math.max(0, (progressMap[progressKey]?.duration || 0) - startSeconds); const timemarkSeconds = parseTimemarkToSeconds(progress.timemark || '0'); const absoluteSeconds = startSeconds + (isFinite(timemarkSeconds) ? timemarkSeconds : 0); @@ -531,6 +563,7 @@ app.get('/api/stream', async (req, res) => { absoluteSeconds, duration: progressMap[progressKey]?.duration || null, startSeconds, + streamSessionId, details: `Streaming transcode ${percent}%`, mp4Url: null }; @@ -538,27 +571,38 @@ app.get('/api/stream', async (req, res) => { broadcastWs(progressKey, { type: 'progress', key, progress: progressState }); }) .on('stderr', (stderrLine) => { + if (transcodeProcesses.get(progressKey)?.streamSessionId !== streamSessionId) { + return; + } console.log(`ffmpeg stderr: ${stderrLine}`); }) .on('end', () => { + if (transcodeProcesses.get(progressKey)?.streamSessionId !== streamSessionId) { + return; + } transcodeProcesses.delete(progressKey); progressMap[progressKey] = { status: 'finished', percent: 100, duration: progressMap[progressKey]?.duration || null, startSeconds, + streamSessionId, details: 'Streaming transcode complete', mp4Url: null }; broadcastWs(progressKey, { type: 'progress', key, progress: progressMap[progressKey] }); }) .on('error', (err) => { + if (transcodeProcesses.get(progressKey)?.streamSessionId !== streamSessionId) { + return; + } transcodeProcesses.delete(progressKey); const failedState = { status: 'failed', percent: progressMap[progressKey]?.percent || 0, duration: progressMap[progressKey]?.duration || null, startSeconds, + streamSessionId, details: err.message || 'Streaming transcode failed', mp4Url: null }; @@ -580,7 +624,7 @@ app.get('/api/stream', async (req, res) => { ffmpegCommand.kill('SIGKILL'); } catch (_) {} } - if (transcodeProcesses.get(progressKey) === ffmpegCommand) { + if (transcodeProcesses.get(progressKey)?.streamSessionId === streamSessionId) { transcodeProcesses.delete(progressKey); } });