Hikvision HCNetSDK: login, streaming and arming

Two protocols sit behind one login call, alarms arrive through three modes, and video has nine link modes. Each choice changes the parser.

Before the AI task, three connections

Two earlier guides cover what is in the SDK archive and how the 42 AI Open Platform request URIs are called. Neither of them gets a detection from the device to your platform, because the AI task only produces the result. Reading that result requires an alarm channel, and looking at the scene requires a stream handle. Both of those run on the SDK private protocol, which is a different path from the JSON endpoints.

This page covers the three connections a working deployment has to make first: login, streaming and arming. It also records what the 1466 page General guide does not say clearly about them, since those are the points where an integration loses a day.

One login call, two protocols

Section 1.1 opens with the design fact that is easy to miss: the network communication of the SDK uses a private protocol built on TCP/IP, and the text protocol support is an addition. A set of APIs and structures exists so that a third party platform can pass through a request URL and a request or response message. In other words the text protocol is not a second SDK. It is a mode of the same library, and the mode is selected at login.

The selection lives in the login structure. The byLoginMode member takes three values: 0 for the private protocol, 1 for the text protocol, and 2 for self-adaptive, which the same table restricts to devices whose protocol type is unknown and which explicitly does not support asynchronous login. The wPort member carries both defaults in its description: 8000 when logging in by private protocol and 80 when logging in by text protocol.

That single field explains most of the confusion around Hikvision integrations. A platform that wants to talk HTTP to the recorder does not add a second library, and a platform that wants the private protocol does not need to disable anything. It logs in differently, on a different port, and the same NET_DVR_Login_V40 returns the same kind of user ID.

One field in the same structure is left unexplained. byUseTransport is described only as whether to enable capability transmission, with 0 as the default and 1 as enabled. The table never says which capability is transmitted or what changes when it is on, so treat it as a field to leave at the default until a specific behaviour has been observed on a device.

What the login structure decides

The login structure has more switches than a first integration usually sets. These are the ones whose values change later behaviour rather than only the handshake.

Member Values What it changes
byLoginMode 0 private, 1 text, 2 self-adaptive Which protocol the whole session uses. Self-adaptive cannot be combined with asynchronous login
wPort 8000 or 80 by protocol Default 8000 for private, 80 for text
bUseAsynLogin 0 sync, 1 async In async mode the result arrives through cbLoginResult, and that callback is only valid when this member is 1
byHttps 0 no, 1 yes, 2 self-adaptive Self-adaptive sends both HTTP and HTTPS requests, which is meant for devices whose protocol is unknown
byVerifyMode 0 none, 1 mutual, 2 unidirectional Mutual verification is marked currently not available. Unidirectional requires loading a CA certificate with NET_DVR_SetSDKLocalCfg under NET_SDK_LOCAL_CFG_CERTIFICATION before login
byProxyType 0 none, 1 standard, 2 EHome Which proxy path the session takes

The hard ceiling is worth planning around. The remarks for NET_DVR_Login_V40 state that up to 2048 users can be logged in to HCNetSDK at the same time, and that returned user IDs range from 0 to 2047. That is a limit of one process, not one device. A platform that opens a fresh login per camera per worker thread will hit it long before a mid-size site is covered, and the error code at that point is 52 rather than a connection failure.

Linux: the library path has two answers

The package ships two conflicting instructions for making the libraries discoverable, and neither document mentions the other.

The readme.txt in the doc directory offers four methods: add the paths to LD_LIBRARY_PATH, append them to /etc/ld.so.conf and run ldconfig, copy the libraries into /lib64 or /usr/lib64, or set -Wl,-rpath in the build. It recommends keeping libhcnetsdk.so, libHCCore.so, libhpr.so and the HCNetSDKCom directory together, in which case no path configuration is needed at all.

The API reference offers a fifth method that the readme does not name. NET_DVR_SetSDKInitCfg takes the enumeration value 2, NET_SDK_INIT_CFG_SDK_PATH, and a pointer to NET_DVR_LOCAL_SDK_PATH, and its remarks state that the call must happen before NET_DVR_Init. That ordering is the part that goes wrong: a platform that initialises the SDK at start-up and sets the path afterwards gets a working library with missing modules.

The component count is a practical check on a failed deployment. The Linux lib directory holds 14 shared objects and the HCNetSDKCom directory holds 17 more. Preview, playback, alarm, display, device configuration, voice talk and stream transport are separate modules, so a missing HCNetSDKCom does not produce one error. It produces a library that logs in and then fails per feature, which is why the missing directory looks like a device problem.

There is one more mismatch worth recording before it costs a build cycle. The enumeration values 3 and 4, NET_SDK_INIT_CFG_LIBEAY_PATH and NET_SDK_INIT_CFG_SSLEAY_PATH, are documented for the OpenSSL libraries of version 1.1.1 and 1.0.2, and the descriptions give libcrypto.so and libssl.so as the Linux file names. The package itself ships libcrypto.so.3 and libssl.so.3. A platform that follows the enumeration table and points at a 1.1.1 build is pointing somewhere the package does not go.

Streaming: nine link modes, two legends for stream type

Live view starts with NET_DVR_RealPlay_V40 and a NET_DVR_PREVIEWINFO structure. The structure has two enumerations that behave differently from the sample code beside them.

dwLinkMode has nine values in the structure table: 0 TCP, 1 UDP, 2 multicast, 3 RTP, 4 RTP over RTSP, 5 RTSP over HTTP, 6 HRUDP, 7 RTSP over HTTPS, and 8 NPQ for network protocol quality. The sample code in section 5.1 lists only the first six, with a comment that stops at RTSP over HTTP. The extra three are the ones that matter on a filtered network, so read the structure table rather than the sample.

dwStreamType has two legends in the same document. The structure table describes 0 as main stream, 1 as sub-stream, 2 as third stream and 3 as virtual stream. The sample code comment describes 0 as main, 1 as sub, 2 as stream 3 and 3 as stream 4. Values 0 and 1 agree, and 2 and 3 do not. A channel with four physical encodings and a channel with a virtual stream are different things, so confirm against the device before treating 3 as the fourth encoding.

Three operational details in the same section are easy to lose. A null hPlayWnd means the SDK does not decode, and the stream then has to be picked up with NET_DVR_SetRealDataCallBack or NET_DVR_SetStandardDataCallBack in PS or RTP container format. When the platform goes offline, the device keeps the streaming connection for 10 seconds, which is stated in both NET_DVR_RealPlay_V40 and NET_DVR_RealPlaySpecial. On Linux, changing the window size during live view requires NET_DVR_ChangeWndResolution to notify the player library first, while Windows adapts without a call.

Streaming by URL is a separate entry point, not a parameter of the same one. NET_DVR_RealPlaySpecial takes NET_DVR_PREVIEWINFO_SPECIAL, whose sURL member accepts a full address such as rtsp://admin:[email protected]:554/Streaming/Channels/101?transportmode=unicast. That structure has its own dwLinkMode list of 0, 1, 3, 4 and 5, with the value 2 printed in the table with no description at all. The URL template itself is documented in the remarks of a different structure, NET_DVR_PU_STREAM_URL, as {rtsp://ip[:port]/urlExtension}[?username=username][?password=password][?linkmode=linkmode].

Alarms: three modes and a fourth path

The General guide devotes four sections to getting an event out of a device, and they are not variations of one method. Section 7.7 arms, section 7.8 listens, section 7.9 subscribes, and section 7.10 searches.

Mode Entry point Login required Direction
Arming NET_DVR_SetupAlarmChan_V50 after NET_DVR_SetDVRMessageCallBack_V50 Yes Platform connects to device, device uploads
Listening NET_DVR_StartListen_V30 Optional Device connects to a host and port configured on the device
Subscription NET_DVR_SetupAlarmChan_V50 with a SubscribeEvent document Yes Arming channel, filtered by event type
Remote config NET_DVR_StartRemoteConfig with NET_DVR_GET_ALARM_INFO, command 4193 Yes Persistent connection, history or real time

Arming and subscription are the same function call, which is the most surprising part of the design. The third parameter of NET_DVR_SetupAlarmChan_V50 is a data buffer and the fourth is its length. Passing null with a length of 0 arms the channel and the device uploads everything it is configured to report. Passing a SubscribeEvent document turns the same call into a subscription, and the remarks confirm that the API supports specifying which alarm or event types the device uploads. A platform that wants fewer events on a busy recorder changes one argument rather than the architecture.

Listening inverts the direction. The remarks for NET_DVR_StartListen_V30 state that the management host server address or the listening host server address configured on the device has to point at the platform IP, and the port has to match the local listening port. The sample uses 7200. Login is listed as optional in section 7.8, which makes this the only one of the four modes that can receive events from a device the platform never authenticates against.

Subscription is the only mode with a capability gate in front of it, and the gate follows the same pattern as the AI Open Platform one. The first step calls NET_DVR_STDXMLConfig with GET /ISAPI/System/capabilities, and the guide says to check for the isSupportSubscribeEvent node in XML_DeviceCap. If the node is returned with a value of true, continue; otherwise the device does not support subscription. A node that is absent is not a false value, which is the same trap as isSupportAIOpenPlatform. The second step reads /ISAPI/Event/notification/subscribeEventCap for the supported types.

The fourth path is the least used and often the most useful. NET_DVR_StartRemoteConfig with command 4193 returns alarms through a persistent connection, and the guide notes that leaving the start and stop times in NET_DVR_ALARM_SEARCH_COND unset turns the same call into a real time feed. That gives a platform a way to receive events without opening an arming channel at all.

The parameters that change the payload shape

The arming structure decides what arrives in the callback, and one member decides whether the receiving code can parse it at all.

byRetAlarmTypeV40 selects the encoding of the four basic alarm classes. At 0, motion detection, video loss, video tampering and alarm input arrive as COMM_ALARM_V30 carrying NET_DVR_ALARMINFO_V30. At 1, the same alarms arrive as COMM_ALARM_V40 carrying NET_DVR_ALARMINFO_V40 in variable size. A callback that copies a fixed structure length out of the buffer works on 0 and reads the wrong bytes on 1, so this member and the callback parser have to be decided together.

byLevel is a priority, not a protocol level: 0 is high, 1 is medium and 2 is low. Every sample in the guide sets 1. The name invites a reading where 1 means level one of something, and the structure table is the only place that says otherwise.

byAlarmInfoType looks general and is not. It selects the intelligent traffic alarm structure only: 0 for the old NET_DVR_PLATE_RESULT and 1 for the new NET_ITS_PLATE_RESULT. On a project without plate recognition it changes nothing, even though the samples set it to 1 in every arming example.

bySupport bit 0 is inverted relative to intuition. It encodes whether to upload a picture, with 0 meaning yes and 1 meaning no. A platform that sets the bit to enable picture upload disables it.

byDeployType distinguishes arming through client software from real time arming, with 0 and 1 respectively. The wording is easy to read as a deployment environment rather than as the arming path.

Four callback surprises

The first is that the callback index is not a filter. NET_DVR_SetDVRMessageCallBack_V50 accepts an index from 0 to 15 and supports 16 callbacks at once, but its remarks state that all alarm and event information is returned in each configured callback function. Registering four callbacks for four event classes means four calls each carrying everything. Dispatch has to happen inside the callback on lCommand.

The second is priority. The remarks for NET_DVR_StartListen_V30 state that its callback takes precedence over other callback functions, and that if it is configured, the others do not receive alarm information at all. A platform that adds listening as a fallback silently stops receiving through its arming channel.

The third is how subscription failure is reported. It does not come through the alarm command. The callback has to be registered for COMM_ALARM_SUBSCRIBE_EVENT, and the result arrives in XML_SubscribeEventResponse. Without that registration a rejected subscription looks like a device that never detects anything.

The fourth is the text protocol command. Under the text protocol the callback receives COMM_ISAPI_ALARM, command number 0x6009, and pAlarmInfo has to be read as NET_DVR_ALARM_ISAPI_INFO. The same paragraph in sections 7.7 and 7.8 states this twice, once for arming and once for listening.

Error codes: 327 names in six groups

Appendix D of the General guide is the SDK error table, and it is larger than the part most integrations ever read. It lists 327 named codes from 0 to 3504, grouped as general errors, RTSP communication library errors, software decoding library errors, container format conversion library errors, two way audio library errors, and QoS stream control library errors. NET_DVR_GetLastError returns the number and NET_DVR_GetErrorMsg returns the text, and a platform should log both plus the call name.

The general group covers the first 96 entries and is where an integration spends its first day.

Code Name Meaning in practice
1 NET_DVR_PASSWORD_ERROR Incorrect user name or password
2 NET_DVR_NOENOUGHPRI No permission for this account
3 NET_DVR_NOINIT SDK not initialised, or initialised after the failing call
7 NET_DVR_NETWORK_FAIL_CONNECT Device offline or network timed out
11 NET_DVR_NETWORK_ERRORDATA Data illegal, often a structure the device does not accept for remote configuration
12 NET_DVR_ORDER_ERROR API called in the wrong order
17 NET_DVR_PARAMETER_ERROR Empty or invalid parameter, including a wrong structure size
23 NET_DVR_NOSUPPORT Device does not support the function
47 NET_DVR_USERNOTEXIST User ID logged out or unavailable
52 NET_DVR_MAX_USERNUM Device refuses more logins

Three of the limit codes read alike and are not. Code 5, NET_DVR_OVER_MAXLINK, is about the number of connections the device allows. Code 46, NET_DVR_MAX_NUM, is about registrations and live views. Code 52 is about logins. When a platform hits a ceiling during a scale test, the code identifies which ceiling it is, and only one of the three points at the 2048 user limit in the login structure.

Documentation defects in this package

These are the points where the text or its sample code does not match the shipped library. They are recorded because each one costs time when followed literally.

Where Problem
Section 7.7 sample The handle is written LlHandle with a capital L. The same typo appears once in the AI Open Platform guide, so the two documents share a sample template. The shipped consoleDemo/src/Alarm.cpp uses the correct lHandle
Section 7.7 sample The sample calls memcpy with a length of 1024 and a SubscribeEvent literal of roughly 150 bytes as the source, so it reads past the end of that literal. The copy also guarantees a non-zero length, so the branch guarded by if (0 == strlen(szSubscribe)) is unreachable although its comment says Arm
Chapter 12 NET_DVR_SetReconnect is called in 11 samples and is declared in HCNetSDK.h with defaults of 30000 and true, but has no API reference entry, so the difference between the sample value of 10000 and the default is undocumented
Section 12.1.40 The OpenSSL path enumerations 3 and 4 describe 1.1.1 and 1.0.2 library names while the package ships libcrypto.so.3 and libssl.so.3
Structure A.200 against section 5.1 dwStreamType is documented as 3 being a virtual stream and 2 a third stream, while the sample comment calls 3 the fourth stream
Section 5.2 The whole section is two sentences that rely on document links for the function names, and the URL template it needs lives in a different structure's remarks

The minimum function set

Across the three connections, the calls that have to exist are few. Everything else is configuration through a command number or a structure.

Stage Calls
Initialise NET_DVR_SetSDKInitCfg on Linux, then NET_DVR_Init, NET_DVR_SetConnectTime, NET_DVR_SetReconnect
Login NET_DVR_Login_V40, NET_DVR_Logout, NET_DVR_Cleanup
Stream NET_DVR_RealPlay_V40 or NET_DVR_RealPlaySpecial, NET_DVR_SetRealDataCallBack, NET_DVR_StopRealPlay
Alarm NET_DVR_SetDVRMessageCallBack_V50, NET_DVR_SetupAlarmChan_V50, NET_DVR_CloseAlarmChan_V30
Text protocol NET_DVR_STDXMLConfig for any ISAPI request, including the 42 AI Open Platform URIs

The AI endpoints and these three connections are separate interfaces that share one login and one error table. A deployment that treats them as one interface spends its time looking for an AI endpoint that was never going to return an alarm, when the alarm is arriving on the arming channel and the AI result is arriving as an event on the same channel.