printServer/utils/cameraOsd.js

406 lines
17 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 摄像头 OSD(屏幕叠加文字)处理工具
*
* 用法:
* import { setCameraOSD } from '../utils/cameraOsd.js';
* await setCameraOSD('rtsp://admin:pass@192.168.1.100:554/stream', '通道名称');
*/
import { createRequire } from 'module';
import { promisify } from 'util';
import fs from 'fs';
import path from 'path';
import os from 'os';
import http from 'http';
import crypto from 'crypto';
const require = createRequire(import.meta.url);
const { Cam } = require('onvif');
// ─── 文件日志 ───
function _logDir() {
const appData = process.env.ProgramData || path.join(process.env.SystemDrive || 'C:', 'ProgramData');
const dir = path.join(appData, 'printServer');
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
return dir;
}
function _writeLog(level, ...args) {
const msg = args.join(' ');
console.log(`[CameraOSD] ${msg}`);
try {
const ts = new Date().toISOString().replace('T', ' ').substring(0, 19);
fs.appendFileSync(path.join(_logDir(), 'cameraOsd.log'), `[${ts}] [${level}] ${msg}\n`, 'utf-8');
} catch (_) { /* ignore */ }
}
const _log = (...a) => _writeLog('INFO', ...a);
const _err = (...a) => _writeLog('ERR', ...a);
/**
* 解析 RTSP URL 提取 [用户名, 密码, 主机, 通道号]
* 格式: rtsp://username:password@host:port/path
* 通道解析: /stream2 → 2;/Streaming/Channels/201 → 2;默认 1
*/
function extractRTSPInfo(rtspUrl) {
const match = rtspUrl.match(/^rtsp:\/\/([^:]+):(.+)@([^:/]+)(?::(\d+))?(\/\S*)?/);
if (!match) {
throw new Error('RTSP URL 格式无效,期望: rtsp://用户名:密码@主机:端口/路径');
}
let channel = 1;
const pathPart = match[5] || '';
// 海康风格 /Streaming/Channels/201(第1位数字=通道号)
const hc = pathPart.match(/\/Streaming\/Channels\/(\d)\d{2}/i);
if (hc) channel = parseInt(hc[1], 10);
else {
const sm = pathPart.match(/stream(\d+)/i);
if (sm) channel = parseInt(sm[1], 10);
}
return { username: match[1], password: match[2], host: match[3], channel };
}
/**
* 给摄像头设置 OSD 文字
* @param {string} rtspUrl - 摄像头 RTSP 地址
* @param {string} osdText - 要显示的 OSD 文字
* @returns {Promise<{ok: boolean, message: string}>}
*/
export async function setCameraOSD(rtspUrl, osdText, posX = -0.9, posY = 0.8) {
return _osdAction(rtspUrl, osdText, posX, posY, 'replace');
}
/**
* 清空 OSD(删除全部文本 OSD,不创建新的)
*/
export async function clearCameraOSD(rtspUrl) {
return _osdAction(rtspUrl, '', 0, 0, 'clear');
}
/**
* 海康 ISAPI 协议 OSD 设置(当 ONVIF 不可用时回退)
* 接口: GET/PUT /ISAPI/System/Video/inputs/channels/1/overlays/text
* 认证: Basic / Digest 自适应
* @returns {Promise<{ok: boolean, message: string}>}
*/
async function _osdActionIsapi(host, username, password, osdText, posX, posY, mode, channel = 1) {
_log('[ISAPI] 开始设置 OSD host=%s mode=%s channel=%d', host, mode, channel);
try {
const ch = Number.isInteger(channel) && channel >= 1 ? channel : 1;
const baseUri = `/ISAPI/System/Video/inputs/channels/${ch}/overlays/text`;
const mainUri = `/ISAPI/System/Video/inputs/channels/${ch}/overlays`;
let auth = await _isapiAuth(host, username, password, baseUri);
if (!auth) {
return { ok: false, message: 'ISAPI 认证失败(Basic/Digest 均不可用)' };
}
// 401 时自动重新握手并重试一次(nonce 过期/stale 场景)
const authedReq = async (method, uri, body) => {
let resp = await _isapiRequest(host, method, uri, body, auth.headers(method, uri));
if (resp.status === 401) {
const newAuth = await _isapiAuth(host, username, password, baseUri);
if (newAuth) {
auth = newAuth;
resp = await _isapiRequest(host, method, uri, body, auth.headers(method, uri));
}
}
return resp;
};
// 1. 读取现有 OSD
const getResp = await authedReq('GET', baseUri, null);
_log('[ISAPI] GET overlays status=%s body=%s', getResp.status, (getResp.body || '').slice(0, 500));
if (mode === 'clear') {
// 清空:提交空列表
const emptyXml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<TextOverlayList xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0"></TextOverlayList>';
const putResp = await authedReq('PUT', baseUri, emptyXml);
_log('[ISAPI] clear PUT status=%s body=%s', putResp.status, (putResp.body || '').slice(0, 300));
if (putResp.status >= 200 && putResp.status < 300) {
return { ok: true, message: 'OSD 已清空 (ISAPI)', count: 0 };
}
return { ok: false, message: 'ISAPI 清空 OSD 失败: HTTP ' + putResp.status };
}
// 2. 设置文字:设备字段兼容 positionX/positionY/displayText(回读确认过)
// 坐标系:从 overlays 总接口读 normalizedScreenSize(实测 GV413 为 704x576,
// 与主码流 1920x1080 无关)。Y 轴方向:实测该设备 positionY 小=靠底部(bottom-up),
// 因此 ONVIF 归一化 posY(-1=下, +1=上)映射为 py = (1-posY)/2*H
let width = 704, height = 576;
try {
const mainResp = await authedReq('GET', mainUri, null);
const wm = /<normalizedScreenWidth>(\d+)</.exec(mainResp.body || '');
const hm = /<normalizedScreenHeight>(\d+)</.exec(mainResp.body || '');
if (wm && hm) { width = +wm[1]; height = +hm[1]; }
} catch (_) { /* 用默认 704x576 */ }
_log('[ISAPI] OSD 坐标系 %dx%d (bottom-up Y)', width, height);
// 重试链:normalized 坐标系 → 安全坐标(0,0)
const attempts = [
{ w: width, h: height },
{ w: 0, h: 0 }
];
let putResp = { status: 0, body: '' };
let xml = '';
for (const a of attempts) {
let px, py;
if (a.w === 0) { px = 0; py = 0; }
else {
px = Math.max(0, Math.min(a.w - 8, Math.round((posX + 1) / 2 * a.w)));
py = Math.max(0, Math.min(a.h - 8, Math.round((1 - posY) / 2 * a.h)));
}
xml = '<?xml version="1.0" encoding="UTF-8"?>\n' +
'<TextOverlayList xmlns="http://www.hikvision.com/ver20/XMLSchema" version="2.0">\n' +
'<TextOverlay>\n<id>1</id>\n<enabled>true</enabled>\n' +
`<positionX>${px}</positionX>\n<positionY>${py}</positionY>\n` +
`<displayText>${_xmlEscape(osdText)}</displayText>\n` +
'<isPersistentText>true</isPersistentText>\n' +
'</TextOverlay>\n</TextOverlayList>';
putResp = await authedReq('PUT', baseUri, xml);
_log('[ISAPI] set PUT(%d,%d) status=%s body=%s', px, py, putResp.status, (putResp.body || '').slice(0, 200));
if (putResp.status >= 200 && putResp.status < 300) break;
}
if (!(putResp.status >= 200 && putResp.status < 300)) {
return { ok: false, message: 'ISAPI 设置 OSD 失败: HTTP ' + putResp.status + ' ' + (putResp.body || '').slice(0, 100) };
}
// 3. 回读验证
const verifyResp = await authedReq('GET', baseUri, null);
const body = verifyResp.body || '';
_log('[ISAPI] verify GET status=%s body=%s', verifyResp.status, body.slice(0, 500));
if (mode === 'clear') {
return { ok: true, message: 'OSD 已清空 (ISAPI)', count: 0 };
}
const found = body.includes(_xmlEscape(osdText)) || body.includes(osdText);
if (found) {
_log('[ISAPI] OK OSD 写入成功:', osdText);
return { ok: true, message: 'OSD 设置成功 (ISAPI): ' + osdText, count: 1 };
}
_err('[ISAPI] FAIL 回读验证失败: 期望="' + osdText + '" body=' + body.slice(0, 300));
return { ok: false, message: 'ISAPI OSD 写入验证失败' };
} catch (e) {
_err('[ISAPI] 异常:', e.message);
return { ok: false, message: 'ISAPI OSD 操作异常: ' + e.message };
}
}
function _xmlEscape(s) {
return String(s ?? '')
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}
/**
* ISAPI 认证握手:先无认证请求,401 后按 WWW-Authenticate 选择 Digest 或 Basic
* @returns {Promise<{headers:(method,uri)=>Object}|null>}
*/
async function _isapiAuth(host, username, password, probeUri) {
try {
const probe = await _isapiRequest(host, 'GET', probeUri, null, {});
const wwwAuth = (probe.headers['www-authenticate'] || '') + ' ' + ((probe.body && probe.status === 401) ? '' : '');
_log('[ISAPI] 探测 status=%s WWW-Authenticate=%s', probe.status, (probe.headers['www-authenticate'] || '无').slice(0, 120));
// 有些设备直接返回 200(无认证)
if (probe.status !== 401 && probe.status !== 0) {
return { headers: () => ({}) };
}
const wa = probe.headers['www-authenticate'] || '';
if (/digest/i.test(wa)) {
const realm = /realm="([^"]*)"/i.exec(wa)?.[1] || '';
const nonce = /nonce="([^"]*)"/i.exec(wa)?.[1] || '';
const qop = /qop="([^"]*)"/i.exec(wa)?.[1] || 'auth';
const opaque = /opaque="([^"]*)"/i.exec(wa)?.[1] || '';
if (!realm || !nonce) return null;
return {
headers: (method, uri) => {
const cnonce = crypto.randomBytes(8).toString('hex');
const nc = '00000001';
const ha1 = _md5(`${username}:${realm}:${password}`);
const ha2 = _md5(`${method}:${uri}`);
const response = _md5(`${ha1}:${nonce}:${nc}:${cnonce}:${qop}:${ha2}`);
let h = `Digest username="${username}", realm="${realm}", nonce="${nonce}", uri="${uri}", response="${response}", qop=${qop}, nc=${nc}, cnonce="${cnonce}"`;
if (opaque) h += `, opaque="${opaque}"`;
return { Authorization: h };
}
};
}
// Basic
const basic = 'Basic ' + Buffer.from(`${username}:${password}`).toString('base64');
return { headers: () => ({ Authorization: basic }) };
} catch (e) {
_err('[ISAPI] 认证探测异常:', e.message);
return null;
}
}
function _md5(s) {
return crypto.createHash('md5').update(s, 'utf8').digest('hex');
}
/** 嗅探设备是否支持海康 ISAPI 协议(快速 GET /ISAPI/System/deviceInfo) */
async function _isapiProbe(host) {
try {
const resp = await _isapiRequest(host, 'GET', '/ISAPI/System/deviceInfo', null, {}, 2500);
// 200 = 无需认证;401 = 接口存在需认证;404/其他 = 不支持
if (resp.status === 200 || resp.status === 401) {
_log('[ISAPI] 嗅探成功 host=%s status=%d', host, resp.status);
return true;
}
_log('[ISAPI] 嗅探不支持 host=%s status=%d', host, resp.status);
return false;
} catch (e) {
_log('[ISAPI] 嗅探失败 host=%s: %s', host, e.message);
return false;
}
}
/** 原生 HTTP 请求(带 Content-Length,避免 chunked 被设备拒绝) */
function _isapiRequest(host, method, uri, body, headers, timeoutMs = 8000) {
return new Promise((resolve, reject) => {
const h = { ...headers };
if (body != null) {
h['Content-Type'] = 'application/xml';
h['Content-Length'] = Buffer.byteLength(body);
}
const req = http.request({ host, port: 80, path: uri, method, headers: h, timeout: timeoutMs }, (res) => {
let data = '';
res.on('data', (c) => (data += c));
res.on('end', () => resolve({ status: res.statusCode, headers: res.headers, body: data }));
});
req.on('timeout', () => { req.destroy(); reject(new Error('ISAPI 请求超时')); });
req.on('error', reject);
if (body != null) req.write(body);
req.end();
});
}
/**
* OSD 核心操作
* @param {string} mode - 'replace'=删旧建新, 'append'=叠加追加, 'clear'=只删不建
*/
async function _osdAction(rtspUrl, osdText, posX, posY, mode) {
_log('收到 OSD 请求, rtspUrl:', rtspUrl.replace(/:[^:@]+@/, ':****@'), 'text:', osdText, 'pos:', posX, posY, 'mode:', mode);
const info = extractRTSPInfo(rtspUrl);
_log('连接摄像头:', info.host, '用户:', info.username, '通道:', info.channel);
// 0. 先嗅探 ISAPI(海康系设备):可用则直接走 ISAPI,无需试 ONVIF
if (await _isapiProbe(info.host)) {
_log('探测到 ISAPI 协议(海康系设备),直接使用 ISAPI');
return _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel);
}
// 1. ONVIF 尝试:端口依次 80(标准)→ 2020(MIPC 等非标),全失败回退 ISAPI
return new Promise((resolve) => {
const onvifPorts = [80, 2020];
const tryPort = (idx) => {
_log('尝试 ONVIF 端口:', onvifPorts[idx]);
new Cam({
hostname: info.host,
username: info.username,
password: info.password,
port: onvifPorts[idx],
timeout: 6000,
preserveAddress: true
}, async function (err) {
if (err) {
_err('ONVIF 端口 %d 失败:', onvifPorts[idx], err.message);
if (idx + 1 < onvifPorts.length) { tryPort(idx + 1); return; }
_log('ONVIF 全部失败 → 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
return;
}
// ONVIF 连接成功,执行原逻辑
const cam = this;
(async () => {
try {
// 转为 Promise 风格
const getOSDs = promisify(cam.getOSDs).bind(cam);
const createOSD = promisify(cam.createOSD).bind(cam);
const setOSD = promisify(cam.setOSD).bind(cam);
const token = cam.defaultProfile.videoSourceConfiguration.$.token;
_log('videoSourceConfigurationToken:', token);
// 检查是否已有文本 OSD(过滤掉时间 OSD 等非 Plain 类型)
let osdList = [];
try {
const resp = await getOSDs(token);
osdList = resp?.getOSDsResponse?.OSDs || [];
_log('已有 OSD 数量:', osdList.length, JSON.stringify(osdList));
} catch (e) {
_err('获取已有 OSD 失败:', e.message);
}
// 只取 Plain 类型的文本 OSD token
const textOSD = osdList.find(o => o.textString?.type === 'Plain');
const osdToken = textOSD?.$?.token;
const createOptions = {
videoSourceConfigurationToken: token,
plaintext: osdText,
position: { x: posX, y: posY }
};
if (mode === 'clear') {
// clear 模式:只删不建
_log('clear 模式,删除所有文本 OSD');
const deleteOSD = promisify(cam.deleteOSD).bind(cam);
for (const o of osdList.filter(x => x.textString?.type === 'Plain')) {
try { await deleteOSD(o.$.token); _log('已删除:', o.$.token); } catch (e) { _err('删除失败:', e.message); }
}
_log('clear 完成');
resolve({ ok: true, message: 'OSD 已清空', count: 0 });
return;
}
// replace 模式:删除已有文本 OSD,再创建新的
if (osdToken) {
_log('replace 模式,删除已有文本 OSD');
const deleteOSD = promisify(cam.deleteOSD).bind(cam);
for (const o of osdList.filter(x => x.textString?.type === 'Plain')) {
try { await deleteOSD(o.$.token); _log('已删除:', o.$.token); } catch (e) { _err('删除失败:', e.message); }
}
}
// 创建新 OSD,最多重试 3 次
_log('创建新 OSD, text:', osdText, 'pos:', posX, posY);
for (let i = 0; i < 3; i++) {
try {
await createOSD(createOptions);
_log('第', i + 1, '次尝试成功');
break;
} catch (e) {
_err('第', i + 1, '次尝试失败:', e.message);
if (i === 2) throw e;
}
}
// 验证写入
const verifyResp = await getOSDs(token);
const verifyList = verifyResp?.getOSDsResponse?.OSDs || [];
const textOSDs = verifyList.filter(o => o.textString?.type === 'Plain');
const verifyTexts = textOSDs.map(o => o.textString?.plainText || '').join(',');
_log('验证读取 OSD: 共', textOSDs.length, '个文本, texts=[', verifyTexts, ']');
const found = textOSDs.some(o => {
const txt = String(o?.textString?.plainText ?? '');
return txt === String(osdText) || txt.includes(String(osdText));
});
if (found) {
_log('OK OSD 写入成功:', osdText);
resolve({ ok: true, message: 'OSD 设置成功: ' + osdText, count: textOSDs.length });
} else {
_err('ONVIF FAIL OSD 写入失败: 期望="' + osdText + '" 实际=[' + verifyTexts + '] → 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
}
} catch (e) {
_err('ONVIF 操作失败:', e.message, '→ 回退海康 ISAPI 协议');
resolve(await _osdActionIsapi(info.host, info.username, info.password, osdText, posX, posY, mode, info.channel));
}
})();
});
};
tryPort(0);
});
}