Skip to content

About

Light implementation of an onvif server intended for use in resource-constrained devices

Topics

Resources

Stars

96 stars

Watchers

6 watching

Forks

Latest commit

 

History

487 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

onvif_simple_server is a C light implementation of an onvif server (Profile S and Profile T) intended for use in resource-constrained devices.

So:

  • no gsoap
  • no libxml

The XML parsing features are replaced by a wrapper that uses ezxml library and a template based strategy.

About security, you can choose between libtomcrypt, mbedtls or wolfssl to handle authentication.

The web service discovery daemon and the notify server daemon are standalone programs and must be started with command line options.

The onvif server instead runs as CGI and therefore needs an http server that supports the CGI standard (for example httpd from busybox).

Simple also means that it does not implement all the functions required and therefore does not fully comply with the Onvif Conformance Test. But usually is enough to work with an onvif client.

Table of Contents

Build

  • Open the Makefile and edit it to suit your needs. Instead of Makefile rename Makefile.static if you want to build a static binary embedding all libraries (ssl and zlib).
  • Export HAVE_WOLFSSL if you want to use wolfssl or HAVE_MBEDTLS if you want to use mbedtls (default libtomcrypt).
  • Export USE_ZLIB if you want to use compressed template files. In this case, all xml files will be compressed to use less disk space but the server will be slower.
  • Run make
  • Run make test to build and run the unit tests (requires a native C compiler and json-c; no crypto library needed)

Httpd

Create a working example with lighttpd

  • Open extras folder
  • Customize build.sh script, if you want
  • Run ./build.sh
  • Copy the content of the _install folder to /usr/local
  • Run /usr/local/bin/lighttpd -f /usr/local/etc/lighttpd.conf
  • Run your preferred client and test the address http://YOUR_IP:8080/onvif/device_service

Use httpd from busybox

If you are using busybox I prepared a patch to use it with onvif_simple_server. The patch is valid for version 1.36.1.

diff -Naur busybox-1.36.1.ori/networking/httpd.c busybox-1.36.1/networking/httpd.c
--- busybox-1.36.1.ori/networking/httpd.c	2024-01-08 16:45:49.504118695 +0100
+++ busybox-1.36.1/networking/httpd.c	2024-01-08 16:52:14.701167800 +0100
@@ -2406,6 +2406,13 @@
 		}
 		cgi_type = CGI_NORMAL;
 	}
+	else if (is_prefixed_with(tptr, "onvif/")) {
+		if (tptr[6] == '\0') {
+			/* protect listing "cgi-bin/" */
+			send_headers_and_exit(HTTP_FORBIDDEN);
+		}
+		cgi_type = CGI_NORMAL;
+	}
 #endif
 
 	if (urlp[-1] == '/') {

Configuration

onvif_simple_server

onvif_simple server supports the following options but you should use them just for debugging purpose

Usage: onvif_simple_server [-c CONF_FILE] [-d] [-f]

        -c CONF_FILE, --conf_file CONF_FILE
                path of the configuration file
        -d LEVEL, --debug LEVEL
                enable debug with LEVEL = 0..5 (default 0 = fatal errors)
        -f, --conf_help
                print the help for the configuration file
        -h, --help
                print this help
Option Description Example
conf_file the path of the file containing the configuration /etc/onvif_simple_server.conf
debug debug level from 0 to 5 -
conf_help print the help to create a configuration file -

The configuration file is shared between various programs. Below an example of the configuration file for a cam:

model=Yi Hack
manufacturer=Yi
firmware_ver=x.y.z
hardware_id=AFUS
serial_num=AFUSY12ABCDE3F456789
#ifs=wlan0  # optional: override interface (auto-detected from client address if omitted)
port=80
scope=onvif://www.onvif.org/Profile/Streaming
scope=onvif://www.onvif.org/Profile/T
scope=onvif://www.onvif.org/hardware
scope=onvif://www.onvif.org/name
user=
password=
#Advanced options
adv_enable_media2=0
adv_enable_imaging=0
adv_enable_analytics=0
adv_fault_if_unknown=0
adv_fault_if_set=0
adv_synology_nvr=0
#Profile M (optional)
analytics_file=/tmp/onvif_simple_server/analytics.json
#Imaging service (optional)
imaging_set_command=/usr/local/bin/set_imaging
imaging_focus_command=/usr/local/bin/set_focus
imaging_status_command=/usr/local/bin/get_focus
imaging_focus_auto=1
imaging_brightness=0.5
imaging_contrast=0.5
imaging_saturation=0.5
imaging_sharpness=0.5
imaging_ircut_on=1
imaging_wb_auto=1
imaging_exposure_auto=1
imaging_wdr_on=0
#SetSynchronizationPoint (optional)
sync_point_command=/usr/local/bin/sync_point

#Profile 0
name=Profile_0
width=1920
height=1080
url=rtsp://%s/ch0_0.h264
snapurl=http://%s/cgi-bin/snapshot.sh?res=high&watermark=yes
type=H264
bitrate=0
framerate=30
audio_encoder=AAC
audio_decoder=G711
metadata=0

#Profile 1
name=Profile_1
width=640
height=360
url=rtsp://%s/ch0_1.h264
snapurl=http://%s/cgi-bin/snapshot.sh?res=low&watermark=yes
type=H264
bitrate=0
framerate=30
audio_encoder=AAC
audio_decoder=NONE

#PTZ
ptz=1
min_step_x=0
max_step_x=360
min_step_y=0
max_step_y=180
min_step_z=0
max_step_z=0
get_position=/tmp/sd/yi-hack/bin/ipc_cmd -g
is_moving=/tmp/sd/yi-hack/bin/ipc_cmd -u
move_left=/tmp/sd/yi-hack/bin/ipc_cmd -m left -s %f
move_right=/tmp/sd/yi-hack/bin/ipc_cmd -m right -s %f
move_up=/tmp/sd/yi-hack/bin/ipc_cmd -m up -s %f
move_down=/tmp/sd/yi-hack/bin/ipc_cmd -m down -s %f
move_in=/tmp/sd/yi-hack/bin/ipc_cmd -m in -s %f
move_out=/tmp/sd/yi-hack/bin/ipc_cmd -m out -s %f
move_stop=/tmp/sd/yi-hack/bin/ipc_cmd -m stop -t %s
move_preset=/tmp/sd/yi-hack/bin/ipc_cmd -p %d
goto_home_position=/tmp/sd/yi-hack/bin/ipc_cmd -p 0
set_preset=/tmp/sd/yi-hack/script/ptz_presets.sh -a add_preset -n %d -m %s
set_home_position=/tmp/sd/yi-hack/script/ptz_presets.sh -a set_home_position
remove_preset=/tmp/sd/yi-hack/script/ptz_presets.sh -a del_preset -n %d
jump_to_abs=/tmp/sd/yi-hack/bin/ipc_cmd -j %f,%f,%f
jump_to_rel=/tmp/sd/yi-hack/bin/ipc_cmd -J %f,%f,%f
get_presets=/tmp/sd/yi-hack/script/ptz_presets.sh -a get_presets

#RELAY OUTPUTS
#Relay 0
idle_state=open
close=/usr/local/bin/set_relay -n 0 -a close
open=/usr/local/bin/set_relay -n 0 -a open
#Relay 1
idle_state=open
close=/usr/local/bin/set_relay -n 1 -a close
open=/usr/local/bin/set_relay -n 1 -a open

#EVENT
events=1
#Event 0
topic=tns1:VideoSource/MotionAlarm
source_name=Source
source_type=tt:ReferenceToken
source_value=VideoSourceToken
input_file=/tmp/onvif_notify_server/motion_alarm
#Event 1
topic=tns1:RuleEngine/MyRuleDetector/PeopleDetect
source_name=VideoSourceConfigurationToken
source_type=xsd:string
source_value=VideoSourceToken
input_file=/tmp/onvif_notify_server/human_detection
#Event 2
topic=tns1:RuleEngine/MyRuleDetector/VehicleDetect
source_name=VideoSourceConfigurationToken
source_type=xsd:string
source_value=VideoSourceToken
input_file=/tmp/onvif_notify_server/vehicle_detection
#Event 3
topic=tns1:RuleEngine/MyRuleDetector/DogCatDetect
source_name=VideoSourceConfigurationToken
source_type=xsd:string
source_value=VideoSourceToken
input_file=/tmp/onvif_notify_server/animal_detection
#Event 4
topic=tns1:RuleEngine/MyRuleDetector/BabyCryingDetect
source_name=AudioSourceConfigurationToken
source_type=xsd:string
source_value=AudioSourceToken
input_file=/tmp/onvif_notify_server/baby_crying
#Event 5
topic=tns1:AudioAnalytics/Audio/DetectedSound
source_name=AudioSourceConfigurationToken
source_type=tt:ReferenceToken
source_value=AudioSourceToken
input_file=/tmp/onvif_notify_server/sound_detection

Note:

  • you can use 1 or 2 profiles.

  • Actually only type=h264 is supported on Profile S and both type=h264 and type=h265 are supported in Profile T. This doesn't mean that if your camera is h265 then it does not work with Profile S. It depends on your onvif client implementation.

  • ipc_cmd is just an example of a local binary that handles ptz, use the specific program of your cam

    If the external command uses stdout, please append a redirect to /dev/null to avoid garbage in the html content

    example: move_right=/tmp/sd/yi-hack/bin/ipc_cmd -m right > /dev/null

  • %s, %d and %f are placeholders replaced runtime with the proper parameter

  move_left=/tmp/sd/yi-hack/bin/ipc_cmd -m left -s %f
  %f is the velocity of the pan movement
  move_right=/tmp/sd/yi-hack/bin/ipc_cmd -m right -s %f
  %f is the velocity of the pan movement
  move_up=/tmp/sd/yi-hack/bin/ipc_cmd -m up -s %f
  %f is the velocity of the tilt movement
  move_down=/tmp/sd/yi-hack/bin/ipc_cmd -m down -s %f
  %f is the velocity of the tilt movement
  move_in=/tmp/sd/yi-hack/bin/ipc_cmd -m in -s %f
  %f is the velocity of the zoom movement
  move_out=/tmp/sd/yi-hack/bin/ipc_cmd -m out -s %f
  %f is the velocity of the zoom movement
  move_stop=/tmp/sd/yi-hack/bin/ipc_cmd -m stop -t %s
  %s is what you want to stop: "pantilt", "zoom" or "all"
  move_preset=/tmp/sd/yi-hack/bin/ipc_cmd -p %d
  %d is the number of the preset you want to move
  set_preset=/tmp/sd/yi-hack/script/ptz_presets.sh -a add_preset -n %d -m %s
  %d is the nunmber of the preset you want to update or -1 if you are adding a preset
  %s is the name of the preset you are adding or changing
  remove_preset=/tmp/sd/yi-hack/script/ptz_presets.sh -a del_preset -n %d
  %d is the nunmber of the preset you want to remove
  jump_to_abs=/tmp/sd/yi-hack/bin/ipc_cmd -j %f,%f,%f
  %f are the pan/tilt/zoom coordinates you want to move
  jump_to_rel=/tmp/sd/yi-hack/bin/ipc_cmd -J %f,%f,%f
  %f are the pan/tilt/zoom coordinates you want to move
  • use the same folder for the input files of the events
  • max 8 events are currently supported (relay_output feature uses events messages to get the relay state, so each relay uses 1 event and the sum of events and relays cannot be greater than 8)

Please pay attention: the order of the lines must be respected. Don't mix them!

Brief explanation of some parameters:

Param Description
ifs override the network interface (optional; auto-detected from client address if omitted)
port the TCP port used by your http server
user the user you want to set for WS-UsernameToken authentication, if blank security is disabled
adv_enable_media2 enable media2 methods for Profile T
adv_enable_imaging set to 1 to advertise the Imaging service
adv_enable_analytics set to 1 to enable Profile M: metadata and the Analytics service (needs adv_enable_media2=1), see Profile M
analytics_file the analytics description file, written by the analytics pipeline
adv_fault_if_unknown try to set to 1 if your ONVIF client is not able to connect to the device
adv_fault_if_set try to set to 1 if your ONVIF client is not able to connect to the device
adv_synology_nvr try to set to 1 to improve compatibility, if you are using a Synology NVR
imaging_set_command the binary command run on SetImagingSettings, see below (empty = settings are read-only)
imaging_focus_command the binary command run on Move and Stop, see below (empty = no focus control is advertised)
imaging_status_command optional command for GetStatus, see below (empty = the focus status is reported as UNKNOWN)
imaging_* the current values reported by GetImagingSettings: brightness, contrast, saturation and sharpness range from 0.0 to 1.0, the others are 1 or 0
sync_point_command the binary command run on SetSynchronizationPoint, see below (empty = the request is only acknowledged)
url the url of your streaming service (it is not provided by onvif server)
snapurl the url of your snapshot service (tipically an http url that provides a jpg image)
audio_decoder set to G711 or AAC if your device support an audio back channel
metadata set to 1 if the stream of the profile carries a metadata track (needs adv_enable_analytics=1)
ptz 1 if onvif_simple_server can control PTZ, 0 otherwise
max_step_* max values of x and y movements reported by the cam (min = 0)
move_* the binary command that moves the PTZ controls, onvif_simple_server will run it with a system call
idle_state the relay state when inactive ("close" or "open")
close the binary command that closes the relay, onvif_simple_server will run it with a system call
open the binary command that opens the relay, onvif_simple_server will run it with a system call
events set to 1 to enable PullPoint, 2 to enable Base Subscription or 3 to enable both
topic the topic of the event
source_name the source name inside the Notify message; each further source_name adds a source item (described events only)
source_type the source type inside the Notify message
source_value the source value inside the Notify message
data_name the name of the data item; makes the event a described event, see below
data_type the type of the data item, e.g. tt:StringList (described events only)
is_property set to 0 for an event that is not a property (described events only, default 1)
input_file the file created when the event is fired

Check the code for information.

Described events

An event with data_name and data_type is a described event. Its data value is the content of input_file, not the existence of the file. Example, the standard object detection event (ONVIF Analytics, Annex A):

topic=tns1:RuleEngine/ObjectDetection/Object
is_property=0
source_name=VideoSource
source_type=tt:ReferenceToken
source_value=VideoSourceToken
source_name=AnalyticsConfiguration
source_type=tt:ReferenceToken
source_value=AnalyticsConfigToken
source_name=Rule
source_type=xsd:string
source_value=ObjectRule
data_name=ClassTypes
data_type=tt:StringList
input_file=/tmp/onvif_notify_server/object_detection

In a JSON file, "sources": [ { "name": ..., "type": ..., "value": ... } ] replaces the three source keys. There is_property is a JSON boolean (true or false).

  • source_type and source_value belong to the source_name before them.
  • A described event has 1 to 4 source items. Each needs a name, a type and a value.
  • Names have at most 256 characters and no spaces, control characters, %, <, >, & or quotes.
  • Names are unique within the event, the data name included.
  • Types use the prefix xsd or tt.
  • A tt:ReferenceToken value has at most 64 characters, other source values 160. They have no % and no control characters.
  • An event that breaks one of these rules is ignored with an error in the log.
  • So is an event with only one of data_name and data_type.
  • So is a plain event with a second source_name or with is_property=0.
  • The file holds the value, e.g. Human Vehicle for a tt:StringList. A missing file is an empty value.
  • Whitespace runs count as one space. The value has at most 127 bytes, no control characters and no %.
  • The file has at most 1024 bytes. A file with an invalid value is ignored.
  • The server sends a message when the value changes. Writing the same value again sends nothing.
  • Write the file to a temporary name in the same folder and rename it. A file written in place can be read half written.
  • A property event (is_property=1) sends its current value to new subscriptions and on SetSynchronizationPoint.
  • A non-property event (is_property=0) sends only changes, without PropertyOperation.
  • A pull point keeps the last 8 changes of each non-property event.
  • Restart onvif_notify_server after an update: it shares memory with the CGI.
  • Update the template folders together with the binaries. All events use new templates.
  • A vendor namespace for an extension topic also goes into notify_files/Notify_start.xml.

wsd_simple_server

wsd_simple server supports the following options

Usage: /tmp/sd/yi-hack/bin/wsd_simple_server [-i INTERFACE] -x XADDR [-m MODEL] [-n MANUFACTURER] [-s SCOPES] -p PID_FILE [-t TEMPLATE_DIR] [-f] [-d LEVEL]

        -i, --if_name
                network interface (auto-detected; use -i to force a specific interface)
        -x, --xaddr
                resource address template (use %s as placeholder for the detected IP;
                IPv6 is auto-detected and the address is bracketed automatically)
        -m, --model
                model name
        -n, --hardware
                hardware manufacturer
        -s, --scopes
                space-separated scope list (default: built-in list)
        -p, --pid_file
                pid file
        -t, --template_dir
                template directory (default: /etc/wsd_simple_server)
        -f, --foreground
                don't daemonize
        -d LEVEL, --debug LEVEL
                enable debug with LEVEL = 0..5 (default 0 = log fatal errors)
        -h, --help
                print this help
Option Description Example
if_name network interface (optional; auto-detected if omitted) eth0
xaddr resource address for the ONVIF server http://%s/onvif/device_service
scopes space-separated scopes sent in Hello and ProbeMatches; replaces the default list "onvif://www.onvif.org/type/video_encoder onvif://www.onvif.org/name/Camera"
pid_file is the pid file created by the daemon /var/run/wsd_simple_server.pid
template_dir the folder containing template files /etc/wsd_simple_server
foreground don't fork -
debug debug level from 0 to 5 -

%s is replaced runtime with the IP address of the device.

The default scopes advertise video_encoder, audio_encoder and ptz on every device. They are not taken from the scope= entries of the onvif_simple_server config. Use -s to send only what the device supports, e.g. the same list as scope=, so that discovery matches GetScopes.

Each message should fit one UDP datagram of 1232 bytes (IPv6 minimum MTU). Larger messages are logged with a warning, as they may be fragmented. The templates are sent as they are, comments included, so keep them free of comments.

IPv6 / dual-stack WS-Discovery

IPv6 is auto-detected.

  • Uses a single AF_INET6 dual-stack UDP socket (IPV6_V6ONLY=0) bound to :::3702
  • Joins the IPv4 WSD multicast group 239.255.255.250:3702 via MCAST_JOIN_GROUP (RFC 3678)
  • Joins the IPv6 WSD multicast group FF02::C:3702 (WS-Discovery 1.1)
  • Each incoming Probe is dispatched by address family: IPv4-mapped senders (::ffff:x.x.x.x) get the IPv4 xaddr; native IPv6 senders get the IPv6 xaddr6

IPv6 is gracefully degraded: if the IPv6 multicast join fails, the server continues in IPv4-only mode.

Auto-detection for IPv6 scans interfaces via getifaddrs, preferring a global unicast address over link-local. The routing-table connect trick used for IPv4 does not work here: Linux requires sin6_scope_id != 0 for link-local multicast destinations such as FF02::C. On multi-homed systems use -i.

Note: onvif_simple_server IPv6 advertising is tracked separately.

onvif_notify_server

onvif_notify_server checks the files related to the events and sends the notify message when an event is fired.

  • When the file is created a new notify message with state "true" is sent to all subscribers.
  • When the file is deleted a new notify message with state "false" is sent to all subscribers.
  • When a Synchronization Point is requested from an onvif client, a new Notify message with the current state is sent to all subscribers.
  • A described event sends a message when the content of its file changes.

The process can use inotify interface if supported from the device, otherwise it can use the standard "access" function.

onvif_notify_server supports the following options but you should use them just for debugging purpose

Usage: /tmp/sd/yi-hack/bin/onvif_notify_server [-c CONF_FILE] [-p PID_FILE] [-t TEMPLATE_DIR] [-f] [-d LEVEL]

        -c CONF_FILE, --conf_file CONF_FILE
                path of the configuration file
        -p PID_FILE, --pid_file PID_FILE
                pid file
        -t TEMPLATE_DIR, --template_dir TEMPLATE_DIR
                template directory (default: /tmp/sd/yi-hack/etc/onvif_notify_server)
        -f, --foreground
                don't daemonize
        -d LEVEL, --debug LEVEL
                enable debug with LEVEL = 0..5 (default 0 = log fatal errors)
        -h, --help
                print this help
Option Description Default
conf_file the path of the file containing the configuration /etc/onvif_simple_server.conf
pid_file the path of the pid file if you want to change it /var/run/onvif_notify_server.pid
foreground don't fork -
debug debug level from 0 to 5 0

Compatibility

I tested this program with the following clients:

  • Onvif Device Manager (Windows)
  • Synology Surveillance Station (DSM 6.x and 7.x)
  • Onvier (Android)
  • Frigate
  • Unifi Protect

If you test it with other clients or NVR, please let me know opening a issue or a pull request.

Services at a glance (details of each function below):

Service Needs configuration Notes
Device no Read-only information plus SystemReboot
Media / Media2 profiles Stream and snapshot URIs, encoder and source configurations
PTZ ptz=1 and the PTZ commands Each action runs the configured shell command
DeviceIO relay outputs Relay state is changed by the configured open and close commands
Events event entries Pull-point and basic notification subscriptions
Analytics adv_enable_analytics=1 and analytics_file Fixed analytics modules and rules, read-only, see Profile M

Below a list of the implemented functions, all other functions return a generic soap fault.

Device

GetCapabilities
GetDeviceInformation
GetDiscoveryMode
GetNetworkInterfaces
GetScopes
GetServices
GetServiceCapabilities
GetSystemDateAndTime
GetUsers
GetWsdlUrl
GetEndpointReference
GetNetworkDefaultGateway
GetNetworkProtocols
GetHostname
GetDNS
GetNTP
SystemReboot

Analytics

CreateAnalyticsModules
CreateRules
DeleteAnalyticsModules
DeleteRules
GetAnalyticsModules
GetRules
GetServiceCapabilities
GetSupportedAnalyticsModules
GetSupportedMetadata
GetSupportedRules

Imaging

GetImagingSettings
GetMoveOptions
GetOptions
GetServiceCapabilities
GetStatus
Move
SetImagingSettings
Stop

SetImagingSettings validates the request and runs imaging_set_command with the requested values in environment variables, so nothing from the request reaches the command line: ONVIF_IMAGING_BRIGHTNESS, ONVIF_IMAGING_CONTRAST, ONVIF_IMAGING_COLOR_SATURATION, ONVIF_IMAGING_SHARPNESS (0.0 to 1.0), ONVIF_IMAGING_IRCUT_FILTER (ON/OFF), ONVIF_IMAGING_WHITE_BALANCE (AUTO/MANUAL), ONVIF_IMAGING_EXPOSURE (AUTO/MANUAL) and ONVIF_IMAGING_WIDE_DYNAMIC_RANGE (ON/OFF). ONVIF_IMAGING_AUTO_FOCUS_MODE (AUTO/MANUAL) is set the same way when focus control is enabled. Only the settings present in the request are set. A non-zero exit status is reported to the client as a fault.

Move (continuous focus only) and Stop run imaging_focus_command with ONVIF_IMAGING_FOCUS_SPEED from -1.0 (near) to 1.0 (far); Stop passes 0. imaging_status_command is run by GetStatus and must print <position> <state> on one line, with the position from 0.0 to 1.0 and the state IDLE, MOVING or UNKNOWN. Anything else is reported as position 0 and UNKNOWN. imaging_focus_auto is the AutoFocusMode reported by GetImagingSettings.

DeviceIO

GetAudioOutputs
GetAudioSources
GetRelayOutputOptions
GetRelayOutputs
GetServiceCapabilities
GetVideoSources
SetRelayOutputSettings
SetRelayOutputState

Events

CreatePullPointSubscription
GetEventProperties
GetServiceCapabilities
PullMessages
Renew
SetSynchronizationPoint
Subscribe
Unsubscribe

Media

GetAudioDecoderConfiguration
GetAudioDecoderConfigurationOptions
GetAudioDecoderConfigurations
GetAudioEncoderConfiguration
GetAudioEncoderConfigurationOptions
GetAudioEncoderConfigurations
GetAudioOutputConfiguration
GetAudioOutputConfigurationOptions
GetAudioOutputConfigurations
GetAudioOutputs
GetAudioSources
GetAudioSourceConfiguration
GetAudioSourceConfigurationOptions
GetAudioSourceConfigurations
GetCompatibleAudioDecoderConfigurations
GetCompatibleAudioEncoderConfigurations
GetCompatibleAudioOutputConfigurations
GetCompatibleAudioSourceConfigurations
GetCompatibleVideoEncoderConfigurations
GetCompatibleVideoSourceConfigurations
GetGuaranteedNumberOfVideoEncoderInstances
GetProfile
GetProfiles
GetServiceCapabilities
GetSnapshotUri
GetStreamUri
GetVideoSourceConfiguration
GetVideoSourceConfigurationOptions
GetVideoSourceConfigurations
GetVideoEncoderConfiguration
GetVideoEncoderConfigurationOptions
GetVideoEncoderConfigurations
GetVideoSources
SetSynchronizationPoint

Media2

GetAnalyticsConfigurations
GetAudioDecoderConfigurationOptions
GetAudioDecoderConfigurations
GetAudioEncoderConfigurationOptions
GetAudioEncoderConfigurations
GetAudioOutputConfigurationOptions
GetAudioOutputConfigurations
GetAudioSourceConfigurationOptions
GetAudioSourceConfigurations
GetMetadataConfigurationOptions
GetMetadataConfigurations
GetProfiles
GetServiceCapabilities
GetSnapshotUri
GetStreamUri
GetVideoEncoderConfigurationOptions
GetVideoEncoderConfigurations
GetVideoSourceConfigurationOptions
GetVideoSourceConfigurations
GetVideoSourceModes
SetSynchronizationPoint

SetSynchronizationPoint (Media and Media2) runs sync_point_command with ONVIF_PROFILE_TOKEN set to the requested profile name. The command should make the stream source send a key frame, and start a new metadata document if the stream carries one. It must return quickly. A non-zero exit status is reported to the client as a fault. Without sync_point_command the request is acknowledged and nothing else happens.

GetStreamUri (Media and Media2) ignores the requested protocol and always returns the url of the profile. A client that asks for RTSP over HTTP gets the same url, so the RTSP server must accept RTSP-over-HTTP tunneling on that port. Requests for multicast or RTSPS get this url as well.

PTZ

AbsoluteMove
ContinuousMove
GetConfiguration
GetConfigurationOptions
GetConfigurations
GetNode
GetNodes
GetPresets
GetServiceCapabilities
GetStatus
GotoHomePosition
GotoPreset
RelativeMove
RemovePreset
SetHomePosition
SetPreset
Stop

Profile M

Profile M support is opt-in and read-only, like the rest of the server. The server describes the metadata and the analytics. It does not produce them. An analytics pipeline produces the metadata stream, the events and a description file.

Setup

  • Set adv_enable_media2=1 and adv_enable_analytics=1.
  • Set metadata=1 in every profile whose stream carries a metadata track.
  • Set analytics_file to the description file the pipeline writes.
  • Add scope=onvif://www.onvif.org/Profile/M to the configuration file. In a JSON file, add it to scopes.
  • Add the same scope to the -s option of wsd_simple_server. WS-Discovery does not read the configuration file.
  • Configure the analytics events as usual (topic, source_name, source_type, input_file).

Each profile with metadata=1 has the video source, the metadata configuration and the analytics configuration. Both configurations are fixed: MetadataConfigToken (Analytics=true) and AnalyticsConfigToken. SetSynchronizationPoint runs sync_point_command (see Media2 above).

Description file

{
  "namespace": { "prefix": "ai", "uri": "http://example.com/analytics" },
  "modules": [
    {
      "type": "ai:ObjectDetector",
      "name": "Detector1",
      "parameters": [ { "name": "Sensitivity", "type": "xsd:int", "value": "50" } ],
      "messages": [ { "topic": "tns1:RuleEngine/MyRuleDetector/PeopleDetect" } ],
      "sample_frame_file": "/tmp/onvif_simple_server/object_detector.xml"
    }
  ],
  "rules": [
    {
      "type": "tt:ObjectDetection",
      "name": "ObjectRule",
      "parameters": [ { "name": "ClassFilter", "type": "tt:StringList", "value": "Human Vehicle" } ],
      "messages": [ { "topic": "tns1:RuleEngine/ObjectDetection/Object" } ]
    }
  ]
}
  • The server reads the file on each Profile M request and for the capabilities, so the pipeline can rewrite it at any time.
  • Write it to a temporary name in the same folder and rename it, so no request reads it half written.
  • It is a regular file of at most 256 KiB.
  • namespace is required. Without a valid one the file is ignored.
  • The uri has at most 160 characters, no spaces, no control characters and no %. The prefix has at most 32 characters.
  • The uri is not the xml or xmlns namespace URI.
  • The prefixes tt, tr2, tan, tds, xsd, tns1 and xml... are reserved.
  • Each type is a QName with the namespace prefix. A rule type may also be an ONVIF type like tt:ObjectDetection.
  • Each module is a fixed instance with a unique name.
  • Modules of the same type share the description, messages and sample frame of the first one.
  • rules are optional. Each rule is a fixed instance with a unique name.
  • Rules of the same type need the same parameter names and types. They share the description and messages of the first one.
  • With at least one usable rule, RuleSupport is true and GetSupportedRules, GetRules, CreateRules and DeleteRules answer. Without rules they answer like unknown methods.
  • A rule lists the events it sends as messages, e.g. tns1:RuleEngine/ObjectDetection/Object for tt:ObjectDetection.
  • Configure such an event with the source items VideoSource (VideoSourceToken), AnalyticsConfiguration (AnalyticsConfigToken) and Rule (the rule name). The server does not check them.
  • ONVIF defines the parameter ClassFilter (tt:StringList) for a tt:ObjectDetection rule. Class names have no spaces. The server does not check the parameters.
  • parameters are optional. Each needs name, type and value.
  • A parameter type uses the prefix xsd, tt or the namespace prefix.
  • A value is a JSON string of at most 160 characters, without % or control characters.
  • Each message topic must match a configured event. Source and data items come from the first event with that topic.
  • That event needs a source_name other than its data item name (State, LogicalState for relays).
  • Its source_type, if set, uses the prefix xsd or tt.
  • A described event brings all its source items and its data item.
  • Topics start in tns1 and have at most 3 levels, like all events of the server.
  • One child topic level may use the namespace prefix, e.g. tns1:RuleEngine/ai:Violation (an extension topic, WS-Topics 6.1).
  • Such a topic needs the namespace declared in events_service_files/GetEventProperties_1.xml, events_service_files/PullMessages_1.xml, notify_files/Notify.xml and notify_files/Notify_start.xml.
  • Without it, GetEventProperties is not well-formed.
  • Names, types and topics have at most 256 characters.
  • They must not contain spaces, control characters, %, <, >, & or quotes.
  • At most 16 modules, 16 rules, 16 parameters and 8 messages per module or rule are used.
  • Invalid entries are skipped with an error in the log. Unknown keys are ignored.

The sample frame file holds one tt:Frame with UtcTime. The root has a prefix and declares it itself, as in the example (no default namespace). It shows every element the metadata stream emits. Its shapes sit in the top left quarter of the image: x from -1 to 0, y from 0 to 1. It declares every namespace prefix it uses. Its root does not declare tan. It does not declare the xml or xmlns namespace URI. At most 32 prefix declarations are in scope at any element. No prefix starts with xml. Element and attribute names use only ASCII letters, digits, _, - and .. It is a regular file with at most 64 KiB, 2048 tags, 64 attributes per element and 32 levels below the root. It has no DOCTYPE and no processing instruction other than the XML declaration. It uses only the predefined entities (&lt; etc.) and character references to valid characters. Comments and CDATA sections contain no & and no <?. A module with a missing or invalid sample frame is left out of GetSupportedMetadata only.

<tt:Frame xmlns:tt="http://www.onvif.org/ver10/schema" UtcTime="2026-01-01T00:00:00Z">
  <tt:Object ObjectId="1">
    <tt:Appearance>
      <tt:Shape>
        <tt:BoundingBox left="-0.8" top="0.8" right="-0.2" bottom="0.2"/>
        <tt:CenterOfGravity x="-0.5" y="0.5"/>
      </tt:Shape>
      <tt:Class><tt:Type Likelihood="0.9">Human</tt:Type></tt:Class>
    </tt:Appearance>
  </tt:Object>
</tt:Frame>

Profile M compliance

The server does not implement all of Profile M:

  • AddConfiguration, RemoveConfiguration and SetMetadataConfiguration answer like the other Set* calls. Profile M makes them mandatory.
  • With adv_fault_if_set=1 they answer ter:ConfigModify, else like an unknown method.
  • The spec does not define ter:ConfigModify for AddConfiguration and RemoveConfiguration.
  • The analytics modules are fixed. CreateAnalyticsModules and DeleteAnalyticsModules answer ter:FixedModules. Profile M wants them to work.
  • GetAnalyticsModuleOptions and ModifyAnalyticsModules are not supported (AnalyticsModuleOptionsSupported=false). Profile M allows that.
  • There are no tns1:Media/ProfileChanged and tns1:Media/ConfigurationChanged events. Nothing ever changes here.
  • Without rules there are no rules (RuleSupport=false). Profile M allows that.
  • Rules are fixed. CreateRules answers ter:FixedRules, DeleteRules too for an existing rule. Profile M wants them to work.
  • GetRuleOptions and ModifyRules are not supported (RuleOptionsSupported=false). With adv_empty_if_unknown=1 they answer with an empty response.
  • HTTP Digest is not supported, only WS-UsernameToken. RTSP Digest is the job of the RTSP server.
  • GetStreamUri ignores the requested protocol (see Media2 above).
  • Media has no metadata. Its GetProfiles does not list it. Use Media2.
  • It is not certified. The ONVIF Device Test Tool is for ONVIF members only.
  • It is not tested with Milestone XProtect. Its box timing and its reaction to the SetMetadataConfiguration fault are unknown.

Metadata stream

These rules apply to mediamtx (checked with v1.21.4) and a pipeline that publishes video and metadata to one path:

  • The metadata rtpmap is vnd.onvif.metadata/90000, as the spec spells it.
  • SDP encoding names are case-insensitive. rtponvifmetadatapay writes VND.ONVIF.METADATA/90000, which is fine too.
  • mediamtx passes the rtpmap on unchanged.
  • Send one complete, closed tt:MetadataStream document per frame. Some clients, such as Milestone, parse whole documents only.
  • Set the RTP marker bit on the packet that closes a document.
  • Start a new document on each sync point, and at least every second.
  • A metadata RTP packet has at most 1452 bytes, RTP header included (1442 with RTSPS). mediamtx drops larger ones. Publish over TCP.
  • The limit follows udpMaxPayloadSize (default 1452, at most 1472).
  • Set useAbsoluteTimestamp: true on the path, and send RTCP sender reports on both tracks. Else boxes arrive late, or packets are dropped.
  • Set alwaysAvailable: false on the path. mediamtx rejects alwaysAvailable: true together with useAbsoluteTimestamp. Its offline tracks also cannot carry the metadata track.
  • Sync the device clock with NTP. Some clients hide boxes when the clocks differ.
  • For RTSP Digest, set rtspAuthMethods: [basic, digest]. This needs the internal auth method and plain passwords.
  • RTP over UDP or TCP, RTSP over HTTP and RTSP over WebSocket work on the RTSP listener without extra settings.
  • RTSPS (port 8322) needs rtspEncryption.
  • mediamtx forwards the metadata track over RTSP only. HLS, WebRTC, recording, RTMP and SRT skip it.
  • The GStreamer ONVIF metadata elements (rtponvifmetadatapay) are part of gst-plugins-rs. Most distributions do not package them. Alpine edge does (gst-plugins-rs-rsonvif).

Testing

Run make test to build and run the unit tests in test/. They use the native host compiler and stub mbedtls headers, so no crypto library is required. They need json-c. The tests currently cover the helpers in utils.c (including the checks and values of described events) and the analytics description file loader. The SOAP handlers are not covered yet, so test changes to them against a real client (see Compatibility).

Credits

Thanks to:

License

GPLv3

DISCLAIMER

NOBODY BUT YOU IS RESPONSIBLE FOR ANY USE OR DAMAGE THIS SOFTWARE MAY CAUSE. THIS IS INTENDED FOR EDUCATIONAL PURPOSES ONLY. USE AT YOUR OWN RISK.

Donation

If you like this project, you can buy me a beer :)

Click here or use the below QR code to donate via PayPal

About

Light implementation of an onvif server intended for use in resource-constrained devices

Topics

Resources

Stars

96 stars

Watchers

6 watching

Forks

Releases

Packages

Used by

Contributors

Languages