v4.2.2: 홈CCTV 앱에 독립 IP카메라 지원 추가(ONVIF PTZ) + 채널 이름/화질 고정

- 메인 NVR과 별개인 독립 IP카메라(예: Mercusys/Tapo) 등록 지원
  (nvr.extraCameras, id 1000+) — RTSP/화면 표시는 메인 NVR과 동일 그리드에 통합
- ONVIF(WS-Security) 기반 PTZ 제어 — 라이브 모달의 기존 PTZ 버튼이 독립 카메라에서도
  그대로 작동(백엔드에서 채널 id로 NVR/독립 카메라 라우팅)
- 카메라 자체에 상하반전 옵션이 없는 모델을 위한 ffmpeg 소프트웨어 180도 회전,
  반전 시 PTZ 팬/틸트 방향도 화면 기준으로 자동 보정
- 채널 이름/위치 라벨 커스텀 표시, 채널별 화질(메인/서브) 강제 고정
- 6분할 라이브로 확장(기존 5분할 하드코딩 제거)

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
kimandClaude Sonnet 5 committed 2026-07-23 11:19:43 +09:00
1 parent 0bab3f7924
commit 174da1e5bd
6 files changed
+492 -70

No files matched your search

+19 -1
View File
@@ -348,6 +348,24 @@
"rtspPort": 80,
"rtspPathTemplate": "/ch{channel}_{stream}.264",
"username": "admin",
"password": "vault:nvr.password"
"password": "vault:nvr.password",
"channelLabels": {},
"channelStream": {
"3": 1
},
"extraCameras": [
{
"id": 1000,
"label": "머큐시스",
"host": "192.168.0.220",
"rtspPort": 554,
"username": "camera",
"password": "vault:nvr.extraCameras.1000.password",
"rtspPath": "/stream1",
"rotate180": true,
"ptz": true,
"onvifPort": 2020
}
]
}
}
+42 -2
View File
@@ -1,12 +1,12 @@
{
"name": "smallclaw",
"version": "3.2.2",
"version": "4.2.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "smallclaw",
"version": "3.2.2",
"version": "4.2.1",
"license": "MIT",
"dependencies": {
"@xterm/addon-fit": "^0.10.0",
@@ -26,6 +26,7 @@
"node-pty": "^1.1.0",
"nodemailer": "^8.0.7",
"ollama": "^0.6.3",
"onvif": "^0.8.1",
"playwright": "^1.59.1",
"pptxgenjs": "^4.0.1",
"rp2040js": "^1.3.3",
@@ -2060,6 +2061,17 @@
"wrappy": "1"
}
},
"node_modules/onvif": {
"version": "0.8.1",
"resolved": "https://registry.npmjs.org/onvif/-/onvif-0.8.1.tgz",
"integrity": "sha512-D0VSuTQutZWQsaWWvh7acbengYNJew25kXpXc/stJc6/xYx2MwU1tkIZA23bu12hr5MxstSQ55decY7we2/LWw==",
"dependencies": {
"xml2js": "^0.6.2"
},
"engines": {
"node": ">=14.0"
}
},
"node_modules/opencollective-postinstall": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/opencollective-postinstall/-/opencollective-postinstall-2.0.3.tgz",
@@ -2446,6 +2458,14 @@
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/sax": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/sax/-/sax-1.6.0.tgz",
"integrity": "sha512-6R3J5M4AcbtLUdZmRv2SygeVaM7IhrLXu9BmnOGmmACak8fiUtOsYNWUS4uK7upbmHIBbLBeFeI//477BKLBzA==",
"engines": {
"node": ">=11.0.0"
}
},
"node_modules/selderee": {
"version": "0.11.0",
"resolved": "https://registry.npmjs.org/selderee/-/selderee-0.11.0.tgz",
@@ -2965,6 +2985,26 @@
}
}
},
"node_modules/xml2js": {
"version": "0.6.2",
"resolved": "https://registry.npmjs.org/xml2js/-/xml2js-0.6.2.tgz",
"integrity": "sha512-T4rieHaC1EXcES0Kxxj4JWgaUQHDk+qwHcYOCFHfiwKz7tOVPLq7Hjq9dM1WCMhylqMEfP7hMcOIChvotiZegA==",
"dependencies": {
"sax": ">=0.6.0",
"xmlbuilder": "~11.0.0"
},
"engines": {
"node": ">=4.0.0"
}
},
"node_modules/xmlbuilder": {
"version": "11.0.1",
"resolved": "https://registry.npmjs.org/xmlbuilder/-/xmlbuilder-11.0.1.tgz",
"integrity": "sha512-fDlsI/kFEx7gLvbecc0/ohLG50fugQp8ryHzMTuW9vSa1GJ0XYWKnhsUx7oie3G98+r56aTQIUB4kht42R3JvA==",
"engines": {
"node": ">=4.0"
}
},
"node_modules/zlibjs": {
"version": "0.3.1",
"resolved": "https://registry.npmjs.org/zlibjs/-/zlibjs-0.3.1.tgz",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "smallclaw",
"version": "4.2.1",
"version": "4.2.2",
"description": "Local AI agent framework powered by Ollama - OpenClaw alternative",
"main": "dist/index.js",
"bin": {
@@ -54,6 +54,7 @@
"node-pty": "^1.1.0",
"nodemailer": "^8.0.7",
"ollama": "^0.6.3",
"onvif": "^0.8.1",
"playwright": "^1.59.1",
"pptxgenjs": "^4.0.1",
"rp2040js": "^1.3.3",
+11
View File
@@ -374,6 +374,17 @@ function migrateSecretsToVault(config: any, configDir: string): any {
}
}
// NVR 독립 카메라(메인 NVR과 별개의 IP카메라) 목록도 배열이라 계정별로 따로 처리
const extraCameras = copy?.nvr?.extraCameras;
if (Array.isArray(extraCameras)) {
for (const cam of extraCameras) {
if (cam?.id == null || !isPlaintext(cam.password)) continue;
const vaultKey = `nvr.extraCameras.${cam.id}.password`;
vault.set(vaultKey, cam.password, 'config:migrate');
cam.password = `vault:${vaultKey}`;
}
}
return copy;
}
+282 -25
View File
@@ -1,6 +1,8 @@
import { Express, Request, Response } from 'express';
import { spawn, ChildProcess } from 'child_process';
import { getConfig } from '../../config/config.js';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { Cam: OnvifCam } = require('onvif');
// EseeCloud/E-SeeNet OEM NVR (K8208-3WS 등) — /netsdk/* REST API는 Basic Auth만 있으면
// 열림(포트 80, HTTP). 라이브 영상은 RTSP(별도 포트 rtspPort, NVR 웹UI에서 활성화 필요 —
@@ -35,6 +37,97 @@ function getNvrConfig(): NvrConfig {
};
}
// ── 독립 카메라(메인 NVR과 별개의 IP카메라, 예: Mercusys) ────────────────────
// 메인 NVR은 EseeCloud OEM 전용 /netsdk API로 채널을 조회하는데, 독립 IP카메라는 그
// API가 없고 host/port/계정/RTSP경로가 전부 제각각이다. 그래서 별도 목록(nvr.extraCameras)
// 으로 관리하고, id는 실제 NVR 채널(보통 0~3)과 안 겹치게 1000+로 부여한다(2026-07-22).
interface ExtraCamera {
id: number;
label: string;
host: string;
rtspPort: number;
username: string;
password: string;
rtspPath: string;
rotate180: boolean;
ptz: boolean;
onvifPort: number;
}
function getExtraCameras(): ExtraCamera[] {
const cm = getConfig();
const cfg = cm.getConfig() as any;
const list = cfg?.nvr?.extraCameras;
if (!Array.isArray(list)) return [];
return list.map((c: any) => ({
id: Number(c.id),
label: String(c.label || ''),
host: String(c.host || ''),
rtspPort: Number(c.rtspPort) || 554,
username: String(c.username || ''),
password: cm.resolveSecret(c.password) || '',
rtspPath: String(c.rtspPath || '/stream1'),
// 카메라 자체에 상하반전(180도) 옵션이 없는 모델(예: Mercusys, 미러만 있음)을 위해
// ffmpeg 단에서 소프트웨어로 180도 돌려준다(2026-07-23).
rotate180: c.rotate180 === true,
// ONVIF PTZ 지원 여부(팬/틸트 되는 모델만 true) + ONVIF 포트(기기마다 다름 — Mercusys
// MC510은 2020번, RTSP/HTTP 포트와 별개). WS-Security 인증은 RTSP와 같은 계정 사용(2026-07-23).
ptz: c.ptz === true,
onvifPort: Number(c.onvifPort) || 80,
}));
}
// ── 독립 카메라 ONVIF PTZ ────────────────────────────────────────────────
// ONVIF 연결(디바이스 능력 조회 등)은 왕복이 있어 버튼 누를 때마다 새로 맺으면 반응이
// 느리다 — 카메라 id별로 연결을 캐싱해 재사용한다.
const onvifCamCache = new Map<number, any>();
function getOnvifCam(cam: ExtraCamera): Promise<any> {
const cached = onvifCamCache.get(cam.id);
if (cached) return Promise.resolve(cached);
return new Promise((resolve, reject) => {
const onvifCam = new OnvifCam(
{ hostname: cam.host, port: cam.onvifPort, username: cam.username, password: cam.password, timeout: 8000 },
(err: Error) => {
if (err) { reject(err); return; }
onvifCamCache.set(cam.id, onvifCam);
resolve(onvifCam);
}
);
});
}
// ONVIF ContinuousMove는 x(팬)/y(틸트)/zoom 속도(-1~1) 벡터를 받는다. 우리 PTZ_CODES는
// NVR용 이산 커맨드라, 여기서 방향별 벡터로 변환한다. 줌/포커스/아이리스는 이 모델(MC510,
// 팬/틸트 전용)엔 없어서 무시 — 다른 독립 카메라가 지원하면 그때 확장.
function onvifVelocityFor(command: string, speed: number): { x: number; y: number; zoom: number } | null {
const v = Math.max(0.1, Math.min(1, speed / 10));
switch (command) {
case 'Up': return { x: 0, y: v, zoom: 0 };
case 'Down': return { x: 0, y: -v, zoom: 0 };
case 'Left': return { x: -v, y: 0, zoom: 0 };
case 'Right': return { x: v, y: 0, zoom: 0 };
case 'LeftUp': return { x: -v, y: v, zoom: 0 };
case 'RightUp': return { x: v, y: v, zoom: 0 };
case 'LeftDown': return { x: -v, y: -v, zoom: 0 };
case 'RightDown': return { x: v, y: -v, zoom: 0 };
default: return null; // ZoomIn/Out, Iris, Focus 등 미지원
}
}
async function onvifPtzControl(cam: ExtraCamera, command: string, speed: number): Promise<{ ok: boolean; detail?: string }> {
const onvifCam = await getOnvifCam(cam);
if (command === 'Stop') {
return new Promise((resolve) => {
onvifCam.stop({ panTilt: true }, (err: Error) => resolve({ ok: !err, detail: err ? String(err.message || err) : undefined }));
});
}
const velocity = onvifVelocityFor(command, speed);
if (!velocity) return { ok: false, detail: '이 카메라는 해당 동작(줌/초점/조리개)을 지원하지 않습니다' };
// 화면을 180도 돌려서 보여주고 있으면(rotate180) 화면상 "왼쪽"이 카메라 자체 좌표계로는
// 반대 방향이라, 팬/틸트 축을 같이 뒤집어야 사용자가 보는 화면 기준으로 방향이 맞는다.
if (cam.rotate180) { velocity.x = -velocity.x; velocity.y = -velocity.y; }
return new Promise((resolve) => {
onvifCam.continuousMove(velocity, (err: Error) => resolve({ ok: !err, detail: err ? String(err.message || err) : undefined }));
});
}
async function nvrFetch(nvrPath: string, opts: { method?: string; body?: any } = {}): Promise<any> {
const { host, port, username, password } = getNvrConfig();
if (!host) throw new Error('NVR host not configured — set it via POST /api/nvr/config first');
@@ -106,16 +199,22 @@ export function registerNvrRoutes(app: Express): void {
app.get('/api/nvr/channels', async (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
let channels: any[] = [];
let nvrError: string | undefined;
try {
const [ipcInfo, ipcStatus] = await Promise.all([
nvrFetch('/netsdk/Channel/IPCamInfo'),
nvrFetch('/netsdk/Stat/IPC'),
]);
const labels = getChannelLabels();
const streamPrefs = getChannelStreamPrefs();
const statusById = new Map<number, any>((ipcStatus as any[]).map((s: any) => [s.ID, s]));
const channels = (ipcInfo as any[]).map((c: any) => {
channels = (ipcInfo as any[]).map((c: any) => {
const st = statusById.get(c.ID) || {};
return {
id: c.ID,
label: labels[String(c.ID)] || '',
preferredStream: streamPrefs[String(c.ID)] ?? null,
enabled: c.Enable === 'True',
model: c.Modelname || '',
ip: c.IPAddr || '',
@@ -134,10 +233,138 @@ export function registerNvrRoutes(app: Express): void {
charging: st.Charging === 'True',
};
});
res.json({ channels });
} catch (e: any) {
res.status(502).json({ error: String(e?.message || e) });
// 메인 NVR이 응답 없어도 독립 카메라(아래)는 계속 보여준다 — 완전히 별개 장치라
// 메인 NVR 장애가 독립 카메라 시청까지 막을 이유가 없다.
nvrError = String(e?.message || e);
}
// 독립 카메라(메인 NVR API가 없는 Mercusys 등)도 같은 그리드에 타일로 추가.
const extra = getExtraCameras().map((c) => ({
id: c.id,
label: c.label || '카메라',
preferredStream: null,
enabled: true,
model: 'Standalone',
ip: c.host,
mac: '',
firmware: '',
interfaceType: 'standalone',
supportHumanDetect: false,
online: true, // 상태 확인은 안 함 — 실제 스트림 열 때 실패하면 그때 표시
statusText: 'Standalone',
wifiSignal: null,
recording: false,
motionEvent: false,
bodyEvent: false,
faceEvent: false,
battery: null,
charging: false,
standalone: true,
rotate180: c.rotate180,
}));
channels.push(...extra);
res.json({ channels, ...(nvrError ? { nvrError } : {}) });
});
// ── 독립 카메라 추가/삭제 ────────────────────────────────────────────────
app.post('/api/nvr/extra-cameras', (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const { label, host, rtspPort, username, password, rtspPath } = req.body || {};
if (!String(host || '').trim()) return res.status(400).json({ error: 'host is required' });
const cm = getConfig();
const cfg = cm.getConfig() as any;
const nvr = cfg?.nvr || {};
const list: any[] = Array.isArray(nvr.extraCameras) ? nvr.extraCameras : [];
// 실제 NVR 채널(0~3 등)과 안 겹치게 1000+로 시작. 삭제로 생긴 구멍은 그냥 두고 max+1.
const nextId = Math.max(999, ...list.map((c: any) => Number(c.id) || 999)) + 1;
const entry = {
id: nextId,
label: String(label || '카메라').trim().slice(0, 60),
host: String(host).trim(),
rtspPort: rtspPort ? Number(rtspPort) : 554,
username: String(username || '').trim(),
password: String(password || ''),
rtspPath: String(rtspPath || '/stream1').trim(),
};
cm.updateConfig({ nvr: { ...nvr, extraCameras: [...list, entry] } } as any);
res.json({ success: true, id: nextId });
});
app.delete('/api/nvr/extra-cameras/:id', (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const id = Number(req.params.id);
const cm = getConfig();
const cfg = cm.getConfig() as any;
const nvr = cfg?.nvr || {};
const list: any[] = Array.isArray(nvr.extraCameras) ? nvr.extraCameras : [];
cm.updateConfig({ nvr: { ...nvr, extraCameras: list.filter((c: any) => Number(c.id) !== id) } } as any);
res.json({ success: true });
});
// 카메라 자체에 상하반전 옵션이 없는 모델(미러만 지원 등)을 위한 소프트웨어 180도 회전
// 토글 — ffmpeg 필터로 적용(아래 launch() 참고).
app.post('/api/nvr/extra-cameras/:id/rotate', (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const id = Number(req.params.id);
const cm = getConfig();
const cfg = cm.getConfig() as any;
const nvr = cfg?.nvr || {};
const list: any[] = Array.isArray(nvr.extraCameras) ? nvr.extraCameras : [];
const rotate180 = req.body?.rotate180 === true;
const updated = list.map((c: any) => (Number(c.id) === id ? { ...c, rotate180 } : c));
cm.updateConfig({ nvr: { ...nvr, extraCameras: updated } } as any);
res.json({ success: true, rotate180 });
});
// ── 채널 이름/위치 라벨 ────────────────────────────────────────────────
// NVR 자체는 채널에 이름/위치 메타데이터가 없음(모델명·IP·MAC만 줌) — 카메라를
// "채널 3" 대신 "현관", "거실" 등으로 구분하고 싶다는 요청(2026-07-21)에 따라
// 우리 쪽 config(nvr.channelLabels: {채널ID: 라벨})에 별도로 저장.
function getChannelLabels(): Record<string, string> {
const cfg = getConfig().getConfig() as any;
return (cfg?.nvr?.channelLabels && typeof cfg.nvr.channelLabels === 'object') ? cfg.nvr.channelLabels : {};
}
app.post('/api/nvr/channels/:channelId/label', (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const channelId = Number(req.params.channelId);
if (!Number.isFinite(channelId) || channelId < 0) return res.status(400).json({ error: 'invalid channelId' });
const label = String(req.body?.label ?? '').trim().slice(0, 60);
const cm = getConfig();
const cfg = cm.getConfig() as any;
const nvr = cfg?.nvr || {};
const channelLabels = { ...(nvr.channelLabels || {}) };
if (label) channelLabels[String(channelId)] = label; else delete channelLabels[String(channelId)];
cm.updateConfig({ nvr: { ...nvr, channelLabels } } as any);
res.json({ success: true, label });
});
// ── 채널별 화질(스트림) 강제 설정 ──────────────────────────────────────
// 신호 약한 무선 카메라는 메인(고화질) 스트림이 계속 끊기는데 서브(저화질)는
// 안정적으로 나온다(2026-07-21, 채널3 WiFi ~18%에서 확인) — 해당 채널만 항상
// 서브스트림을 쓰도록 강제 지정. null/미지정이면 화면(라이브 모달·5분할)의
// 기본 선택을 따름. nvr.channelStream: {채널ID: 0|1}에 저장.
function getChannelStreamPrefs(): Record<string, number> {
const cfg = getConfig().getConfig() as any;
return (cfg?.nvr?.channelStream && typeof cfg.nvr.channelStream === 'object') ? cfg.nvr.channelStream : {};
}
app.post('/api/nvr/channels/:channelId/stream', (req: Request, res: Response) => {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const channelId = Number(req.params.channelId);
if (!Number.isFinite(channelId) || channelId < 0) return res.status(400).json({ error: 'invalid channelId' });
const raw = req.body?.stream;
const stream = raw === 0 || raw === 1 ? raw : null;
const cm = getConfig();
const cfg = cm.getConfig() as any;
const nvr = cfg?.nvr || {};
const channelStream = { ...(nvr.channelStream || {}) };
if (stream === null) delete channelStream[String(channelId)]; else channelStream[String(channelId)] = stream;
cm.updateConfig({ nvr: { ...nvr, channelStream } } as any);
res.json({ success: true, stream });
});
app.post('/api/nvr/events', async (req: Request, res: Response) => {
@@ -255,31 +482,48 @@ export function registerNvrRoutes(app: Express): void {
const user = (req as any).user;
if (!user) return res.status(401).json({ error: 'Unauthorized' });
const { host, rtspPort, username, password, rtspPathTemplate } = getNvrConfig();
if (!host) return res.status(400).json({ error: 'NVR host not configured' });
const channelId = Number(req.params.channelId);
// 채널 ID는 0-based(이 NVR은 id=0,1,2,3 = 1~4번 카메라). 0부터 허용.
// 독립 카메라는 1000+ id(getExtraCameras 참고)라 여기도 그대로 통과한다.
if (!Number.isFinite(channelId) || channelId < 0) {
return res.status(400).json({ error: 'invalid channelId' });
}
// ?stream=0 (main, 기본) | 1 (sub, 저화질·저부하)
const stream = req.query.stream === '1' ? 1 : 0;
// ?stream=0 (main) | 1 (sub, 저화질·저부하). 명시 안 하면 채널별 강제 화질(있으면)을
// 따르고, 그것도 없으면 메인이 기본값 — 클라이언트가 항상 쿼리를 보내지만, 방어적으로
// 서버에서도 한 번 더 강제(2026-07-21, 신호 약한 채널 서브 고정 기능).
const streamQuery = req.query.stream;
const stream = streamQuery === '1' ? 1 : streamQuery === '0' ? 0 : (getChannelStreamPrefs()[String(channelId)] ?? 0);
// RTSP 경로 조립 — 템플릿 치환. 치환자:
// {username} {password} — 기기 계정(경로 쿼리용, raw 치환 — NVR이 raw 매치)
// {channel} — 1-based 채널번호(Movols /user=...&channel=A 형식용)
// {channel0} — 0-based 채널번호(이 기기 실제 형식 /ch{N}_{S}.264 — ch0=첫카메라)
// {stream} — 0(main)/1(sub)
// 경로가 '/'로 시작 안 하면 자동 붙임(사용자가 'ch0_0.264'만 적어도 동작).
let rtspPath = rtspPathTemplate
.replaceAll('{username}', username)
.replaceAll('{password}', password)
.replaceAll('{channel0}', String(channelId - 1))
.replaceAll('{channel}', String(channelId))
.replaceAll('{stream}', String(stream));
if (!rtspPath.startsWith('/')) rtspPath = '/' + rtspPath;
const rtspUrl = `rtsp://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${rtspPort}${rtspPath}`;
// 독립 카메라(메인 NVR과 별개, id 1000+)면 그 카메라 자신의 host/계정/경로로 URL을
// 직접 만든다(템플릿 치환 없음 — Mercusys 등은 이미 완전한 경로를 그대로 씀).
const extraCam = getExtraCameras().find((c) => c.id === channelId);
let rtspUrl: string;
if (extraCam) {
if (!extraCam.host) return res.status(400).json({ error: 'camera host not configured' });
let path = extraCam.rtspPath;
// stream=1(서브)이 오면 흔한 관례로 stream1→stream2 치환 시도(정확한 매핑은 카메라마다
// 달라 완벽하진 않음 — 안 맞으면 그냥 rtspPath 그대로 유지).
if (stream === 1 && /stream1$/i.test(path)) path = path.replace(/stream1$/i, 'stream2');
if (!path.startsWith('/')) path = '/' + path;
rtspUrl = `rtsp://${encodeURIComponent(extraCam.username)}:${encodeURIComponent(extraCam.password)}@${extraCam.host}:${extraCam.rtspPort}${path}`;
} else {
const { host, rtspPort, username, password, rtspPathTemplate } = getNvrConfig();
if (!host) return res.status(400).json({ error: 'NVR host not configured' });
// RTSP 경로 조립 — 템플릿 치환. 치환자:
// {username} {password} — 기기 계정(경로 쿼리용, raw 치환 — NVR이 raw 매치)
// {channel} — 1-based 채널번호(Movols /user=...&channel=A 형식용)
// {channel0} — 0-based 채널번호(이 기기 실제 형식 /ch{N}_{S}.264 — ch0=첫카메라)
// {stream} — 0(main)/1(sub)
// 경로가 '/'로 시작 안 하면 자동 붙임(사용자가 'ch0_0.264'만 적어도 동작).
let rtspPath = rtspPathTemplate
.replaceAll('{username}', username)
.replaceAll('{password}', password)
.replaceAll('{channel0}', String(channelId - 1))
.replaceAll('{channel}', String(channelId))
.replaceAll('{stream}', String(stream));
if (!rtspPath.startsWith('/')) rtspPath = '/' + rtspPath;
rtspUrl = `rtsp://${encodeURIComponent(username)}:${encodeURIComponent(password)}@${host}:${rtspPort}${rtspPath}`;
}
const streamKey = `${channelId}:${stream}`;
@@ -349,6 +593,9 @@ export function registerNvrRoutes(app: Express): void {
const launch = () => {
if (closed) return;
// 카메라 자체에 상하반전 옵션이 없는 모델(예: Mercusys — 미러만 지원)을 위해 ffmpeg
// 필터로 소프트웨어 180도 회전을 넣는다(2026-07-23). hflip+vflip 조합 = 180도 회전.
const rotateFilterArgs = extraCam?.rotate180 ? ['-vf', 'hflip,vflip'] : [];
const proc: ChildProcess = spawn('ffmpeg', [
// HEVC 디코딩을 GPU(NVDEC)로 옮겨 4분할 고화질 동시 재생시 CPU 부하 감소.
// 클로서버(3060×2) 전제. GPU 없는 환경에선 이 두 줄을 제거해야 함.
@@ -363,6 +610,7 @@ export function registerNvrRoutes(app: Express): void {
'-probesize', '5000000',
'-analyzeduration', '5000000',
'-i', rtspUrl,
...rotateFilterArgs,
'-c:v', 'mjpeg',
'-q:v', '5',
'-r', '10',
@@ -429,7 +677,7 @@ export function registerNvrRoutes(app: Express): void {
proc.on('error', (err: Error) => {
if (closed) return;
if (firstFrameTimer) { clearTimeout(firstFrameTimer); firstFrameTimer = null; }
console.error('[nvr/stream] ffmpeg spawn error:', err.message);
console.error(`[nvr/stream] channel ${channelId}:${stream} ffmpeg spawn error:`, err.message);
// spawn 자체 실패도 재시도로 복구 시도(일시적일 수 있음)
scheduleRespawn();
});
@@ -440,7 +688,9 @@ export function registerNvrRoutes(app: Express): void {
if (!headersSent) {
// 첫 프레임도 못 받고 종료(NVR이 EOF로 연결 끊음 등) — 일시적일 수 있으니
// 바로 502 주지 않고 재시도. 진짜 설정 오류면 cap 도달시 502.
console.error(`[nvr/stream] ffmpeg exited ${code} before first frame (attempt ${respawnCount + 1}/${MAX_RESPAWN}). stderr tail:\n${stderrBuf.slice(-800)}`);
console.error(`[nvr/stream] channel ${channelId}:${stream} ffmpeg exited ${code} before first frame (attempt ${respawnCount + 1}/${MAX_RESPAWN}). stderr tail:\n${stderrBuf.slice(-800)}`);
} else {
console.error(`[nvr/stream] channel ${channelId}:${stream} mid-stream drop (attempt ${respawnCount + 1}/${MAX_RESPAWN}). stderr tail:\n${stderrBuf.slice(-800)}`);
}
// 스트리밍 중 끊김이든 첫 프레임 실패든 모두 재시도로 복구 시도.
scheduleRespawn();
@@ -451,7 +701,7 @@ export function registerNvrRoutes(app: Express): void {
if (closed) return;
if (respawnCount >= MAX_RESPAWN) {
// 프레임 없이 연속 실패 → 진짜 고장, 포기.
console.error(`[nvr/stream] respawn cap (${MAX_RESPAWN}) reached — giving up`);
console.error(`[nvr/stream] channel ${channelId}:${stream} respawn cap (${MAX_RESPAWN}) reached — giving up`);
if (!res.headersSent && !headersSent) {
// 한 번도 스트리밍 못 했으면 502로 의미있는 에러 전달(abort는 res.end만 하므로 먼저 응답).
closed = true;
@@ -519,6 +769,13 @@ export function registerNvrRoutes(app: Express): void {
const cmdCode = PTZ_CODES[String(command || '')];
if (cmdCode == null) return res.status(400).json({ error: 'invalid command' });
const sp = Math.max(1, Math.min(10, Number(speed) || 5));
// 독립 카메라(메인 NVR과 별개, id 1000+)면 ONVIF PTZ로 보낸다.
const extraCam = getExtraCameras().find((c) => c.id === ch);
if (extraCam) {
if (!extraCam.ptz) return res.status(400).json({ error: '이 카메라는 PTZ를 지원하지 않습니다' });
const result = await onvifPtzControl(extraCam, String(command), sp);
return res.json(result);
}
const result = await nvrFetch('/netsdk/Channel/PTZ', {
method: 'POST',
body: {
+136 -41
View File
@@ -37,6 +37,8 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
.chn-dot.on{background:#22c55e;box-shadow:0 0 6px #22c55e;}
.chn-name{font-size:13px;font-weight:700;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
.chn-id{font-size:10px;color:var(--muted);}
.chn-edit{background:none;border:none;color:var(--muted);cursor:pointer;font-size:12px;padding:2px 4px;font-family:inherit;flex-shrink:0;}
.chn-edit:hover{color:var(--brand);}
.chn-row{font-size:11px;color:var(--muted);display:flex;justify-content:space-between;margin-top:3px;}
.chn-badges{display:flex;gap:4px;flex-wrap:wrap;margin-top:8px;}
.badge{font-size:9px;font-weight:700;padding:2px 6px;border-radius:8px;background:var(--panel-2);color:var(--muted);}
@@ -138,7 +140,7 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
<div class="dev-info" id="dev-info">장치 정보 로딩 중...</div>
<div class="quad-wrap">
<div class="quad-toolbar">
<b>🔊 5분할 라이브</b>
<b>🔊 6분할 라이브</b>
<span class="quad-hint" id="quad-hint"></span>
<span class="quad-sp"></span>
<button class="hdr-btn" id="quad-play-btn" onclick="toggleQuad()">▶ 재생</button>
@@ -147,6 +149,9 @@ body{background:var(--bg);color:var(--text);font-family:system-ui,sans-serif;dis
<div class="quad-grid" id="quad-grid"></div>
</div>
<details class="chn-details"><summary>상세 채널 정보</summary>
<div style="display:flex;justify-content:flex-end;margin:8px 0">
<button class="hdr-btn" onclick="addExtraCamera()">+ 독립 카메라 추가</button>
</div>
<div class="chn-grid" id="chn-grid"><div class="empty">채널 로딩 중...</div></div>
</details>
</div>
@@ -284,14 +289,26 @@ function killImg(img,channelId,streamQ){ // multipart fetch 중단 + 서버 즉
stopChannel(channelId,streamQ); // 서버단 확실한 즉시 SIGKILL
}
let currentLiveChannel=null;
let currentLiveStream=0;
// 채널별로 강제 지정된 화질(preferredStream)이 있으면 그걸 쓰고, 없으면 null(화면 기본값 사용).
// 신호 약한 카메라는 메인이 계속 끊겨서 서브로 고정해두는 용도(2026-07-21).
function chnStreamOverride(channelId){
const c=lastChannels.find(x=>x.id===channelId);
return (c && (c.preferredStream===0||c.preferredStream===1)) ? c.preferredStream : null;
}
function chnPreferredStream(channelId){ // 라이브 모달용 — 오버라이드 없으면 메인(0)
const o=chnStreamOverride(channelId);
return o==null?0:o;
}
function openLive(channelId,btn){
const img=document.getElementById('live-img');
// 모달이 이미 다른 채널을 보고 있는 채로 새 채널을 여는 경우(카메라 넘기기) —
// 이전 채널을 먼저 명시적으로 끊어야 함(안 그러면 좀비로 남아 세션 잠식).
if(currentLiveChannel!=null && currentLiveChannel!==channelId){
stopChannel(currentLiveChannel,0);
stopChannel(currentLiveChannel,currentLiveStream);
}
currentLiveChannel=channelId;
currentLiveStream=chnPreferredStream(channelId);
// 5분할이 재생중이면 잠시 정지 — NVR 동시 RTSP 세션 수 제한(보통 4) 때문에
// 5분할 자체가 이미 한계치라, 모달까지 더하면 NVR이 거부 → "영상 불러오지 못했습니다"(캠2 사례).
// 모달은 전체화면 오버레이라 5분할이 안 보이므로 정지해도 무방. 닫으면 재개.
@@ -300,7 +317,7 @@ function openLive(channelId,btn){
const errEl=document.getElementById('live-err');
const titleEl=document.getElementById('live-title');
errEl.style.display='none';errEl.textContent='';
titleEl.textContent=btn?btn.getAttribute('data-name')||('채널 '+channelId):('채널 '+channelId);
titleEl.textContent=(btn?btn.getAttribute('data-name')||('채널 '+channelId):('채널 '+channelId))+(currentLiveStream?' (저화질 고정)':'');
img.style.display='block';
img.onerror=()=>{ // 서버가 502 JSON을 보내거나 프레임이 안 오면 img가 깨짐
img.style.display='none';
@@ -308,15 +325,16 @@ function openLive(channelId,btn){
errEl.style.display='block';
};
// 캐시 방지 위해 채널 id + 타임스탵 쿼리(같은 src 재사용시 onerror 안 트리는 브라우저 대비)
img.src='/api/nvr/stream/'+channelId;
img.src='/api/nvr/stream/'+channelId+(currentLiveStream?'?stream=1':'');
modal.classList.add('show');
}
function closeLive(){
const closingChannel=currentLiveChannel;
const closingStream=currentLiveStream;
currentLiveChannel=null;
const modal=document.getElementById('live-modal');
const img=document.getElementById('live-img');
killImg(img,closingChannel,0); // 연결 종료 + 서버 즉시-컷(모달은 항상 메인=stream 0)
killImg(img,closingChannel,closingStream); // 연결 종료 + 서버 즉시-컷
modal.classList.remove('show');
// 모달을 위해 멈췄던 5분할 재개(채널 탭이 보이는 중이고 재생중이었으면).
if(quadPlaying && isChnActive()){ startQuadStreams(); }
@@ -390,50 +408,125 @@ function switchTab(t){
else ensureQuadAutoPlay();
}
// ── 채널 이름/위치 라벨 ──
// NVR은 채널 이름을 모델명으로만 줌("5323-W-Q") — 카메라를 위치("현관","거실")로
// 구분하고 싶을 때 편집. 서버 nvr.channelLabels에 채널ID별로 저장(POST로 갱신).
let lastChannels=[];
function chnDisplayName(c){return c.label||c.model||('채널 '+c.id);}
async function editChannelLabel(channelId){
const c=lastChannels.find(x=>x.id===channelId);
const val=prompt('채널 #'+channelId+' 이름/위치 (비워두면 모델명 표시)',c?c.label||'':'');
if(val===null) return; // 취소
try{
const r=await fetch('/api/nvr/channels/'+channelId+'/label',{method:'POST',headers:authH({'Content-Type':'application/json'}),body:JSON.stringify({label:val})});
const d=await r.json();
if(!r.ok) throw new Error(d.error||'저장 실패');
showToast('저장됨');
loadChannels();
}catch(e){showToast('오류: '+e.message,true);}
}
// ── 채널별 화질 강제 ──
// 신호 약한 무선 카메라는 메인(고화질)이 계속 끊기고 서브(저화질)만 안정적일 때
// 그 채널만 항상 서브를 쓰도록 고정(2026-07-21, 채널3 사례). 5분할·라이브 모달 둘 다 적용.
async function toggleChannelStream(channelId){
const forced=chnStreamOverride(channelId)===1;
try{
const r=await fetch('/api/nvr/channels/'+channelId+'/stream',{method:'POST',headers:authH({'Content-Type':'application/json'}),body:JSON.stringify({stream:forced?null:1})});
const d=await r.json();
if(!r.ok) throw new Error(d.error||'저장 실패');
showToast(forced?'화질 고정 해제됨':'저화질(서브) 고정됨');
loadChannels();
}catch(e){showToast('오류: '+e.message,true);}
}
async function loadChannels(){
const devEl=document.getElementById('dev-info');
const gridEl=document.getElementById('chn-grid');
let channels=[];
let nvrError=null;
// 채널 목록은 독립 카메라(메인 NVR과 별개)도 포함하므로, 메인 NVR이 응답 없어도
// 이 요청 자체는 성공한다(서버가 nvrError 필드로 알려줌) — 그래서 상태 조회와 분리.
try{
const [statusR, chnR] = await Promise.all([
fetch('/api/nvr/status',{headers:authH()}),
fetch('/api/nvr/channels',{headers:authH()}),
]);
const statusD=await statusR.json();
const chnR=await fetch('/api/nvr/channels',{headers:authH()});
const chnD=await chnR.json();
if(!statusR.ok) throw new Error(statusD.error||'상태 조회 실패');
if(!chnR.ok) throw new Error(chnD.error||'채널 조회 실패');
const dev=statusD.device||{};
devEl.innerHTML=`<b>${escHtml(dev.DeviceName||'NVR')}</b> (${escHtml(dev.DeviceModel||'')}) · 펌웨어 ${escHtml(dev.FWVersion||'')} · 최대 ${escHtml(dev.MAX_CHN||'?')}채널`;
const channels=(chnD.channels||[]).filter(c=>c.enabled);
if(!channels.length){gridEl.innerHTML='<div class="empty">활성화된 채널이 없습니다.</div>';return;}
gridEl.innerHTML=channels.map(c=>`
<div class="chn-card ${c.online?'':'offline'}">
<div class="chn-top">
<span class="chn-dot ${c.online?'on':''}"></span>
<span class="chn-name">${escHtml(c.model||('채널 '+c.id))}</span>
<span class="chn-id">#${c.id}</span>
</div>
<div class="chn-row"><span>상태</span><span>${escHtml(c.statusText)}</span></div>
<div class="chn-row"><span>IP</span><span>${escHtml(c.ip)}</span></div>
${c.wifiSignal!=null?`<div class="chn-row"><span>WiFi 신호</span><span>${c.wifiSignal}%</span></div>`:''}
<div class="chn-badges">
${c.recording?'<span class="badge rec">● 녹화중</span>':''}
${c.motionEvent?'<span class="badge warn">움직임 감지</span>':''}
${c.bodyEvent?'<span class="badge warn">사람 감지</span>':''}
${c.faceEvent?'<span class="badge warn">얼굴 감지</span>':''}
</div>
<button class="chn-live" data-name="${escHtml(c.model||('채널 '+c.id))}" onclick="openLive(${c.id},this)" ${c.online?'':'disabled'}>▶ 라이브</button>
</div>`).join('');
// 5분할: 온라인 채널(최대 5)로 셀 구성. 빈 칸은 placeholder.
quadChannels=channels.filter(c=>c.online).slice(0,5);
renderQuad();
channels=(chnD.channels||[]).filter(c=>c.enabled);
nvrError=chnD.nvrError||null;
}catch(e){
devEl.textContent='오류: '+e.message;
gridEl.innerHTML=`<div class="empty">채널 정보를 불러오지 못했습니다. 설정 탭에서 NVR 연결정보를 확인하세요.</div>`;
quadChannels=[];renderQuad();
return;
}
try{
const statusR=await fetch('/api/nvr/status',{headers:authH()});
const statusD=await statusR.json();
if(!statusR.ok) throw new Error(statusD.error||'상태 조회 실패');
const dev=statusD.device||{};
devEl.innerHTML=`<b>${escHtml(dev.DeviceName||'NVR')}</b> (${escHtml(dev.DeviceModel||'')}) · 펌웨어 ${escHtml(dev.FWVersion||'')} · 최대 ${escHtml(dev.MAX_CHN||'?')}채널`;
}catch(e){
// 메인 NVR 상태 조회는 부가 정보 — 실패해도 독립 카메라 목록/라이브는 그대로 보여준다.
devEl.textContent=nvrError?`메인 NVR 응답 없음(${nvrError}) — 독립 카메라만 표시됩니다`:'오류: '+e.message;
}
lastChannels=channels;
if(!channels.length){gridEl.innerHTML='<div class="empty">활성화된 채널이 없습니다.</div>';return;}
gridEl.innerHTML=channels.map(c=>`
<div class="chn-card ${c.online?'':'offline'}">
<div class="chn-top">
<span class="chn-dot ${c.online?'on':''}"></span>
<span class="chn-name">${escHtml(chnDisplayName(c))}</span>
<button class="chn-edit" onclick="editChannelLabel(${c.id})" title="이름/위치 편집">✎</button>
${c.standalone?`<button class="chn-edit" onclick="deleteExtraCamera(${c.id})" title="카메라 삭제">🗑</button>`:''}
<span class="chn-id">#${c.id}</span>
</div>
${c.label?`<div class="chn-row"><span>모델</span><span>${escHtml(c.model)}</span></div>`:''}
<div class="chn-row"><span>상태</span><span>${escHtml(c.statusText)}</span></div>
<div class="chn-row"><span>IP</span><span>${escHtml(c.ip)}</span></div>
${c.wifiSignal!=null?`<div class="chn-row"><span>WiFi 신호</span><span>${c.wifiSignal}%</span></div>`:''}
<div class="chn-badges">
${c.recording?'<span class="badge rec">● 녹화중</span>':''}
${c.motionEvent?'<span class="badge warn">움직임 감지</span>':''}
${c.bodyEvent?'<span class="badge warn">사람 감지</span>':''}
${c.faceEvent?'<span class="badge warn">얼굴 감지</span>':''}
${c.preferredStream===1?'<span class="badge warn">저화질 고정</span>':''}
</div>
<button class="chn-live" data-name="${escHtml(chnDisplayName(c))}" onclick="openLive(${c.id},this)" ${c.online?'':'disabled'}>▶ 라이브</button>
<button class="hdr-btn" style="margin-top:6px" onclick="toggleChannelStream(${c.id})">${c.preferredStream===1?'화질 고정 해제':'저화질(서브) 고정'}</button>
${c.standalone?`<button class="hdr-btn" style="margin-top:6px" onclick="toggleExtraCameraRotate(${c.id},${!c.rotate180})">${c.rotate180?'상하반전 해제':'상하반전(180도)'}</button>`:''}
</div>`).join('');
// 6분할: 온라인 채널(최대 6, 독립 카메라 포함)로 셀 구성. 빈 칸은 placeholder.
quadChannels=channels.filter(c=>c.online).slice(0,6);
renderQuad();
}
async function addExtraCamera(){
const label=prompt('카메라 이름(예: 마당, 현관)', '카메라');
if(label==null) return;
const host=prompt('카메라 IP 주소', '192.168.0.2');
if(!host) return;
const rtspPort=prompt('RTSP 포트', '554');
const username=prompt('RTSP 사용자명', 'camera');
const password=prompt('RTSP 비밀번호', '');
const rtspPath=prompt('RTSP 경로(메인 스트림)', '/stream1');
try{
const r=await fetch('/api/nvr/extra-cameras',{method:'POST',headers:authH({'Content-Type':'application/json'}),
body:JSON.stringify({label,host,rtspPort:Number(rtspPort)||554,username,password,rtspPath})});
const d=await r.json();
if(!r.ok||!d.success) throw new Error(d.error||'추가 실패');
loadChannels();
}catch(e){ alert('오류: '+e.message); }
}
async function deleteExtraCamera(id){
if(!confirm('이 카메라를 삭제할까요?')) return;
try{
await fetch('/api/nvr/extra-cameras/'+id,{method:'DELETE',headers:authH()});
loadChannels();
}catch(e){ alert('오류: '+e.message); }
}
async function toggleExtraCameraRotate(id,rotate180){
try{
await fetch('/api/nvr/extra-cameras/'+id+'/rotate',{method:'POST',headers:authH({'Content-Type':'application/json'}),body:JSON.stringify({rotate180})});
loadChannels();
}catch(e){ alert('오류: '+e.message); }
}
// ── 5분할 라이브 ──
@@ -449,8 +542,8 @@ function renderQuad(){
for(let i=0;i<6;i++){
const c=quadChannels[i];
if(c){
cells.push(`<div class="quad-cell" data-id="${c.id}" data-name="${escHtml(c.model||('채널 '+c.id))}" onclick="openLive(${c.id},this)">
<span class="lbl">${escHtml(c.model||('채널 '+c.id))} · #${c.id}</span>
cells.push(`<div class="quad-cell" data-id="${c.id}" data-name="${escHtml(chnDisplayName(c))}" onclick="openLive(${c.id},this)">
<span class="lbl">${escHtml(chnDisplayName(c))} · #${c.id}</span>
<div class="ph">…</div>
</div>`);
}else{
@@ -483,9 +576,11 @@ function toggleQuad(){
else{startQuad();}
}
function startQuadStreams(){
const stream=document.getElementById('quad-main').checked?0:1; // 기본 서브(저부하), 체크시 메인
const globalStream=document.getElementById('quad-main').checked?0:1; // 기본 서브(저부하), 체크시 메인
document.querySelectorAll('#quad-grid .quad-cell:not(.empty-slot)').forEach(cell=>{
const id=cell.dataset.id;
const override=chnStreamOverride(Number(id));
const stream=override==null?globalStream:override; // 채널별 강제 화질이 있으면 전역 설정보다 우선
let img=cell.querySelector('img');
if(!img){
img=document.createElement('img');img.alt='RTSP';