Documentation
¶
Overview ¶
Package baichuan implements the Reolink Baichuan protocol.
Index ¶
- Constants
- Variables
- func AESDecrypt(key, buf []byte) ([]byte, error)
- func AESEncrypt(key, buf []byte) ([]byte, error)
- func AESKey(nonce, password string) []byte
- func BCCrypt(offset uint32, buf []byte) []byte
- func ConfigNames() []string
- func EncOffsetFor(channel, stream, counter, handle byte) uint32
- func ExplainStatus(status int16) string
- func HeaderLen(class uint16) int
- func MsgName(id uint32) string
- func ReadConfig(ctx context.Context, conn *Conn, id uint32) ([]byte, int16, error)
- func SetHeartBeatTwoPart(v bool)
- func StreamID(stream string) byte
- func TalkPacket(block []byte) []byte
- func UnsafeToRewrite(id uint32) bool
- func WriteConfig(ctx context.Context, conn *Conn, id uint32, body []byte) (int16, error)
- type Ability
- type ConfigPair
- type Conn
- func (c *Conn) Abilities() error
- func (c *Conn) Close() error
- func (c *Conn) DeviceInfo() []byte
- func (c *Conn) Err() error
- func (c *Conn) GetConfig(msgID uint32) error
- func (c *Conn) HeartBeat() error
- func (c *Conn) Messages() <-chan Message
- func (c *Conn) Nonce() string
- func (c *Conn) Ping() error
- func (c *Conn) RawChannelRequest(msgID uint32) error
- func (c *Conn) SetConfig(msgID uint32, body []byte) error
- func (c *Conn) Snap(stream string) error
- func (c *Conn) StartVideo(stream string) error
- func (c *Conn) Talk(packet []byte) error
- func (c *Conn) TalkAbility() error
- func (c *Conn) TalkConfig(cfg TalkFormat) error
- type Depacketiser
- type DeviceInfo
- type Frame
- type FrameKind
- type Header
- type HeartBeatReply
- type Message
- type Options
- type ReadOutcome
- type Reader
- type SnapReader
- type StreamInfo
- type Support
- type SupportChannel
- type TalkFormat
- type Writer
Constants ¶
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 )
Message IDs.
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.
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.
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.
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 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 )
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.
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.
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.
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.
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 ¶
var ( ErrBadMagic = errors.New("baichuan: bad magic") ErrShortHeader = errors.New("baichuan: short header") )
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.
var ErrMessageTooLarge = errors.New("baichuan: message body exceeds MaxMessageSize")
ErrMessageTooLarge means a header declared a body bigger than MaxMessageSize.
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.
ErrUnauthorised 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".
Functions ¶
func AESEncrypt ¶
AESEncrypt applies AES-128-CFB with the fixed IV.
func AESKey ¶
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 ¶
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 only: the negotiation reply, the login request and the DeviceInfo reply. Everything after login is AES.
func ConfigNames ¶
func ConfigNames() []string
ConfigNames lists the keys of ConfigMessages in sorted order.
func EncOffsetFor ¶
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 ¶
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 ReadConfig ¶
ReadConfig sends a config read that takes only a channel and waits for its reply, or for ctx to end.
func SetHeartBeatTwoPart ¶
func SetHeartBeatTwoPart(v bool)
SetHeartBeatTwoPart switches that choice.
func TalkPacket ¶
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 ¶
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 WriteConfig ¶
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 and message 288 both accept a valid document, on hardware that implements the matching read, answer 200, and change nothing observable. Callers that need to know whether a write took effect must read the block back on a fresh connection and compare.
Types ¶
type Ability ¶
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 ¶
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 ¶
ParseAbilities reads an AbilityInfo reply into a sorted list.
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 normalised key. Normalising 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 ¶
Dial connects to a camera and logs in. addr may omit the port, in which case 9000 is used.
func (*Conn) Abilities ¶
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) DeviceInfo ¶
DeviceInfo returns the raw <DeviceInfo> document the camera sent as its login reply. Parse it with ParseDeviceInfo.
func (*Conn) Err ¶
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) GetConfig ¶
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) HeartBeat ¶
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) Ping ¶
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) RawChannelRequest ¶
RawChannelRequest sends a bare request carrying only a channel, for probing message ids whose shape is not yet known.
func (*Conn) SetConfig ¶
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) Snap ¶
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) StartVideo ¶
StartVideo requests a stream: StreamMain, StreamSub or StreamExtern.
func (*Conn) Talk ¶
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 ¶
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 Depacketiser ¶
type Depacketiser struct {
// contains filtered or unexported fields
}
Depacketiser 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 NewDepacketiser ¶
func NewDepacketiser() *Depacketiser
func (*Depacketiser) Filler ¶
func (d *Depacketiser) 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 (*Depacketiser) Next ¶
func (d *Depacketiser) Next() (Frame, bool)
Next returns the next complete frame, or false if more bytes are needed.
func (*Depacketiser) Skipped ¶
func (d *Depacketiser) 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 (*Depacketiser) Write ¶
func (d *Depacketiser) 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"`
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.
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 ¶
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 Header ¶
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 ¶
DecodeHeader parses a header from the front of b and reports its length.
type HeartBeatReply ¶
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
}
Message is a decoded Baichuan message. XML is decrypted; Payload is the binary remainder, which is media data and is never encrypted.
type Options ¶
type Options struct {
Username string
Password string
Channel int
// 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 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.
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 StreamInfo ¶
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 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"`
// 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 behaviour 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 ¶
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 ¶
ParseSupport reads a Support reply.
func (Support) CanTalk ¶
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 ¶
HasExternStream reports whether the camera serves the balanced stream.
func (Support) HasFishEye ¶ added in v0.1.3
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
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 does answer it: 0 on the fisheye, 38 on the pano. Nonzero means present in some form, per this type's own warning about magnitudes.
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 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 (*Writer) WriteMedia ¶
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 ¶
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.