From 28a0b5db379cc2a3627921d902370da2c1d6f606 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Mon, 24 Aug 2026 02:20:57 +0800 Subject: [PATCH] =?UTF-8?q?fix(live-stream):=20MJPEG=E9=99=90=E5=B8=A7?= =?UTF-8?q?=E9=BB=98=E8=AE=A45fps=E3=80=81streamType=3D0=E5=AD=90=E7=A0=81?= =?UTF-8?q?=E6=B5=81=E7=94=9F=E6=95=88=E3=80=81=E4=B8=89=E8=B7=AF=E8=BD=AC?= =?UTF-8?q?=E5=8F=91=E8=83=8C=E5=8E=8B=E4=B8=A2=E5=B8=A7=E9=98=B2=E5=86=85?= =?UTF-8?q?=E5=AD=98=E6=B3=84=E6=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- core/main.js | 83 ++++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 68 insertions(+), 15 deletions(-) diff --git a/core/main.js b/core/main.js index cd43635..2d7c4b6 100644 --- a/core/main.js +++ b/core/main.js @@ -702,6 +702,40 @@ class Main extends EventEmitter { if (this._hikScheduleTimer) return; this._hikScheduleTimer = setInterval(() => this._scheduleHikTasks(), 3000); console.log('[Hikvision] 任务调度器已启动(每3秒),空闲拉取(间隔5分钟)'); + + // 每小时 1 次:录制开启时,重新拉起创建时间 24~48 小时的失败任务 + if (!this._hikHourlyRetryTimer) { + this._hikHourlyRetryTimer = setInterval(() => this._sweepOldFailedTasks(), 3600 * 1000); + console.log('[Hikvision] 失败任务重扫器已启动(每小时1次,仅录制模式,扫描24~48小时前创建的失败任务)'); + } + } + + /** + * 每小时执行:仅录制模式(isRecording)下, + * 将创建时间在 24~48 小时前且状态为失败的任务 retry 重置为 0, + * 由现有调度器(每3秒)自动重新启动 + */ + _sweepOldFailedTasks() { + try { + const hik = this.config && this.config.hikvision; + if (!hik || !hik.isRecording) { + return; // 非录制模式,跳过 + } + + const res = this.db.run(` + UPDATE hik_tasks + SET retry = 0 + WHERE status IN ('failed','timeout','error') + AND created_at >= datetime('now', '-48 hours') + AND created_at < datetime('now', '-24 hours') + `); + + if (res.changes > 0) { + console.log(`[Hikvision] 失败任务重扫: ${res.changes} 个(创建于24~48小时前) retry 已重置为 0,等待调度器自动重启`); + } + } catch (e) { + console.error('[Hikvision] 失败任务重扫异常:', e.message); + } } /** @@ -742,7 +776,9 @@ class Main extends EventEmitter { return; } try { - const info = await hikvisionService.getLiveUrl(body.ip, body.httpPort || 80, body.user, body.pass, body.port || 7681, body.channel || 33, body.streamType || 1); + const stRaw = Number(body.streamType); + const st = Number.isNaN(stRaw) ? 1 : stRaw; + const info = await hikvisionService.getLiveUrl(body.ip, body.httpPort || 80, body.user, body.pass, body.port || 7681, body.channel || 33, st); this._sendJson(res, 200, { success: true, ...info }); } catch (err) { this._sendJson(res, 500, { success: false, message: err.message }); @@ -760,8 +796,13 @@ class Main extends EventEmitter { const user = params.get('user'); const pass = params.get('pass'); const channel = parseInt(params.get('channel')) || 33; - const streamType = parseInt(params.get('streamType')) || 1; // 1=主码流, 2=子码流(海康标准) + // 0=子码流/1=主码流(海康标准),NaN 才回退默认,避免 0 被 || 吞掉拉成高清流 + const rawStreamType = parseInt(params.get('streamType')); + const streamType = Number.isNaN(rawStreamType) ? 1 : rawStreamType; const mode = params.get('mode') || 'auto'; // auto=RTSP优先→失败降级HTTP + // 输出帧率限制:无限制时按源帧率(~25fps)推 MJPEG,浏览器持续解码大图导致内存暴涨,默认 5fps + const rawFps = parseInt(params.get('fps')); + const fps = Number.isNaN(rawFps) ? 5 : Math.min(15, Math.max(1, rawFps)); const channelCode = 100 * channel + streamType; if (!ip || !user || !pass) { @@ -775,7 +816,7 @@ class Main extends EventEmitter { // WebSocket 模式:通过 ISAPI WebSocket 取流(7681 端口) if (mode === 'ws') { if (!ffmpegPath) { this._sendJson(res, 500, { success: false, message: 'ffmpeg 未找到' }); return; } - return this._handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params }); + return this._handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params, fps }); } // HTTP 快照模式:纯 HTTP 轮询 ISAPI 快照(仅需 80 端口) @@ -846,6 +887,7 @@ class Main extends EventEmitter { '-rtsp_transport', 'tcp', '-timeout', '3000000', // RTSP 连接超时 3s(微秒) '-i', rtspUrl, + '-vf', 'fps=' + fps, '-f', 'mjpeg', '-q:v', '5', '-an', @@ -941,9 +983,12 @@ class Main extends EventEmitter { } if (!res.destroyed) { - res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`); - res.write(frame); - res.write('\r\n'); + // 背压保护:客户端消费慢时丢帧,避免 res 缓冲无限堆积导致内存持续增长 + if (res.writableLength < 512 * 1024) { + res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`); + res.write(frame); + res.write('\r\n'); + } } } }); @@ -961,7 +1006,7 @@ class Main extends EventEmitter { * WebSocket 模式实时预览(公网可用,走 7681 端口) * 通过 ISAPI WebSocket 取流 → ffmpeg 转 MJPEG */ - async _handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params }) { + async _handleHikvisionLiveStreamWs(res, { ip, user, pass, channel, streamType, channelCode, ffmpegPath, hikvisionService, params, fps }) { const wsPort = parseInt(params.get('wsPort')) || 7681; const httpPort = parseInt(params.get('httpPort')) || parseInt(params.get('port')) || 80; @@ -1001,6 +1046,7 @@ class Main extends EventEmitter { ffmpeg = spawn(ffmpegPath, [ '-f', 'mpegts', '-i', 'pipe:0', + '-vf', 'fps=' + fps, '-f', 'mjpeg', '-q:v', '5', '-an', @@ -1103,9 +1149,12 @@ class Main extends EventEmitter { } if (!res.destroyed) { - res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`); - res.write(frame); - res.write('\r\n'); + // 背压保护:客户端消费慢时丢帧,避免 res 缓冲无限堆积导致内存持续增长 + if (res.writableLength < 512 * 1024) { + res.write(`--ffmpeg\r\nContent-Type: image/jpeg\r\nContent-Length: ${frame.length}\r\n\r\n`); + res.write(frame); + res.write('\r\n'); + } } } }); @@ -1170,10 +1219,14 @@ class Main extends EventEmitter { if (result.statusCode === 200 && result.body && result.body.length > 500) { const jpeg = result.body; // Buffer (binary=true) if (!res.destroyed) { - res.write(`--snapshot\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`); - res.write(jpeg); - res.write('\r\n'); - frameCount++; + // 背压保护:客户端消费慢(如浏览器后台标签页)时丢帧, + // 避免 res 缓冲无限堆积导致内存持续增长 + if (res.writableLength < 512 * 1024) { + res.write(`--snapshot\r\nContent-Type: image/jpeg\r\nContent-Length: ${jpeg.length}\r\n\r\n`); + res.write(jpeg); + res.write('\r\n'); + frameCount++; + } } } else if (result.statusCode === 401) { // Session 过期,重新登录 @@ -1801,7 +1854,7 @@ class Main extends EventEmitter { const wsPort = Number(options.wsPort) || Number(this.config.wsPort) || 17301; // 托管后端进程由桌面壳监管,当前进程不直接执行本地热重启。 - if (hasProcessArg('--backend-runner') || hasProcessArg('--service-runner')) { + if (hasProcessArg('--backend-runner')) { return { wsPort }; }