diff --git a/services/hikvision.js b/services/hikvision.js
index 90d682b..9a1a225 100644
--- a/services/hikvision.js
+++ b/services/hikvision.js
@@ -4,7 +4,7 @@ import http from 'http';
import https from 'https';
import fs from 'fs';
import path from 'path';
-import { exec } from 'child_process';
+import { exec, spawn } from 'child_process';
import { createRequire } from 'module';
import { promisify } from 'util';
import BaseService from '../core/BaseService.js';
@@ -474,11 +474,29 @@ class HikvisionService extends BaseService {
const loginResult = await this.login(ip, httpPort, user, pass);
const { token, cookieJar, sessionTag, httpBase } = loginResult;
- // [5] WS 下载
+ // [5] WS 下载(7681 连接失败时自动降级 RTSP 回放下载,兼容无 ISAPI WebSocket 的老固件)
task.status = 'downloading';
- const result = await this._wsDownload({ ip, port, channel, start, end, speed, output, token, task });
+ let result;
+ try {
+ result = await this._wsDownload({ ip, port, channel, start, end, speed, output, token, task });
+ } catch (e) {
+ const msg = (e && (e.message || e.code)) || '';
+ const connErr = /ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|ECONNRESET/.test(msg);
+ if (!connErr) throw e;
+ console.log('[Hikvision] 7681 连接失败(%s),降级 HTTP 回放下载 %s ch=%d', msg.split('\n')[0], ip, channel);
+ // 原下载超时按 4x 速计算,HTTP 回放下载耗时不定,需清除改用降级自身超时
+ if (task._downloadTimer) { clearTimeout(task._downloadTimer); task._downloadTimer = null; }
+ result = await this._httpPlaybackDownload({ ip, httpPort, user, pass, channel, start: origStart, end: origEnd, speed, output, task, session: loginResult });
+ }
- // [6] 转码
+ // [6] 转码(HTTP 回放降级已直接输出 mp4,跳过转码)
+ if (result.httpFallback) {
+ const size = fs.existsSync(result.mp4Path) ? fs.statSync(result.mp4Path).size : 0;
+ const finalResult = { success: true, output: result.mp4Path, size, duration: result.elapsed, speed, httpFallback: true };
+ task._onDone?.(finalResult);
+ console.log(`[Hikvision] HTTP回放完成: ${finalResult.output} ${(size / 1048576).toFixed(1)}MB`);
+ return;
+ }
if (result.total === 0) {
task._onDone?.({ success: false, output, size: 0 });
return;
@@ -533,6 +551,126 @@ class HikvisionService extends BaseService {
// session 由缓存 TTL(20分钟)自然过期
}
+ /**
+ * HTTP 回放下载(兜底):NVR 没有 ISAPI WebSocket(7681) 时使用(老固件,如 HNVR5116 V4.75)
+ * 链路:ISAPI 搜索录像 → GET /ISAPI/ContentMgmt/download(token+playbackURI 原样)→
+ * ffmpeg 以 HTTP 流为输入,-ss 靠设备 Range 支持定位到工单窗口,-t 切片落盘 mp4
+ * @returns {Promise<{total, chunks, elapsed, httpFallback:true, mp4Path}>}
+ * 无录像时抛错「录像机无此时间视频」(与 WS 路径语义一致)
+ */
+ _httpPlaybackDownload({ ip, httpPort, user, pass, channel, start, end, speed, output, task, session }) {
+ const trackId = channel * 100 + 1; // 主码流(与 WS playback 通道编号一致)
+ const parseDate = (iso) => { const d = new Date(iso); return isNaN(d) ? null : d; };
+ const sD = parseDate(start), eD = parseDate(end);
+ const isoUtc = (d) => d.toISOString().replace(/\.\d{3}Z$/, 'Z');
+ if (!sD || !eD) return Promise.reject(new Error('HTTP回放: 时间格式无效 ' + start + ' ~ ' + end));
+ // 搜索窗口前后放宽 30 秒(防边界缺失;搜索 body 时间用 ISO 带横线 UTC)
+ const sFrom = isoUtc(new Date(sD.getTime() - 30000)), sTo = isoUtc(new Date(eD.getTime() + 30000));
+
+ const doSearch = async () => {
+ const searchId = `{${crypto.randomUUID().toUpperCase()}}`;
+ const searchXml = `\n` +
+ `${searchId}` +
+ `${trackId}` +
+ `${sFrom}${sTo}` +
+ `500` +
+ `//recordType.meta.hikvision.com/timing` +
+ ``;
+ const headers = { 'Content-Type': 'application/xml' };
+ if (session.sessionTag) headers['SessionTag'] = session.sessionTag;
+ return this._req('POST', `http://${ip}:${httpPort}/ISAPI/ContentMgmt/search`, searchXml, headers, session.cookieJar);
+ };
+
+ // 紧凑时间解码(playbackURI 内的时间格式: YYYYMMDDTHHMMSSZ)
+ const decodeCompact = (s) => {
+ const m = String(s || '').match(/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/);
+ return m ? new Date(Date.UTC(+m[1], +m[2] - 1, +m[3], +m[4], +m[5], +m[6])) : null;
+ };
+
+ return doSearch().then(async (searchRes) => {
+ if (searchRes.statusCode !== 200) throw new Error(`HTTP回放: 搜索录像失败 HTTP ${searchRes.statusCode}`);
+ const uriList = [...String(searchRes.body || '').matchAll(/([\s\S]*?)<\/playbackURI>/g)]
+ .map((m) => m[1].replace(/&/g, '&').trim())
+ .filter(Boolean);
+ if (uriList.length === 0) {
+ console.log('[Hikvision] HTTP回放: 录像机无此时间视频 ch=%d %s ~ %s', channel, start, end);
+ throw new Error('录像机无此时间视频');
+ }
+ // 选与工单窗口相交的段:优先完全覆盖,否则取相交长度最长者
+ let best = null;
+ for (const u of uriList) {
+ const segS = decodeCompact(u.match(/starttime=([0-9A-Za-z]+)/i)?.[1]);
+ const segE = decodeCompact(u.match(/endtime=([0-9A-Za-z]+)/i)?.[1]);
+ if (!segS || !segE) continue;
+ const ovS = segS > sD ? segS : sD;
+ const ovE = segE < eD ? segE : eD;
+ const overlap = ovE - ovS;
+ if (overlap <= 0) continue;
+ if (!best || overlap > best.overlap) best = { uri: u, segS, segE, ovS, ovE, overlap };
+ }
+ if (!best) {
+ console.log('[Hikvision] HTTP回放: 录像机无此时间视频 ch=%d %s ~ %s', channel, start, end);
+ throw new Error('录像机无此时间视频');
+ }
+ // 输入侧偏移 = 工单窗口起点相对段起点的秒数(下载接口返回整段流,ffmpeg -ss 走 Range 定位)
+ const offsetSec = Math.floor((best.ovS - best.segS) / 1000);
+ const durSec = Math.ceil((best.ovE - best.ovS) / 1000);
+ // token 与 playbackURI 必须原样传递(URL 编码反而 400/401)
+ const downloadUrl = `http://${ip}:${httpPort}/ISAPI/ContentMgmt/download?token=${session.token}&playbackURI=${best.uri}`;
+
+ return new Promise((resolve, reject) => {
+ const ffmpegPath = this._findFfmpeg();
+ if (!ffmpegPath) { reject(new Error('HTTP回放: 未找到 ffmpeg')); return; }
+ const outFile = output.endsWith('.mp4') ? output : output.replace(/\.ps$/i, '') + '.mp4';
+ const outDir = path.dirname(outFile);
+ if (outDir && outDir !== '.') fs.mkdirSync(outDir, { recursive: true });
+ const t0 = Date.now();
+ const timeoutMs = Math.max(60000, durSec * 1000 + 120000);
+ const cookieStr = Object.entries(session.cookieJar || {}).map(([k, v]) => `${k}=${v}`).join('; ');
+ console.log('[Hikvision] HTTP回放: ffmpeg 下载 ch=%d 段偏移 %ds 时长 %ds', channel, offsetSec, durSec);
+
+ const args = ['-hide_banner', '-loglevel', 'warning'];
+ if (cookieStr) args.push('-headers', `Cookie: ${cookieStr}\r\n`);
+ args.push('-ss', String(offsetSec), '-t', String(durSec), '-i', downloadUrl,
+ '-c:v', 'copy', '-an', '-y', outFile);
+ const child = spawn(ffmpegPath, args, { stdio: ['ignore', 'ignore', 'pipe'] });
+ let stderrTail = '';
+ child.stderr.on('data', (d) => { stderrTail = (stderrTail + d.toString()).slice(-800); });
+ const timer = setTimeout(() => {
+ try { child.kill('SIGKILL'); } catch { /* */ }
+ reject(new Error(`HTTP回放: 下载超时(${Math.round(timeoutMs / 1000)}s)`));
+ }, timeoutMs);
+ if (task) {
+ task._abortDownload = () => { try { child.kill('SIGKILL'); } catch { /* */ } };
+ }
+ // 下载期间定期更新进度(按已写入文件大小)
+ const progTimer = setInterval(() => {
+ if (!task) return;
+ try {
+ const sz = fs.existsSync(outFile) ? fs.statSync(outFile).size : 0;
+ task.progress.totalBytes = sz;
+ task.progress.totalMB = Math.round(sz / 1048576 * 10) / 10;
+ } catch { /* */ }
+ }, 3000);
+ const stopProg = () => clearInterval(progTimer);
+ child.on('error', (err) => { clearTimeout(timer); stopProg(); reject(new Error('HTTP回放: ffmpeg 启动失败 ' + err.message)); });
+ child.on('close', (code) => {
+ clearTimeout(timer);
+ stopProg();
+ if (task && task._aborted) { reject(new Error('任务已中止')); return; }
+ const size = fs.existsSync(outFile) ? fs.statSync(outFile).size : 0;
+ if (code === 0 && size > 0) {
+ const elapsed = (Date.now() - t0) / 1000;
+ console.log('[Hikvision] HTTP回放: 下载完成 %s (%.1fMB, %.1fs)', outFile, size / 1048576, elapsed);
+ resolve({ total: size, chunks: 0, elapsed, httpFallback: true, mp4Path: outFile });
+ } else {
+ reject(new Error(`HTTP回放: 下载失败(exit=${code}) ${stderrTail.slice(-300)}`));
+ }
+ });
+ });
+ });
+ }
+
_wsDownload({ ip, port, channel, start, end, speed, output, token, task }) {
return new Promise((resolve, reject) => {
// 和 Python hik_download.py 完全一致的流程