baichuan

package
v0.2.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: AGPL-3.0 Imports: 21 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package baichuan implements the Reolink Baichuan protocol.

Index

Constants

View Source
const (
	MsgIDLogin = 1
	MsgIDVideo = 3
	MsgIDPing  = 93
	// MsgIDHeartBeat is wrong and is kept only so the reocam heartbeat
	// command still names something. Two firmware dispatch tables agree
	// that 5 is "replay start"; 5 came from rpc_msg_name(5) in the NVR's
	// internal IPC enum, where index 5 is MSG_APP_HB, a different
	// namespace entirely. That is why every model answers 421: the camera
	// is refusing a playback request, not declining a heartbeat. The
	// Baichuan dispatch table calls id 0 "heartbeat".
	MsgIDHeartBeat   = 5
	MsgIDSnap        = 109
	MsgIDTalkAbility = 10
	MsgIDTalkConfig  = 201
	MsgIDTalk        = 202
	MsgIDAbilityInfo = 151
	// MsgIDKeepAlive is the battery camera's keepalive; see docs/udp.md.
	MsgIDKeepAlive = 234
)

Message IDs.

View Source
const (
	ClassLegacy   uint16 = 0x6514 // 20 bytes
	ClassModern20 uint16 = 0x6614 // 20 bytes
	ClassModern24 uint16 = 0x6414 // 24 bytes
	ClassZero     uint16 = 0x0000 // 24 bytes
)

Message classes. The class determines the header length.

View Source
const (
	NegotiateByte byte = 0x12
	DirRequest    byte = 0xdc
	DirReply      byte = 0xdd
)

Negotiation bytes observed on the wire. The protocol notes describe values 0x01..0x03 here, but this firmware sends 0x12 and replies 0x12/0xdd, so we send exactly what a working client sends rather than what the notes say.

View Source
const (
	StreamMain   = "mainStream"
	StreamSub    = "subStream"
	StreamExtern = "externStream"
)

StreamKind names the three streams a camera serves. externStream is the "balanced" middle stream, which most third-party clients leave out.

View Source
const (
	MsgIDHeartbeat                   = 0   // heartbeat
	MsgIDLogout                      = 2   // logout
	MsgIDPreviewStop                 = 4   // preview stop
	MsgIDReplayStart                 = 5   // replay start
	MsgIDGetSysDataTime              = 6   // get sys data time
	MsgIDReplayStart2                = 7   // replay start
	MsgIDGetPresets                  = 8   // get presets
	MsgIDGetDns                      = 9   // get dns
	MsgIDTalkClose                   = 11  // talk close
	MsgIDLogin2                      = 12  // login
	MsgIDSetImagingSettings          = 13  // set imaging settings
	MsgIDFindFileInfo                = 14  // find file info
	MsgIDFindFileInfoNext            = 15  // find file info next
	MsgIDFindFileClose               = 16  // find file close
	MsgIDSetVideoEncoderCfg          = 17  // set video encoder cfg
	MsgIDPtzControl                  = 18  // ptz control
	MsgIDPtzPreset                   = 19  // ptz preset
	MsgIDPtzCruise                   = 20  // ptz cruise
	MsgIDGetEventProperties          = 21  // get event properties
	MsgIDCreatePullPointSubscription = 22  // create pull point subscription
	MsgIDReboot                      = 23  // reboot
	MsgIDUnsubscribe                 = 24  // unsubscribe
	MsgIDIspSet                      = 25  // isp set
	MsgIDIspGet                      = 26  // isp get
	MsgIDLogin3                      = 27  // login
	MsgIDLogout2                     = 28  // logout
	MsgIDGetOsd                      = 29  // get osd
	MsgIDSetOsd                      = 30  // set osd
	MsgIDGetSyscpuload               = 31  // get syscpuload
	MsgIDGetEncbitrate               = 32  // get encbitrate
	MsgIDAlarmReport                 = 33  // alarm report
	MsgIDGetSysversion               = 34  // get sysversion
	MsgIDEmailCfgGet                 = 42  // email cfg get
	MsgIDEmailCfgSet                 = 43  // email cfg set
	MsgIDOsdGet                      = 44  // osd get
	MsgIDOsdSet                      = 45  // osd set
	MsgIDMdGet                       = 46  // md get
	MsgIDMdSet                       = 47  // md set
	MsgIDShelterGet                  = 52  // shelter get
	MsgIDShelterSet                  = 53  // shelter set
	MsgIDRecCfgGet                   = 54  // rec cfg get
	MsgIDRecCfgSet                   = 55  // rec cfg set
	MsgIDGetEnc                      = 56  // get enc
	MsgIDSetEnc                      = 57  // set enc
	MsgIDGetUserCfg                  = 58  // get user cfg
	MsgIDSetUserCfg                  = 59  // Set user cfg
	MsgIDPtzCruise2                  = 64  // ptz cruise
	MsgIDUpdateDev                   = 67  // update_dev
	MsgIDFtpCfgGet                   = 68  // ftp cfg get
	MsgIDFtpCfgSet                   = 69  // ftp cfg set
	MsgIDFtpTaskGet                  = 70  // ftp task get
	MsgIDFtpTaskSet                  = 71  // ftp task set
	MsgIDGetLocalLink                = 76  // get local link
	MsgIDIspBase                     = 78  // isp base
	MsgIDPtzParam                    = 79  // ptz param
	MsgIDVersionInfo                 = 80  // version info
	MsgIDRecTaskGet                  = 81  // rec task get
	MsgIDRecTaskSet                  = 82  // rec task set
	MsgIDRestore                     = 99  // restore
	MsgIDAutoRebootSet               = 100 // auto reboot set
	MsgIDSdcardGet                   = 102 // sdcard get
	MsgIDSdcardFormat                = 103 // sdcard format
	MsgIDGetGeneral                  = 104 // get general
	MsgIDSetGeneral                  = 105 // set general
	MsgIDDstGet                      = 106 // dst get
	MsgIDDstSet                      = 107 // dst set
	MsgIDOsdDefGet                   = 110 // osd def get
	MsgIDShelterDef                  = 111 // shelter def
	MsgIDEncDefGet                   = 112 // enc def get
	MsgIDMdDefGet                    = 113 // md def get
	MsgIDGetUidCfg                   = 114 // get uid cfg
	MsgIDWifiInfoGet                 = 116 // wifi info get
	MsgIDWifiInfoSet                 = 117 // wifi info set
	MsgIDPerformanceInfo             = 122 // performance info
	MsgIDReplaySeek                  = 123 // replay seek
	MsgIDIspDef                      = 132 // isp def
	MsgIDDownloadCut                 = 143 // download cut
	MsgIDIframeRequest               = 189 // iframe request
	MsgIDPtzPreset2                  = 190 // ptz preset
	MsgIDGetAutoUpdate               = 195 // get auto update
	MsgIDSetAutoUpdate               = 196 // set auto update
	MsgIDWifiSignal                  = 115 // wifi signal
	MsgIDWifiSignalScan              = 198 // wifi signal scan
	MsgIDGetSupport                  = 199 // get support
	MsgIDWifiTest                    = 200 // wifi test
	MsgIDLedGet                      = 208 // led get
	MsgIDLedSet                      = 209 // led set
	MsgIDRfCfgGet                    = 212 // rf cfg get
	MsgIDRfCfgSet                    = 213 // rf cfg set
	MsgIDEmailTaskSet                = 216 // email task set
	MsgIDEmailTaskGet                = 217 // email task get
	MsgIDPushTaskSet                 = 218 // push task set
	MsgIDPushTaskGet                 = 219 // push task get
	MsgIDAfLearning                  = 222 // af learning
	MsgIDGetAutoFocusCfg             = 224 // get auto focus cfg
	MsgIDSetAutoFocusCfg             = 225 // set auto focus cfg
	MsgIDCropGet                     = 228 // crop get
	MsgIDCropSet                     = 229 // crop set
	MsgIDAudioTaskSet                = 231 // audio task set
	MsgIDAudioTaskGet                = 232 // audio task get
	MsgIDSetdeviceSleep              = 233 // setdevice sleep
	MsgIDBatteryInfoReport           = 252 // battery info report
	MsgIDBatteryInfoGet              = 253 // battery info get
	MsgIDGet4gModuleInfo             = 257 // get 4g module info
	MsgIDAudioFileInfoGet            = 260 // audio file info get
	MsgIDImportAudio                 = 261 // import audio
	MsgIDSaveAudio                   = 262 // save audio
	MsgIDPlayStopAudio               = 263 // play stop audio
	MsgIDAudioCfgGet                 = 264 // audio cfg get
	MsgIDAudioCfgSet                 = 265 // audio cfg set
	MsgIDAudioAlarmMute              = 266 // audio alarm mute
	MsgIDStartAlarmVideo             = 272 // start alarm video
	MsgIDFindAlarmVideo              = 273 // find alarm video
	MsgIDStopAlarmVideo              = 274 // stop alarm video
	MsgIDAgingTestDataGet            = 285 // aging test data get
	MsgIDAgingTestStart              = 286 // aging test start
	MsgIDFloodlightSet               = 288 // floodlight set
	MsgIDFloodlightTaskGet           = 289 // floodlight task get
	MsgIDFloodlightTaskSet           = 290 // floodlight task set
	MsgIDFloodlightReport            = 291 // floodlight report
	MsgIDZoomFocusGet                = 294 // zoom focus get
	MsgIDZoomFocusStart              = 295 // zoom focus start
	MsgIDThresholdGet                = 296 // threshold get
	MsgIDThresholdSet                = 297 // threshold set
	MsgIDCoverPreview                = 298 // cover preview
	MsgIDAiCfgGet                    = 299 // ai cfg get
	MsgIDAiCfgSet                    = 300 // ai cfg set
	MsgIDGetTimelapseCfg             = 319 // get timelapse cfg
	MsgIDSetTimelapseCfg             = 320 // set timelapse cfg
	MsgIDPtzGuard                    = 331 // ptz guard
	MsgIDPtzGuard2                   = 332 // ptz guard
	MsgIDPtzAutoTest                 = 340 // ptz auto test
	MsgIDPtzAutoTest2                = 341 // ptz auto test
	MsgIDAiDetectCfgGet              = 342 // ai detect cfg get
	MsgIDAiDetectCfgSet              = 343 // ai detect cfg set
	MsgIDAiDefaultDetectCfgGet       = 344 // ai default detect cfg get
	MsgIDGetAudioFileInfoList        = 347 // get audio file info list
	MsgIDDeleteAutoFile              = 348 // delete auto file
	MsgIDPlayAudioFile               = 349 // play audio file
	MsgIDStopAutoFile                = 350 // stop auto file
	MsgIDAfLearningResGet            = 355 // af learning res get
	MsgIDSdCardTest                  = 356 // sd card test
	MsgIDBinoAdjust                  = 359 // bino adjust
	MsgIDAdjustResultGet             = 360 // adjust result get
	MsgIDLinewidthGet                = 361 // linewidth get
	MsgIDZfBacklashGet               = 365 // zf backlash get
	MsgIDZfBacklashSet               = 366 // zf backlash set
	MsgIDSetAudioFileInfoList        = 368 // set audio file info list
	MsgIDFtyResultGet                = 369 // fty result get
	MsgIDFtyPeripheralStatSet        = 370 // fty peripheral stat set
	MsgIDFtyIrCutInfo                = 371 // fty ir_cut info
	MsgIDRelayHeader                 = 381 // relay header
	MsgIDRelayv2Stop                 = 382 // relayv2 stop
	MsgIDRelayv2Seek                 = 383 // relayv2 seek
	MsgIDFtyRangeGet                 = 384 // fty range get
	MsgIDFtyRangeGet2                = 385 // fty range get
	MsgIDOffsetAdjust                = 389 // offset adjust
	MsgIDOffsetAdjustResultGet       = 390 // offset adjust result get
	MsgIDSetIotAction                = 396 // set iot action
	MsgIDSmtCmdProc                  = 400 // smt cmd proc
	MsgIDExportAudio                 = 410 // export_audio
	MsgIDBandwidthTest               = 413 // bandwidth_test
	MsgIDGetBinoSttichCfg            = 417 // get bino sttich cfg
	MsgIDSetBinoSttichCfg            = 418 // set bino sttich cfg
	MsgIDFtyPeripheralStatGet        = 419 // fty peripheral stat get
	MsgIDImportImage                 = 420 // import image
	MsgIDExportImage                 = 421 // export image
	MsgIDOptocouplerCalib            = 426 // optocoupler calib
	MsgIDGetAutoReply                = 427 // get auto reply
	MsgIDSetAutoReply                = 428 // set auto reply
	MsgIDFtyDoorbellTest             = 432 // fty doorbell test
	MsgIDGetPtzCurPos                = 433 // get ptz cur_pos
	MsgIDGetAiTrackLimitCfg          = 434 // get ai track limit cfg
	MsgIDSetAiTrackLimitCfg          = 435 // set ai track limit cfg
	MsgIDGetAiTrackTaskCfg           = 436 // get ai track task cfg
	MsgIDSetAiTrackTaskCfg           = 437 // set ai track task cfg
	MsgIDGetAiDenoiseCfg             = 439 // get ai denoise cfg
	MsgIDSetAiDenoiseCfg             = 440 // set ai denoise cfg
	MsgIDGetFishEyeCfg               = 443 // get fish eye cfg
	MsgIDSetFishEyeCfg               = 444 // set fish eye cfg
	MsgIDSet3dLocation               = 445 // set 3d location
	MsgIDGetLargeBattery             = 449 // get large battery
	MsgIDSetLargeBattery             = 450 // set large battery
	MsgIDGetPowerMode                = 451 // get power mode
	MsgIDSetPowerMode                = 452 // set power mode
	MsgIDGetAfAlgCfg                 = 453 // get af alg cfg
	MsgIDSetAfAlgCfg                 = 454 // set af alg cfg
	MsgIDDingdongCtrl                = 483 // dingdong ctrl
	MsgIDDingdongPairedList          = 484 // dingdong paired list
	MsgIDDingdongDevOpt              = 485 // dingdong dev opt
	MsgIDGetDingdongCfg              = 486 // get dingdong cfg
	MsgIDSetDingdongCfg              = 487 // set dingdong cfg
	MsgIDGetHomebaseWakeupTask       = 488 // get homebase wakeup task
	MsgIDSetHomebaseWakeupTask       = 489 // set homebase wakeup task
	MsgIDDingdongScanlistReport      = 490 // dingdong scanlist report
	MsgIDGetAccessUsercfg            = 511 // get access usercfg
	MsgIDSetAccessUsercfg            = 512 // set access usercfg
	MsgIDFskRfPairReport             = 514 // fsk rf pair report
	MsgIDFskRfPairSet                = 515 // fsk rf pair set
	MsgIDGetCrosslineDetectCfg       = 527 // get crossline detect cfg
	MsgIDSetCrosslineDetectCfg       = 528 // set crossline detect cfg
	MsgIDGetIntrusionDetectCfg       = 529 // get intrusion detect cfg
	MsgIDSetIntrusionDetectCfg       = 530 // set intrusion detect cfg
	MsgIDGetLoiteringDetectCfg       = 531 // get loitering detect cfg
	MsgIDSetLoiteringDetectCfg       = 532 // set loitering detect cfg
	MsgIDWifiSdbInfoGet              = 537 // wifi sdb info get
	MsgIDWifiSdbInfoSet              = 538 // wifi sdb info set
	MsgIDFishEyeSubchnCtrl           = 541 // fish eye subchn ctrl
	MsgIDSirenStatusReport           = 547 // siren status report
	MsgIDSetPreviewStatSuccess       = 548 // set preview stat success
	MsgIDGetLegacyDetectCfg          = 549 // get legacy detect cfg
	MsgIDSetLegacyDetectCfg          = 550 // set legacy detect cfg
	MsgIDGetLossDetectCfg            = 551 // get loss detect cfg
	MsgIDSetLossDetectCfg            = 552 // set loss detect cfg
	MsgIDGetWifiRetcode              = 553 // get wifi retcode
	MsgIDRptStationListGet           = 563 // rpt station list get
	MsgIDGetSleepStateCfg            = 574 // get sleep state cfg
	MsgIDSetSleepStateCfg            = 575 // set sleep state cfg
	MsgIDSnapForSession              = 578 // snap for session
	MsgIDSnapTlps                    = 579 // snap tlps
	MsgIDCfgModifyReport             = 580 // cfg modify report
	MsgIDRestartMesh                 = 589 // restart mesh
	MsgIDDelayRecStatReport          = 590 // delay rec stat report
	MsgIDGetLongrunCfg               = 594 // get longrun cfg
	MsgIDSetLongrunCfg               = 595 // set longrun cfg
	MsgIDGetSilentMode               = 609 // get silent mode
	MsgIDSetSilentMode               = 610 // set silent mode
	MsgIDBatFlagReport               = 622 // bat flag report
	MsgIDSleepStatusReport           = 623 // sleep status report
	MsgIDGetBatteryMode              = 626 // get battery mode
	MsgIDSetBatteryMode              = 627 // set battery mode
	MsgIDAovInfoReport               = 687 // aov info report
	MsgIDGetPirMotionDetectCfg       = 694 // get pir motion detect cfg
	MsgIDSetPirMotionDetectCfg       = 695 // set pir motion detect cfg
	MsgIDForwardProxyMsg             = 705 // forward proxy msg
	MsgIDCoordinatePointReport       = 723 // coordinate point report
	MsgIDSetCoordinatePoint          = 724 // set coordinate point
	MsgIDGetPriSign                  = 729 // get pri sign
	MsgIDGetTamperAlarmCfg           = 763 // get tamper alarm cfg
	MsgIDSetTamperAlarmCfg           = 764 // set tamper alarm cfg
)
View Source
const (
	MsgIDGetNetPort = 37
	MsgIDSetNetPort = 36
)

Message ids for the camera's network-service (ServerPort) config. GET is a single empty document; SET must use the two-section SetConfig framing, or the camera acknowledges it and changes nothing.

View Source
const DefaultIdleTimeout = 15 * time.Second

DefaultIdleTimeout is how long a post-login connection tolerates the camera sending nothing before readLoop gives up.

docs/measurements.md and internal/stream/stream.go's own ping-cadence comment establish the baseline this is set against: on a live stream frames arrive roughly every 40ms, and the client pings the camera every 10 seconds purely to hold the session open (the ping is never acked, so it does not by itself put anything on the read side). A healthy camera therefore has no legitimate reason to be silent for more than a fraction of a second, ping cadence included. 15s is chosen as several multiples of that 10s ping interval, not tuned close to it, so ordinary jitter, a stalled TCP segment, or a camera stuttering under load cannot trip it, while still being short enough that a supervisor built on top of Conn notices a held or dead session in seconds rather than the minutes the 2026-09-08 incident actually ran for.

View Source
const DefaultMaxPreviews = 4

DefaultMaxPreviews is Pool.MaxPreviews when it is zero.

View Source
const MaxMessageSize = 3840 * 2160 * 3 / 2

MaxMessageSize bounds a single message body.

h.MsgLen comes straight off the wire, before the body is allocated, so a malfunctioning or hostile peer declaring a huge length must be rejected before make() runs rather than after. The bound is the size of one uncompressed 4K frame: docs/measurements.md records the main stream at 3840x2160, and no message on this protocol carries more than one frame's worth of compressed data, which can never exceed the raw pixel data it encodes. 3840 * 2160 * 3 / 2 (YUV 4:2:0, the format the sensor captures before encoding) = 12,441,600 bytes.

View Source
const StatusBadRequest = 400

StatusBadRequest is what a camera answers when it parsed the document and refused it, for instance an element name it does not know.

View Source
const StatusNotImplemented = 405

StatusNotImplemented is the status a camera answers for a config message it does not implement, instead of failing the connection. docs/control.md establishes this is what makes probing every known read safe.

View Source
const StatusWrongShape = 421

StatusWrongShape is the trap. A camera answers 421 when the message was built wrong, not when the feature is missing: a configuration write is two sections, the channel in an extension and the document in a second section, and sent as a single section every model answers 421 and changes nothing. The mis-numbered heartbeat produced the same 421 for a year while the feature it was aimed at was fine.

Variables

View Source
var (
	ErrBadMagic    = errors.New("baichuan: bad magic")
	ErrShortHeader = errors.New("baichuan: short header")
)
View Source
var ConfigMessages = map[string]uint32{}/* 103 elements not displayed */

ConfigMessages names the read requests that take nothing but a channel.

The ids and the comments come from the dispatch table in the NVR's camera-facing client, not from the Wireshark dissector, which had several of them wrong. Three corrections worth naming, because the old values were in use: "userlist" was 59, which the firmware calls "Set user cfg" and is a write; the battery read is 253, not the 252 report; and 93 is not a Baichuan config id at all, it is the ping.

Every id here is one whose firmware description only reads. A camera that does not implement one answers status 405 rather than failing the connection, so asking a model for something it lacks is safe and is how this list gets checked against new hardware.

Generated; see docs/msgids.json.

View Source
var ErrLoginRefused = errors.New("baichuan: camera refused the login (status 400, no reason given)")

ErrLoginRefused is a login answered with status 400 and no body. Some firmware answers every login that way for a minute or more after a burst of logins (RLC-410 v3.0.0.136, Duo 3, E1 Pro, emulated 2026-10-29), while a wrong password there is 401. Calling it a wrong password sends someone to retype a password that is right.

View Source
var ErrMessageTooLarge = errors.New("baichuan: message body exceeds MaxMessageSize")

ErrMessageTooLarge means a header declared a body bigger than MaxMessageSize.

View Source
var ErrNoSpeaker = errors.New("baichuan: this camera has no speaker (Support reports audioTalk 0)")

ErrNoSpeaker is OpenTalk refusing a camera whose Support block says it has nothing to play sound through.

View Source
var ErrPayloadOffsetOutOfRange = errors.New("baichuan: PayloadOff exceeds body length")

ErrPayloadOffsetOutOfRange means a header's PayloadOff pointed past the end of the body it belongs to.

View Source
var ErrReaderStalled = errors.New("baichuan: reader fell behind the shared connection and was dropped")

ErrReaderStalled ends a reader that stopped taking its messages; see stallTimeout.

View Source
var ErrSharedClosed = errors.New("baichuan: shared connection closed")

ErrSharedClosed is a subscription to a Shared whose connection has ended.

View Source
var ErrUnauthorized = errors.New("baichuan: authentication rejected (empty login reply)")

ErrUnauthorized is what Dial returns when a camera's login reply carries no XML body.

The wire gives no separate "wrong password" document: a rejected credential and an accepted one differ only in whether the login reply's body is empty. Read on its own, that symptom is indistinguishable from a camera holding a dead session (see DefaultIdleTimeout), which is exactly the confusion a first time user hits when a typed password is wrong. This sentinel is what lets a caller tell the two apart and say "authentication failed" instead of "something is wrong with the network".

A Reolink NVR (RLN8-410, v3.5.1.368 emulated) does send a document for a wrong password, <LoginErrInfo> with the attempts left before it locks logins, which is a refusal too and not a DeviceInfo.

View Source
var UsefulServices = Services{HTTP: true, RTSP: true, ONVIF: true}

UsefulServices is the set worth enabling for an NVR: RTSP to stream (and the fallback for a TrackMix zoom lens), ONVIF for PTZ and discovery, and HTTP for the camera's own settings page.

Functions

func AESDecrypt

func AESDecrypt(key, buf []byte) ([]byte, error)

AESDecrypt reverses AESEncrypt.

func AESEncrypt

func AESEncrypt(key, buf []byte) ([]byte, error)

AESEncrypt applies AES-128-CFB with the fixed IV.

func AESKey

func AESKey(nonce, password string) []byte

AESKey derives the AES-128 key from the login nonce and the plaintext password: the uppercase hex MD5 of "nonce-password", truncated to 16 chars.

func BCCrypt

func BCCrypt(offset uint32, buf []byte) []byte

BCCrypt applies the BC cipher. It is XOR, so the same call encrypts and decrypts. The key is rotated by the header's encryption offset and every byte is additionally XORed with the low byte of that offset.

This cipher covers the handshake: the negotiation reply, the login request and the DeviceInfo reply. Everything after login is AES, except on firmware that negotiated BC for the whole session (see Cipher).

func ConfigNames

func ConfigNames() []string

ConfigNames lists the keys of ConfigMessages in sorted order.

func EncOffsetFor

func EncOffsetFor(channel, stream, counter, handle byte) uint32

EncOffsetFor builds the encryption-offset field. Observed on the wire as [channel, stream, counter, handle] little-endian, where the counter increments once per outbound request.

func ExplainStatus

func ExplainStatus(status int16) string

ExplainStatus turns a reply status into something an operator can act on. The wording matters more than it looks: 421 and 405 are routinely confused for each other, and treating 421 as "unsupported" is how a working feature gets written off.

func FloodlightManualXML added in v0.2.9

func FloodlightManualXML(channel int, on bool) []byte

FloodlightManualXML is the 288 document: status 1 lights the light, 0 puts it out.

func HeaderLen

func HeaderLen(class uint16) int

HeaderLen reports the header size for a class.

func IsAlarmEvent added in v0.2.0

func IsAlarmEvent(m Message) bool

IsAlarmEvent reports whether a message is an alarm push.

func IsRecorder added in v0.2.5

func IsRecorder(deviceInfo []byte) bool

IsRecorder reports whether a login reply came from an NVR or Home Hub: every camera has "ipc" in its type at login, and a recorder does not.

func MsgName

func MsgName(id uint32) string

MsgName returns the firmware's description for a message id.

func ReadConfig

func ReadConfig(ctx context.Context, conn *Conn, id uint32) ([]byte, int16, error)

ReadConfig sends a config read that takes only a channel and waits for its reply, or for ctx to end.

func ReadConfigWith added in v0.2.3

func ReadConfigWith(ctx context.Context, conn *Conn, id uint32, req []byte) ([]byte, int16, error)

ReadConfigWith is ReadConfig for a read that takes a request document (see Conn.GetConfigWith). A nil req is a plain ReadConfig.

func SetHeartBeatTwoPart

func SetHeartBeatTwoPart(v bool)

SetHeartBeatTwoPart switches that choice.

func SirenXML added in v0.2.9

func SirenXML(channel int) []byte

SirenXML is the 263 document the app sends for its siren button: the siren sound played once (playMode 0, playTimes 1). It runs about 3 seconds on a Lumus and stops by itself; there is no stop to send.

func StreamID

func StreamID(stream string) byte

StreamID is the value the encryption-offset field carries for each stream.

func TakeSnap added in v0.2.8

func TakeSnap(ctx context.Context, conn *Conn, stream string) ([]byte, string, error)

TakeSnap asks conn's camera for a still and waits until all of it has arrived or ctx ends. It returns the image, trimmed to the size the camera declared, and the filename the camera gave it.

The bytes are whatever the camera made, returned as they came. Every camera that has answered one so far made a JPEG, but checking that is the caller's business: reocam saves the file regardless, the control page refuses to label anything else image/jpeg.

func TalkPacket

func TalkPacket(block []byte) []byte

TalkPacket wraps one encoded ADPCM block in the media packet framing the cameras use, which is the same framing they send audio back in: the magic, the payload length twice, then a four byte inner header naming the DVI4 block size.

The doubled length is not a typo. It is doubled on the wire in both directions; a capture of a camera's own AAC shows the two fields carrying the same value.

func UnsafeToRewrite

func UnsafeToRewrite(id uint32) bool

UnsafeToRewrite reports whether writing a document back to this message, even unchanged, could disturb a camera that is carrying traffic.

Re-applying an encoder or image configuration makes the camera reconfigure the pipeline, which interrupts the stream, and a firmware update or reboot setting speaks for itself. Nothing here is about the message being malformed; these are the writes whose success is the problem.

func UploadSound added in v0.2.3

func UploadSound(ctx context.Context, conn *Conn, adpcm []byte) error

UploadSound sends adpcm as the camera's custom siren sound and saves it.

func WriteConfig

func WriteConfig(ctx context.Context, conn *Conn, id uint32, body []byte) (int16, error)

WriteConfig sends body to id as a config write and reports the status the camera answered.

A 200 from this function is not evidence the camera did anything. Message 47 accepts a valid document, on hardware that implements the matching read, answers 200, and changes nothing observable; message 288 does the same with the right root element and wrong fields inside it. Callers that need to know whether a write took effect must read the block back on a fresh connection and compare.

Types

type Ability

type Ability struct {
	Module   string
	Name     string
	Writable bool
}

Ability is one thing a camera can do, and whether the logged in user may only read it or also change it.

The camera reports these as a comma separated list of "name_rw" and "name_ro" strings grouped by module, so the suffix is the permission and the rest is the name.

func GetAbilities

func GetAbilities(ctx context.Context, conn *Conn) ([]Ability, error)

GetAbilities reads what the logged in user may do, module by module (message 151, AbilityInfo). This is the read cmd/reocam's abilities command has always used.

func ParseAbilities

func ParseAbilities(x []byte) ([]Ability, error)

ParseAbilities reads an AbilityInfo reply into a sorted list.

type AlarmEvent added in v0.2.0

type AlarmEvent struct {
	Channel int
	// Status is the camera's own word for what it sees ("MD" for motion,
	// "none" when it stops), and AI the object types it named, if any.
	Status    string
	AI        []string
	Recording bool
	Raw       []byte
}

AlarmEvent is one state the camera reported.

func ParseAlarmEvents added in v0.2.0

func ParseAlarmEvents(doc []byte) ([]AlarmEvent, error)

ParseAlarmEvents reads one AlarmEventList.

func (AlarmEvent) Motion added in v0.2.0

func (e AlarmEvent) Motion() bool

Motion reports whether the camera says something is moving. A doorbell's call button arrives as status "visitor"; that is a press, not motion.

func (AlarmEvent) Visitor added in v0.2.5

func (e AlarmEvent) Visitor() bool

Visitor reports a doorbell's call button being pressed.

type Cipher added in v0.2.6

type Cipher int

Cipher is how message bodies are sealed once login completes.

The camera picks it: the negotiation probe asks for full AES, and the reply names what the camera will actually use in byte 16, with DirReply in byte 17. Current firmware answers 0x12 and the v3.0.0.136 MIPS builds answer 0x02, both AES. Firmware from 2017-2019 (C1 Pro, RLC-410 on v2.0.0.x) answers 0x01 and keeps the BC cipher for the whole session, and a Preview sealed with AES is something it cannot read, so it never answers and the stream looks like a held session (#23).

const (
	// CipherBC is the XOR cipher every session starts with, and the zero
	// value, so a fresh Reader or Writer can read and write the handshake.
	CipherBC Cipher = iota
	CipherAES
	CipherNone
)

func (Cipher) String added in v0.2.6

func (c Cipher) String() string

type CommandRefused added in v0.2.9

type CommandRefused struct {
	What   string
	Status int16
}

CommandRefused is a 288 or 263 the camera answered with a status other than 200.

func (*CommandRefused) Error added in v0.2.9

func (e *CommandRefused) Error() string

type ConfigPair

type ConfigPair struct {
	Get  uint32
	Set  uint32
	Name string // the read's description, as the firmware words it
}

ConfigPair is a read message and the write that takes the same document.

func ConfigPairs

func ConfigPairs() []ConfigPair

ConfigPairs returns the read/write pairs in the recovered table.

Pairing is on the firmware's exact description, "osd get" to "osd set", rather than on a normalized key. Normalizing collapses "osd get" (44) and "get osd" (29) onto one name and pairs 44 with 30, and a write sent to the wrong message id is the one mistake in this package with real consequences.

A read with no matching write, such as "osd def get", yields no pair.

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn is one Baichuan session carrying one stream.

A camera permits one connection per stream (main, sub and extern are independent), so a Conn must be closed cleanly. Close sends the stream-stop message that releases the camera's session; a process killed without doing so leaves that stream refusing connections for minutes.

func Dial

func Dial(ctx context.Context, addr string, opts Options) (*Conn, error)

Dial connects to a camera and logs in. addr may omit the port, in which case 9000 is used. With opts.UID set, addr is a battery camera reached over UDP.

func (*Conn) Abilities

func (c *Conn) Abilities() error

Abilities asks the camera what the logged in user may do, module by module. The reply arrives on Messages as MsgIDAbilityInfo; parse it with ParseAbilities.

This is the Baichuan equivalent of the HTTP API's GetAbility, and it is worth preferring over a hardcoded assumption about a model. It is not infallible: the HTTP ability list reports "talk" on cameras that have no speaker at all.

func (*Conn) Channel added in v0.2.3

func (c *Conn) Channel() int

Channel is the channel this connection was opened for.

func (*Conn) Cipher added in v0.2.6

func (c *Conn) Cipher() Cipher

Cipher reports the cipher the camera chose for this session.

func (*Conn) Close

func (c *Conn) Close() error

Close stops the stream and releases the camera's session.

func (*Conn) DeviceInfo

func (c *Conn) DeviceInfo() []byte

DeviceInfo returns the raw <DeviceInfo> document the camera sent as its login reply. Parse it with ParseDeviceInfo.

func (*Conn) Download added in v0.2.0

func (c *Conn) Download(ctx context.Context, from, to time.Time, sub bool, idle time.Duration, fn func(Frame) error) (end string, err error)

Download asks the camera for the recording between from and to and passes every media frame to fn as it arrives. The camera starts at the requested second, not at a keyframe, so frames before the first I frame are dropped. It returns when the camera has been quiet for idle, when fn returns an error, or when ctx ends.

func (*Conn) EnableRTSP added in v0.2.0

func (c *Conn) EnableRTSP(ctx context.Context) (bool, error)

EnableRTSP turns RTSP on if it is off, leaving everything else as it is.

func (*Conn) EnableServices added in v0.2.0

func (c *Conn) EnableServices(ctx context.Context, want Services) (changed bool, err error)

EnableServices turns on each requested service that is off, leaving the rest untouched, and reports whether it changed anything. The camera takes its ports as two groups (ServerPort/Http/Https and Rtsp/Onvif/Rtmp), so a change touches at most one write per group, each carrying its whole group.

func (*Conn) Err

func (c *Conn) Err() error

Err reports the read error that ended the read loop and closed the channel from Messages, or nil if the loop is still running. After Close, this is the "use of closed network connection" error the read side sees, not a camera-side failure; callers that care about that distinction should check it before calling Close.

func (*Conn) FloodlightNow added in v0.2.9

func (c *Conn) FloodlightNow(ctx context.Context, wait time.Duration) (st FloodlightStatus, ok bool, err error)

FloodlightNow reads the light's state from the report the camera pushes after login, waiting up to wait for it. ok is false when no report came: not every model sends one, and a connection that has already read other replies may have passed it by, so call this first on a fresh connection.

func (*Conn) GetConfig

func (c *Conn) GetConfig(msgID uint32) error

GetConfig asks the camera for one configuration block and returns nothing; the reply arrives on Messages carrying the same message id, with the XML in Message.XML.

Most read requests share one shape: an extension naming the channel and nothing else. That covers the LED state, the encoder settings, the ISP settings, the record schedule and the rest, so they need one implementation rather than one each. A message that wants more than a channel is not this, and needs its own method.

func (*Conn) GetConfigWith added in v0.2.3

func (c *Conn) GetConfigWith(msgID uint32, req []byte) error

GetConfigWith asks for a configuration block whose read takes a request document as well as the channel, such as the per-type AI settings (342, with <type>people</type>). It goes out in the two-section shape a write uses, which is how the Reolink app sends it.

func (*Conn) GetNetPort added in v0.2.0

func (c *Conn) GetNetPort(ctx context.Context) (NetPort, error)

GetNetPort reads the camera's network-service configuration.

func (*Conn) GetPtzGuard added in v0.2.0

func (c *Conn) GetPtzGuard(ctx context.Context) (PtzGuard, error)

GetPtzGuard reads the guard (message 332).

func (*Conn) HeartBeat

func (c *Conn) HeartBeat() error

HeartBeat sends the real heartbeat, message 5, and returns nothing: the reply arrives on Messages and parses with ParseHeartBeat.

Unlike Ping this is a round trip measurement rather than a liveness poke. The camera answers with its own clock and a count of overlapped requests, so it reports how far behind the client is rather than only that it is still there. The camera's side of the same mechanism is the log line "heartbeat timeout, session:%d chn:%d devname:%s disconnected".

The message id is not in the dissector's table. It came from the camera firmware, where bc_module::heartbeat's failure path calls rpc_msg_name(5) to name the message it could not send.

func (*Conn) Messages

func (c *Conn) Messages() <-chan Message

Messages yields every message the camera sends after login.

func (*Conn) Nonce

func (c *Conn) Nonce() string

Nonce reports the login nonce.

func (*Conn) Ping

func (c *Conn) Ping() error

Ping keeps the session alive. The camera times out a session it stops hearing from, logging "session:%u login timeout", and the official NVR heartbeats continuously.

func (*Conn) PtzCalibrate added in v0.2.0

func (c *Conn) PtzCalibrate(ctx context.Context) (answered bool, err error)

PtzCalibrate starts the self test, reading its state first as the client does (the camera refuses a cold start). It reports whether the camera answered 341 at all.

A TrackMix answers 341 only when the sweep has finished, a minute or so later, and until then answers nothing else on this connection either (fake hardware, 10-30: a 340 on the same session went unanswered while one on a fresh session read testStat 1). Waiting for the answer under the 15 s idle timeout reported every calibrate as refused while the camera calibrated. So a refusal within calibrateAnswerWait is still a refusal, and silence means it started; the caller confirms with PtzCalibrateState on a new connection, and closes this one.

func (*Conn) PtzCalibrateState added in v0.2.0

func (c *Conn) PtzCalibrateState(ctx context.Context) (int, error)

PtzCalibrateState reads the self test's state (testStat; 2 when one has finished).

func (*Conn) PtzControl added in v0.2.0

func (c *Conn) PtzControl(ctx context.Context, command string, speed int) error

PtzControl moves the camera: command is left, right, up, down, a diagonal (leftUp, leftDown, rightUp, rightDown), zoomInc, zoomDec or stop. The document is the one the Reolink desktop client sends (captured 2026-10-22: speed 34 for a move, speed 0 with stop). A move or a zoom continues until a stop arrives, so a caller that starts one must send the stop. The diagonals and zoom are the firmware's own command words (libnetpublic's _get_ptz_cmd); the fake TrackMix moved both motors for leftUp and zoomed for zoomInc (10-30).

func (*Conn) PtzPatrol added in v0.2.6

func (c *Conn) PtzPatrol(ctx context.Context, start bool, id int) error

PtzPatrol starts or stops the camera touring its patrol (cruise) id, the presets it was given in the Reolink app. Same message as PtzControl; the fake TrackMix toured its cruise on startPatrol with patrolId 0 (10-30).

func (*Conn) PtzPreset added in v0.2.0

func (c *Conn) PtzPreset(ctx context.Context, command string, id int, name string) error

PtzPreset saves the current position as preset id (command "setPos") or moves to it ("toPos"). The document is the client's (message 19).

func (*Conn) PtzPresets added in v0.2.0

func (c *Conn) PtzPresets(ctx context.Context) ([]Preset, int, error)

PtzPresets reads the saved positions (message 190) and how many the camera can hold.

func (*Conn) PtzZoomRange added in v0.2.6

func (c *Conn) PtzZoomRange(ctx context.Context) (lo, hi, cur int, err error)

PtzZoomRange reads the zoom lens's range and position (message 294). A camera with no zoom answers otherwise, or with an empty range.

func (*Conn) RawChannelRequest

func (c *Conn) RawChannelRequest(msgID uint32) error

RawChannelRequest sends a bare request carrying only a channel, for probing message ids whose shape is not yet known.

func (*Conn) RecordDays added in v0.2.0

func (c *Conn) RecordDays(ctx context.Context, month time.Time) ([]time.Time, error)

RecordDays lists the days in month that have recordings. One month per request, as the client asks: a range spanning two months comes back with no days at all (seen on an Argus PT Ultra).

func (*Conn) RecordFiles added in v0.2.0

func (c *Conn) RecordFiles(ctx context.Context, day time.Time) ([]RecordFile, error)

RecordFiles lists the recordings that start on day, oldest first.

func (*Conn) SendDocument added in v0.2.0

func (c *Conn) SendDocument(msgID uint32, body []byte) error

SendDocument sends msgID carrying body as a single section with a zero PayloadOff: the whole body is the document and there is no extension. The netport GET uses it to send an empty request.

func (*Conn) SetConfig

func (c *Conn) SetConfig(msgID uint32, body []byte) error

SetConfig sends a configuration write.

The body is the caller's XML. For every get/set pair the right body is the document the matching get returned with one field changed: the camera supplies its own schema, so nothing here needs to know a model's fields, and echoing the document back preserves the exact byte formatting that some messages insist on.

The reply status says the camera accepted the message, not that it acted on it. Verify the effect, not the call.

func (*Conn) SetFloodlight added in v0.2.9

func (c *Conn) SetFloodlight(ctx context.Context, on bool, settle time.Duration) (st FloodlightStatus, reported bool, err error)

SetFloodlight lights the light (on) or puts it out, with message 288, and waits up to settle for a floodlight report saying it did. reported is false when the camera accepted the command and sent no report for this channel in time; st is then zero and means nothing.

A report already queued before the command's own answer (the one pushed at login) is the state before, not after, and is skipped.

func (*Conn) SetIdleTimeout added in v0.2.6

func (c *Conn) SetIdleTimeout(d time.Duration)

SetIdleTimeout changes how long the camera may send nothing before the connection gives up, from now on, including for a read already waiting. A stream that is receiving video shortens it (see stream.Run): a camera streaming sends a frame every 40 to 100 ms, so one silent for seconds has dropped the session, and waiting out DefaultIdleTimeout cost about 17 s of footage for a 5 s link blip (a link-drop test, 10-30).

func (*Conn) SetPorts added in v0.2.0

func (c *Conn) SetPorts(ctx context.Context, np NetPort) error

SetPorts writes np's ports and on/off states, one write per group that differs from what the camera holds now. The media port (ServerPort) is never changed: it is how reostream itself reaches the camera.

func (*Conn) SetPtzGuard added in v0.2.0

func (c *Conn) SetPtzGuard(ctx context.Context, doc []byte) error

SetPtzGuard writes doc (the camera's own guard document, edited) to the guard write (message 331).

func (*Conn) SetServices added in v0.2.0

func (c *Conn) SetServices(ctx context.Context, want Services) (changed bool, err error)

SetServices sets each service exactly as want says, on or off, and reports whether it changed anything. Ports are kept as the camera has them. Same two-group write as EnableServices; the media port (ServerPort, 9000) is never touched, since it is how reostream itself reaches the camera.

func (*Conn) Snap

func (c *Conn) Snap(stream string) error

Snap asks the camera for a still image. The camera answers with one message naming the file and its size, then sends the JPEG bytes across as many further messages as it needs. Collect them with a SnapReader.

stream is "main" or "sub" and selects which encoder the still comes from, so it is also the resolution control.

func (*Conn) SoundSiren added in v0.2.9

func (c *Conn) SoundSiren(ctx context.Context) error

SoundSiren plays the siren once (263) and returns when the camera has answered.

func (*Conn) StartAlarms added in v0.2.0

func (c *Conn) StartAlarms(ctx context.Context) error

StartAlarms asks the camera to push its alarm events.

func (*Conn) StartVideo

func (c *Conn) StartVideo(stream string) error

StartVideo requests a stream: StreamMain, StreamSub or StreamExtern.

func (*Conn) StartVideoOn added in v0.2.2

func (c *Conn) StartVideoOn(channel, handle int, stream string) error

StartVideoOn requests a stream on any channel of this connection, with an explicit handle, beside whatever StartVideo asked for. The camera echoes a request's encryption offset on every media message it sends for it, and the offset's low byte is the channel, so a caller running two streams on one connection tells them apart by byte(Header.EncOffset).

It exists for the TrackMix zoom lens: channel 1 answers a request made on its own with a stream info frame and audio but never any video, and sends video only on a connection that is also streaming channel 0 (the Reolink app opens both on one connection; captured 2026-10-24).

func (*Conn) StopVideoOn added in v0.2.5

func (c *Conn) StopVideoOn(channel, handle int, stream string) error

StopVideoOn stops one stream StartVideoOn opened, leaving the connection and every other stream on it running. A recorder's shared connection (see Shared) uses it when the last reader of a stream goes away.

func (*Conn) Talk

func (c *Conn) Talk(packet []byte) error

Talk sends one framed audio packet, as built by TalkPacket. The camera plays it through its speaker, so this is the one call in this package with an effect outside the machine it runs on.

func (*Conn) TalkAbility

func (c *Conn) TalkAbility() error

TalkAbility asks the camera to describe its two-way audio support: the duplex modes, the stream modes and the audio encodings it will accept. The reply arrives on Messages as MsgIDTalkAbility.

func (*Conn) TalkConfig

func (c *Conn) TalkConfig(cfg TalkFormat) error

TalkConfig opens a two-way audio session in the format cfg describes. It must be sent before any Talk data, and cfg should come from the camera's own TalkAbility reply rather than from constants.

type Depacketizer added in v0.2.4

type Depacketizer struct {
	// contains filtered or unexported fields
}

Depacketizer reassembles media packets from the byte stream carried in message id 3. A media packet may straddle message boundaries, so bytes are buffered until a whole packet is present.

func NewDepacketizer added in v0.2.4

func NewDepacketizer() *Depacketizer

func (*Depacketizer) Filler added in v0.2.4

func (d *Depacketizer) Filler() int

Filler reports bytes dropped between a packet's end and the end of the message carrying it. A healthy stream has a nonzero, slowly growing count: this is the camera's own padding, not a parsing error.

func (*Depacketizer) Lost added in v0.2.4

func (d *Depacketizer) Lost() int

Lost reports video packets cut short by the start of the next one.

func (*Depacketizer) Next added in v0.2.4

func (d *Depacketizer) Next() (Frame, bool)

Next returns the next complete frame, or false if more bytes are needed.

func (*Depacketizer) Skipped added in v0.2.4

func (d *Depacketizer) Skipped() int

Skipped reports bytes discarded because the buffer did not begin with a packet magic where one was required. It should stay zero; a climbing count means packets are being mis-framed.

func (*Depacketizer) TakeGap added in v0.2.4

func (d *Depacketizer) TakeGap() bool

TakeGap reports whether a video packet was lost since the last call.

func (*Depacketizer) Write added in v0.2.4

func (d *Depacketizer) Write(b []byte, startsPacket bool)

Write adds the payload of one message. startsPacket must be true when the message's extension header declared binaryData, which is what marks the start of a new media packet: anything still buffered at that point is trailing filler from the previous packet's last message and is dropped. The presence of an extension header alone is not the boundary, since some cameras put one on continuation messages too (see Message.StartsPacket).

type DeviceInfo

type DeviceInfo struct {
	XMLName    xml.Name `xml:"body"`
	DeviceInfo struct {
		FirmVersion string `xml:"firmVersion"`
		Type        string `xml:"type"`     // "ipc" on every camera captured so far
		TypeInfo    string `xml:"typeInfo"` // "IPC"; same information, differently cased
		ChannelNum  int    `xml:"channelNum"`
		// NeedRotate is set by firmware that encodes a picture sideways
		// and expects the client to turn it back (the 16 MP NT17 boards'
		// full resolution). Every build sends the element; only those set
		// it non-zero. The value's meaning beyond "non-zero" has not been
		// seen on the wire yet.
		NeedRotate string `xml:"needRotate"`
		AudioNum   int    `xml:"audioNum"`
		Resolution struct {
			Name   string `xml:"resolutionName"`
			Width  int    `xml:"width"`
			Height int    `xml:"height"`
		} `xml:"resolution"`
	} `xml:"DeviceInfo"`
}

DeviceInfo is the document a camera sends as its login reply on success, before it names anything about a stream or asks a config question of its own. Captured whole on a real camera (internal/baichuan/testdata, login_s2c.bin, message 1): a firmware version, a device type ("ipc"), the channel and audio counts also carried in Support, and the camera's own top resolution.

It carries no marketing model name ("RLC-810A" and similar never appear anywhere in it), so nothing here should be presented as one.

func ParseDeviceInfo

func ParseDeviceInfo(x []byte) (DeviceInfo, error)

ParseDeviceInfo reads the document Conn.DeviceInfo returns.

func (DeviceInfo) SecondLens added in v0.2.8

func (d DeviceInfo) SecondLens() bool

SecondLens reports a camera with a second lens on channel 1: the TrackMix's zoom lens (and the other two-lens trackers, the TrackFlex and the Omvi 3i, which report the same way). It is in the login reply, so knowing it costs nothing, where asking channel 1 for video takes one of the camera's two main stream slots and waits on an answer a camera with its slots taken never sends.

An NVR or Home Hub reports a channel per camera it holds, so only a device that calls itself a camera ("ipc", "fisheye_ipc") counts. The dual-lens panoramas (Duo 2, Duo 3) stitch both lenses into one picture and report one channel (pano, 10-27 sweep), so they are not counted.

type FloodlightStatus added in v0.2.9

type FloodlightStatus struct {
	Channel    int `xml:"channel"`
	Status     int `xml:"status"`
	Brightness int `xml:"brightness"`
}

FloodlightStatus is one channel's line in a floodlight report (291). A TrackMix reports both its lenses, channels 0 and 1.

func ParseFloodlightReport added in v0.2.9

func ParseFloodlightReport(doc []byte) ([]FloodlightStatus, error)

ParseFloodlightReport reads a 291 document.

func (FloodlightStatus) On added in v0.2.9

func (f FloodlightStatus) On() bool

On reports whether the light is lit.

type Frame

type Frame struct {
	Kind   FrameKind
	Codec  string
	Micros uint32
	Data   []byte
	Width  int
	Height int
	FPS    int
}

Frame is one decoded media packet.

Micros is the camera's own capture time. Emitting it downstream is what keeps timing correct: a raw elementary stream carries no timing at all, so anything muxing it has to invent timestamps, and invents them badly.

func (Frame) Video

func (f Frame) Video() []byte

Video returns the frame's video data starting at its first NAL start code.

HEVC frames from these cameras carry a variable-length proprietary prefix before the first start code -- 80, 112 or 152 bytes have been observed -- while H.264 frames start at the start code directly. Feeding that prefix to a decoder produces sporadic errors, so anything writing an elementary stream should use this rather than Data.

type FrameKind

type FrameKind int

FrameKind identifies a media packet type.

const (
	FrameUnknown FrameKind = iota
	FrameInfo
	FrameIFrame
	FramePFrame
	FrameAAC
	FrameADPCM
)

func (FrameKind) String

func (k FrameKind) String() string
type Header struct {
	MsgID      uint32
	MsgLen     uint32
	EncOffset  uint32
	EncByte    byte
	DirByte    byte
	Class      uint16
	PayloadOff uint32
}

Header is a Baichuan message header. Bytes 16 and 17 carry different meanings by direction: a request sends a negotiation byte followed by 0xdc, a reply sends a status code followed by 0x00 or 0xdd.

func DecodeHeader

func DecodeHeader(b []byte) (Header, int, error)

DecodeHeader parses a header from the front of b and reports its length.

func (Header) Encode

func (h Header) Encode() []byte

Encode renders the header back to bytes.

func (Header) Status

func (h Header) Status() int16

Status reads bytes 16 and 17 as the little endian status code a reply carries: 200 for success, 400 for a request the camera could not parse. On a request these bytes mean something else, so this is only meaningful on a message that came from a camera.

type HeartBeatReply

type HeartBeatReply struct {
	Size         int
	Sec          int64
	Usec         int64
	OverlapCount int
	Delay        int
}

HeartBeatReply is what a camera returns for a heartbeat.

Sec and Usec are the camera's own clock, which makes this a round trip measurement: the difference against a local reading is clock offset plus path delay, and the change in that difference between two heartbeats is drift. OverlapCount is the camera's count of requests that arrived while an earlier one was still outstanding, so a climbing value means the client is heartbeating faster than the camera can answer.

func ParseHeartBeat

func ParseHeartBeat(x []byte) (HeartBeatReply, error)

ParseHeartBeat reads a heartbeat reply.

func (HeartBeatReply) CameraTime

func (h HeartBeatReply) CameraTime() time.Time

CameraTime is the camera's clock at the moment it answered.

type Message

type Message struct {
	Header  Header
	XML     []byte
	Payload []byte

	// StartsPacket reports that this message begins a new media packet.
	//
	// A media packet always starts at the beginning of a message carrying an
	// extension header, and continues through following messages that carry
	// none. Any bytes between the packet's declared end and the end of its
	// final message are filler and must be discarded.
	StartsPacket bool

	// PayloadXML and WholeXML are the other two ways a config reply that
	// came with a payload section can be read, filled only for messages
	// that are not video. PayloadXML is the payload decrypted on its own,
	// the layout neolink parses: an extension, then the document as a
	// separately encrypted payload. WholeXML is the entire body decrypted
	// as one, for a camera whose PayloadOff falls inside the document. No
	// camera here sends either, so they exist for a caller to fall back on
	// when XML does not parse, and to describe the reply when none do.
	PayloadXML []byte
	WholeXML   []byte
}

Message is a decoded Baichuan message. XML is decrypted; Payload is the binary remainder, which is media data and is never encrypted.

type NetPort added in v0.2.0

type NetPort struct {
	ServerPort PortService
	HTTP       PortService
	HTTPS      PortService
	RTSP       PortService
	ONVIF      PortService
	RTMP       PortService
}

NetPort is which network services a camera serves and on which ports. RTSP is the one that matters here: it is the fallback for a second-lens camera (TrackMix) whose zoom lens sends no video over Baichuan, and many cameras ship with RTSP off.

type Options

type Options struct {
	Username string
	Password string
	Channel  int

	// UID, when set, reaches a battery camera over UDP (see docs/udp.md)
	// instead of TCP port 9000.
	UID string

	// IdleTimeout bounds how long a read may wait for the camera to send
	// anything before Conn gives up on it. Zero means DefaultIdleTimeout.
	IdleTimeout time.Duration
}

Options configures a connection.

type Pool added in v0.2.5

type Pool struct {
	// MaxPreviews caps the streams one shared connection carries before
	// the next one opens. A recorder has room for about ten connections,
	// so a handful of streams on each keeps an eight camera recorder's
	// main and sub streams to four connections, while no single
	// connection has to carry every camera's 4K main stream at once.
	MaxPreviews int
	// contains filtered or unexported fields
}

Pool hands out streams from NVRs and Home Hubs over a few shared connections (see Shared), and plain connections everywhere else.

Whether an address is a recorder is learned from its own login reply, not configured: a camera on its own keeps one connection per stream, which is how every camera here has run since the first release and which nothing about a camera's session limit asks to change.

func NewPool added in v0.2.5

func NewPool() *Pool

NewPool returns an empty Pool.

func (*Pool) Connections added in v0.2.5

func (p *Pool) Connections() int

Connections is how many shared connections the pool holds open.

func (*Pool) Open added in v0.2.5

func (p *Pool) Open(ctx context.Context, addr string, opts Options, channel int, stream string) (*Sub, *Conn, error)

Open starts channel's stream at addr. From a recorder it returns a reader on a shared connection; from a camera on its own, or a battery camera (opts.UID), it returns that camera's own logged-in connection with nothing started, exactly as Dial would, for the caller to run and close as before. Exactly one of the two is non-nil when err is nil.

type PortService added in v0.2.0

type PortService struct {
	Port    int
	Enabled bool
}

PortService is one service's port and whether it is enabled.

type Preset added in v0.2.0

type Preset struct {
	ID   int    `xml:"id"`
	Name string `xml:"name"`
}

Preset is one saved camera position.

type PtzGuard added in v0.2.0

type PtzGuard struct {
	Enable  bool
	Timeout int
	Valid   bool
	Doc     []byte
}

PtzGuard is the guard position the camera returns to when left alone: whether it does (Enable), after how many seconds (Timeout), and whether a guard position has been set at all (Valid). Doc is the camera's own document, kept so a write echoes it back with only these fields changed.

type PtzRefused added in v0.2.6

type PtzRefused struct {
	What   string
	Status int
}

PtzRefused is a PTZ command the camera answered with a status other than 200: the connection is fine, the camera said no. A TrackMix says 400 to every move while its pan/tilt self check runs, about a minute after it starts and during a calibrate.

func (*PtzRefused) Error added in v0.2.6

func (e *PtzRefused) Error() string

type ReadOutcome

type ReadOutcome string

ReadOutcome is what a config read's answer says about whether a camera implements that message.

const (
	ReadSupported   ReadOutcome = "supported"
	ReadWantsParams ReadOutcome = "wants parameters"
	ReadAbsent      ReadOutcome = "not implemented"
)

func ClassifyRead

func ClassifyRead(status int16) ReadOutcome

ClassifyRead sorts a config read's reply into the three answers a camera can give about a message it was asked for, by status alone.

Status alone, not a non-empty body, is what a camera says about a message it does not implement (StatusNotImplemented) versus one it understood but refused for lacking arguments (StatusBadRequest): a camera answering a refusal is free to send an error document rather than an empty one, and a caller that treats "got some bytes back" as "this is supported" gets it backwards on exactly that reply. That is not hypothetical: cmd/reocam's own probe command checked body length before status, and camctl's page checked status alone, and against a real RLC-810A they disagreed on three of 103 reads. usercfg answers 400 with a body, which the body-first check misread as supported; dns and syscpuload answer 200 with an empty body, which it misread as absent (and mislabeled "not implemented (405)" without the status ever being 405). The status-only rule is correct on both counts, so both callers now share it.

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

Reader reads framed messages from a stream.

The camera sends messages back to back on one TCP connection and a message may be split across packets, so each read takes exactly the header and then exactly MsgLen bytes.

func NewReader

func NewReader(r io.Reader) *Reader

func (*Reader) Next

func (r *Reader) Next() (Message, error)

Next reads one complete message, blocking until all of it has arrived.

func (*Reader) SetAESKey

func (r *Reader) SetAESKey(k []byte)

SetAESKey switches body decryption to AES. Call it once login completes: the handshake uses the BC cipher, everything after it uses AES.

func (*Reader) SetCipher added in v0.2.6

func (r *Reader) SetCipher(c Cipher, k []byte)

SetCipher switches body decryption to the cipher the camera chose during login. k is the session's AES key and only matters for CipherAES.

type RecordFile added in v0.2.0

type RecordFile struct {
	Name       string
	Path       string
	Type       string
	Start, End time.Time
	Size       int64
	HasAudio   bool
	HasSub     bool
}

RecordFile is one recording on the card.

type Services added in v0.2.0

type Services struct {
	HTTP  bool
	HTTPS bool
	RTSP  bool
	ONVIF bool
	RTMP  bool
}

Services names the network services to ensure are on. A false field is left exactly as the camera has it; EnableServices never turns anything off.

type Shared added in v0.2.5

type Shared struct {
	// contains filtered or unexported fields
}

Shared runs many streams over one connection to an NVR or Home Hub.

A recorder counts sessions, not streams: an RLN8-410 holds about ten connections and resets the eleventh and twelfth during login, so one connection per stream fits only half of an eight camera recorder. The Reolink app opens every channel it shows over a single connection, and the recorder allows it: measured on the RLN8-410 (firmware 3.5.1.368, 2026-10-28), ten sub stream previews on one connection all ran at the camera's full 15 fps, and channel 1's main and sub ran side by side at 25 and 15 fps.

The recorder echoes each preview request's encryption offset on every media message it sends for it, so the offset's channel and stream bytes say which preview a message belongs to (see StartVideoOn). Two requests for the same channel and stream are both served, as two copies of the same picture told apart only by the request counter, so Shared asks for each channel and stream once and hands its messages to every reader of it: a TrackMix's main and zoom streams behind an NVR are the same channel 1 main stream, and are fetched once.

Once a preview has had one message carrying its own request's counter byte, so the device is known to echo it, a message is handed on only if it carries that counter. A recorder can send a preview that no reader asked for, or no longer does: behind an RLN8-410 (#49) a camera that dropped and came back had its sub stream's readers handed its main stream as well, at once, in the same channel and stream bytes. Matching the channel and stream alone let that through. The echo is proven on cameras (testdata/stream_s2c.bin); a device that does not echo it never matches, and is read by channel and stream alone as before.

The recorder can also get stuck serving a stream's old requests and not its current one (#62, an RLN8-410): while a channel was dark, each retry left a request there; when the channel came back the recorder served those, and answered the current request with its status reply only. Every frame was another request's, and stopping and asking again did not change that, so the channel stayed dark for three hours until a restart opened a new connection. When a preview has had no media of its own for strayReset while its channel and stream arrive for other requests, the connection is closed, which ends every reader on it, and they start again on a new one, as a restart would.

Shared pings the connection itself; a reader's own Ping does nothing.

func NewShared added in v0.2.5

func NewShared(conn *Conn, sup Support, supErr error) *Shared

NewShared takes over conn, which must have just been dialed and have nothing streaming yet. sup and supErr are the recorder's Support read, made before the connection is shared, since a read's reply cannot be told apart from any other once many readers share the connection.

func (*Shared) Close added in v0.2.5

func (s *Shared) Close() error

Close ends the connection and every reader on it.

func (*Shared) Closed added in v0.2.5

func (s *Shared) Closed() bool

Closed reports whether the connection has ended.

func (*Shared) DeviceInfo added in v0.2.5

func (s *Shared) DeviceInfo() []byte

DeviceInfo is the recorder's login reply (see Conn.DeviceInfo).

func (*Shared) Done added in v0.2.5

func (s *Shared) Done() <-chan struct{}

Done closes when the connection ends.

func (*Shared) Err added in v0.2.5

func (s *Shared) Err() error

Err is why the connection ended, once it has.

func (*Shared) Previews added in v0.2.5

func (s *Shared) Previews() int

Previews is how many distinct streams the connection is carrying.

func (*Shared) Subscribe added in v0.2.5

func (s *Shared) Subscribe(channel int, stream string) (*Sub, error)

Subscribe starts reading one channel's stream: StreamMain, StreamSub or StreamExtern. The stream is asked for only if no other reader on this connection already has it.

type SnapReader

type SnapReader struct {
	// contains filtered or unexported fields
}

SnapReader assembles a still from the messages a Snap request produces.

The size is not known until the first reply arrives and the image is usually split across several messages, so this is a small state machine rather than a single read. Feed it every message until Done reports true.

func (*SnapReader) Done

func (s *SnapReader) Done() bool

Done reports whether the whole image has arrived.

func (*SnapReader) Image

func (s *SnapReader) Image() []byte

Image returns the still, trimmed to the size the camera declared. The trailing bytes exist because the final message is padded, the same filler the media path discards.

func (*SnapReader) Name

func (s *SnapReader) Name() string

Name is the filename the camera gave the still, which carries its timestamp: "01_20230518140240.jpg".

func (*SnapReader) Read

func (s *SnapReader) Read(m Message) error

Read takes one message. It reports an error only for a reply it cannot parse; a message that has nothing to do with the snap is ignored.

func (*SnapReader) Size

func (s *SnapReader) Size() int

Size is the length the camera declared, valid once the first reply has been read.

type SnapRefusedError added in v0.2.8

type SnapRefusedError struct{ Status int16 }

SnapRefusedError is a camera answering a Snap with a status other than success: 405 from a model or recorder that does not make stills over this protocol, 400 for a stream it does not have.

func (*SnapRefusedError) Error added in v0.2.8

func (e *SnapRefusedError) Error() string

type StreamInfo

type StreamInfo struct {
	Codec  string
	Width  int
	Height int
}

StreamInfo is what a camera's own media told us about one of its streams.

func GetStreamInfo

func GetStreamInfo(ctx context.Context, addr string, opts Options, stream string) (StreamInfo, error)

GetStreamInfo opens stream (StreamMain, StreamSub or StreamExtern) on its own connection and reads real media back long enough to learn the codec and resolution the camera is actually sending.

This exists because no config message in ConfigMessages has ever been read against a captured reply and shown to carry a stream's resolution and codec: "enc" (message 56) is in the table as a read cmd/reocam can dump raw, but nothing has decoded its schema from a real camera, and docs/control.md's rule against sending a document nobody has seen applies to guessing a reply's shape as much as a request's. What is proven, because it is exactly how every number in docs/measurements.md's stream tables was established, is opening the stream itself and reading what the camera actually sends: the Info packet that starts it, and the first coded frame's own codec tag.

It dials its own Conn rather than taking one that is already probing something else, and closes it before returning. Conn's own doc comment establishes that a camera permits one connection per stream; nothing establishes that calling StartVideo a second time on one connection, to switch which stream it is pulling, is safe, and a first-run setup probe is not the place to find that out against a real camera for the first time.

type Sub added in v0.2.5

type Sub struct {
	// contains filtered or unexported fields
}

Sub is one reader's view of one stream on a Shared connection. It offers the part of Conn's surface a stream reads through.

func (*Sub) Close added in v0.2.5

func (r *Sub) Close() error

Close stops reading. The stream itself stops only when its last reader closes, and the connection stays up for the others.

func (*Sub) DeviceInfo added in v0.2.5

func (r *Sub) DeviceInfo() []byte

DeviceInfo is the recorder's login reply.

func (*Sub) Err added in v0.2.5

func (r *Sub) Err() error

Err reports why Messages closed.

func (*Sub) Messages added in v0.2.5

func (r *Sub) Messages() <-chan Message

Messages yields this stream's media messages. It closes when the shared connection ends or this reader is dropped for falling behind; Err then says which.

func (*Sub) Ping added in v0.2.5

func (r *Sub) Ping() error

Ping does nothing: the shared connection pings itself.

func (*Sub) Support added in v0.2.5

func (r *Sub) Support() (Support, error)

Support is the recorder's Support document, read once when the connection was opened.

type Support

type Support struct {
	XMLName xml.Name `xml:"body"`
	Support struct {
		IOInputPortNum  int    `xml:"IOInputPortNum"`
		IOOutputPortNum int    `xml:"IOOutputPortNum"`
		DiskNum         int    `xml:"diskNum"`
		ChannelNum      int    `xml:"channelNum"`
		AudioNum        int    `xml:"audioNum"`
		PTZMode         string `xml:"ptzMode"`
		PTZCfg          int    `xml:"ptzCfg"`
		B485            int    `xml:"B485"`
		WiFi            int    `xml:"wifi"`
		WiFiVersion     int    `xml:"wifiVersion"`
		GPS             int    `xml:"gps"`
		PowerSavingCfg  int    `xml:"powerSavingCfg"`
		RFVersion       int    `xml:"rfVersion"`
		AudioTalk       int    `xml:"audioTalk"`
		AudioAlarm      int    `xml:"audioAlarm"`
		AudioCfg        int    `xml:"audioCfg"`
		NoExternStream  int    `xml:"noExternStream"`
		RTSP            int    `xml:"rtsp"`
		ONVIF           int    `xml:"onvif"`
		RTMP            int    `xml:"rtmp"`
		Record          int    `xml:"record"`
		StorageMode     int    `xml:"storagemode"`
		Reboot          int    `xml:"reboot"`
		Upgrade         int    `xml:"upgrade"`
		// FTP is the camera's FTP feature bitmask: nonzero on a camera with
		// FTP upload, 0 on builds that ship with it switched off (the
		// compact E1/E320/E330 and NVC-D12M firmware, support_ftp="0" in
		// their dvr.xml), which refuse every FTP request with 400. A pointer
		// so a camera that leaves the element out is not read as a no.
		FTP *int `xml:"ftp"`

		// Item carries the per channel capabilities, and it is where most of
		// what distinguishes one model from another actually lives. The same
		// element is reused for smart home integrations, which have a name
		// and a version and no channel, so entries are told apart by whether
		// they carry a chnID.
		Item []SupportChannel `xml:"item"`
	} `xml:"Support"`
}

Support is the camera's own account of its hardware, from message 199.

This is the capability source to trust. The other two lists each fail in a way this one does not: the HTTP GetAbility list varies by model but reports `talk` on cameras with no speaker, and Baichuan's AbilityInfo is a per-user permission list that reads identically across every model.

Checked against behavior established the slow way on eight cameras: AudioTalk is 1 on exactly the two that make a sound and 0 on the six that accept a talk session once and then refuse forever, and NoExternStream is 1 on exactly the one camera that answers a balanced stream request with silence. Both would have been one query instead of an afternoon.

func GetSupport

func GetSupport(ctx context.Context, conn *Conn) (Support, error)

GetSupport reads the camera's own hardware description, message 199 ("get support"). This is the read cmd/reocam's support command has always used, lifted here rather than duplicated so the CLI and anything else in this module cannot answer the question two different ways.

func ParseSupport

func ParseSupport(x []byte) (Support, error)

ParseSupport reads a Support reply.

func (Support) CanTalk

func (s Support) CanTalk() bool

CanTalk reports whether the camera has a speaker to talk through.

Worth checking before opening a talk session rather than after: a camera without one accepts the configuration, answers 200, makes no sound, and then refuses every later session until it reboots.

func (Support) Channel

func (s Support) Channel(id int) (SupportChannel, bool)

Channel returns the capabilities for one channel, or false if the camera did not report it.

func (Support) HasExternStream

func (s Support) HasExternStream() bool

HasExternStream reports whether the camera serves the balanced stream.

func (Support) HasFishEye added in v0.1.3

func (s Support) HasFishEye(id int) bool

HasFishEye reports whether channel id has the dewarping view modes that GetFishEye and SetFishEye drive. Measured: 3 on the fisheye, 0 on the pano, which has two lenses stitched instead.

func (Support) HasFloodlight added in v0.1.3

func (s Support) HasFloodlight(id int) bool

HasFloodlight reports whether channel id has a white light to drive.

GetWhiteLed cannot answer this. Measured on this fleet, a camera with no light and one with a real one return the same WhiteLed document, mode, state, brightness and schedule alike, differing only in an unrelated AI flag. So a page that renders whatever GetWhiteLed returns shows a floodlight control on cameras that have no floodlight, which is what happened.

ledCtrl answers it, but as bits, not as zero or not: 0 on the fisheye, 38 (bits 1, 2, 5) on the pano and the TrackMix, 4111 (bits 0-3, 12) on the Argus PT Ultra, all three with a white light, and 64 (bit 6 alone) on the RLC-810A, which has none and was being offered floodlight controls (click test, 10-27). Bits 1 and 2 are what every camera here with a white light has and the others lack.

func (Support) HasPTZ

func (s Support) HasPTZ() bool

HasPTZ reports whether the camera has motors. ptzMode reads "none" on every fixed camera here.

func (Support) HasSiren added in v0.2.9

func (s Support) HasSiren() bool

HasSiren reports whether the camera has a siren to sound. audioAlarm is 1 on the TrackMix, the pano, the fisheye and the Argus PT Ultra, and 0 on the RLC-810As, which have no speaker.

func (Support) HasStitch added in v0.1.4

func (s Support) HasStitch(id int) bool

HasStitch reports whether channel id has two lenses whose seam GetStitch and SetStitch adjust.

Measured on this fleet, binoCfg is exactly the inverse of fishEye: 1 on the pano and 0 on the fisheye, against 0 and 3 for fishEye. That is the physical fact behind it -- one sensor behind one lens has no seam, and two lenses have nothing to dewarp -- so the two controls are never both offered, and neither is ever offered on the six ordinary cameras.

func (Support) LacksFTP added in v0.2.5

func (s Support) LacksFTP() bool

LacksFTP reports whether the camera says outright that it has no FTP upload. Only a positive no counts: a Support block without the element says nothing either way.

type SupportChannel

type SupportChannel struct {
	Name        string `xml:"name"`
	ChannelID   *int   `xml:"chnID"`
	PTZType     int    `xml:"ptzType"`
	PTZControl  int    `xml:"ptzControl"`
	PTZPreset   int    `xml:"ptzPreset"`
	PTZPatrol   int    `xml:"ptzPatrol"`
	PTZTattern  int    `xml:"ptzTattern"`
	AutoPT      int    `xml:"autoPt"`
	AutoFocus   int    `xml:"autoFocus"`
	ZFBacklash  int    `xml:"zfBacklash"`
	Battery     int    `xml:"battery"`
	BatAnalysis int    `xml:"batAnalysis"`
	NoAudio     int    `xml:"noAudio"`
	AudioVer    int    `xml:"audioVersion"`
	LEDCtrl     int    `xml:"ledCtrl"`
	ISPCfg      int    `xml:"ispCfg"`
	NewISPCfg   int    `xml:"newIspCfg"`
	OSDCfg      int    `xml:"osdCfg"`
	EncCtrl     int    `xml:"encCtrl"`
	Motion      int    `xml:"motion"`
	AIType      int    `xml:"aitype"`
	Snap        int    `xml:"snap"`
	VideoClip   int    `xml:"videoClip"`
	Timelapse   int    `xml:"timelapse"`
	Thumbnail   int    `xml:"thumbnail"`
	DynamicReso int    `xml:"dynamicReso"`
	RFCfg       int    `xml:"rfCfg"`
	FishEye     int    `xml:"fishEye"`
	BinoCfg     int    `xml:"binoCfg"`
}

SupportChannel is one channel's capabilities.

The values are not all booleans. Several are bitmasks or version numbers: FishEye reads 3 on the fisheye here, AIType 3879, ISPCfg 195. Treat a nonzero value as "present, in some form" and do not read the magnitude as a count of anything without checking.

type TalkFormat

type TalkFormat struct {
	Duplex           string
	StreamMode       string
	AudioType        string
	SampleRate       int
	SamplePrecision  int
	LengthPerEncoder int
	SoundTrack       string
}

TalkFormat is one audio configuration a camera will accept for two-way audio, as reported in its TalkAbility reply.

func OpenTalk added in v0.1.9

func OpenTalk(ctx context.Context, conn *Conn) (TalkFormat, error)

OpenTalk opens a two-way audio session on conn and returns the format the camera agreed to, which every Talk packet on conn must then be in.

The speaker check comes first and is not optional. A camera without one accepts the configuration with a 200, plays nothing, and then refuses every later session until it reboots, so asking costs one round trip and not asking can cost the feature on that camera until someone power cycles it.

func ParseTalkAbility

func ParseTalkAbility(x []byte) (TalkFormat, error)

ParseTalkAbility reads a TalkAbility reply and returns the camera's preferred format: the first duplex mode, the first stream mode and the audioConfig with the lowest priority value, which is how the cameras rank them.

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer writes framed messages, encrypting bodies to match what the camera expects at each stage of the session.

func NewWriter

func NewWriter(w io.Writer) *Writer

func (*Writer) SetAESKey

func (w *Writer) SetAESKey(k []byte)

SetAESKey switches body encryption to AES, mirroring Reader.SetAESKey.

func (*Writer) SetCipher added in v0.2.6

func (w *Writer) SetCipher(c Cipher, k []byte)

SetCipher switches body encryption to c, mirroring Reader.SetCipher.

func (*Writer) Write

func (w *Writer) Write(h Header, body []byte) error

func (*Writer) WriteMedia

func (w *Writer) WriteMedia(h Header, xmlPart, mediaPart []byte) error

WriteMedia writes a message whose second section is media rather than a second XML document, so the section is left in plaintext.

The rule is the extension header's own: a payload is encrypted only as far as <encryptLen> says, and a message that declares no encryptLen carries plaintext. That is how the camera's own audio and video arrive, and an outbound media message follows the same rule. A TalkConfig is the other case, since its second section is XML, and it is refused unless sealed.

func (*Writer) WriteParts

func (w *Writer) WriteParts(h Header, xmlPart, binPart []byte) error

Write frames and sends one message. MsgLen is set from the encrypted body. WriteParts writes a message that has an XML header and a binary section, sealing each as its own cipher stream.

The two parts are sealed separately, both starting from the fixed IV, and that detail is the whole reason this exists. Write seals a body as one continuous stream, which is right for a message that is XML to the end and wrong for one that is not: a TalkConfig sent that way is refused with status 400, and so is one whose binary section is left in plaintext. Only separate streams are accepted.

It mirrors the receive side, where a message's payload is decrypted as its own stream rather than as a continuation of the one covering the XML. The camera's parser is symmetric; ours has to be too.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL