Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ General-purpose ONVIF library for Node.js with TypeScript support.

- TypeScript + Promise API
- Typed ONVIF/WSDL interfaces (26.06)
- Profiles [S](https://www.onvif.org/profiles/profile-s/), [T](https://www.onvif.org/profiles/profile-t/),
- Compatible with devices advertising Profiles
[S](https://www.onvif.org/profiles/profile-s/), [T](https://www.onvif.org/profiles/profile-t/),
[G](https://www.onvif.org/profiles/profile-g/), [M](https://www.onvif.org/profiles/profile-m/),
[C](https://www.onvif.org/profiles/profile-c/), [A](https://www.onvif.org/profiles/profile-a/),
[D](https://www.onvif.org/profiles/profile-d/)
Expand All @@ -27,8 +28,6 @@ General-purpose ONVIF library for Node.js with TypeScript support.
> `npm install onvif@previous`, use the `onvif/compatibility` layer with this package, or browse
> [branch v0.x](https://github.com/agsh/onvif/tree/v0.x).

[![ONVIF](https://github.com/user-attachments/assets/f58fb3c8-6bf6-406c-bcc7-883c1da33c5d)](http://onvif.org)

## Installation

Requires Node.js 18+. The published package ships compiled `build/` (CommonJS + `.d.ts`),
Expand Down Expand Up @@ -493,6 +492,8 @@ Thanks to [HappyTimeSoft](https://www.happytimesoft.com/index.html) for
used in integration tests, to [@RogerHardiman](https://github.com/RogerHardiman) for support
and real-camera testing, and to everyone who filed issues over the years.

[![OBEY!][obey-img]](https://www.onvif.org/resources/)
## Disclaimer

[obey-img]: https://github.com/user-attachments/assets/8cc43a86-4610-4e1a-8700-3a46aa2c1da3
ONVIF is a registered trademark of ONVIF, Inc. This project is an independent open-source
client for the ONVIF protocol. It is not affiliated with, endorsed by, or sponsored by
ONVIF. No ONVIF conformance or certification is claimed.
56 changes: 56 additions & 0 deletions __tests__/subscription.resubscribe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,62 @@ describe('Subscription resubscribe (SOAP mock server)', () => {
await sub.unsubscribe();
});

it('overlapping subscribe calls leave a single pull-point (no orphan Create)', async () => {
let releaseFirst!: () => void;
mock.createGate = new Promise<void>((resolve) => {
releaseFirst = resolve;
});
mock.pullBehavior = 'ok';
const sub = (activeSub = prepareSub(cam));

const first = sub.subscribe();
await waitFor(() => mock.stats.create >= 1, 5000, 'first create started');

// Second subscribe while Create is gated — previously could orphan the first pull-point.
const second = sub.subscribe();
releaseFirst();
mock.createGate = null;
await Promise.all([first, second]);

await waitFor(() => mock.stats.pull >= 1, 5000, 'single session pull');
// First create is disposed when superseded; second create owns the live subscription.
expect(mock.stats.create).toBe(2);
expect(mock.stats.unsubscribe).toBeGreaterThanOrEqual(1);

await sub.unsubscribe();
await delay(RECONNECT_MS);
const pullsAtStop = mock.stats.pull;
await delay(RECONNECT_MS * 2);
expect(mock.stats.pull).toBe(pullsAtStop);
});

it('Onvif event listener on/off/on during gated Create does not leave a zombie pull loop', async () => {
let releaseCreate!: () => void;
mock.createGate = new Promise<void>((resolve) => {
releaseCreate = resolve;
});
mock.pullBehavior = 'ok';
// Use globalSubscription via Onvif auto hooks (same path as broviki WS refcount).
const handler = () => undefined;
cam.on('event', handler);
await waitFor(() => mock.stats.create >= 1, 5000, 'auto create started');

cam.off('event', handler);
cam.on('event', handler);
releaseCreate();
mock.createGate = null;

await waitFor(() => mock.stats.pull >= 1, 8000, 'pull after rapid re-subscribe');
// At least one Create was abandoned (unsubscribe after first listener drop / supersede).
expect(mock.stats.unsubscribe).toBeGreaterThanOrEqual(1);

cam.off('event', handler);
await delay(RECONNECT_MS * 2);
const pullsAtStop = mock.stats.pull;
await delay(RECONNECT_MS * 2);
expect(mock.stats.pull).toBe(pullsAtStop);
});

it('retries CreatePullPointSubscription after create failures then starts pulling', async () => {
mock.createFailuresLeft = 2;
mock.pullBehavior = 'ok';
Expand Down
125 changes: 125 additions & 0 deletions __tests__/unit.media.updateEncoder.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
/**
* Unit tests for Media1 updateVideoEncoderConfiguration sugar (mocked request).
* @jest-environment node
*/

import { Onvif, OnvifValidationError } from '../src';
import Media from '../src/services/media';
import type {
VideoEncoderConfiguration,
VideoEncoderConfigurationOptions,
} from '../src/interfaces/onvif';

describe('Media.updateVideoEncoderConfiguration (mocked)', () => {
const onvif = new Onvif({ hostname: '127.0.0.1', autoConnect: false });

function baseCfg(): VideoEncoderConfiguration {
return {
token: 'enc1',
name: 'Main',
useCount: 1,
encoding: 'H264',
resolution: { width: 1920, height: 1080 },
quality: 4,
rateControl: { frameRateLimit: 25, encodingInterval: 1, bitrateLimit: 4096 },
H264: { govLength: 30, H264Profile: 'Main' },
multicast: {
address: { type: 'IPv4', IPv4Address: '0.0.0.0' },
port: 0,
TTL: 1,
autoStart: false,
},
sessionTimeout: 'PT60S',
};
}

function options(): VideoEncoderConfigurationOptions {
return {
qualityRange: { min: 1, max: 5 },
MPEG4: {
resolutionsAvailable: [
{ width: 640, height: 480 },
{ width: 1280, height: 720 },
],
govLengthRange: { min: 1, max: 100 },
frameRateRange: { min: 1, max: 25 },
encodingIntervalRange: { min: 1, max: 5 },
mpeg4ProfilesSupported: ['SP', 'ASP'],
},
H264: {
resolutionsAvailable: [{ width: 1920, height: 1080 }],
govLengthRange: { min: 1, max: 120 },
frameRateRange: { min: 1, max: 30 },
encodingIntervalRange: { min: 1, max: 5 },
H264ProfilesSupported: ['Baseline', 'Main', 'High'],
},
JPEG: {
resolutionsAvailable: [{ width: 640, height: 480 }],
frameRateRange: { min: 1, max: 30 },
encodingIntervalRange: { min: 1, max: 10 },
},
};
}

it('merges bitrate without fetching options when encoding is unchanged', async () => {
const media = new Media(onvif);
const cfg = baseCfg();
jest.spyOn(media, 'getVideoEncoderConfiguration').mockResolvedValue(cfg);
const optionsSpy = jest.spyOn(media, 'getVideoEncoderConfigurationOptions');
const setSpy = jest.spyOn(media, 'setVideoEncoderConfiguration').mockResolvedValue(undefined);

const merged = await media.updateVideoEncoderConfiguration({
configurationToken: 'enc1',
bitrateLimit: 900,
});

expect(merged.rateControl?.bitrateLimit).toBe(900);
expect(optionsSpy).not.toHaveBeenCalled();
expect(setSpy).toHaveBeenCalledWith({ configuration: merged, forcePersistence: true });
});

it('fetches options and rebuilds bags when encoding changes', async () => {
const media = new Media(onvif);
onvif.activeMediaProfile = {
profileToken: 'p1',
videoEncoderConfigurationToken: 'enc1',
} as never;
const cfg = baseCfg();
jest.spyOn(media, 'getVideoEncoderConfiguration').mockResolvedValue(cfg);
const optionsSpy = jest
.spyOn(media, 'getVideoEncoderConfigurationOptions')
.mockResolvedValue(options());
const setSpy = jest.spyOn(media, 'setVideoEncoderConfiguration').mockResolvedValue(undefined);

const merged = await media.updateVideoEncoderConfiguration({
encoding: 'MPEG4',
govLength: 20,
profile: 'ASP',
});

expect(optionsSpy).toHaveBeenCalledWith({
configurationToken: 'enc1',
profileToken: 'p1',
});
expect(merged.encoding).toBe('MPEG4');
expect(merged.H264).toBeUndefined();
expect(merged.MPEG4).toEqual({ govLength: 20, mpeg4Profile: 'ASP' });
expect(setSpy).toHaveBeenCalled();
});

it('propagates validation error when options lack the target encoding', async () => {
const media = new Media(onvif);
jest.spyOn(media, 'getVideoEncoderConfiguration').mockResolvedValue(baseCfg());
jest.spyOn(media, 'getVideoEncoderConfigurationOptions').mockResolvedValue({
qualityRange: { min: 1, max: 5 },
});
jest.spyOn(media, 'setVideoEncoderConfiguration').mockResolvedValue(undefined);

await expect(
media.updateVideoEncoderConfiguration({
configurationToken: 'enc1',
encoding: 'JPEG',
}),
).rejects.toBeInstanceOf(OnvifValidationError);
});
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "onvif",
"version": "1.1.0",
"author": "Andrew D.Laptev <a.d.laptev@gmail.com>",
"description": "TypeScript-first ONVIF library for Node.js.",
"description": "TypeScript-first ONVIF library for Node.js. Supports Profiles S/T/G/M/C/A/D, WS-Discovery, WS-Security/Digest, Events, Media/Media2, PTZ, Recording/Replay.",
"main": "build/index.js",
"types": "build/index.d.ts",
"files": [
Expand Down
2 changes: 2 additions & 0 deletions src/compatibility/cam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,8 @@ export class Cam extends EventEmitter {
// v0.x used `warning`; Onvif emits `warn`
this.onvif.on(Onvif.WARN, relay('warning'));

// Same newListener/removeListener timing as Onvif: length === 0 is correct
// (newListener fires before add; removeListener fires after remove).
this.on('newListener', (name) => {
if (name === 'event' && this.listeners('event').length === 0) {
this.onvif.on(Onvif.EVENT, this.onOnvifEvent);
Expand Down
46 changes: 41 additions & 5 deletions src/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,12 @@ export class Subscription extends EventEmitter<SubscriptionEvents> {
* @private
*/
private dontWantToRestartEvent = false;
/**
* Bumped on every subscribe/unsubscribe intent so an in-flight CreatePullPoint can tell
* it was superseded (rapid on/off/on via Onvif `event` listeners, overlapping subscribe()).
* Do not gate unsubscribe behind an in-flight Create — that deadlocks when Create is slow.
*/
private lifecycleGen = 0;
private reconnectTimer?: ReturnType<typeof setTimeout>;
private reconnectTimerResolve?: () => void;

Expand Down Expand Up @@ -639,23 +645,46 @@ export class Subscription extends EventEmitter<SubscriptionEvents> {
});
}

private isLifecycleCurrent(gen: number): boolean {
return !this.dontWantToRestartEvent && gen === this.lifecycleGen;
}

/**
* Create a pull-point subscription and start the background {@link eventPull} loop.
*
* Overlapping subscribe/unsubscribe is coordinated with {@link lifecycleGen}: a Create that
* loses the race Unsubscribes its *own* pull-point by reference (without touching a newer
* winner's {@link subscription}). Unsubscribe stays non-blocking w.r.t. in-flight Create.
*/
async subscribe() {
this.dontWantToRestartEvent = false;
this.subscription = await this.onvif.events.createPullPointSubscription({
const gen = ++this.lifecycleGen;

const created = await this.onvif.events.createPullPointSubscription({
initialTerminationTime: PULL_TERMINATION_TIME,
...this.options,
});
// Store expiry in local wall clock so later Date.now() comparisons survive device clock skew.
if (this.subscription.currentTime && this.subscription.terminationTime) {
this.subscription.terminationTime = localTerminationTime(this.subscription);
if (created.currentTime && created.terminationTime) {
created.terminationTime = localTerminationTime(created);
}
if (this.dontWantToRestartEvent) {
await this.unsubscribe(false);

if (!this.isLifecycleCurrent(gen)) {
// Lost to unsubscribe or a newer subscribe — do not clobber this.subscription.
await this.unsubscribePullPoint(created);
return;
}

// Replace any previous live pull-point (rebuild / rare overlap).
if (this.subscription) {
await this.disposePullPoint(true);
if (!this.isLifecycleCurrent(gen)) {
await this.unsubscribePullPoint(created);
return;
}
}

this.subscription = created;
this.pulling = true;
void this.eventPull();
}
Expand Down Expand Up @@ -857,6 +886,8 @@ export class Subscription extends EventEmitter<SubscriptionEvents> {
async unsubscribe(resetAgent = true) {
this.dontWantToRestartEvent = true;
this.pulling = false;
// Invalidate in-flight subscribe() immediately (must not await Create — would deadlock).
this.lifecycleGen += 1;
this.clearReconnectTimer();
await this.disposePullPoint(resetAgent);
}
Expand All @@ -874,6 +905,11 @@ export class Subscription extends EventEmitter<SubscriptionEvents> {
if (resetAgent) {
this.onvif.events.resetAgent();
}
await this.unsubscribePullPoint(subscription);
}

/** Unsubscribe a concrete pull-point (including one that never became {@link subscription}). */
private async unsubscribePullPoint(subscription: PullPointSubscription): Promise<void> {
try {
const subscriptionParams = getSubscriptionUrlAndHeaders(
this.onvif,
Expand Down
5 changes: 3 additions & 2 deletions src/onvif.ts
Original file line number Diff line number Diff line change
Expand Up @@ -715,12 +715,13 @@ export class Onvif extends EventEmitter<OnvifEvents> {
this.analyticsDevice = lazyService<AnalyticsDevice>(this, () => import('./services/analyticsdevice'));
this.receiver = lazyService<Receiver>(this, () => import('./services/receiver'));

/** Bind event handling to the `event` event */
/**
* Auto pull-point: first `event` listener → subscribe, last removal → unsubscribe.
*/
this.onEventNewListener = (name) => {
if (this.closed) {
return;
}
// if this is the first listener, start pulling subscription
if (name === 'event' && this.listeners(name).length === 0) {
this.events.globalSubscription.subscribe().catch((error) => this.emit(Onvif.EVENT_ERROR, error));
}
Expand Down
Loading