Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Welcome & Goals

viva-genicam provides pure Rust building blocks for the GenICam ecosystem supporting GigE Vision and USB3 Vision, with first-class support for Windows, Linux, and macOS.

Who is this book for?

People using viva-genicam: building a camera application in Rust or Python, running viva-camctl, or using Viva Studio. Working on viva-genicam itself? The developer documentation lives in the repository — see Developing viva-genicam.

What works today

  • GigE Vision: GVCP discovery, broadcast or of one address, flagging a camera configured for another subnet; control privilege given back when a camera is closed, and read-only monitors that watch a camera — and its multicast stream — while another application controls it; GVSP streaming on a receive thread per stream, tolerant of reordered, repeated and extended-ID packets, with every frame’s fate counted; chunk and event features read through the camera’s own XML, action commands, FORCEIP, persistent IP configuration. Lost packets are requested again from cameras that support packet resend; resend recovery has also run on the Manta G-125B (tested cameras).
  • USB3 Vision: discovery without opening the device, GenCP register I/O, streaming with several USB transfers in flight that recovers from a failed transfer and ends with an error of its own when the camera is unplugged, chunks, events, frame timestamps on the host’s clock, and a warning when a camera runs below SuperSpeed — see Status.
  • Camera API: features read and written by type; helpers for exposure, gain, triggers, region of interest, binning, frame rate and user sets that accept the older names cameras still use (ExposureTimeAbs, GainRaw, …); acquisition locks the transport parameters; a camera’s configuration saved to a file and restored, selectors and dependencies included; a blocking API for programs without an async runtime.
  • GenApi: NodeMap with the standard node types (Integer, Float, Enumeration, Boolean, Command, Category, String, Register, SwissKnife, Converter, IntConverter), pValue delegation, selectors, device, chunk and event ports, runtime access predicates (pIsLocked, pIsAvailable, pIsImplemented), node metadata and visibility filtering; values cached only as the XML’s <Cachable> allows and read again after their <PollingTime>, with a query for what changed since a viewer last looked.
  • CLI (viva-camctl): discovery; the feature tree, a feature’s full description and every value; get/set, command execution, configuration save and load; raw register access and action commands; streaming (including raw event-vision capture), events, chunks, benchmarks, IP configuration, XML dump, and a diagnostic report bundle — see the command line.
  • GenTL producer: viva_gentl.cti lets GenTL consumers such as Harvesters use GigE Vision cameras through viva — see Use viva from other tools.
  • Service bridge: expose cameras over Zenoh for Viva Studio, the desktop app in studio/.

Status

viva-genicam is pre-1.0: the API still changes between releases.

  • GigE Vision: users have run discovery, control and streaming against real cameras from several vendors, on Linux, Windows and macOS; tested cameras records the evidence.
  • USB3 Vision has run on one camera: a MATRIX VISION mvBlueFOX3-2004G, on macOS (Apple silicon), over a USB 2 (High Speed) link. Discovery, control, streaming, chunks, events and the host clock were checked against it. It streams on Windows too, once the WinUSB driver is installed (USB3 Vision setup). Not yet tried: Linux, a SuperSpeed link, any other vendor’s camera, and a transfer that fails in the middle of a stream. Pulling the cable while it streams ends the stream as an unplug, checked on macOS. If you have a USB3 Vision camera, a report from viva-camctl report --usb 0 is the most useful thing you can send (Reporting a camera we can’t open).
  • Viva Studio is experimental: it works, and it has been driven against very little hardware.
  • The GenTL producer is new: Harvesters drives it on every change, against the fake camera. Harvesters and the independent C harness also acquired complete frames from the Manta G-125B (tested cameras).
  • There is no camera in CI. The tests run against built-in fake cameras and a corpus of real vendor GenApi XML; hardware confirmations come from users with their own devices.

The full, current list of known gaps is issue #191, updated as fixes land. If your camera hits something that is not on it, tell us.

How this book is organized

  • Getting started: the Quick Start runs a first discovery; the Primer and How the library fits together give the big picture, errors and logging included.
  • Using the library: tutorials and networking.
  • Python and Viva Studio each have a part of their own.
  • Help: FAQ & Troubleshooting, and how to report a camera we cannot open.
  • Reference: the crates, the API docs, a glossary.

Quick Start

From nothing to a list of the cameras on your network.

Install what you need

  • A Rust application: add the facade crate and an async runtime. Rust 1.88 or newer.

    cargo add viva-genicam
    cargo add tokio --features full
    
  • The command line: viva-camctl comes with the Python package (pip install viva-genicam), and in the viva-genicam-<version>-<platform> archives on each GitHub release, next to viva-service.

  • Python: pip install viva-genicam — see Install & hello-camera.

  • A desktop app: Viva Studio.

For a GigE Vision camera, the host must allow UDP broadcast on the network interface the camera is on; Networking covers firewalls, addressing and jumbo frames.

Find your cameras

From the command line:

viva-camctl list
# Only on one network interface, named by its address or its OS name:
viva-camctl list --iface 192.168.0.5

From Rust, discovery is one call; the snippet comes from the list_cameras example:

    // `discover` broadcasts on the interfaces the library can see; naming one
    // pins it to that NIC, which is what you want on a multi-homed host.
    // `IfaceSelector` takes either spelling — `--iface 192.168.0.5` or
    // `--iface eth0` — so the flag means the same thing here as in
    // `viva-camctl` and `viva-service`.
    let devices = if let Some(selector) = iface.as_ref() {
        let iface = selector.resolve()?;
        viva_genicam::gige::discover_on_interface(timeout, iface.name()).await?
    } else {
        viva_genicam::gige::discover(timeout).await?
    };

    if devices.is_empty() {
        println!("No cameras found.");
        return Ok(());
    }

    println!("{:<16} {:<17} {:<20} Model", "IP", "MAC", "Manufacturer");
    for dev in devices {
        println!(
            "{:<16} {:<17} {:<20} {}",
            dev.ip,
            format_mac(&dev.mac),
            dev.manufacturer.as_deref().unwrap_or("-"),
            dev.model.as_deref().unwrap_or("-"),
        );
    }

Then connect to one and read or write a feature by name (get_set_feature):

    // `connect_gige` fetches the GenApi XML and builds the NodeMap, so every
    // feature the camera declares is addressable by name from here on.
    let mut camera = connect_gige(&device).await?;

    // Feature access is synchronous even inside an async program: the register
    // I/O behind it blocks, and `GigeRegisterIo` steps off the async worker on
    // its own rather than making every caller do it.
    println!("{name} = {}", camera.get(&name)?);

    if let Some(value) = value.as_deref() {
        camera.set(&name, value)?;
        println!("{name} = {} (after write)", camera.get(&name)?);
    }

From a clone of the repository the examples run as cargo run -p viva-genicam --example list_cameras, and the CLI as cargo run -p viva-camctl -- list.

Control path: read / write & XML

# Read a feature by name
viva-camctl get --ip 192.168.0.10 --name ExposureTime

# Set a feature value
viva-camctl set --ip 192.168.0.10 --name ExposureTime --value 5000

# Dump the camera's GenApi XML
viva-camctl xml --ip 192.168.0.10 --out camera.xml

When something does not work

# Collect everything a bug report needs, in one file
viva-camctl report --ip 192.168.0.10 --out viva-report.txt

The report lists the network interfaces the library can see, the camera’s reply to discovery, its bootstrap registers, its GenApi XML, and any feature the camera has that this library could not build. Neither report nor xml needs the camera to open successfully — that is what they are for — so both still produce output when nothing else does. Attach the file to an issue.

Streaming

# Receive a GVSP stream and save 2 frames to the current directory.
# By default the camera's GevSCPSPacketSize is kept; --auto sizes packets from
# the NIC MTU, --packet-size N sets an explicit ceiling.
viva-camctl stream --ip 192.168.0.10 --iface 192.168.0.5 --auto --save 2

See Streaming → Packet size and MTU.

Windows specifics

The firewall prompt, NIC power saving and jumbo frames are the usual obstacles; see Networking → Windows. A USB3 Vision camera needs the WinUSB driver; see USB3 Vision setup → Windows.

Next steps

  • Read the Primer for the concepts behind discovery, control, and streaming.
  • Jump to the Discovery tutorial for a step‑by‑step walkthrough with troubleshooting tips.
  • No camera yet? Testing without hardware runs everything against an in-process fake.

GenICam & Vision Standards Primer

This chapter orients you in the standards behind GigE Vision and USB3 Vision cameras: skim the concepts, then jump to the tutorials.

1) Control vs. Data paths (big picture)

  • Control: configure the device, read status, fetch the GenApi XML. In GigE Vision, control is GVCP (GigE Vision Control Protocol, UDP): register and memory reads and writes. GVCP is a protocol of its own that GenCP (Generic Control Protocol) generalised — the same ideas and a shared core of status codes, but its own opcodes, headers and big-endian fields. USB3 Vision carries GenCP itself.
  • Data: receive image/metadata stream(s). In GigE Vision, data is GVSP (GigE Vision Streaming Protocol, UDP), typically one-way from camera → host.
  • Events & Actions: GVCP supports device→host events and host→device action commands for sync/triggering.
   +------------------------+        +--------------------+
   |        Host            |        |     Camera         |
   |  (this repository)     |        |  (GigE Vision)     |
   +-----------+------------+        +----------+---------+
               | GVCP (UDP, control)           |
               |  registers, memory, XML       |
               v                                ^
       Configure, query, XML                    |
                                                |
               ^                                v
               | GVSP (UDP, data)         Image/Chunks
               | (streaming)                    |

2) GenApi XML & NodeMap

  • The device exposes an XML description of its features (nodes). Nodes form a graph with types like Integer, Float, Boolean, Enumeration, Command, String, Register, and expression nodes like SwissKnife.
  • Nodes have AccessMode (RO/RW), Visibility (Beginner/Expert/Guru), Units, Min/Max/Inc, Selector links, and Dependencies (i.e., a node’s value depends on other nodes).
  • The host builds a NodeMap from the XML and evaluates nodes on demand: some read/write device registers; others compute values from expressions.

SwissKnife (implemented)

  • A SwissKnife node computes its value from an expression referencing other nodes (e.g., arithmetic, logic, conditionals). Typical uses:
    • Derive human‑readable features from raw register fields.
    • Apply scale/offset and conditionals depending on selectors.
  • In this project, SwissKnife is evaluated in the NodeMap, so reads of dependent nodes trigger the calculation transparently.

Selectors

  • Selectors (e.g., GainSelector) change the addressing or active branch so the same feature name maps to different underlying registers or computed paths.

3) Streaming: GVSP

  • UDP packets carry payloads (image data/metadata). The host reassembles frames, chooses a packet size that fits the path MTU, and may introduce packet delay to avoid NIC/driver overflow.
  • Chunks: optional metadata blocks (e.g., Timestamp, ExposureTime) sent with each frame; the camera’s GenApi XML declares, per chunk, the features that read it.
  • Time mapping: devices often use tick counters; the host maintains a mapping between device ticks and host time for cross‑correlation.

4) How standards map to crates

Each layer of the standards is a crate of its own; How the library fits together shows which.

5) USB3 Vision

  • Similar split between control and data paths, but with USB3 transport (viva-u3v): GenCP over USB bulk endpoints for control, and a separate bulk endpoint for image data. Discovery is USB enumeration rather than a broadcast. The higher‑level GenApi and NodeMap concepts remain the same.

How the library fits together

viva-genicam is a stack of crates, each one a layer of the GenICam standards. Most applications use only the top one, viva-genicam; the layers below are there when you need to reach past it.

The layers

  your application          viva-camctl (CLI)      Python (viva-genicam on PyPI)
          \                        |                      /
           +---------------- viva-genicam ---------------+     discovery, Camera, streams, events
                          /                  \
                 viva-genapi                  transports
           NodeMap: features by name          viva-gige (GigE Vision: GVCP control, GVSP streaming)
                       |                      viva-u3v  (USB3 Vision: GenCP over USB bulk endpoints)
               viva-genapi-xml                         \
           the camera's GenApi XML                    viva-gencp (GenCP / GVCP message primitives)
  • viva-genicam — start here. It discovers cameras, opens them, fetches their XML, and gives you a Camera whose features you read and write by name, plus frame streams, events, chunks and time mapping.
  • viva-genapi — the GenApi engine: it turns a feature name such as ExposureTime into register reads and writes, evaluating formulas, selectors and access rules on the way.
  • viva-genapi-xml — parses a camera’s GenApi XML, from the camera or from a file.
  • viva-gige and viva-u3v — the two transports.
  • viva-gencp — the control-protocol message formats both build on.

Around the stack: viva-pfnc names pixel formats and converts their pixels, viva-sfnc names standard features; viva-service and viva-service-u3v serve cameras over Zenoh for Viva Studio and other clients, with the messages defined in viva-zenoh-api; viva-gentl is the GenTL producer, viva_gentl.cti, through which other software uses the stack (Use viva from other tools); viva-fake-gige and viva-fake-u3v are cameras that run in your process (Testing without hardware). The Crates page says which of them you are likely to need.

What happens when you open a camera

  1. Discovery finds cameras: a GVCP broadcast on each network interface, or USB enumeration.
  2. Connecting opens the control channel. For GigE Vision this also takes control privilege and starts a heartbeat that keeps it.
  3. The GenApi XML is read from the camera — its address is in the camera’s bootstrap registers — and parsed.
  4. The NodeMap is built from it. A declaration the library cannot build is listed in NodeMap::skipped() instead of failing the camera.
  5. Feature access goes through the NodeMap: a direct feature reads and writes its registers, a computed one evaluates its formula over others.
  6. Streaming configures the camera’s stream channel and receives frames — GVSP packets reassembled over UDP, or USB3 Vision blocks over a bulk endpoint — with their timestamps and chunk data.

Blocking and async

Discovery, stream setup and frame reception are async (Tokio): FrameStream::next_frame is an async fn.

Feature access is synchronous: Camera::get and Camera::set block until the camera answers. That keeps the GenApi engine independent of any runtime, and it is safe to call them inside #[tokio::main] — the GigE transport bridges onto its async client itself. In a GUI or a server, call them where a short block is acceptable, such as a blocking-pool task. The reasoning is in ADR-0014.

Errors and logs

The facade returns GenicamError: it carries a GenApiError from the NodeMap as it is, and a transport failure with what it was doing and the transport’s own error as its source — GenicamError::Gige { during: "claim control", source }, whose source is a GigeError, and a GigeError::Status holds the camera’s GigeStatus. Every error prints its cause, and every error enum is #[non_exhaustive], so a match needs a wildcard arm. Below the facade, each crate has an error type of its own, and all of them implement std::error::Error:

ErrorCrateRaised by
GenicamErrorviva-genicamconnecting, Camera, streams
ChunkErrorviva-gige (re-exported by viva-genicam)a chunk payload that does not tile into tagged chunks
GenApiErrorviva-genapifeature access: access mode, range, locks, formulas, register I/O (the variants)
XmlErrorviva-genapi-xmlfetching or parsing a GenApi document
GigeErrorviva-gigeGVCP discovery and control, including a status code the camera returned (GigeStatus)
GvspErrorviva-gigemalformed or unsupported GVSP packets
U3vErrorviva-u3vUSB I/O, timeouts and device status on USB3 Vision (U3vStatus)
GenCpErrorviva-gencpdecoding a control message

Everything logs through tracing. Install a subscriber that reads RUST_LOG — tracing_subscriber::fmt::init() does, with tracing-subscriber’s env-filter feature — and set RUST_LOG=debug to see the protocol traffic. viva-camctl -v and -vv log at debug and trace.

Platforms

Linux, macOS and Windows. Network setup — firewalls, interface selection, jumbo frames — is in Networking. On a host with several network interfaces, name the one your camera is on.

Tutorials

This section walks you through typical workflows step by step.

The focus is a GigE Vision camera accessed over Ethernet, using:

  • The viva-camctl CLI for quick experiments and ops work.
  • The viva-genicam crate for Rust examples you can copy into your own code.

Each tutorial has a CLI variant and a Rust variant built on the examples in crates/viva-genicam/examples/.

If you haven’t yet, start with the Quick start: it installs the library and the CLI and runs a first discovery.


  1. Discovery — find cameras on your network, verify that discovery works, and understand basic NIC and firewall requirements.
  2. Registers & features — read and write GenApi features (e.g. ExposureTime), use selectors such as GainSelector, and learn when you might need raw registers.
  3. Common tasks — exposure, gain, triggers, region of interest, binning, frame rate and user sets, whatever names the camera uses for them; and a program without an async runtime.
  4. GenApi XML — fetch the GenICam XML from a device, inspect it, and see how it maps to the NodeMap used by viva-genapi.
  5. Streaming — start a GVSP stream, receive frames, read the statistics, and learn which knobs matter for throughput and robustness.
  6. Testing without hardware — run everything above against an in-process fake camera, for tests, demos, or before your camera arrives.

You can stop after Discovery and Streaming if you only need to verify that your camera works. The other tutorials are useful when you want to build a full application or debug deeper GenApi issues.


What you need before starting

  • A Rust toolchain, 1.88 or newer, and a clone of the repository. The commands run from its root, as cargo run -p viva-camctl -- … and cargo run -p viva-genicam --example …:

    git clone https://github.com/VitalyVorobyev/viva-genicam
    cd viva-genicam
    

    With viva-camctl installed (Quick start), viva-camctl … does the same as cargo run -p viva-camctl -- ….

  • At least one GigE Vision camera reachable from your machine — connected directly to a NIC, or through a switch on a dedicated subnet. No camera yet? Start with Testing without hardware.

For networking details (MTU, jumbo frames, firewalls, link-local addressing), see the Networking Guide.

Discovery

Goal of this tutorial:

  • Verify that your host can see your GigE Vision camera.
  • Run discovery from the viva-camctl CLI and from Rust.
  • Understand the usual reasons it fails (NIC selection, firewall, subnets).

If discovery does not work, the other tutorials will not help much — fix this first.


Before you begin

Make sure that:

  • The workspace builds:

    cargo build --workspace
    
  • Your camera and host are physically connected — a direct cable from host NIC to camera, or a switch on a subnet dedicated to the cameras.

  • The camera has a valid IPv4 address: from DHCP on your camera network, a static address matching the host NIC’s subnet, or a link-local (APIPA) address. Link-local setups need a little extra care on the host — see Link-local (APIPA) cameras.

For jumbo frames, MTU and throughput tuning, see the Networking Guide.


Step 1 – Discover with viva-camctl

1.1. Basic discovery

cargo run -p viva-camctl -- list

On success you get one line per device with its IP, MAC, manufacturer and model. If nothing appears:

  • Check that the camera is powered and the link LED is lit.
  • Check that your NIC is on the same subnet as the camera.
  • Check that your host firewall allows UDP broadcast on that NIC.

1.2. Selecting an interface explicitly

On multi-NIC systems, tell viva-camctl which interface to use. --iface names your host NIC — never the camera — and accepts either of the two ways a host NIC is normally identified:

cargo run -p viva-camctl -- list --iface 192.168.0.5   # one of its IPv4 addresses
cargo run -p viva-camctl -- list --iface eth0          # its OS name

Both spellings work in viva-service, in the Python iface= argument and in the Rust examples too, so the value you found once carries across the tools. Use whichever you have: on Windows an interface name is a GUID like {6394C55F-F630-4BC7-92D2-7AC320C73D1C}, which is far harder to obtain than the address.

If you are not sure which NIC to use, ip addr (Linux), ifconfig (macOS) or ipconfig (Windows) will tell you — and so will an unresolvable --iface, which lists every interface the library can see. That list matters on its own: it is not always the same set the OS reports, and an interface missing from it is invisible to discovery no matter what anything else says.

If discovery works with --iface but not without it, your machine has several active interfaces and the automatic choice is not the one you expect.

1.3. Machine-readable output

--json is a top-level flag, so it goes before the subcommand:

cargo run -p viva-camctl -- --json list

Step 2 – Discover from Rust

cargo run -p viva-genicam --example list_cameras
cargo run -p viva-genicam --example list_cameras -- --iface eth0
cargo run -p viva-genicam --example list_cameras -- --iface 192.168.0.5

The part that matters is short:

    // `discover` broadcasts on the interfaces the library can see; naming one
    // pins it to that NIC, which is what you want on a multi-homed host.
    // `IfaceSelector` takes either spelling — `--iface 192.168.0.5` or
    // `--iface eth0` — so the flag means the same thing here as in
    // `viva-camctl` and `viva-service`.
    let devices = if let Some(selector) = iface.as_ref() {
        let iface = selector.resolve()?;
        viva_genicam::gige::discover_on_interface(timeout, iface.name()).await?
    } else {
        viva_genicam::gige::discover(timeout).await?
    };

    if devices.is_empty() {
        println!("No cameras found.");
        return Ok(());
    }

    println!("{:<16} {:<17} {:<20} Model", "IP", "MAC", "Manufacturer");
    for dev in devices {
        println!(
            "{:<16} {:<17} {:<20} {}",
            dev.ip,
            format_mac(&dev.mac),
            dev.manufacturer.as_deref().unwrap_or("-"),
            dev.model.as_deref().unwrap_or("-"),
        );
    }

Three entry points exist, and the difference matters more than it looks:

FunctionScans
gige::discover(timeout)Every IPv4 interface the library can enumerate, except loopback
gige::discover_on_interface(timeout, name)One named interface — loopback too, if you name it
gige::discover_all(timeout)Every interface including loopback

Use discover_all only when you are talking to the fake camera on 127.0.0.1. Against real hardware it adds a loopback scan that can only produce noise.


Step 3 – Interpreting results

Record two things — you will reuse them in every later tutorial:

  • The camera’s IP address (e.g. 192.168.0.10) → --ip 192.168.0.10
  • The host NIC you used (e.g. 192.168.0.5 or eth0) → --iface 192.168.0.5

If several cameras answer, label them physically now rather than guessing later.


Troubleshooting checklist

If neither viva-camctl list nor list_cameras finds anything:

  1. Physical link — is the link LED lit on NIC, switch and camera? Try another cable or port.
  2. Subnets — host NIC and camera must share a subnet. Two NICs on the same subnet confuse routing; avoid it.
  3. Firewall — the camera’s reply is inbound UDP from port 3956, and a default-deny policy drops it silently. On Windows, allow the program on the network profile the camera NIC uses — see Networking → Windows. On Linux with firewalld, add the rule in Letting the reply back in.
  4. Multiple NICs — force the right one with --iface <host-ip>, or disable the others temporarily to confirm that NIC selection is the problem.
  5. Link-local addresses — a camera on 169.254.x.y needs the host to have a link-local address too; see Link-local (APIPA) cameras.
  6. Vendor tools — if the vendor’s viewer sees the camera and viva-camctl does not, see Vendor tool works, viva-genicam does not.

Still failing? Capture the details and send them:

cargo run -p viva-camctl -- report --out viva-report.txt

The report records your interfaces as the library sees them and everything discovery did or did not hear — which is precisely what we need and cannot guess. See Reporting a camera we can’t open.

Registers & features

Goal of this tutorial:

  • Read and write GenApi features such as ExposureTime or Gain.
  • Understand how features map to the underlying registers.
  • Use selectors (e.g. GainSelector) and understand what they change.
  • Do all of it from both the viva-camctl CLI and Rust.

Work through Discovery first, so you know your camera’s IP and which host interface you are using.


Concepts: features vs registers

GenICam describes camera configuration as features in the GenApi XML:

  • A feature has a name (ExposureTime, Gain, PixelFormat, …) and a type (Integer, Float, Boolean, Enumeration, Command, String, …).
  • Under the hood, a feature usually corresponds to one or more registers. A simple one reads a single 32-bit register; others are derived through SwissKnife expressions, or depend on selectors.

The layering:

  • viva-genapi-xml parses the XML into an XmlModel.
  • viva-genapi builds a NodeMap from it and evaluates nodes on demand.
  • viva-genicam and viva-camctl sit on top and hide the addressing.

Step 1 – Inspect features with viva-camctl

You need the camera IP from the discovery tutorial, and the host interface IP if you have several NICs.

1.1. Read a feature by name

cargo run -p viva-camctl -- get --ip 192.168.0.10 --name ExposureTime

For machine-readable output, note that --json is a top-level flag and goes before the subcommand:

cargo run -p viva-camctl -- --json get --ip 192.168.0.10 --name ExposureTime

1.2. Write a feature by name

cargo run -p viva-camctl -- set --ip 192.168.0.10 --name ExposureTime --value 5000
cargo run -p viva-camctl -- get --ip 192.168.0.10 --name ExposureTime

If the value does not change, the usual causes are:

  • The feature is locked right now. GenApi expresses this with pIsLocked, which the library evaluates before every write — so a locked feature is refused locally with a clear error, rather than being sent to the camera and failing there.
  • The value violates a constraint — Min, Max or Inc. Many cameras report these at run time (pMin/pMax/pInc in the XML: a Width whose maximum shrinks as OffsetX grows), and the library reads them and refuses an out-of-range write locally, before anything reaches the camera.
  • Another feature is overriding manual control — ExposureAuto is the usual culprit for ExposureTime, GainAuto for Gain.

1.3. Which features does this camera have?

The report bundle lists node and feature counts along with the XML itself:

cargo run -p viva-camctl -- report --ip 192.168.0.10 --out viva-report.txt

Step 2 – Work with selectors

Many cameras multiplex several logical settings onto the same registers:

  • GainSelector = All, Red, Green, Blue, …
  • Gain = the value for the currently selected channel.

Changing the selector changes which “row” you are editing. The camera’s XML lists, on the selector, the features it selects (<pSelected>); the NodeMap re-resolves their addressing and drops their cached values, so a read after a selector write returns the new channel’s value rather than a stale one.

viva-camctl get reads the selector’s current value only. To see which entries it accepts, call Camera::enum_entries("GainSelector") in Rust or cam.enum_entries("GainSelector") in Python, or look the node up in the XML that viva-camctl xml dumps.

# Which channel is selected now?
cargo run -p viva-camctl -- get --ip 192.168.0.10 --name GainSelector

# Different gain per channel
cargo run -p viva-camctl -- set --ip 192.168.0.10 --name GainSelector --value Red
cargo run -p viva-camctl -- set --ip 192.168.0.10 --name Gain --value 5.0

cargo run -p viva-camctl -- set --ip 192.168.0.10 --name GainSelector --value Blue
cargo run -p viva-camctl -- set --ip 192.168.0.10 --name Gain --value 3.0

The selectors_demo example shows the same pattern in Rust:

cargo run -p viva-genicam --example selectors_demo

Step 3 – Do the same from Rust

cargo run -p viva-genicam --example get_set_feature
cargo run -p viva-genicam --example get_set_feature -- --name Gain --value 3.0

The whole of it:

    // `connect_gige` fetches the GenApi XML and builds the NodeMap, so every
    // feature the camera declares is addressable by name from here on.
    let mut camera = connect_gige(&device).await?;

    // Feature access is synchronous even inside an async program: the register
    // I/O behind it blocks, and `GigeRegisterIo` steps off the async worker on
    // its own rather than making every caller do it.
    println!("{name} = {}", camera.get(&name)?);

    if let Some(value) = value.as_deref() {
        camera.set(&name, value)?;
        println!("{name} = {} (after write)", camera.get(&name)?);
    }

Two things are worth pointing out.

Values are strings at this boundary. Camera::get returns String and Camera::set takes &str; the node’s own type decides how that text is parsed and encoded. get_integer, get_float and their siblings read and write a feature as its own type, and Common tasks has the helpers for exposure, gain and the rest.

Feature access is synchronous, including inside #[tokio::main]. The register I/O behind it blocks, and GigeRegisterIo steps off the async worker by itself — you do not need to wrap calls in spawn_blocking.

If you have no camera to hand, the same calls work against the fake camera:

cargo run -p viva-genicam --example demo_fake_camera
    // `get` and `set` are synchronous. They block on register I/O, and
    // `GigeRegisterIo` steps off the async worker itself, so no `spawn_blocking`
    // wrapper is needed even here inside `#[tokio::main]`.
    println!("Reading camera features:");
    for feature in [
        "Width",
        "Height",
        "PixelFormat",
        "ExposureTime",
        "Gain",
        "GevTimestampTickFrequency",
    ] {
        match camera.get(feature) {
            Ok(value) => println!("  {feature} = {value}"),
            Err(err) => println!("  {feature} = <error: {err}>"),
        }
    }
    println!();

    // ── 5. Write a feature ──────────────────────────────────────────────────
    println!("Setting Width = 320, ExposureTime = 10000 ...");
    camera.set("Width", "320")?;
    camera.set_exposure_time(10_000.0)?;
    println!("  Width readback = {}\n", camera.get("Width")?);

Step 4 – When you might need raw register access

Prefer features by name. You get the node’s type, you respect the vendor’s declared constraints, and your code stays portable across cameras.

Raw registers are still occasionally the right tool:

  • Debugging unusual vendor behaviour or firmware bugs.
  • Reaching something genuinely absent from the XML.
  • Bringing up a device whose GenApi description is incomplete.

viva-gige and viva-gencp expose the primitives — see the viva-gige and viva-gencp chapters. Be careful: writing arbitrary registers can leave a device unusable until it is power-cycled.


Recap

You should now be able to:

  • Read and write features by name, from the CLI and from Rust.
  • Recognise why a write was refused — a lock, a constraint, or an auto feature.
  • Use selectors to address per-channel settings.
  • Know that raw register access exists and is a last resort.

Next: GenApi XML — where the feature list comes from in the first place.

Common tasks

The things nearly every camera application does — set the exposure and the gain, trigger, crop, bin, fix the frame rate, save a configuration — have a method each on Camera. They work with the names cameras actually use: a camera that predates the current feature naming standard (SFNC 2) calls its exposure ExposureTimeAbs or ExposureTimeRaw and its gain GainRaw, and the same call handles it.

Everything here runs against the fake camera, no hardware needed:

cargo run -p viva-genicam --example common_tasks
cargo run -p viva-genicam --example common_tasks -- --legacy   # the older names

Features by type

get_integer, get_float, get_bool, get_enum, get_string and their set_ counterparts read and write a feature as its own type. get and set remain for text — a command line, a configuration file:

    // Each feature as its own type; `get` and `set` remain for text.
    let width: i64 = camera.get_integer("Width")?;
    camera.set_integer("Width", width / 2)?;
    let format: String = camera.get_enum("PixelFormat")?;
    println!(
        "Width {} -> {}, {format}",
        width,
        camera.get_integer("Width")?
    );

A category has no value and a command is not set: get on one, or set on the other, is an error. Run a command with execute_command, or with execute_and_wait, which also waits for the camera to report it finished — asking it as often as the command’s <PollingTime> says, where it has one.

Values the camera changes on its own

A value read once is kept until something the camera’s XML links to it is written — unless the XML says otherwise. A temperature, an exposure under auto exposure, a status bit change on the camera with nothing to announce it, and the XML says so with <Cachable>NoCache</Cachable>: such a feature is read from the camera every time. A <PollingTime> says how long a value may be shown before it is read again; after that, the next read asks the camera. After a write to a WriteAround feature — a float register’s default — the next read shows what the camera stored, a gain it rounded, say.

A display that shows many features asks what to read again rather than reading everything:

    // DeviceTemperature is `NoCache` in the camera's XML: every read asks the
    // camera. Its `<PollingTime>` says how often a display should.
    let every = camera
        .nodemap()
        .polling_time("DeviceTemperature")
        .unwrap_or(std::time::Duration::from_secs(1));
    println!("{} °C", camera.get_float("DeviceTemperature")?);
    // A viewer keeps the generation it drew, and reads again what changed
    // since: what a write touched, and what `poll` found due.
    let mut drawn = camera.generation();
    for _ in 0..3 {
        tokio::time::sleep(every).await;
        camera.poll();
        let (changed, now) = camera.changed_since(drawn);
        if changed.iter().any(|name| name == "DeviceTemperature") {
            println!("{} °C", camera.get_float("DeviceTemperature")?);
        }
        drawn = now;
    }
    // A value the camera changed in a way its XML does not describe:
    camera.execute_command("TimestampLatch")?;
    camera.invalidate("GevTimestampValue");
    println!("latched at {}", camera.get_integer("GevTimestampValue")?);

changed_since names every feature whose value may have changed since a generation: written, or invalidated because something it depends on was. poll adds those whose polling time has passed. invalidate and invalidate_all are for a change the XML does not describe; Python has those two as cam.invalidate(name) and cam.invalidate_all(). Viva Studio re-reads the features on screen this way.

Exposure and gain

    // ExposureTime, else ExposureTimeAbs, else ExposureTimeRaw: the helper
    // says which it wrote, and in which unit.
    let exposure = camera.set_exposure_time(10_000.0)?;
    println!(
        "exposure: {} = {} {}",
        exposure.name,
        camera.exposure_time()?,
        exposure.unit.as_deref().unwrap_or("(device units)")
    );
    // Gain, else GainRaw, on the control GainSelector selects where there is one.
    if camera.resolve(StandardFeature::GainSelector).is_ok() {
        camera.select_gain("All")?;
    }
    let gain = camera.set_gain(6.0)?;
    println!("gain: {} = {}", gain.name, camera.gain()?);

Each helper tries the names in order and uses the first the camera declares, then says which one that was, with its unit. ExposureTime and ExposureTimeAbs are in microseconds and Gain in decibels; ExposureTimeRaw and GainRaw are in the camera’s own units, so the value you write means what that camera’s manual says it means.

Region of interest and binning

    // Offsets to zero, then the size, then the offsets: the order that
    // reaches any region the sensor allows.
    camera.set_roi(Roi {
        x: 64,
        y: 32,
        width: 320,
        height: 240,
    })?;
    println!("roi: {:?}", camera.roi()?);
    camera.set_binning(1, 1)?;

A width’s maximum shrinks as its offset grows, so the order of the writes decides whether a region can be reached at all; set_roi gets it right whichever way the region moves. A value off the feature’s increment is refused before anything is written, with the nearest values that would be accepted.

Frame rate

    // Turns AcquisitionFrameRateEnable on first, where the camera has one.
    let rate = camera.set_frame_rate(25.0)?;
    println!("frame rate: {} = {} Hz", rate.name, camera.frame_rate()?);

disable_frame_rate lets the camera choose again.

User sets

    // Select, execute, and wait for the camera to finish.
    camera.save_user_set("UserSet1")?;
    camera.load_user_set("Default")?;
    camera.set_default_user_set("UserSet1")?;

set_default_user_set chooses the set the camera loads at power-up.

Saving and restoring a configuration

A user set lives in the camera. To keep a configuration on the host — to version it, or to copy it onto another camera of the same model — save it to a file:

    // Every feature the camera's XML marks streamable, each selected one
    // under every entry of its selector; the file's comments say what was
    // left out and why.
    let saved = camera.save_features(&mut std::fs::File::create(&path)?)?;
    println!("saved {} values to {}", saved.values.len(), path.display());

    // Later — on this camera or another of the same model:
    let report = camera.load_features(&mut std::fs::File::open(&path)?)?;
    for warning in &report.warnings {
        eprintln!("warning: {warning}"); // saved from another model, say
    }
    for failure in &report.failures {
        eprintln!("not written: {failure}"); // `Feature[Selector=Entry] = value: why`
    }

What is saved is what the camera’s XML marks <Streamable>. A feature behind a selector — TriggerMode behind TriggerSelector, Gain behind GainSelector — is saved once for each of the selector’s entries, and under each entry of a selector that selects that selector in turn; the selectors are put back as they were. A feature that is not available, or locked, is left out with a comment saying why; save while the camera is not acquiring, or what acquisition locks (Width, PixelFormat) is left out.

Check the reported saved-value count. Some devices mark no features streamable and produce a successful save with zero values; that file cannot restore their settings. Record the features and selector states you intend to change explicitly on such a device.

A load writes in the order the camera needs, whatever the order of the file: a selector before what it selects, ExposureAuto before the ExposureTime it locks, BinningHorizontal before the Width it rescales. A write that fails is tried once more after the others, because some features bound each other (Width and OffsetX). Whatever still fails is in the report, with its reason, and the rest is written. A file saved from another camera model loads too, with a warning.

The file is text, one feature per line, in the layout GenApi’s reference implementation writes:

# {05D8C294-F295-4dfb-9D01-096BD04049F4}
# ModelName = VivaCam_Fake
Width	320
TriggerMode	{TriggerSelector=FrameStart}	Off

From the command line: viva-camctl save --ip <CAMERA-IP> --out camera.txt and viva-camctl load --ip <CAMERA-IP> --file camera.txt (the command line); from Python, cam.save_features(path) and cam.load_features(path).

Triggers

    let mut frames = camera.open_stream(StreamOptions::new())?;
    camera.enable_trigger("FrameStart", "Software")?;
    // Sets TLParamsLocked too: Width and PixelFormat are locked until the stop.
    camera.acquisition_start()?;
    for _ in 0..3 {
        camera.trigger_software()?;
        let frame = frames.next_frame().await?.ok_or("the stream ended")?;
        println!("triggered frame {}x{}", frame.width, frame.height);
    }
    camera.acquisition_stop()?;
    camera.disable_trigger("FrameStart")?;

acquisition_start sets TLParamsLocked where the camera has it, so features that would change the size of a frame — Width, PixelFormat — are locked while it streams; acquisition_stop clears it.

When the camera lacks a feature

A camera that declares none of a feature’s names says so, naming every name it tried:

the camera has no exposure time: it declares none of ExposureTime, ExposureTimeAbs, ExposureTimeRaw

camera.resolve(StandardFeature::ExposureTime) asks without writing anything.

Without an async runtime

A program with no async runtime uses viva_genicam::blocking to discover and open a camera. The camera it returns is the ordinary Camera: everything above works on it unchanged, and frames come from next_frame_blocking.

cargo run -p viva-genicam --example blocking_grab                 # the fake camera
cargo run -p viva-genicam --example blocking_grab -- 192.168.1.20  # a real one
    // Each call blocks for its timeout.
    let timeout = Duration::from_millis(500);
    let device = match address {
        Some(ip) => blocking::discover_ip(ip, timeout)?.ok_or("that camera did not answer")?,
        // Loopback included, for the fake camera.
        None => blocking::discover_with(timeout, &DiscoveryOptions::new().include_loopback(true))?
            .into_iter()
            .find(|device| device.ip.is_loopback())
            .ok_or("no camera found")?,
    };
    // The camera carries a small runtime of its own, shut down on drop.
    let mut camera = blocking::connect(&device)?;
    // Executes UserSetLoad and waits for the camera to finish; any command
    // waits the same way with `execute_and_wait_blocking`.
    camera.load_user_set("Default")?;
    camera.set_exposure_time(5_000.0)?;
    let mut frames = camera.open_stream(StreamOptions::new())?;
    camera.acquisition_start()?;
    for _ in 0..5 {
        match frames.next_frame_blocking(Duration::from_secs(2))? {
            Some(frame) => println!(
                "frame {}x{} {:?}, {} bytes",
                frame.width,
                frame.height,
                frame.pixel_format,
                frame.payload.len()
            ),
            None => break,
        }
    }
    camera.acquisition_stop()?;

The camera brings a small runtime of its own — one thread that keeps its control channel alive — and stops it when the camera is dropped. The async API works from a current-thread Tokio runtime as well.

GenApi XML

Goal of this tutorial:

  • Understand what the GenICam XML is and where it lives.
  • See how viva-genapi-xml fetches it from the device and parses it.
  • Fetch it yourself, from the CLI and from Rust.
  • Know when you actually need to look at it.

You should already have worked through Discovery and Registers & features.


1. What is the GenICam XML?

Every GenICam-compliant device carries a self-description document:

  • It lists every feature the device supports — name, type, access mode, range.
  • It defines how those features map to device registers.
  • It encodes categories, selectors, and SwissKnife expressions.
  • It declares which GenApi schema version the document uses.

The document normally lives in the device’s non-volatile memory. To get it, the host:

  1. Reads the GevFirstURL register at 0x0200.
  2. Interprets the result as a URL saying where the document actually is — usually local: plus a memory address and length, in principle also http:// or file://.
  3. Reads those bytes.
  4. Hands the string to a GenApi implementation.

Two details that the specification permits and real devices use:

  • If GevFirstURL is empty or its document cannot be retrieved, GevSecondURL at 0x0400 is tried next.
  • The document is often ZIP-compressed. viva-genapi-xml decompresses it transparently, subject to a 64 MiB cap so a malformed length field cannot exhaust memory.

2. The shape of the API

viva-genapi-xml exposes three things you are likely to call:

// Follow the URL registers and return the document.
pub async fn fetch_and_load_xml<F, Fut>(read_mem: F) -> Result<String, XmlError>
where
    F: FnMut(u64, usize) -> Fut,
    Fut: Future<Output = Result<Vec<u8>, XmlError>>;

// Cheap, deliberately lossy: schema version and top-level names.
pub fn parse_into_minimal_nodes(xml: &str) -> Result<MinimalXmlInfo, XmlError>;

// The full parse: every node declaration, plus the ones that had to be skipped.
pub fn parse(xml: &str) -> Result<XmlModel, XmlError>;

Application code rarely calls these directly — connect_gige does it for you. They matter when you are debugging why a feature behaves as it does, inspecting how a vendor encoded something, or adding support for a construct viva-genapi does not handle yet.


3. Getting the XML

3.1. From the command line

cargo run -p viva-camctl -- xml --ip 192.168.0.10 --out camera.xml

This never parses the document, so it works on a camera the library cannot open — which is the only camera anyone ever needs it for. If you are reporting a problem, send this: see Reporting a camera we can’t open.

3.2. From Rust

fetch_and_load_xml knows nothing about GVCP, sockets or cameras. It calls a closure with (address, length) and expects bytes back, so any transport that can read device memory can drive it:

    // `fetch_and_load_xml` knows nothing about GVCP, sockets or cameras. It
    // asks for `(address, length)` and expects bytes back, so any transport
    // that can read device memory can supply the closure.
    let xml = {
        let cam = Arc::clone(&camera);
        viva_genapi_xml::fetch_and_load_xml(move |address, length| {
            let cam = Arc::clone(&cam);
            async move {
                let mut guard = cam.lock().await;
                guard
                    .read_mem(address, length)
                    .await
                    .map_err(XmlError::transport)
            }
        })
        .await?
    };

Run it with:

cargo run -p viva-genicam --example fetch_xml

4. Inspecting the document

parse_into_minimal_nodes answers the cheap questions — which schema version, what is at the top level, does this look broken at all:

    // A deliberately lossy parse: enough to answer "which schema is this, and
    // what is at the top level", robust to node types we do not yet handle.
    let meta = viva_genapi_xml::parse_into_minimal_nodes(&xml)?;
    if let Some(version) = meta.schema_version.as_deref() {
        println!("Schema version: {version}");
    }
    println!("Top level features ({}):", meta.top_level_features.len());
    for feature in meta.top_level_features.iter().take(8) {
        println!("  - {feature}");
    }

It is intentionally lossy. It does not understand every node type; its job is to be fast and to survive schema extensions that are not implemented yet.

parse is the full path, and it is what NodeMap is built from. It returns an XmlModel with a flat list of node declarations carrying:

  • Feature name and type (Integer, Float, Enumeration, Boolean, Command, Category, SwissKnife, Converter, …).
  • Addressing: the sum of <Address>, <pAddress> and <pIndex> terms.
  • Access mode, bitfield layout and byte order.
  • Limits — Min/Max/Inc, or the pMin/pMax/pInc nodes that supply them at run time; a limit the XML leaves out is None, not i64::MIN.
  • Selector relationships (<pSelected>, on the selector) and expression text.

Skipped nodes

A construct the parser cannot handle does not fail the whole document — it goes into XmlModel::skipped, and the corresponding GenApi-level list is NodeMap::skipped(). Both are logged.

Degrading to “this one feature is missing” is far better than “this camera does not work”, and the vendor-corpus tests fail on any skip that is not on their allowlist, so new gaps surface rather than accumulate.


5. From XML to a NodeMap

viva-genapi takes the XmlModel and:

  • Instantiates a NodeMap.
  • Resolves feature dependencies, pValue delegation, selectors and expressions at access time rather than at load time.
  • Invalidates cached values when something they depend on changes.

You do not do this plumbing yourself in an application: connect_gige fetches, parses and builds, and viva-camctl get / set use the same pipeline. See the viva-genapi chapter for the internals.


6. When should you look at the XML?

Most of the time, treat it as an implementation detail. Crack it open when:

  • A feature behaves differently from what SFNC describes.
  • Selectors are not doing what you expect.
  • You hit a SwissKnife or bitfield corner case.
  • You are adding support for a vendor-specific wrinkle.

A workable order: dump it with viva-camctl xml, run fetch_xml for the schema version and skip list, then read the document itself in an XML viewer for the category you care about.

If you have a camera the library cannot open, that document is the single most useful thing you can send us — see Reporting a camera we can’t open.


7. Recap

You should now:

  • Know what the GenICam XML is, where it lives, and how the URL registers point at it.
  • Be able to fetch it with viva-camctl xml or fetch_and_load_xml.
  • Know the difference between the minimal scan and the full parse, and what a skipped node means.

Next: Streaming — getting image data out, now that you know how the camera describes itself.

Streaming

Goal of this tutorial:

  • Start a GVSP stream, from the CLI and from Rust.
  • Read the statistics the stream reports — and know which of them mean something today.
  • Understand the knobs that decide whether streaming is stable: packet size and MTU, packet delay, and packet resend.

You should already know your camera’s IP and the host NIC you reach it on (Discovery), and be able to set features (Registers & features).


1. How GVSP streaming works

  1. On the control path (GVCP), the host configures the stream: destination IP and port, packet size, and the acquisition settings themselves.
  2. On AcquisitionStart, the camera sends GVSP packets on the stream channel — a leader, the payload packets, and a trailer per frame.
  3. The host reassembles them into frames and reports statistics.

viva-gige parses the packets. In viva-genicam, Camera::open_stream sets the stream up and returns a FrameStream, whose receive engine reads the socket on a thread of its own — whether or not your code is asking for a frame at that moment — and hands you whole frames. viva-camctl stream is a thin CLI over that.

Note that the stream channel is UDP to a different port than the control channel, and that the camera chooses when to send. A firewall that permits GVCP and not GVSP produces the confusing case where features work perfectly and no image ever arrives.


2. Streaming with viva-camctl

cargo run -p viva-camctl -- stream --help

2.1. A basic stream

cargo run -p viva-camctl -- stream \
  --ip 192.168.0.10 --iface 192.168.0.5 --duration-s 10

--iface names the host NIC, either by one of its IPv4 addresses or by its OS name (eth0, or a GUID on Windows) — and it is optional: omit it and the OS is asked which interface routes to --ip. Without --duration-s the stream runs until Ctrl+C.

Once a second you get a progress line, and a summary at the end:

[stream] fps=30.0 Mbps=73.73 complete=30 incomplete=0 missed=0 backpressure=0 resend=0/0/0 bytes=9216000
Summary: fps=30.0 Mbps=73.73 complete=300 incomplete=0 missed=0 backpressure=0 resend=0/0/0 bytes=92160000

§4.3 says what each counter means.

If no frames arrive at all:

  • Confirm nothing else is already consuming the stream (a vendor viewer holds the control channel exclusively).
  • Confirm the host firewall permits inbound UDP on the stream port. Each stream gets a free port from the operating system unless you name one with --port (destination_port in Rust and Python), which is the way to go behind a firewall that admits only known ports — see Networking → Letting the reply back in.
  • Confirm the --iface interface is one the camera can actually reach.

2.2. Saving frames

--save N writes the first N frames to the current directory as frame_0001.pgm (Mono8) or frame_0001.ppm (anything else, and always with --rgb). Both are plain NetPBM, readable by ImageJ, GIMP, OpenCV and Pillow without a decoder.

cargo run -p viva-camctl -- stream \
  --ip 192.168.0.10 --iface 192.168.0.5 --duration-s 5 --save 3

--save defaults to 1, so a plain stream run leaves one file behind; pass --save 0 to write nothing.

NetPBM files are 8-bit, so a camera deeper than that loses its low bits in them. --save-format png or --save-format tiff keeps every bit:

  • Monochrome frames are saved grey and everything else RGB; --rgb makes a grey frame RGB too.
  • A camera with more than 8 bits per sample gets a 16-bit file: Mono10 to Mono16, packed or not, and Bayer mosaics, which are demosaiced at their own depth.
  • 16-bit files hold the samples scaled to the full 16-bit range, as the PNG standard requires: a 12-bit 0xABC is stored as 0xABCA. Shift right by 16 − bits to get the camera’s values back. A PNG records bits in its sBIT chunk; a TIFF holds the same samples without it.
cargo run -p viva-camctl -- stream \
  --ip 192.168.0.10 --iface 192.168.0.5 --duration-s 5 --save 3 --save-format tiff

stream --usb 0 takes the same --save-format.

Every format can be saved that the library converts: monochrome and Bayer at 8 to 16 bits, including the packed Mono10p/Mono12p and GigE Vision Mono10Packed/Mono12Packed families; RGB and BGR, with or without alpha; and 8-bit YUV / Y’CbCr at 4:4:4, 4:2:2 and 4:1:1. A 3D or event-vision frame cannot be converted, and saving it fails with a message saying so.

2.3. Event-vision cameras

Event-based (EVS) cameras send blocks of encoded events rather than images. viva-camctl stream recognises the Prophesee EVT 3.0 and EVT 2.1 formats, and handles those blocks differently from image frames:

  • --save N writes the first N blocks as raw payloads, block_0001.evt3 or block_0001.evt21, in the current directory. --rgb does not apply.
  • --raw-out <FILE> writes every block’s payload to one file, in arrival order — a continuous recording you can replay with event-vision tooling. The file is created, or replaced, when the first block arrives, so a stream that sends no event data leaves no file; --append adds to it instead. With --raw-out, --save writes no block files unless you give it a count. Image frames are never written there.
cargo run -p viva-camctl -- stream \
  --ip 192.168.0.10 --iface 192.168.0.5 --duration-s 10 --raw-out capture.evt3

2.4. Multicast

cargo run -p viva-camctl -- stream \
  --ip 192.168.0.10 --iface 192.168.0.5 \
  --mode multicast --group 239.192.0.10

Another host can then watch the same stream without touching the camera: see Networking → One camera, several applications.


3. Streaming from Rust

cargo run -p viva-genicam --example grab_gige -- --iface eth0 --save 5

The example streams from the first camera discovery finds, on the host interface you name with --iface (an IPv4 address or an OS name; required). It saves --save N frames (default 1) and stops. Unless you pass --packet-size, it opts into automatic packet sizing — see §4.1.

Setup — connect, open the stream, start acquisition:

    // Connect to camera (fetches XML, builds nodemap).
    let mut camera = connect_gige(&device).await?;

    // Open the stream: destination, packet size, socket, and a receive engine
    // sized by the camera's PayloadSize.
    let mut options = StreamOptions::new().iface(iface.clone());
    if let Some(group) = args.multicast {
        options = options.multicast(group);
    }
    if let Some(port) = args.port {
        options = options.destination_port(port);
    }
    options = match args.packet_size {
        Some(size) => options.packet_size(size),
        None => options.auto_packet_size(),
    };
    let mut frame_stream = camera.open_stream(options)?;

    // Start acquisition.
    camera.acquisition_start()?;

Then the loop. Reassembly, ordering and buffering all stay inside FrameStream; what you get is whole frames:

    // `next_frame` yields a complete frame; reassembly runs on the stream's
    // own receive thread, and `stats` counts every block the camera sent.
    // `None` means the stream ended.
    while let Some(frame) = frame_stream.next_frame().await? {
        frame_index += 1;
        print_frame_info(frame_index, &frame);

        if save_remaining > 0 {
            match save_frame(&frame, frame_index, args.rgb) {
                Ok(path) => println!("  saved {}", path.display()),
                Err(err) => warn!(error = %err, "failed to save frame"),
            }
            save_remaining = save_remaining.saturating_sub(1);
        }

        // Print stats overlay every second.
        if last_overlay.elapsed() >= Duration::from_secs(1) {
            print_overlay(&stats.snapshot());
            last_overlay = Instant::now();
        }

        // Stop after saving requested number of frames.
        if frame_index >= args.save {
            break;
        }
    }

    camera.acquisition_stop()?;

Two things to note. open_stream does the whole setup through the camera’s own control channel: it claims control, binds the socket, points the stream channel at it (or at a multicast group), negotiates the packet size, reads whether the camera can resend lost packets, and starts the receive engine with the camera’s PayloadSize. And acquisition_start / acquisition_stop are ordinary synchronous calls — see Registers & features.

Every frame carries its block_id and a status. By default a stream delivers only FrameStatus::Complete frames; see §4.4 to receive the others. Code without an async runtime can call next_frame_blocking(timeout) instead of next_frame().await.

Each Frame carries its payload and its PFNC pixel format. Frame::to_rgb8() converts any format listed in §2.2 to 8-bit RGB, with samples deeper than 8 bits reduced to their top eight and Bayer mosaics demosaiced by bilinear interpolation; Viva Studio’s viewer draws with the same conversion, so it shows exactly these pixels. For the camera’s own sample values, viva_genicam::pfnc::convert::unpack_u16 returns one u16 per pixel, and with the crate’s image-io feature viva_genicam::image_io writes PNG and TIFF files as viva-camctl does.

No camera? The fake camera streams over loopback:

cargo run -p viva-genicam --example demo_fake_camera

3.1. Chunks and events

A camera can attach values to each frame — the timestamp, the exposure and gain it used, a frame counter, the state of its I/O lines — as chunks, and send events on the message channel when something happens: an exposure ends, a line toggles. Which chunks and events a camera has, and how each value is encoded, is in its own GenApi XML: the Chunk* and Event* features read their values from the frame or the event the way any other feature reads a register. There is no table of known chunks to fall short of.

Turn chunk mode on and enable the chunks you want:

    // Chunk mode: each frame carries the values the camera used for it.
    camera.configure_chunks(&ChunkConfig {
        selectors: vec!["Timestamp".into(), "ExposureTime".into(), "FrameID".into()],
        active: true,
    })?;

Each frame then carries its chunks (frame.chunks), and frame.payload is the image alone. Read every chunk feature the frame carries, or one of them:

        // Read through the camera's XML: which chunk holds each value, at
        // which offset, in which byte order.
        for (name, value) in camera.chunk_features(&frame) {
            match value {
                Ok(value) => println!("    {name} = {value}"),
                Err(err) => println!("    {name} = <error: {err}>"),
            }
        }
        let exposure = camera.with_chunks(&frame, |cam| cam.get("ChunkExposureTime"))?;

Outside with_chunks, a chunk feature has nothing to read and fails with NotAttached: a value never outlives its frame, and nothing is read from the camera for it.

Events work the same way. Point the message channel at the host and enable the events you want:

    let host: std::net::Ipv4Addr = [127, 0, 0, 1].into();
    camera
        .configure_events(host, 10_020, &["ExposureEnd"])
        .await?;
    let events = camera.open_event_stream(host, 10_020).await?;

and read an event’s features from the event itself:

    let event = tokio::time::timeout(Duration::from_secs(5), events.next()).await??;
    println!("  Event 0x{:04X} for block {}:", event.id, event.block_id);
    for (name, value) in camera.event_features(&event) {
        match value {
            Ok(value) => println!("    {name} = {value}"),
            Err(err) => println!("    {name} = <error: {err}>"),
        }
    }

The names come from your camera’s XML — SFNC calls them ChunkTimestamp, ChunkExposureTime, EventExposureEndTimestamp and so on — which viva-camctl xml --ip <CAMERA-IP> --out camera.xml saves for you to read. USB3 Vision cameras carry both too: chunks in the frame, events on the camera’s event interface (viva-camctl events --usb 0).


4. Tuning for stability

4.1. Packet size and MTU

The single most important setting. GevSCPSPacketSize is the size of the transmitted IP packet, so it must fit the path MTU end to end — camera, every switch, and the host NIC.

  • Too large: packets are fragmented or silently dropped, and frames arrive incomplete.
  • Too small: more packets per frame, more per-packet overhead, and the host CPU becomes the bottleneck sooner.

The usual approach is jumbo frames (MTU 9000) on a dedicated camera network, with the packet size set just below the path MTU — every hop, not only the host NIC. A NIC that advertises 16114 and a switch that only forwards ~9216-byte frames will accept a write of 16114 at both ends and still deliver nothing (Vieworks FS-3200T through an ipTIME PoE4002; the same camera direct to the NIC streams up to 16114).

What the library does. There are three packet-size policies:

PolicyCLIRustPythonStarting size
Preserve (default)———The camera’s current GevSCPSPacketSize, never raised
Auto--autoStreamOptions::auto_packet_size()auto_packet_size=TrueDerived from the host NIC’s MTU
Explicit--packet-size NStreamOptions::packet_size(n)packet_size=NN, used as a ceiling

Auto and explicit are mutually exclusive. The default leaves a camera that is already configured for a narrower path alone; the reasoning is in ADR-0021.

All three then probe the path: the library asks the camera for a GVSP test packet and bisects downward when the size does not arrive. The probe only ever lowers, so it cannot override a size you chose — it can only refuse to stream at one the path drops, which is undetectable from either endpoint’s registers. A device that answers no test packet keeps its size unchanged, so cameras that do not implement the mechanism are not walked down to 1500. StreamBuilder::probe(false) turns it off and makes preserve literal.

Cameras clamp a packet size they cannot honour, and the write succeeds when they do — nothing on the wire distinguishes “accepted” from “accepted and reduced”. The library reads GevSCPSPacketSize back after writing it and follows the effective value, logging a warning when the two differ.

If a stream produces nothing, the library says so after a few seconds and names the likely causes rather than leaving you with frames=0. Two messages are worth recognising:

  • no GVSP packet has arrived — a firewall, a lost control privilege, a camera waiting for a trigger, or a path MTU smaller than the packet size. Try --packet-size 9000 or 1500 before assuming the camera is broken.
  • packets are arriving but no frame has completed — the two ends disagree about the packet size. Retry with --packet-size 1500.

See Networking → MTU and jumbo frames for the host-side configuration.

4.2. Packet delay

Many cameras expose GevSCPD, an inter-packet gap in timestamp ticks. Zero means the camera sends a frame as fast as the link allows, which is what overruns switch buffers and NIC rings first. A modest delay trades a little latency for a lot of stability, and is usually the first thing to try when drops appear only at high frame rates.

Opening a stream leaves GevSCPD as the camera has it. To set it, give a time:

CLIRustPython
--packet-delay-ns 2000StreamOptions::packet_delay(Duration::from_micros(2))packet_delay_ns=2000

The library converts it to the camera’s ticks at the frequency the camera reports, and refuses to open the stream if the camera reports none.

4.3. What the statistics tell you

FrameStream::stats() counts every block the camera sent exactly once, when its fate is decided:

CounterMeaning
frames_completeDelivered to you with every packet present.
frames_incompleteClosed with packets missing, without a trailer, or with an error status from the camera.
frames_missedNever seen at all: gaps in the block-id sequence.
frames_backpressureAssembled, then discarded because your code did not take them in time. The stream keeps the sixteen newest frames.
resend_requestedLost packets asked for again (§4.6), each counted once.
resend_recoveredOf those, the ones that arrived.
resend_unavailableOf those, the ones the camera said it no longer has.

So frames_complete + frames_incomplete + frames_missed + frames_backpressure is the number of frames the camera sent; frames_lost() is everything but the first. The packet counters say why: packets_missing, packets_duplicate, and packets_ignored_* for what arrived and could not be used (late, out of range, malformed, an unsupported payload type, an error status, or sent from an address that is not the camera’s). packets_size_mismatch above zero means the camera and the host disagree about the packet size — retry with --packet-size 1500. On the command line, resend= shows requested, recovered and unavailable.

incomplete and missed point at the network or the camera; backpressure points at your code. A frame whose lost packets were resent counts as complete, so resend_recovered is the early warning that the network drops packets.

4.4. Incomplete frames and the block timeout

A block closes as incomplete when nothing has arrived for it for the block timeout, 100 ms by default, counted from its last packet: a large frame on a slow or paced link takes as long as it takes, and only silence ends it. FrameStream::set_block_timeout changes it.

Incomplete frames are counted and, by default, not delivered. set_deliver_incomplete(true) hands them over too, with a status that says what happened — Incomplete { missing_packets }, TrailerMissing or DeviceStatus(code) — and zeros where the lost packets’ bytes belong.

4.5. The socket receive buffer

The receive engine asks the operating system for a receive buffer of twice the frame size (at least 4 MiB) and reads back what it got. If the system grants less than half, it warns once and names the limit to raise — net.core.rmem_max on Linux, kern.ipc.maxsockbuf on macOS. Below that, a burst the size of a frame overflows the socket and the kernel drops packets before any counter can see them.

4.6. Packet resend

When a packet goes missing, the stream asks the camera to send it again, if the camera says it can (bit 0x4 of its GVCP Capability register): a gap in a frame’s packets that is still open after 2 ms is requested, again every 20 ms while it stays open, three times at most, and never more than a quarter of the frame’s packets in all. A frame that lost more than that is not worth flooding the camera for; it closes incomplete. A lost trailer cannot be asked for — nothing after it says it is missing.

Requests leave from the stream’s own socket for the camera’s control port (UDP 3956), and the packets come back on the stream. A firewall that admits the stream needs nothing more.

CLIRustPython
Turn it off--no-resendStreamOptions::resend(ResendPolicy::Off)resend=False

FrameStream::set_resend_delay, set_resend_retry_interval, set_resend_max_requests and set_resend_budget change the numbers above. A multicast stream never asks, nor does one built with FrameStream::from_socket on a camera another application controls; only the controlling application should.

Resend has been exercised on the Allied Vision Manta G-125B; other vendors and stream channels still need hardware coverage (see tested cameras). If a camera of yours misbehaves with it on, --no-resend is the workaround, and the report bundle is how we fix it.


4.7. Frame rate and processing overhead

Use a release build when measuring throughput. A smaller ROI and shorter exposure can raise the camera’s frame-rate limit; read that limit after changing geometry, and verify the resulting rate with viva-camctl bench. Mono8 avoids colour conversion when grayscale is sufficient. Binning changes the sampling and does not necessarily increase FPS.

Keep taking frames promptly and move expensive processing or saving off the acquisition loop. The receive thread continues independently, but its delivery queue holds up to sixteen completed frames: if your application falls behind, the oldest waiting frame is dropped and counted as backpressure. Packet resend cannot recover an application-side queue eviction. Compare complete frames and loss counters alongside FPS.

The queue absorbs short startup or scheduling pauses; it cannot compensate for a consumer that is consistently slower than the camera. It can retain up to 16 frame payloads, in addition to assembly buffers and frames your code holds. A larger pending queue also permits older frames to wait longer; keep reading promptly when image freshness matters. Frame allocation and payload copying are unchanged.


5. Troubleshooting

Frames go missing immediately (incomplete or missed climbing). Check MTU and packet size alignment first, then lower the frame rate or ROI to confirm it is a bandwidth problem rather than a configuration one. A dedicated NIC and switch removes a whole class of cause.

Discovery and feature access work, but no frames arrive. Almost always the stream port: check the firewall for inbound UDP on it (see 2.1). A warning that datagrams arrive only from an address that is not the camera’s means something else is sending to the stream’s port; the stream ignores it. On Linux with firewalld, this is a separate rule from the GVCP one — see Letting the reply back in.

Frames arrive with the wrong size or format. Read PixelFormat, Width and Height back from the camera rather than assuming; a Bayer format interpreted as Mono8 looks like a plausible grey image with a fine crosshatch.

Intermittent hiccups under load. Look at CPU usage and other traffic on the same NIC. On Windows, check the power profile and NIC driver settings — see Networking → Windows.

When in doubt, save a few frames, re-run with -vv, and compare against the vendor’s viewer on the same cabling. If it still makes no sense, send us the report bundle.


6. Recap

You should now be able to:

  • Start a stream from the CLI and from Rust, and save frames or event blocks.
  • Read the chunk values a frame carries and the features of an event.
  • Tell from the counters whether frames are lost on the network (incomplete, missed) or in your own code (backpressure).
  • Know which knob to reach for first: packet size and MTU, then packet delay; and read resend recoveries as a network that drops packets.

Next: the Networking Guide for host and switch configuration, or the viva-gige chapter for how the packets are actually handled.

Testing without hardware

This tutorial shows how to evaluate the full viva-genicam stack without physical cameras or external tools. The viva-fake-gige crate provides an in-process GigE Vision camera simulator that speaks real GVCP/GVSP protocols on localhost.

Quick start

# Run the self-contained demo
cargo run -p viva-genicam --example demo_fake_camera

The demo starts a camera, discovers it, connects, reads and writes features, and streams five frames — the whole stack, on loopback:

Starting fake GigE Vision camera on 127.0.0.1:3956 ...
Discovering cameras (2 s timeout) ...
  Found 1 device(s):
    IP: 127.0.0.1  Model: FakeGigE  Manufacturer: viva-genicam

Connecting to 127.0.0.1 ...
  Connected. GenApi XML: … bytes, … features.

Reading camera features:
  Width = 640
  ...

Setting Width = 320, ExposureTime = 10000 ...
  Width readback = 320

Streaming 5 frames ...
  Frame 1: 320x480 Mono8 payload=153600B ts=7393542
  ...

Demo complete. All operations succeeded without hardware.

What the fake camera supports

FeatureStatus
GVCP discovery (broadcast on loopback)Supported
GenCP register read/write (READREG, WRITEREG, READMEM, WRITEMEM)Supported
Control Channel Privilege (CCP)Supported
GenApi XML with SFNC featuresWidth, Height, PixelFormat, ExposureTime, Gain
GVSP frame streamingSynthetic gradient images at configurable FPS
Device timestamps (1 GHz tick rate)Supported (ns since acquisition start)
Timestamp latch (GevTimestampValue)Supported
Chunk data (Timestamp, ExposureTime, FrameID, ImageInfo)In the GigE Vision layout when ChunkModeActive=1, per ChunkEnable
Events (StartOfTransfer, ExposureEnd with data)Per EventNotification, on the message channel

Using the fake camera in your own code

Add viva-fake-gige as a dev-dependency:

[dev-dependencies]
viva-fake-gige = { git = "https://github.com/VitalyVorobyev/viva-genicam" }

Start a fake camera in your test. The value build() returns is a guard: the camera answers GVCP and streams GVSP for as long as it is alive, and shuts down when dropped.

    // The guard owns the camera's tasks: it answers GVCP and streams GVSP for
    // as long as it is alive, and shuts down when dropped.
    let _camera_guard = FakeCamera::builder()
        .width(640)
        .height(480)
        .fps(10)
        .bind_ip([127, 0, 0, 1].into())
        .port(3956)
        .build()
        .await?;

Then discover it — note discover_all, not discover, because the fake lives on loopback:

    println!("Connecting to {} ...", dev_info.ip);
    let (mut camera, xml) = connect_gige_with_xml(dev_info).await?;
    println!(
        "  Connected. GenApi XML: {} bytes, {} features.\n",
        xml.len(),
        camera.nodemap().node_names().count()
    );

From there it is the ordinary API:

    // `get` and `set` are synchronous. They block on register I/O, and
    // `GigeRegisterIo` steps off the async worker itself, so no `spawn_blocking`
    // wrapper is needed even here inside `#[tokio::main]`.
    println!("Reading camera features:");
    for feature in [
        "Width",
        "Height",
        "PixelFormat",
        "ExposureTime",
        "Gain",
        "GevTimestampTickFrequency",
    ] {
        match camera.get(feature) {
            Ok(value) => println!("  {feature} = {value}"),
            Err(err) => println!("  {feature} = <error: {err}>"),
        }
    }
    println!();

    // ── 5. Write a feature ──────────────────────────────────────────────────
    println!("Setting Width = 320, ExposureTime = 10000 ...");
    camera.set("Width", "320")?;
    camera.set_exposure_time(10_000.0)?;
    println!("  Width readback = {}\n", camera.get("Width")?);

The full program those excerpts come from is examples/demo_fake_camera.rs, which goes on to build a FrameStream, grab five frames with their chunks, and read an ExposureEnd event.

Running as a standalone server

The viva-fake-gige binary starts a long-running fake camera that stays alive until Ctrl+C. This is the way to test interactively with viva-camctl, or with viva-service and Viva Studio. It runs from a clone of the repository.

# Terminal 1: start the fake camera
cargo run -p viva-fake-gige

# Custom dimensions, frame rate and pixel format (mono8 or rgb8)
cargo run -p viva-fake-gige -- --width 512 --height 512 --fps 15 --pixel-format rgb8

Output:

Fake camera running on 127.0.0.1:3956 (640x480 MONO8 @ 30 fps)
Identity: model '…', serial '…', user name '…'
Press Ctrl+C to stop.

cargo run -p viva-fake-gige -- --help lists the remaining options.

Using the CLI with the fake camera

With the fake camera running in Terminal 1, use viva-camctl in Terminal 2:

# Discover (use --iface to include loopback)
cargo run -p viva-camctl -- list --iface 127.0.0.1

# Read / write features
cargo run -p viva-camctl -- get --ip 127.0.0.1 --name Width
cargo run -p viva-camctl -- set --ip 127.0.0.1 --name Width --value 512
cargo run -p viva-camctl -- get --ip 127.0.0.1 --name DeviceModelName

# FORCEIP (temporary) and persistent IP, against the fake's MAC address
cargo run -p viva-camctl -- --iface 127.0.0.1 set-ip --mac DE:AD:BE:EF:CA:FE --ip 192.168.1.100 --force
cargo run -p viva-camctl -- --iface 127.0.0.1 set-ip --mac DE:AD:BE:EF:CA:FE --ip 192.168.1.100

Watching it in Viva Studio

Run the fake behind viva-service and start Viva Studio in remote mode: Viva Studio → Trying it without a camera.

Fake camera configuration

The FakeCameraBuilder supports:

let camera = FakeCamera::builder()
    .width(1920)                     // default: 640
    .height(1080)                    // default: 480
    .fps(60)                         // default: 30
    .bind_ip([127, 0, 0, 1].into())  // default: 127.0.0.1
    .port(3956)                      // default: 3956
    .pixel_format(viva_fake_gige::RGB8)  // default: MONO8
    .zip_xml(true)                   // default: false
    .enforce_heartbeat(true)         // default: false
    .heartbeat_timeout_ms(3_000)     // default: the device's own value
    .build()
    .await
    .unwrap();

The last three are there to reproduce behaviour real cameras have and fakes usually do not:

  • zip_xml serves the GenApi document ZIP-compressed, which many vendors do and which exercises a decompression path that would otherwise never be tested.
  • enforce_heartbeat makes the camera actually revoke control privilege when no GVCP command arrives inside heartbeat_timeout_ms. Without it, a client that forgets to send keepalives passes every test and fails on real hardware.

Image dimensions, exposure and gain can also be changed at runtime through GenApi writes — the fake responds to Width, Height, ExposureTime and Gain the way a real camera does.

Networking

This chapter is a practical GigE Vision networking cookbook.

It focuses on:

  • Typical topologies (direct cable vs switch, single vs multi-camera).
  • NIC and IP configuration on Windows, Linux, and macOS.
  • MTU / jumbo frames and packet delay basics.
  • Common pitfalls and troubleshooting.

It is not a replacement for vendor or A3 documentation, but gives you enough background to make viva-camctl and the viva-genicam examples work reliably.

If you have not yet done so, first go through:

They show the CLI and Rust-side pieces that depend on a working network setup.


1. Typical topologies

1.1. Single camera, direct connection

The simplest and most robust setup:

[Camera]  <── Ethernet cable ──>  [Host NIC]

Characteristics:

  • One camera, one host, one NIC.
  • No other traffic on that link.
  • Easy to reason about MTU and packet delay.

Recommended when:

  • You’re bringing up a new camera.
  • You’re debugging issues and want to remove variables.

1.2. One or more cameras through a switch

Common in real systems:

[Cam A] ──\
           \
[Cam B] ────[Switch]──[Host NIC]
           /
[Cam C] ─/

Characteristics:

  • Multiple cameras share the link to the host.
  • The switch must handle the aggregate throughput.
  • Switch configuration (buffer sizes, jumbo frames, spanning tree) matters.

Recommended when:

  • You need more than one camera.
  • You need long cable runs or multi-drop layouts.

1.3. Host with multiple NICs

For high throughput or separation from office traffic:

[Cam network]  <── NIC #1 ──>  [Host]  <── NIC #2 ──>  [Office / internet]

Characteristics:

  • Camera traffic isolated from the general network.
  • Easier to tune MTU, QoS, and firewall rules.
  • In discovery and streaming, you may need to specify --iface (see §7).

Recommended for:

  • High data rates.
  • Multi-camera setups.
  • Systems that must not be disturbed by office network traffic.

2. IP addressing basics

GigE Vision uses standard IPv4 + UDP. Each device needs a valid IPv4 address, and the host and camera(s) must share a subnet.

2.1. Choose a camera subnet

Pick a private network, for example:

  • 192.168.0.0/24 (addresses 192.168.0.1–192.168.0.254)
  • 10.0.0.0/24

Decide on:

  • One address for your host NIC (e.g. 192.168.0.5).
  • One address per camera (e.g. 192.168.0.10, 192.168.0.11, …).

Make sure this subnet does not conflict with your office / internet network.

2.2. Windows

Give the camera NIC a static address:

  1. Open Network & Internet Settings → Change adapter options.
  2. Right-click the NIC used for cameras → Properties.
  3. Select Internet Protocol Version 4 (TCP/IPv4) → Properties.
  4. Choose “Use the following IP address”:
    • IP address: e.g. 192.168.0.5
    • Subnet mask: 255.255.255.0
    • Gateway: leave empty (for isolated camera networks).

Then check the three things that most often stop a camera working on Windows:

  • Firewall. On first run Windows may ask whether to allow the program on Private / Public networks. Allow it on the profile the camera network uses — if in doubt, both. Discovery replies and the GVSP stream are both inbound UDP (the stream arrives on a port the operating system picks for each stream, unless you name one — see §3.3), so a firewall that blocks them breaks discovery or streaming even though nothing reports an error. Allowing the program, rather than a port, covers both. Running the terminal as Administrator the first time makes sure the prompt can appear.
  • Power saving. Turn off “energy efficient Ethernet” and similar options in the NIC driver’s advanced settings, and keep the power plan on high performance; they add latency and jitter.
  • Jumbo frames and receive buffers. If the whole path supports them, enable “Jumbo Packet” in the NIC’s advanced settings (see §4), and raise the receive buffers — they default low on many desktop NICs.

2.3. Linux

Use either NetworkManager or manual configuration.

Manual example:

# Assign IP and bring interface up (replace eth1 with your device)
sudo ip addr add 192.168.0.5/24 dev eth1
sudo ip link set eth1 up

To make this permanent, use your distro’s network configuration tools (e.g. Netplan on Ubuntu, NetworkManager connection files on RHEL).

If the host runs firewalld, discovery replies and the stream need explicit rules — see §3.3; the same two rules apply outside the link-local range with your own subnet in place of 169.254.0.0/16.

2.4. macOS

Use System Settings → Network:

  1. Select the camera NIC (e.g. USB Ethernet).
  2. Set “Configure IPv4” to “Manually”.
  3. Enter:
    • IP address: 192.168.0.5
    • Subnet mask: 255.255.255.0
  4. Leave router/gateway empty for a dedicated camera network.

A GigE Vision camera with no static IP and no DHCP server on the segment falls back to an IPv4 link-local address in 169.254.0.0/16 — what Windows calls APIPA. This is the normal state of a camera plugged straight into a host with nothing else configured, so it is worth knowing even if you plan to assign static addresses later.

The library discovers such cameras on all platforms, but the host must hold a link-local address of its own first, and on Linux the firewall usually has to be told to let the reply back in.

This section is based on a bring-up write-up by @InsuJeong496 in issue #57, which streamed from a link-local camera on Linux with the two firewall rules below and no vendor driver installed.

3.1. What is fixed and what is yours

Recipes like this one mix values the protocol fixes with values that belong to one particular machine. Copying an address out of someone else’s guide is the usual reason they fail.

Fixed — do not change these:

ItemValue
IPv4 link-local network169.254.0.0/16
Directed broadcast for that network169.254.255.255
GVCP port on the cameraUDP 3956

Yours — substitute your own:

ItemWhere to get it
Host interface nameip -brief address (Linux)
Host link-local addressLet the OS assign one, or pick an unused 169.254.x.y
Camera addressWhatever viva-camctl list reports; it can change between sessions
firewalld zonefirewall-cmd --get-active-zones
GVSP destination portPicked by the operating system for each stream, unless you name one: --port on viva-camctl stream, destination_port in Rust and Python

Normally NetworkManager assigns one automatically when a link comes up with no DHCP answer. If it has not, add one by hand:

# Replace enp9s0f3u3 with your camera NIC. Keep the /16 and the broadcast.
sudo ip address add 169.254.105.107/16 \
  broadcast 169.254.255.255 \
  dev enp9s0f3u3

Check what an interface currently has:

ip -brief address

Once the host has a link-local address, discovery sends its directed broadcast to 169.254.255.255:3956.

On Windows this step is normally automatic — an adapter with no DHCP lease self-assigns a 169.254.x.y address. On macOS the same is true.

3.3. Letting the reply back in (firewalld)

The most common symptom is that discovery finds nothing while the camera is plainly on the link. The camera answers from UDP port 3956 to whatever ephemeral port the client bound, so a default-deny inbound policy drops the ACK and discovery simply times out.

Find the zone that owns the camera interface, then allow that source port:

firewall-cmd --get-active-zones

sudo firewall-cmd --zone=public \
  --add-rich-rule='rule family="ipv4" source address="169.254.0.0/16" source-port port="3956" protocol="udp" accept'

Replace public with your zone. Keep 169.254.0.0/16 and 3956.

Streaming needs a second rule, because GVSP arrives on the port the host asked the camera to send to. By default that is a free port the operating system picks for each stream, so either let in UDP from the camera’s network:

sudo firewall-cmd --zone=public \
  --add-rich-rule='rule family="ipv4" source address="169.254.0.0/16" protocol value="udp" accept'

or name the port — --port on viva-camctl stream, destination_port in Rust (StreamOptions, StreamBuilder) and Python — and allow just that one:

viva-camctl stream --ip <camera-ip> --iface <host-link-local-ip> --port <PORT>
sudo firewall-cmd --zone=<your-zone> --add-port=<PORT>/udp

A named port belongs to one stream: a second stream asking for the same port on the same host fails to open, rather than sharing the camera’s packets.

These are runtime rules. They vanish on the next firewall reload or reboot unless you repeat them with --permanent.

3.4. Checking it worked

viva-camctl --iface <host-link-local-ip> list

At -v the discovery log names the interface it sent from and the address it heard back from:

INFO sending GVCP discovery interface_name=enp9s0f3u3 local=169.254.105.107 dest=169.254.255.255:3956
INFO received GVCP response interface_name=enp9s0f3u3 src=169.254.253.222:3956

If the first line is missing, the host has no link-local address on that NIC (§3.2). If the first line appears but the second never does, suspect the firewall (§3.3).


4. MTU and jumbo frames

MTU (Maximum Transmission Unit) determines the largest Ethernet frame size. Standard MTU is 1500 bytes; jumbo frames extend this (e.g. 9000 bytes). For large images, jumbo frames can significantly reduce protocol overhead and CPU load.

4.1. When to care

You probably need to look at MTU when:

  • Frame sizes are large (multi-megapixel).
  • Frame rates are high (tens or hundreds of FPS).
  • You see frame drops at otherwise reasonable loads.

For simple bring-up and low/moderate data rates, standard MTU=1500 usually works.

4.2. Enabling jumbo frames

All components in the path must agree:

  • Camera
  • Switch (if present)
  • Host NIC

The host NIC MTU is not the path MTU. A jumbo-capable NIC behind a switch with a smaller frame limit still lets both ends configure a large GevSCPSPacketSize; the switch then drops the oversized GVSP datagrams and the stream shows complete=0. When in doubt, cap the size with viva-camctl stream --packet-size 9000 (or lower) rather than trusting the NIC alone. How the library chooses and verifies the packet size is covered in Streaming → Packet size and MTU.

Typical steps:

  • Camera: set GevSCPSPacketSize (or the vendor’s equivalent feature) to a value below the path MTU (e.g. 8192 for MTU 9000), with viva-camctl set or --packet-size on stream.
  • Switch: enable jumbo frames in the management UI (name and steps vary by vendor). Confirm the switch’s actual maximum frame size — “jumbo” is not one number.
  • Host NIC:
    • Windows: NIC properties → Advanced → “Jumbo Packet” or similar.
    • Linux: sudo ip link set dev eth1 mtu 9000
    • macOS: System Settings → Network → the interface → Details → Hardware, where the driver supports it; others do not support jumbo frames.

The library reads the interface’s MTU on Linux, Windows and macOS, so --auto (auto_packet_size) sizes packets from it.

After changing MTU, confirm it took effect:

# Linux example
ip link show eth1

5. Packet delay and flow control

Some cameras allow configuring an inter-packet delay (GevSCPD) or packet interval:

  • Without delay, the camera sends packets as fast as possible, and the bursts can overwhelm NICs and switches.
  • With a modest delay, traffic is smoother at the cost of a small increase in latency.

If you see frame drops at high frame rates:

  1. Try slightly increasing the inter-packet delay — in nanoseconds: viva-camctl stream --packet-delay-ns 2000, StreamOptions::packet_delay in Rust, packet_delay_ns= in Python. The library converts it to the camera’s timestamp ticks; without a delay it leaves GevSCPD as it is. Some cameras honour GevSCPD only in a bandwidth mode of their own: an Allied Vision Manta G-125B paces packets by StreamBytesPerSecond unless BandwidthControlMode is SCPD or Both.
  2. Check whether the drop rate decreases, and whether overall throughput is still sufficient.

Some vendors also expose “frame rate limits” or “burst size” options. These can also ease pressure on the network at the cost of lower peak FPS.


6. Multi-camera considerations

When running multiple cameras, total throughput is roughly the sum of each camera’s stream, and the bottleneck can be:

  • The switch’s uplink to the host.
  • The host NIC’s capacity.
  • Host CPU / memory bandwidth.

Practical tips:

  • Prefer a dedicated NIC for cameras.
  • For 2–4 high-speed cameras, consider multi-port NICs, or separating cameras onto different NICs.
  • Stagger packet timing: slightly different inter-packet delays per camera, or slightly different frame rates where acceptable.

Monitor:

  • Per-camera statistics: incomplete and missed frames, and throughput.
  • Host CPU usage.
  • Switch port statistics if your hardware exposes them.

6.1. One camera, several applications

A GigE Vision camera takes configuration from one application at a time: the one holding its control privilege. Opening a camera claims it, and closing it — dropping the Camera; in Python close(), the end of a with block, or garbage collection — gives it back, so the next application, or the next run of yours, can open the camera at once.

While one application controls the camera, a second one opening it normally is refused. It can still watch:

  • Open the camera read-only — connect_gige_as with Access::Monitor in Rust, monitor=True in Python, --access monitor in viva-camctl (the default of every command that only reads, such as get and dump). A monitor claims nothing and writes nothing; reading features works, and a write is refused with an error that says why.
  • If the controlling application streams to a multicast group, a monitor receives the same frames: Camera::open_stream with StreamOptions::monitor() (Python: stream(monitor=True), viva-camctl stream --monitor) reads the group, port and packet size from the camera and joins the group. A camera streaming to one host’s own address cannot be watched by another.

An application that wants nobody else even reading claims exclusive access instead: Access::Exclusive in Rust, exclusive=True in Python, --access exclusive in viva-camctl. While it holds it, the camera refuses other applications’ reads too, so a monitor cannot open it either.

An application that loses the privilege — its heartbeat lapsed, or another application took it meanwhile — is told: the camera’s control_state() becomes Lost (in Python, control_state is ControlState.LOST), and reclaim_control() asks for it again. A takeover shows at once on a camera that names its controller; on one that does not, at the next write it refuses.


7. Using –iface and discovery quirks

On systems with more than one active NIC, automatic interface selection might pick the wrong one. --iface forces the choice, and means the same thing everywhere: in viva-camctl, in viva-service, in the Python iface= argument and in the Rust examples. It names the host NIC, by either:

  • one of its IPv4 addresses — --iface 192.168.0.5, or
  • its OS name — --iface eth0, or a GUID like {6394C55F-F630-4BC7-92D2-7AC320C73D1C} on Windows.

Use whichever you have; the address is usually easier to find, and on Windows much easier. A value that resolves to nothing prints every interface the library can see, which is the fastest way to learn the GUID.

If discovery only works when you specify --iface, you likely have multiple NICs on overlapping subnets, or a default route that prefers a different interface. This is not unusual; be explicit in production setups.

7.1. Asking one camera directly: --ip

Discovery broadcasts, and a broadcast stops at a router. A camera you know the address of can be asked directly:

viva-camctl list --ip 192.168.10.20

In Rust that is gige::discover_ip. It finds a camera behind a router, or on a network where broadcasts are filtered.

7.2. A camera configured for another subnet

Discovery sends to each interface’s subnet broadcast and to 255.255.255.255, so a camera whose address does not belong to your network still answers — and then every connection to it fails, because the host cannot reach that address. viva-camctl list says so under the table:

WARNING [0]: 192.168.77.10 is configured for 192.168.77.10/24, which the host address 169.254.1.2/16 is not on. ...

The diagnostic report shows each camera’s subnet and gateway too. Give the camera an address on your subnet with viva-camctl set-ip, or give the host one on the camera’s (see §2). A camera that cannot answer the host at all may still answer if allowed to broadcast its reply: viva-camctl list --allow-broadcast-ack.


8. Troubleshooting checklist

8.1. Discovery fails

Work through the Discovery troubleshooting checklist. If the camera has a 169.254.x.y address, go to §3 Link-local (APIPA) cameras instead — the causes there are specific and the fixes are two commands. If none of this helps, the camera itself is the evidence we need: see Reporting a camera we can’t open.

8.2. Streaming is unstable (frames lost)

  • Read the counters first. incomplete or missed climbing is the network or the camera; backpressure climbing is the application not taking frames fast enough — no network change will help it (what each counter means). Lost packets the camera sent again show up as resend recovered; many of them still mean a network that drops packets.
  • A warning that the kernel granted a small GVSP receive buffer means bursts overflow the socket before the stream sees them: raise the limit it names (net.core.rmem_max, kern.ipc.maxsockbuf).
  • Check packet size against the path MTU; see §4.2.
  • For high data rates, enable jumbo frames end to end (camera, switch, NIC).
  • Reduce stress: lower the frame rate or ROI, or increase the inter-packet delay slightly.
  • Use a dedicated NIC and switch where possible.
  • Watch host CPU; if it is near 100%, consider a better NIC or driver, or moving processing to another thread or core.

8.3. Vendor tool works, viva-genicam does not

When the vendor’s viewer sees the camera or streams from it and viva-camctl does not, compare what the two tools actually do:

  • Which host NIC and IP the vendor tool uses. Pass the same one to viva-camctl with --iface.
  • Whether the vendor tool changed the camera’s address — DHCP, or a “force IP” button. Run viva-camctl list again afterwards.
  • Where the camera streams to. The vendor tool may leave the camera configured with its own destination IP and port; make sure viva-camctl uses a host IP and port the firewall allows, or reset the camera to defaults.
  • Packet size and inter-packet delay. Vendor tools often tune these automatically. Note the GevSCPSPacketSize and GevSCPD values the vendor tool shows, then reproduce them with viva-camctl stream --packet-size N and viva-camctl set.
  • Control privilege. Close the vendor tool first: while it holds the control channel, nothing else can configure the camera (§6.1).

Capture logs with -vv (or RUST_LOG=debug) at the same frame rate and resolution, and if it still makes no sense, send us the report bundle.


9. Recap

After this chapter you should:

  • Understand basic GigE Vision network topologies and when to use each.
  • Be able to configure a host NIC and camera addresses on Windows, Linux, and macOS.
  • Know when and how to enable jumbo frames and adjust packet delay.
  • Have a structured approach to debugging discovery and streaming issues.

For protocol-level details and tuning options exposed by this project:

Reopening a GigE Vision camera

A camera that disappears must be opened in a new session. Drop its old stream and camera, retain its discovery DeviceInfo, and call reopen_gige with Reopen options. It looks at the old address first, then discovers the known MAC on the selected interface if the camera moved. A record made with DeviceInfo::from_ip has no MAC and can only identify whatever answers at that address.

Reopen::patience bounds discovery, connecting and retry delays. The new session fetches XML again. An optional configuration captured with Camera::save_features is then restored with ordinary register timeouts; inspect Reopened::restored for per-feature failures. Restoration does not restart acquisition. Open a new stream and start acquisition explicitly. Cancellation releases any control already claimed, on a best-effort basis.

The GigE service retires and recreates its served camera when control is lost, the camera disappears from discovery, or its address or selected interface changes. This refreshes its XML and connection metadata together. Configuration replay is explicit in the library helper; the service does not silently restore an application’s saved settings or restart acquisition.

USB3 Vision setup

A USB3 Vision camera needs no network setup, but the operating system must let viva-genicam claim the camera’s USB interfaces. How that works depends on the platform:

  • macOS: no setup.
  • Windows: install the WinUSB driver once per camera, as described below.
  • Linux: not yet tried on a camera. If it fails for you, please report it.

viva-camctl list-usb lists a camera without claiming it. So a camera can appear in the list, or in Viva Studio’s device list, and still fail to open.

Windows

Windows has no built-in driver for USB3 Vision cameras, and viva-genicam talks to USB devices through Microsoft’s generic WinUSB driver. Until WinUSB is installed for the camera, opening it fails with:

claim the control interface (0): could not determine driver for interface

If a vendor driver holds the camera instead, the end of the message reads incompatible driver is installed for this interface. The fix is the same in both cases.

To install WinUSB with Zadig, a free tool:

  1. Close every program that uses the camera, including Viva Studio and the vendor’s own software.
  2. Run Zadig and choose Options → List All Devices.
  3. In the device list, select the camera’s Interface 0 entry.
  4. Choose WinUSB as the target driver and click Install Driver. If the camera already has a driver, the button says Replace Driver.
  5. Open the camera again.

On the camera we tested (a MATRIX VISION mvBlueFOX3), WinUSB on interface 0 was enough for streaming too. If yours opens but streaming or events fail with claim the stream interface or claim the event interface, look for the camera’s other interfaces in Zadig and install WinUSB on those too.

WinUSB replaces the vendor’s driver for that camera. To go back to the vendor’s SDK, open Device Manager, find the camera, and choose Update driver or Roll back driver. Reinstalling the vendor’s driver package also works.

The command line (viva-camctl)

viva-camctl does from a terminal what a field engineer does with a vendor tool: find a camera, read it, change it, save and restore its configuration, reach a register the XML does not describe, and stream from it. It comes with the Python package (pip install viva-genicam), with every GitHub release, and from crates.io (cargo install viva-camctl).

viva-camctl <command> --help lists each command’s flags.

Choosing a camera

Commands that act on one camera take one of:

  • --ip <ADDRESS> — a GigE Vision camera by address;
  • --index <N> — the Nth GigE Vision camera list finds;
  • --usb <N> — the Nth USB3 Vision camera list-usb finds.

get, set, execute, features, describe, dump, save, load, read-reg, write-reg, stream, events, chunks, bench and report take --usb too. xml, action and set-ip are GigE Vision only.

Global options

These go before the command name:

  • -v / -vv — log at debug / trace (RUST_LOG overrides);
  • --json — machine-readable output, where the command has any;
  • --iface <IFACE> — the host interface, by one of its IPv4 addresses (192.168.0.5) or its OS name (eth0, or a GUID on Windows). list, xml, report, stream, events and bench also take it after the command name.

Commands

CommandWhat it does
listDiscover GigE Vision cameras; --ip asks one address directly
list-usbDiscover USB3 Vision cameras
featuresThe category tree: every feature with its type, access and value; --filter keeps the names that contain a word, --all shows invisible features too
describeOne feature in full: tooltip, description, unit, range and increment, enumeration entries, the selectors it has or is, and the nodes it depends on; a state it could not read is printed as such, and the command fails
dumpEvery value the camera has to read now, in XML order
get / setRead a feature, or write it from text
executeRun a command feature (UserSetLoad) and wait until the camera reports it done
save / loadSave the camera’s configuration to a file, and restore it (how)
read-reg / write-regRead device registers, or write one 32-bit register, past the XML
actionSend a GigE Vision action command and count the acknowledgements
streamStream frames and save some, or raw event-vision blocks; with --usb, from a USB3 Vision camera
benchSustained streaming benchmark, with an optional JSON report
eventsConfigure and read events: GigE Vision’s message channel, or a USB3 Vision camera’s event interface
chunksSwitch chunk mode and chunk selectors
set-ipGive a GigE Vision camera an address by MAC (FORCEIP with --force, persistent otherwise)
xmlThe camera’s GenApi XML, unparsed — so it works on a camera the library cannot open
reportA diagnostic bundle for a bug report (what to send)

A field engineer’s session

# What is this camera, and how is it set?
viva-camctl features --ip 192.168.0.10
viva-camctl features --ip 192.168.0.10 --filter exposure
viva-camctl describe --ip 192.168.0.10 --name ExposureTime
viva-camctl dump --ip 192.168.0.10 > before.txt

# Keep its configuration, change it, put it back.
viva-camctl save --ip 192.168.0.10 --out camera.txt
viva-camctl set  --ip 192.168.0.10 --name ExposureTime --value 5000
viva-camctl load --ip 192.168.0.10 --file camera.txt

# The same on a USB3 Vision camera.
viva-camctl save --usb 0 --out camera.txt

load prints each value it could not write, with the reason, and exits with an error if there was one; it warns when the file was saved from another camera model.

Registers

read-reg and write-reg reach the device without its XML, so they work on a camera whose XML we cannot read. Addresses and values are decimal or 0x-hexadecimal:

viva-camctl read-reg  --ip 192.168.0.10 --addr 0x0938            # GevHeartbeatTimeout
viva-camctl read-reg  --ip 192.168.0.10 --addr 0x0200 --len 512   # the first URL
viva-camctl write-reg --ip 192.168.0.10 --addr 0x0938 --value 3000
viva-camctl read-reg  --usb 0 --addr 0x0 --len 64

A 32-bit value is shown and written in the device’s byte order: big-endian on GigE Vision, little-endian on USB3 Vision. GigE Vision registers are whole 32-bit words at addresses that are multiples of 4; anything else is refused before it is sent. write-reg on GigE Vision takes control privilege for the write and gives it back.

Action commands

viva-camctl action --device-key 0x42 --group-key 1 --group-mask 0xffffffff
viva-camctl action --destination 192.168.0.10 --device-key 0x42 --group-key 1 \
    --group-mask 1 --scheduled-time 1700000000000000000

Every camera whose ActionDeviceKey, ActionGroupKey and ActionGroupMask match acts and acknowledges; action reports how many did, and names any camera that answered with an error instead — a camera without action commands may answer NOT_IMPLEMENTED whatever the keys, or say nothing. Broadcast is the default; --destination sends to one address, or to a subnet’s broadcast address. A scheduled action carries its time in the cameras’ timestamp ticks.

Streaming

viva-camctl stream --ip 192.168.0.10 --save 2                      # keep the camera's packet size
viva-camctl stream --ip 192.168.0.10 --auto --save 2               # size packets from the NIC MTU
viva-camctl stream --ip 192.168.0.10 --save 2 --save-format png    # 16-bit above 8 bits
viva-camctl bench  --ip 192.168.0.10 --duration-s 60 --json-out bench.json
viva-camctl bench  --usb 0 --duration-s 60
viva-camctl stream --usb 0 --save 3

list-usb shows each camera’s link speed, and opening a camera below SuperSpeed logs a warning: behind a USB 2 port, hub or cable a camera works, but only as fast as 480 Mbit/s carries. A USB3 Vision stream’s summary also counts USB transfers, transfers skipped, the transfer errors it recovered from, and frames the camera numbered but never delivered.

Packet size, receive port and resend are covered in the Networking Guide.

Use viva from other tools

Much machine-vision software does not talk to cameras itself: it loads a camera driver written to the EMVA’s GenTL standard, a GenTL producer — a shared library with the extension .cti. viva-genicam ships one, viva_gentl.cti, so that software can find, configure and stream from GigE Vision cameras through viva, with no vendor SDK.

Harvesters, the Python GenTL consumer, is tested against it on every change. No other consumer has been tried yet beyond the project’s C ABI harness: if you use one, tell us how it went. Both consumers have acquired frames from the Manta G-125B; see tested cameras.

What it offers

  • GigE Vision cameras. USB3 Vision cameras are not offered through it yet.
  • One interface per network interface of the host, loopback included, so the fake camera shows up too.
  • Read-only, control and exclusive access. Read-only access watches a camera that another application controls.
  • One data stream per camera, into buffers your software allocates or the producer allocates. A frame with lost packets is delivered and marked incomplete; chunk data is located in the buffer.
  • The camera’s own features, from its XML, through the consumer’s GenApi.

Get the .cti

Releases from 0.9.0 attach one per platform to the GitHub release:

OSFile
Linux x86_64viva_gentl-x86_64-unknown-linux-gnu.cti
macOS, Apple Siliconviva_gentl-aarch64-apple-darwin.cti
Windows x86_64viva_gentl-x86_64-pc-windows-msvc.cti

They are 64-bit only. The Linux build needs glibc 2.39 (Ubuntu 24.04) or newer. The files are not signed: macOS may refuse to load one downloaded with a browser until its quarantine flag is cleared:

xattr -d com.apple.quarantine viva_gentl-aarch64-apple-darwin.cti

To build it from source instead, with Rust installed, from a clone of the repository:

scripts/build-cti.sh          # prints target/gentl/viva_gentl.cti

Point your software at it

GenTL consumers look for producers in the directories listed in GENICAM_GENTL64_PATH, separated by : on Linux and macOS and by ; on Windows (GenTL 1.6 §6.1.1). Put the .cti in a directory of its own and add that directory:

export GENICAM_GENTL64_PATH="$HOME/viva-gentl:$GENICAM_GENTL64_PATH"
$env:GENICAM_GENTL64_PATH = "C:\viva-gentl;$env:GENICAM_GENTL64_PATH"

Some consumers take the file directly instead; Harvesters is one.

Harvesters

pip install harvesters installs Harvesters and the EMVA’s GenApi. Load the .cti, list the cameras it finds, and open one by any of the fields it lists (model, serial_number, id_, …):

from harvesters.core import Harvester

def open_camera(cti, model):
    """Load the producer, list what it finds, and open a camera by model."""
    harvester = Harvester()
    harvester.add_file(cti)
    harvester.update()
    print([info.property_dict["model"] for info in harvester.device_info_list])
    return harvester, harvester.create({"model": model})
harvester, acquirer = open_camera("viva_gentl.cti", "FakeGigE")

The camera’s features are on acquirer.remote_device.node_map — for example acquirer.remote_device.node_map.ExposureTime.value. Start acquisition with acquirer.start(), then fetch frames:

def fetch_image(acquirer):
    """The next frame, as a 2-D array, and its block ID."""
    with acquirer.fetch(timeout=3) as buffer:
        component = buffer.payload.components[0]
        image = component.data.reshape(component.height, component.width)
        # The buffer goes back to the producer when the block ends: copy
        # what you keep.
        return image.copy(), buffer.module.frame_id

acquirer.stop() ends acquisition; acquirer.destroy() and harvester.reset() close the camera and unload the producer.

The two functions come from the script that CI runs against the fake camera, scripts/gentl-harvesters.py. To try them without a camera, start the fake first (viva-fake-gige, see Testing without hardware); its model is FakeGigE.

When something goes wrong

Set RUST_LOG=debug before starting your software and the producer logs to standard error, as the rest of viva does. Every failed call also leaves a message, which a consumer reads with GCGetLastError; whether and how it shows it depends on the consumer. If a camera works in viva-camctl but not through your software, report it with the name and version of that software.

Python bindings

The viva-genicam Python package wraps the Rust workspace behind a NumPy-friendly API. It ships as a pre-built wheel on PyPI — no C toolchain, no aravis, no system USB library.

pip install viva-genicam

The install also provides the viva-camctl CLI — see Install & hello-camera.

import viva_genicam as vg

cams = vg.discover(timeout_ms=500)
with vg.connect_gige(cams[0]) as cam:    # control is given back at the end
    print(cam.get("DeviceModelName"))

    with cam.stream() as frames:
        for frame in frames:
            arr = frame.to_numpy()       # shape and dtype follow the pixel format
            break

to_numpy() returns the camera’s values: (H, W) uint8 for 8-bit monochrome, (H, W) uint16 for 10- to 16-bit monochrome, packed or not, a Bayer mosaic as sent unless asked to demosaic it, and (H, W, 3) uint8 for RGB and BGR — see Streaming → to_numpy().

A camera, a frame and a stream may be used from any thread, and every call that waits on the camera lets other Python threads run.

Tutorials

  1. Install & hello-camera — install the wheel, run the self-contained fake-camera demo.
  2. Discovery — enumerate GigE and U3V cameras, restrict to one NIC.
  3. Control & introspection — read and write features, walk the NodeMap, discover which features apply.
  4. Streaming — context-manager streams, NumPy frames, pixel formats, timestamps.

Reference

  • API reference — every public class, function, and exception in one place.
  • Example scripts — runnable Python files mirroring the most common Rust examples.

Supported

GigE Vision and USB3 Vision discovery, control and streaming. Supported Python versions and the platforms with pre-built wheels are listed in Install & hello-camera.

Not exposed to Python yet

The Rust API is wider than the bindings. These exist in viva-genicam and have no Python equivalent today:

  • Chunk data. frame.chunks is not surfaced; ChunkConfig, configure_chunks and the chunk features (Camera::chunk_features) are Rust-only.
  • Events. There is no binding for the message channel or EventStream.
  • Action commands and FORCEIP / persistent IP configuration. (GenApi <Command> features — UserSetLoad, TriggerSoftware — are a different thing and are exposed, via cam.execute(name); see Control.)

If you need one of these, viva-camctl covers most of them from the command line, and the Rust crates cover all of them.

Install & hello-camera

Install from PyPI

pip install viva-genicam

Wheels ship for:

OSArchPython
Linux (manylinux_2_28)x86_643.10+ (abi3)
macOSarm643.10+ (abi3)
Windowsx86_643.10+ (abi3)

USB3 Vision support is pure Rust: there is no libusb or other system USB library to install.

If you are on a platform without a pre-built wheel, pip falls back to the sdist; you will need a Rust toolchain (rustup) and a C compiler installed.

The CLI comes with it

The same install provides viva-camctl, the diagnostic CLI. It is linked into the extension module rather than shipped as a separate binary, so it is present in every wheel and in an sdist build too:

viva-camctl list
viva-camctl report --ip 192.168.0.10 --out viva-report.txt   # bug-report bundle
viva-camctl xml    --ip 192.168.0.10 --out camera.xml        # just the GenApi XML

Neither report nor xml needs the camera to open — xml never parses the document, and report records a parse failure instead of stopping — so both work on a camera the library cannot open, which is the only camera anyone reports. Attach the output to a GitHub issue; see Reporting a camera we can’t open.

Verify the install

import viva_genicam as vg
print(vg.__version__)
print(vg.discover(timeout_ms=300))

If no cameras are physically connected, you should see an empty list — not an exception.

Hello camera — no hardware needed

The wheel ships an in-process fake GigE Vision camera. Just run:

import viva_genicam as vg
from viva_genicam.testing import FakeGigeCamera

with FakeGigeCamera(width=640, height=480, fps=10) as fake:
    cam = vg.connect_gige(fake.device_info())
    print(cam.get("DeviceModelName"))
    with cam.stream() as frames:
        frame = frames.next_frame(timeout_ms=5000)
        print(frame.width, frame.height, frame.pixel_format)

No clone, no cargo build, no subprocess — the fake camera lives inside the same process as your script.

For a fuller end-to-end walkthrough, the repo ships a runnable example:

python crates/viva-pygenicam/examples/demo_fake_camera.py

Expected output:

1. Starting in-process fake GigE camera ...
   bound to 127.0.0.1:3956
2. Discovering ...
   found FakeGigE @ 127.0.0.1
3. Connecting ...
   connected; XML is … bytes, … features
4. Reading features:
   Width          = 640
   Height         = 480
   ...
6. Streaming 5 frames ...
   frame 1: 640x480 Mono8  numpy shape=(480, 640) dtype=uint8
   ...
Demo complete — everything ran without any real hardware.

This covers discovery, connection, feature read/write, and streaming — the full surface you will use with a real camera.

Next

→ Discovery — enumerate cameras with interface control.

Discovery

GigE and USB3 Vision have separate discovery pipelines. Both return frozen dataclasses you can pass straight to connect_gige / connect_u3v.

GigE Vision

import viva_genicam as vg

cams = vg.discover(timeout_ms=500)
for c in cams:
    print(c.ip, c.mac, c.model, c.manufacturer)

vg.discover() sends a GVCP discovery broadcast on every IPv4 interface except loopback and collects the replies for timeout_ms milliseconds. Returns a list of GigeDeviceInfo:

@dataclass(frozen=True)
class GigeDeviceInfo:
    ip: str                        # "192.168.1.42"
    mac: str                       # "DE:AD:BE:EF:CA:FE"
    manufacturer: Optional[str]
    model: Optional[str]
    transport: Literal["gige"]

Restrict to one NIC

cams = vg.discover(timeout_ms=500, iface="en0")
cams = vg.discover(timeout_ms=500, iface="192.168.0.5")   # same thing

Use this when the host has multiple NICs and you only want to broadcast out one of them.

iface= accepts the host NIC’s OS name or one of its IPv4 addresses. On Windows the name is a GUID like {6394C55F-F630-4BC7-92D2-7AC320C73D1C}, so the address is usually the easier value to supply.

Include loopback

cams = vg.discover(timeout_ms=500, all=True)

all=True adds the loopback interface to the scan. That is only useful for a fake camera on 127.0.0.1 (see Install & hello-camera); real cameras are already covered by the default scan. iface= takes precedence when both are given.

One camera by address

cam_info = vg.discover_ip("192.168.2.25")   # None when nothing answers

vg.discover_ip() asks one address directly instead of broadcasting, for a camera that broadcast discovery does not reach, such as one on a routed subnet. viva-camctl list --ip does the same.

A camera configured for another subnet

cams = vg.discover(timeout_ms=500, allow_broadcast_ack=True)

A camera whose address is outside every host subnet may be unable to answer the host directly. allow_broadcast_ack=True lets it broadcast its answer instead, as viva-camctl list --allow-broadcast-ack does. Every listener on the subnet then hears it, which is why it is not the default.

Slower cameras

Some cameras are slow to reply or sit on busy networks. Bump the timeout:

cams = vg.discover(timeout_ms=3000)

USB3 Vision

cams = vg.discover_u3v()
for c in cams:
    print(f"vid:pid=0x{c.vendor_id:04x}:0x{c.product_id:04x}")
    print(f"  bus={c.bus} addr={c.address}")
    print(f"  model={c.model}  serial={c.serial}")

vg.discover_u3v() lists the USB devices with a USB3 Vision interface (class 0xEF, subclass 0x05). It reads what the operating system already knows about each device — strings and link speed included — without opening it, so a camera another program holds is listed too. Returns a list of U3vDeviceInfo:

@dataclass(frozen=True)
class U3vDeviceInfo:
    bus: str                    # the OS's bus identifier; its form varies by OS
    address: int
    vendor_id: int
    product_id: int
    serial: Optional[str]
    manufacturer: Optional[str]
    model: Optional[str]
    speed: Optional[str]        # e.g. "high speed (480 Mbit/s, USB 2)"
    transport: Literal["u3v"]

USB discovery is synchronous (there is no timeout_ms knob) and does not require any broadcast.

Connecting

Either DeviceInfo type can be passed directly:

cam = vg.connect_gige(cams[0])                 # GigE
cam = vg.connect_u3v(u3v_cams[0])              # U3V
cam = vg.Camera.open(cams[0])                  # dispatches on info type

connect_gige accepts an optional iface= override if you know which NIC should stream from the camera:

cam = vg.connect_gige(info, iface="en0")
cam = vg.connect_gige(info, iface="192.168.0.5")   # same thing

When omitted, the stream interface is auto-resolved by matching the camera IP against every local NIC’s subnet. For loopback (e.g. the fake camera) this resolves to lo/lo0 automatically.

Next

→ Control & introspection — read and write features, walk the NodeMap.

Control & introspection

The examples use info, a GigeDeviceInfo from vg.discover(), and cam, the camera vg.connect_gige(info) opened.

Reading and writing features

Camera.get(name) returns the value as a string, formatted per the node’s type. Camera.set(name, value) parses the string according to the node type and writes it.

cam.get("ExposureTime")         # "5000"
cam.get("PixelFormat")          # "Mono8"
cam.get("Width")                # "640"

cam.set("Width", "320")
cam.set("PixelFormat", "Mono8")
cam.set("ExposureTime", "7500.0")

Reading and writing by type

Each node type has its own pair, which skips the round trip through text and returns a Python value of the feature’s type:

cam.set_integer("Width", 320)
assert cam.get_integer("Width") == 320
cam.set_float("ExposureTime", 7500.0)
cam.set_bool("AcquisitionFrameRateEnable", False)
cam.set_enum("AcquisitionMode", "Continuous")
print(cam.get_string("DeviceModelName"))

get_register/set_register read and write a <Register> feature’s bytes; set_register takes exactly its length. A type that does not match the feature — get_integer on a Float — raises GenApiError.

Standard features

Exposure, gain, triggers, the region of interest, binning, frame rate and user sets have helpers that find the feature the camera has for them — SFNC’s name, or an older one such as ExposureTimeAbs or GainRaw — and raise GenicamError, naming every name tried, when it has none:

cam.set_exposure_time(10_000.0)   # returns the feature written: "ExposureTime"
cam.set_gain(6.0)                 # "Gain", or "GainRaw" on an older camera
cam.set_roi(vg.Roi(x=0, y=0, width=320, height=240))
cam.set_binning(1, 1)

cam.enable_trigger("FrameStart", "Software")
cam.trigger_software()            # one frame
cam.disable_trigger("FrameStart")

cam.save_user_set("UserSet1")
cam.load_user_set("UserSet1")
cam.set_roi(vg.Roi(0, 0, 640, 480))

The exposure goes to ExposureTime, else ExposureTimeAbs (both in microseconds), else ExposureTimeRaw (the camera’s own units, rounded to an integer); the gain to Gain (decibels), else GainRaw (the camera’s own units). Each setter has a getter — exposure_time(), gain(), roi(), binning(), frame_rate(), acquisition_mode(), user_sets() — and set_frame_rate(hz) switches the camera’s frame-rate enable on first, where it has one.

One feature’s whole state

feature_state(name) reads what a viewer shows, at once: the typed value, what the camera permits now, whether the feature is implemented and available, its range, the entries an enumeration accepts now, its unit, and how often to read it again:

state = cam.feature_state("DeviceTemperature")
print(state.value, state.unit)   # e.g. 40.25 C
print(state.polling_time)        # 0.5: read it again every half second
print(state.caching)             # "NoCache": the camera changes it on its own

available_enum_entries(name) is the list an enumeration accepts now, after each entry’s own pIsImplemented/pIsAvailable; enum_entries(name) lists every entry the XML declares.

Values that change

A value the camera changes by itself — a temperature, an exposure under auto exposure — is read from the camera again when the XML says so: a feature declared NoCache every time, one with a PollingTime once that has passed. Two calls tell a viewer what to read again:

seen = cam.generation()
# ... writes, here or from another thread ...
changed, seen = cam.changed_since(seen)   # features written or invalidated since
due = cam.poll()                          # features whose PollingTime has passed

Error model

Every control error raises a subclass of vg.GenicamError:

try:
    cam.set("Width", "not-a-number")
except vg.ParseError as e:
    print("bad input:", e)
except vg.GenApiError as e:
    print("nodemap rejected the write:", e)
except vg.TransportError as e:
    print("register I/O failed:", e)
ExceptionWhen
GenApiErrorNodemap evaluation: unknown feature, value out of range, predicate failed
TransportErrorGVCP/USB register read or write failed
ParseErrorUser-supplied value couldn’t be parsed per the node’s type
MissingChunkFeatureErrorconfigure_chunks() on a camera whose XML has no chunk mode, selector or enable
UnsupportedPixelFormatErrorNo RGB conversion path for the reported pixel format

All five inherit from GenicamError, so except vg.GenicamError: catches every error the bindings raise deliberately; a closed camera, and a GigE Vision call on a USB3 Vision camera, raise GenicamError itself. A panic in the Rust layer would surface as pyo3_runtime.PanicException, a BaseException that except Exception: misses: a service that must not die catches BaseException at the top of its worker as well.

Threads

A Camera, a Frame and a stream can be used from any thread. Calls to one camera from several threads take turns; every call that waits on the camera — a register read, a frame, an event — releases the GIL, so other Python threads run meanwhile.

Closing a camera

A GigE camera holds the camera’s control privilege until it is closed, and another application — or a second run of this one — cannot take control meanwhile. Close it with close(), or use the camera as a context manager:

with vg.connect_gige(info) as cam:
    print(cam.get("Width"))
# control is given back here; `cam` raises GenicamError from now on

Without either, control is given back when the camera is garbage-collected.

Control privilege

control_state says where a GigE session stands: HELD, MONITOR (opened with monitor=True), LOST (the camera timed the heartbeat out, or gave control to another application) or RELEASED. Only HELD writes; in every other state a write raises before anything is sent.

cam.release_control()          # let another application take the camera
assert cam.control_state is vg.ControlState.RELEASED
cam.reclaim_control()          # raises while someone else holds it
assert cam.control_state is vg.ControlState.HELD

Introspection

List features

cam.nodes()            # ['AcquisitionStart', 'ExposureTime', ...]

A feature you expected but cannot find may be one the library could not build from the camera’s XML rather than one the camera lacks. skipped() lists those, with the reason — worth an issue with the camera’s XML attached:

for node in cam.skipped():   # [] for a document the library fully understands
    print(node.tag, node.name, node.error)

Node metadata

info = cam.node_info("ExposureTime")
print(info.kind)         # "Float"
print(info.access)       # "RW"
print(info.visibility)   # "Beginner"
print(info.description)  # "Exposure time of the sensor in microseconds."
print(info.writable)     # True
print(info.readable)     # True
print(info.effective_access)  # "RW" — or "RO" while the feature is locked

NodeInfo fields:

  • name — feature name
  • kind — "Integer", "Float", "Enumeration", "Boolean", "Command", "Category", "SwissKnife", "Converter", "IntConverter", "StringReg", "Register"
  • access — the access mode the XML declares: "RO", "RW", "WO", or None (for categories)
  • visibility — "Beginner", "Expert", "Guru", "Invisible"
  • display_name, description, tooltip
  • effective_access — the access mode the camera permits right now: a "RW" feature reads as "RO" while a pIsLocked lock is engaged or while the feature is unavailable. Only node_info() fills it in, and leaves it None if the predicates cannot be evaluated; all_node_info() always leaves it None, because resolving it costs register reads per node.

Plus two convenience properties, both computed from the declared access: readable (access in {"RO","RW"}) and writable (access in {"RW","WO"}).

Enum entries

cam.enum_entries("PixelFormat")
# ['Mono8', 'Mono16', 'BayerRG8', 'RGB8Packed']

Executing commands

Some features are actions, not values — UserSetLoad, TimestampLatch, TriggerSoftware. node_info(name).kind == "Command" identifies one, and execute runs it:

cam.set("UserSetSelector", "UserSet1")
cam.execute("UserSetLoad")            # load user set 1, and wait until it is loaded

Commands carry no value of their own; the camera’s XML says what executing one writes. Often it is a constant. Sometimes it is another feature’s value: on a Hikrobot MV-CS050, UserSetSave and UserSetLoad write the selected set’s number, so the set you select is the set that is saved or loaded. cam.get() on a Command raises, and there is nothing to read back.

execute waits until the camera reports the command finished — GenICam’s IsDone — for up to timeout seconds (5 by default), and returns True once it does. If the camera has not reported completion by then, execute emits a RuntimeWarning and returns False; the command was still sent. Most commands write a write-only register and count as finished as soon as the write is acknowledged. A self-clearing one is polled until it clears. execute(name, wait=False) returns False once the write is acknowledged, without asking.

A command can be refused before anything is sent: Hikrobot’s UserSetSave is unavailable while Default is selected, and execute raises GenApiError rather than writing.

Two more things worth knowing:

  • A command is executed, never set: cam.set("UserSetLoad", "1") raises GenApiError.

  • A read after the command returns the new value when the camera’s XML says it should. A register may declare <pInvalidator> nodes: “when this one changes, my cached value is stale”. The FLIR Blackfly S BFS-PGE-31S4C-C names UserSetLoad’s register as an invalidator of 171 of its registers, and the features built on them — ExposureTime and Gain among them — go stale with them, so a cam.get("ExposureTime") after cam.execute("UserSetLoad") reads the camera again. A feature with no such link, direct or indirect, keeps its cached value; cam.invalidate(name) (or cam.invalidate_all()) makes the next read ask the camera.

    Values the camera changes on its own — a temperature, ExposureTime under auto exposure — need none of this when the XML says so: a feature declared <Cachable>NoCache</Cachable> is read from the camera every time, and one with a <PollingTime> once that has passed.

From the command line, which waits the same way (--wait-ms bounds it, --no-wait skips it):

viva-camctl execute --name UserSetLoad --ip <CAMERA-IP>

Saving and restoring a configuration

saved = cam.save_features("camera.txt")      # {"values": 42, "left_out": [...]}
report = cam.load_features("camera.txt")
for failure in report["failures"]:
    print("not written:", failure)

What is saved, the order of the writes, and the file are described in Common tasks.

Categories

cats = cam.categories()
for cat, children in cats.items():
    print(cat, "->", children)

The categories map mirrors the GenICam XML category tree; each value is the list of child feature names. Use this to render a tree UI or to filter features by area (acquisition, image format, device control, etc.).

All node metadata at once

for info in cam.all_node_info():
    print(info.name, info.kind, info.access)

Useful for exporting a CSV, auto-generating GUI forms, or diffing two cameras’ feature surfaces.

Acquisition control

Without streaming (for example, trigger-mode tests):

cam.acquisition_start()
# ... do something that causes frames to be produced on another channel ...
cam.acquisition_stop()

When you use with cam.stream() as frames: the stream context manager calls these for you on entry/exit. Don’t call them manually if you are using stream().

Raw registers

read_register(address, length=4) and write_register(address, data) reach the camera’s register space past GenApi — a bootstrap register, or one the XML does not name. A raw write forgets every cached value, since it may have changed any of them.

ccp = cam.read_register(0x0A00)   # GigE Vision's control channel privilege
print(ccp.hex())                  # "00000002": this application has control

Action commands and IP configuration

An action command triggers every camera whose keys match at once — ActionDeviceKey, ActionGroupKey, ActionGroupMask — and each that acts acknowledges:

summary = vg.send_action(device_key=0x42, group_key=1, group_mask=1, destination=info.ip)
print(summary.acks, "camera(s) acted")   # 1 when the keys are the camera's

Without destination= the command goes to the broadcast address, so every camera on the subnet hears it; scheduled_time= (in the cameras’ timestamp ticks) asks them to act then.

A camera configured for another network still answers discovery, at an address the host cannot reach. vg.force_ip(mac, ip, subnet) gives it a temporary address, until it restarts; cam.set_persistent_ip(ip, subnet, gateway) stores one in a camera you have opened, for its next power-up. viva-camctl set-ip does the same from the command line.

Raw XML

print(cam.xml[:500])     # first 500 chars of the GenICam XML

Handy for feeding into a GenICam tool, debugging a mystery feature, or archiving the exact schema a camera presented at connect time.

Next

→ Streaming — sync iterator, NumPy frames, timestamps.

Streaming

Camera.stream() returns a context manager that starts acquisition on entry, stops it on exit, and yields Frame objects while it’s open:

with cam.stream() as frames:
    for frame in frames:
        arr = frame.to_numpy()
        ...

No asyncio required — the stream’s receive engine runs on a thread of its own inside the extension, and iteration blocks the calling thread while other Python threads stay runnable (the GIL is released during the blocking read). The stream, and every frame, may be handed to another thread, for a producer–consumer loop.

Only complete frames come out of the iterator, unless you ask for the others (see Incomplete frames). A frame that lost packets on the network is counted by the stream and skipped. Gaps can also come from host backpressure: the bounded delivery queue drops old pending frames if the application falls behind. Check the stream counters to distinguish those cases.

The Frame object

frame.width              # int
frame.height             # int
frame.pixel_format       # "Mono8", "Mono12p", "BayerRG8", "RGB8Packed", ...
frame.pixel_format_code  # raw PFNC integer
frame.block_id           # the camera's number for the frame
frame.status             # vg.FrameStatus.COMPLETE, unless incomplete frames were asked for
frame.ts_dev             # device tick count, Optional[int]
frame.ts_host            # POSIX seconds, Optional[float]: None until cam.time_calibrate()
frame.chunks             # {chunk_id: bytes}, or None without chunk mode
frame.payload()          # raw bytes, one copy

ts_host is the frame’s device timestamp mapped onto the host clock, which needs a fit of the two clocks first. On a GigE camera, call cam.time_calibrate() before opening the stream; without it ts_host is None. cam.map_dev_ts(ticks) maps any device timestamp the same way.

to_numpy() — the camera’s values

For high-rate acquisition, import NumPy (import numpy) before opening the stream. Otherwise its first import happens during conversion and can pause the consumer long enough to overflow the delivery queue. Keep file I/O and heavy processing out of the acquisition loop, and check host-drop counters as well as network loss.

arr = frame.to_numpy()
Pixel formatArray shapedtype
Mono8(H, W)uint8
Mono10, Mono12, Mono14, Mono16, and the packed Mono10p, Mono12p, Mono10Packed, Mono12Packed(H, W)uint16
Bayer, any depth(H, W) — the mosaic as the camera sent ituint8 for 8 bits, else uint16
Bayer with to_numpy(demosaic=True)(H, W, 3)the same depth
RGB8, BGR8 (reordered to RGB), with or without alpha, and 8-bit Y’CbCr(H, W, 3)uint8
anything else(N,) raw bytesuint8

A 16-bit array holds the camera’s values, not values scaled to 16 bits: a 12-bit pixel is 0 to 4095. Line padding the camera declares is skipped. Demosaicing is bilinear, the kernel Viva Studio’s viewer uses — fine for preview, not a substitute for an ISP.

# Mono12p: two 12-bit pixels, 0xABC and 0x123, packed least significant bit first.
frame = vg.Frame.from_bytes(bytes([0xBC, 0x3A, 0x12]), 2, 1, "Mono12p")
arr = frame.to_numpy()
assert arr.dtype == np.uint16 and arr.tolist() == [[0xABC, 0x123]]

Frame.from_bytes(payload, width, height, pixel_format, padding_x=0) builds a frame from bytes saved earlier or received elsewhere, for the same conversions.

to_rgb8() — always RGB

rgb = frame.to_rgb8()     # always (H, W, 3) uint8

Useful when you want one code path regardless of the camera’s pixel format. It converts monochrome and Bayer at 8 to 16 bits, packed formats such as Mono12p and Mono12Packed included, RGB and BGR with or without alpha, and 8-bit YUV; samples deeper than 8 bits keep their top eight. Other formats raise UnsupportedPixelFormatError.

Raw bytes

frame.payload()           # bytes, copy of the whole GVSP payload

Use this when you need to feed bytes to another decoder or serialize to disk as-is.

Event-vision blocks

An event camera, such as a LUCID Triton2 EVS, streams Prophesee EVT 3.0 or EVT 2.1 data instead of images. next_frame() hands each such block out as a Frame holding the raw bytes; next_block() tells the two apart, returning a Frame for an image and an EvsBlock for event data:

with cam.stream() as frames:
    block = frames.next_block(timeout_ms=5000)
if isinstance(block, vg.EvsBlock):
    print(block.format, block.block_id, len(block.payload()))  # "evt3.0" or "evt2.1"
elif block is not None:
    print("image", block.width, block.height)
block.format             # "evt3.0" (16-bit words) or "evt2.1" (64-bit events)
block.block_id           # the camera's number for the block
block.status             # vg.FrameStatus, as for a frame
block.ts_dev             # device tick count, Optional[int]
block.ts_host            # POSIX seconds, Optional[float]: None until cam.time_calibrate()
block.leader_size_x      # Size X and Size Y from the GVSP leader, as sent
block.leader_size_y
block.trailer_size_y     # Size Y from the GVSP trailer, as sent
block.chunks             # {chunk_id: bytes}, or None
block.payload()          # the EVT bytes as the camera sent them, one copy

The leader’s sizes are not an image’s geometry: an EVT block has none. Decode the payload with event-vision tooling; viva-camctl stream --raw-out records the same bytes to a file (Streaming → Event-vision cameras). A USB3 Vision stream returns only frames.

Streaming options

The stream() call accepts GigE-specific knobs:

cam.stream(
    iface="en0",               # NIC override — or "192.168.0.5"
    auto_packet_size=True,     # size packets from the NIC MTU (or packet_size=N)
    multicast="239.255.42.99", # have the camera stream to a multicast group, and join it
    destination_port=34567,    # a fixed UDP port, for a firewall; default: the OS picks one
    packet_delay_ns=2000,      # GevSCPD, converted to the camera's ticks; default: left alone
    resend=False,              # never ask for lost packets; default: ask if the camera can
)

None of these are required. iface= is auto-resolved by subnet match if you omit it; the rest fall back to the defaults noted above. What packet delay and resend do is in Streaming → Packet delay and Packet resend.

Packet size has three settings. Omit both arguments and the camera’s current GevSCPSPacketSize is kept. auto_packet_size=True sets it from the host NIC’s MTU; packet_size=N writes N as a ceiling. Pass at most one of the two. In every case a test-packet probe may lower the size if the network path drops it — see Streaming → Packet size and MTU.

iface= takes the host NIC’s IPv4 address or its OS name, the same two spellings viva-camctl --iface and viva-service --iface accept — so the address you read off discover() is a legal value here.

For U3V cameras all options are silently ignored.

Incomplete frames

with cam.stream(deliver_incomplete=True) as frames:
    for frame in frames:
        if frame.status is vg.FrameStatus.INCOMPLETE:
            print(frame.block_id, "lost", frame.missing_packets, "packets")

Lost packets’ bytes are zero in the payload. Every incomplete frame is counted in the stream’s statistics either way.

Counters

with cam.stream() as frames:
    frames.next_frame(timeout_ms=5000)
    stats = frames.stats()
print(stats.frames_complete, stats.frames_lost, stats.resend_recovered)

stats() returns every counter of the GigE receive engine: each frame’s fate (complete, incomplete, missed, dropped because the application fell behind), each packet’s, the packets asked for again and what became of them, and rates. What each counts is in Streaming → What the statistics tell you.

Watching another application’s stream

A camera opened with connect_gige(info, monitor=True) claims and writes nothing. It can watch a multicast stream the controlling application set up:

with vg.connect_gige(info, monitor=True) as watcher:
    with watcher.stream(monitor=True) as frames:   # starts no acquisition
        frame = frames.next_frame(timeout_ms=5000)

The group, port and packet size come from the camera; only iface= may be given. A USB3 Vision camera has no monitor access — one application opens the device — so stream(monitor=True) on one raises GenicamError. See Networking → One camera, several applications.

Chunks

A camera in chunk mode sends values with each frame — its timestamp, its exposure, its number. configure_chunks turns them on, and chunk_features reads them through the camera’s XML, like any other feature:

cam.configure_chunks(["FrameID", "Timestamp"])
with cam.stream() as frames:
    frame = frames.next_frame(timeout_ms=5000)
cam.configure_chunks([], active=False)
print(cam.chunk_features(frame))   # {"ChunkFrameID": "1", "ChunkTimestamp": "...", ...}

A value that could not be read maps to the exception that kept it, instead of a string.

Events

A camera reports what happens — an exposure ending, a frame starting — on its message channel (GigE Vision) or its event interface (USB3 Vision):

with cam.events(["ExposureEnd"]) as events:
    with cam.stream():
        event = events.next_event(timeout_ms=5000)
print(hex(event.id), event.block_id, cam.event_features(event))

event_features reads the features the camera’s XML derives from the event, such as EventExposureEndTimestamp. On a GigE camera events() takes iface= and port= as stream() does; a USB3 Vision camera needs neither.

Timeouts and ending a stream

Iteration blocks until a frame arrives. To time out a single read:

with cam.stream() as frames:
    frame = frames.next_frame(timeout_ms=1000)
    if frame is None:
        print("stream ended cleanly")
    else:
        ...

next_frame() returns None when the stream closes cleanly, or raises TransportError on timeout / network failure. The for frame in frames path uses a 5-second default timeout that raises on expiry.

Exit the with block to stop acquisition and release the socket / USB endpoint. You can also call frames.close() explicitly if you stored the iterator outside a with statement.

Complete example: save 5 frames as PNGs

import viva_genicam as vg
from PIL import Image

cam = vg.connect_gige(vg.discover(timeout_ms=500)[0])

with cam.stream() as frames:
    for i, frame in enumerate(frames, 1):
        Image.fromarray(frame.to_numpy()).save(f"frame_{i:03d}.png")
        if i >= 5:
            break

Identical in spirit to the Rust grab_gige example, 12 lines of Python.

Next

→ API reference — every public symbol, in one page.

API reference

Every public symbol exported from viva_genicam, plus the viva_genicam.testing module.

vg.__version__            # "X.Y.Z", the installed package version

Discovery

vg.discover(timeout_ms=500, iface=None, all=False, allow_broadcast_ack=False) -> list[GigeDeviceInfo]
vg.discover_ip(ip: str, timeout_ms=500) -> Optional[GigeDeviceInfo]
vg.discover_u3v() -> list[U3vDeviceInfo]
@dataclass(frozen=True)
class GigeDeviceInfo:
    ip: str
    mac: str
    manufacturer: Optional[str]
    model: Optional[str]
    transport: Literal["gige"]

@dataclass(frozen=True)
class U3vDeviceInfo:
    bus: str                    # the OS's bus identifier; its form varies by OS
    address: int
    vendor_id: int
    product_id: int
    serial: Optional[str]
    manufacturer: Optional[str]
    model: Optional[str]
    speed: Optional[str]        # e.g. "high speed (480 Mbit/s, USB 2)"
    transport: Literal["u3v"]

Both dataclasses expose .to_dict() for JSON-friendly export.

DeviceInfo is the Union[GigeDeviceInfo, U3vDeviceInfo] alias.

Connection

vg.connect_gige(device_info: GigeDeviceInfo, iface: Optional[str] = None, monitor: bool = False, exclusive: bool = False) -> Camera
vg.connect_u3v(device_info: U3vDeviceInfo) -> Camera
vg.Camera.open(device_info, **kwargs) -> Camera   # dispatches on type

monitor=True opens a GigE camera read-only, alongside the application that controls it; exclusive=True claims exclusive access, which keeps every other application from reading it too (Networking → One camera, several applications).

Camera

Any thread may use a camera; every call that waits on it releases the GIL. Methods marked GigE raise GenicamError on a USB3 Vision camera.

class Camera:
    transport: str                           # "gige" or "u3v"
    xml: str                                 # raw GenICam XML
    closed: bool
    control_state: ControlState              # GigE

    # Lifetime: close() gives control privilege back; so does leaving `with`.
    def close(self) -> None: ...
    def __enter__(self) -> "Camera": ...
    def __exit__(self, *exc) -> None: ...

    # Features as text, and by type.
    def get(self, name: str) -> str: ...
    def set(self, name: str, value: str) -> None: ...
    def get_integer(self, name: str) -> int: ...
    def set_integer(self, name: str, value: int) -> None: ...
    def get_float(self, name: str) -> float: ...
    def set_float(self, name: str, value: float) -> None: ...
    def get_bool(self, name: str) -> bool: ...
    def set_bool(self, name: str, value: bool) -> None: ...
    def get_enum(self, name: str) -> str: ...
    def set_enum(self, name: str, entry: str) -> None: ...
    def get_string(self, name: str) -> str: ...
    def set_string(self, name: str, value: str) -> None: ...
    def get_register(self, name: str) -> bytes: ...
    def set_register(self, name: str, data: bytes) -> None: ...
    def feature_state(self, name: str) -> FeatureState: ...
    def enum_entries(self, name: str) -> list[str]: ...            # declared
    def available_enum_entries(self, name: str) -> list[str]: ...  # accepted now

    # What changed: every write and invalidation advances the generation.
    def generation(self) -> int: ...
    def changed_since(self, since: int) -> tuple[list[str], int]: ...
    def poll(self) -> list[str]: ...           # values whose PollingTime passed
    def invalidate(self, name: str) -> None: ...
    def invalidate_all(self) -> None: ...

    # Standard features, by SFNC's names or the older ones cameras use.
    def exposure_time(self) -> float: ...
    def set_exposure_time(self, value: float) -> str: ...   # the feature written
    def gain(self) -> float: ...
    def set_gain(self, value: float) -> str: ...
    def gain_selectors(self) -> list[str]: ...
    def select_gain(self, selector: str) -> None: ...
    def acquisition_mode(self) -> str: ...
    def set_acquisition_mode(self, mode: str) -> None: ...
    def enable_trigger(self, selector: str, source: str) -> None: ...
    def disable_trigger(self, selector: str) -> None: ...
    def trigger_software(self) -> None: ...
    def roi(self) -> Roi: ...
    def set_roi(self, roi: Roi) -> None: ...
    def binning(self) -> tuple[int, int]: ...
    def set_binning(self, horizontal: int, vertical: int) -> None: ...
    def frame_rate(self) -> float: ...
    def set_frame_rate(self, hz: float) -> str: ...
    def disable_frame_rate(self) -> None: ...
    def user_sets(self) -> list[str]: ...
    def load_user_set(self, user_set: str) -> None: ...
    def save_user_set(self, user_set: str) -> None: ...
    def set_default_user_set(self, user_set: str) -> str: ...

    # Introspection.
    def nodes(self) -> list[str]: ...
    def node_info(self, name: str) -> Optional[NodeInfo]: ...
    def all_node_info(self) -> list[NodeInfo]: ...
    def categories(self) -> dict[str, list[str]]: ...
    def skipped(self) -> list[SkippedNode]: ...

    # Commands. execute: True once the camera reports completion; False with a
    # RuntimeWarning if it does not within `timeout` (the command was still
    # sent); False with wait=False.
    def execute(self, name: str, *, wait: bool = True, timeout: float = 5.0) -> bool: ...
    def is_done(self, name: str) -> bool: ...

    # The streamable features to a file and back. save: {"values": int,
    # "left_out": [(feature, reason)]}; load: {"written": int,
    # "written_on_retry": int, "failures": [str], "warnings": [str]}.
    def save_features(self, path: str | os.PathLike) -> dict: ...
    def load_features(self, path: str | os.PathLike) -> dict: ...

    def acquisition_start(self) -> None: ...
    def acquisition_stop(self) -> None: ...

    # Time.
    def time_calibrate(self, samples: int = 8, interval_ms: int = 20) -> None: ...  # GigE
    def time_reset(self) -> None: ...
    def map_dev_ts(self, ticks: int) -> Optional[float]: ...   # POSIX seconds

    # Chunks and events. A value that could not be read maps to its exception.
    def configure_chunks(self, selectors: Sequence[str], active: bool = True) -> None: ...
    def chunk_features(self, frame: Frame) -> dict[str, str | GenicamError]: ...
    def events(self, names: Sequence[str], iface: Optional[str] = None, port: int = 0) -> EventStream: ...  # GigE
    def event_features(self, event: Event) -> dict[str, str | GenicamError]: ...

    # Registers past GenApi; a write forgets every cached value.
    def read_register(self, address: int, length: int = 4) -> bytes: ...
    def write_register(self, address: int, data: bytes) -> None: ...

    # Control privilege and IP configuration (GigE).
    def reclaim_control(self) -> None: ...
    def release_control(self) -> None: ...
    def set_persistent_ip(self, ip: str, subnet: str, gateway: str = "0.0.0.0") -> None: ...

    def stream(
        self,
        iface: Optional[str] = None,
        packet_size: Optional[int] = None,
        auto_packet_size: bool = False,
        multicast: Optional[str] = None,
        destination_port: Optional[int] = None,
        packet_delay_ns: Optional[int] = None,
        resend: bool = True,
        deliver_incomplete: bool = False,
        monitor: bool = False,
    ) -> FrameStream: ...

class ControlState(str, Enum):
    HELD = "Held"; MONITOR = "Monitor"; LOST = "Lost"; RELEASED = "Released"

@dataclass(frozen=True)
class Roi:
    x: int
    y: int
    width: int
    height: int

Features

@dataclass(frozen=True)
class FeatureState:
    kind: str                          # a NodeKind value
    value: int | float | bool | str | None
    access: Optional[str]              # now: "RO" | "RW" | "WO" | None
    is_implemented: bool
    is_available: bool
    range: Optional[ValueRange]        # ValueRange(min, max, inc)
    enum_entries: Optional[list[str]]  # accepted now
    unit: Optional[str]
    polling_time: Optional[float]      # seconds
    caching: str                       # "NoCache" | "WriteThrough" | "WriteAround"

class NodeKind(str, Enum):
    INTEGER       = "Integer"
    FLOAT         = "Float"
    ENUMERATION   = "Enumeration"
    BOOLEAN       = "Boolean"
    COMMAND       = "Command"
    CATEGORY      = "Category"
    SWISS_KNIFE   = "SwissKnife"
    CONVERTER     = "Converter"
    INT_CONVERTER = "IntConverter"
    STRING_REG    = "StringReg"
    REGISTER      = "Register"

@dataclass(frozen=True)
class NodeInfo:
    name: str
    kind: str                          # a NodeKind value
    access: Optional[str]              # declared: "RO" | "RW" | "WO" | None
    visibility: str                    # "Beginner" | "Expert" | "Guru" | "Invisible"
    display_name: Optional[str]
    description: Optional[str]
    tooltip: Optional[str]
    effective_access: Optional[str] = None   # live; set by node_info() only

    @property
    def readable(self) -> bool: ...    # from the declared access
    @property
    def writable(self) -> bool: ...
    def to_dict(self) -> dict: ...

kind is a plain string holding a NodeKind value. See Control & introspection → Node metadata for what effective_access means.

FrameStream

class FrameStream:
    def __enter__(self) -> "FrameStream": ...      # acquisition_start(), unless monitor=True
    def __exit__(self, *exc) -> None: ...           # acquisition_stop() + close()
    def __iter__(self) -> Iterator[Frame]: ...
    def __next__(self) -> Frame: ...                # 5-second default timeout
    def next_frame(self, timeout_ms: Optional[int] = None) -> Optional[Frame]: ...
    def next_block(self, timeout_ms: Optional[int] = None) -> Frame | EvsBlock | None: ...
    def stats(self) -> StreamStats: ...             # GigE
    def close(self) -> None: ...

StreamStats is a frozen dataclass with every counter of the receive engine — frames_complete, frames_incomplete, frames_missed, frames_lost, packets_received, packets_missing, resend_requested, resend_recovered, avg_fps, elapsed and the rest; durations are in seconds.

Frame

class Frame:
    width: int
    height: int
    pixel_format: str
    pixel_format_code: int
    block_id: int
    payload_type: int                  # 0x0001 image, 0x4001 image with chunks
    padding_x: int                     # bytes after each line
    status: FrameStatus
    is_complete: bool
    missing_packets: Optional[int]     # for INCOMPLETE
    device_status: Optional[int]       # for DEVICE_STATUS
    chunks: Optional[dict[int, bytes]]
    ts_dev: Optional[int]
    ts_host: Optional[float]

    @classmethod
    def from_bytes(cls, payload: bytes, width: int, height: int,
                   pixel_format: str | int, padding_x: int = 0) -> "Frame": ...
    def payload(self) -> bytes: ...
    def to_numpy(self, demosaic: bool = False) -> NDArray[np.uint8] | NDArray[np.uint16]: ...
    def to_rgb8(self) -> NDArray[np.uint8]: ...     # always (H, W, 3)

class FrameStatus(str, Enum):
    COMPLETE = "Complete"; INCOMPLETE = "Incomplete"
    DEVICE_STATUS = "DeviceStatus"; TRAILER_MISSING = "TrailerMissing"

What shape and type to_numpy returns for each format: Streaming → to_numpy().

EvsBlock

class EvsBlock:                        # from FrameStream.next_block()
    format: str                        # "evt3.0" | "evt2.1"
    block_id: int
    status: FrameStatus
    leader_size_x: int                 # GVSP leader and trailer, as sent
    leader_size_y: int
    trailer_size_y: int
    chunks: Optional[dict[int, bytes]]
    ts_dev: Optional[int]
    ts_host: Optional[float]

    def payload(self) -> bytes: ...    # the EVT bytes as sent

See Streaming → Event-vision blocks.

Events

class EventStream:                     # from Camera.events(); a context manager
    port: int
    def next_event(self, timeout_ms: Optional[int] = None) -> Event: ...
    def __iter__(self) -> Iterator[Event]: ...
    def close(self) -> None: ...

class Event:
    id: int
    stream_channel: int
    block_id: int
    ts_dev: int
    ts_host: Optional[float]
    data: bytes

Network commands

vg.send_action(device_key: int, group_key: int, group_mask: int,
               scheduled_time: Optional[int] = None,
               destination: str = "255.255.255.255",
               timeout_ms: int = 200) -> AckSummary     # AckSummary(sent, acks)
vg.force_ip(mac: str, ip: str, subnet: str, gateway: str = "0.0.0.0",
            iface: Optional[str] = None) -> None

Testing

from viva_genicam.testing import FakeGigeCamera

class FakeGigeCamera:
    def __init__(
        self,
        width: int = 640,
        height: int = 480,
        fps: int = 30,
        bind_ip: str = "127.0.0.1",
        port: int = 3956,
        pixel_format: str = "Mono8",           # any PFNC name
        *,
        packet_resend: bool = True,
        drop_packets: Optional[Sequence[tuple[int, int]]] = None,  # (block, packet)
        delay_ack: Optional[Mapping[int, float]] = None,           # address -> seconds
    ) -> None: ...
    def start(self) -> None: ...
    def stop(self) -> None: ...
    ip: str
    port: int
    def device_info(self, timeout_ms: int = 1500) -> GigeDeviceInfo: ...
    def __enter__(self) -> "FakeGigeCamera": ...    # calls start()
    def __exit__(self, *exc) -> None: ...            # calls stop()

    # What the camera itself holds, for tests:
    def controller(self) -> Optional[str]: ...       # "ip:port" holding control
    def revoke_control(self) -> None: ...
    def peek(self, address: int, length: int) -> bytes: ...
    def software_triggers(self) -> int: ...
    def saved_exposure(self, user_set: int) -> Optional[float]: ...
    def actions(self) -> int: ...
    def blocks_sent(self) -> int: ...
    def writes(self) -> int: ...
    REGISTERS: Mapping[str, int]                     # its register map
    DEVICE_KEY: int; GROUP_KEY: int; GROUP_MASK: int; MAC: str

An in-process fake GigE Vision camera, for tests and demos without hardware. Keep port=3956: discovery only looks there, so device_info() and vg.connect_gige cannot find a fake bound elsewhere, and only one fake per host can hold that port at a time.

from viva_genicam.testing import FakeU3vCamera

class FakeU3vCamera:
    def __init__(self, width: int = 640, height: int = 480,
                 pixel_format: str = "Mono8") -> None: ...
    def connect(self) -> Camera: ...                 # as connect_u3v opens one
    def acquiring(self) -> bool: ...
    def peek(self, address: int, length: int) -> bytes: ...

An in-process fake USB3 Vision camera. No USB enumeration finds it, so connect() opens it.

Exceptions

GenicamError                      # base class
├── GenApiError
├── TransportError
├── ParseError
├── MissingChunkFeatureError
└── UnsupportedPixelFormatError

Everything the bindings raise deliberately inherits from GenicamError, so one except vg.GenicamError: covers it. A panic in the Rust layer surfaces as pyo3_runtime.PanicException, a BaseException — see Control & introspection.

Viva Studio

Viva Studio is the desktop application that comes with viva-genicam: find a camera, browse and change its features, watch the live image, and save the diagnostic report we ask for when something goes wrong. It runs the library itself, so it is also the quickest way to try viva-genicam on your camera.

Experimental. Studio discovers cameras, reads and writes features and streams live images, but it is the least-exercised part of the project: its hardware reports come from a few users and camera models (Status). If what Studio shows disagrees with your camera, please report it.

Install

Each release from 0.8.0 attaches Viva Studio to its GitHub release, under the same version as the library, as viva-studio-<tag>-<target>.<ext>:

OSFileInstall
macOS, Apple Silicon.dmgOpen it and drag Viva Studio to Applications
Linux x86_64.deb or .AppImagesudo apt install ./viva-studio-….deb, or chmod +x the AppImage and run it
Windows x86_64.msiRun the installer

The Linux builds need glibc 2.39 (Ubuntu 24.04) or newer and WebKitGTK 4.1, which the .deb pulls in. Running the AppImage needs FUSE 2 (libfuse2t64 on Ubuntu 24.04). SHA256SUMS.txt on the release lists every file’s checksum. There is no Intel Mac build.

First launch

The bundles are not signed — signing needs paid certificates from Apple and Microsoft — so the first launch asks you to confirm:

  • macOS refuses to open the app the first time. Open System Settings → Privacy & Security and choose Open Anyway for Viva Studio, or clear the download’s quarantine flag:

    xattr -dr com.apple.quarantine "/Applications/Viva Studio.app"
    
  • Windows SmartScreen shows “Windows protected your PC”: choose More info, then Run anyway. If Windows Firewall then asks whether Viva Studio may use the network, allow the network your camera is on: GigE Vision discovery and streaming arrive as inbound UDP.

To build Studio from source instead, see studio/README.md.

Connect to a camera

Studio lists the cameras it finds in the device menu at the top right. Pick one to connect with Control access (the default). The separate Monitor action opens an embedded GigE Vision camera read-only, including while another application controls it. Direct monitor access is unavailable for USB cameras and in remote mode, where the service owns camera access.

  • GigE Vision cameras are found by broadcast on every network interface. If yours does not appear, it is almost always the network: Networking covers addressing, firewalls and jumbo frames.
  • A GigE camera on the wrong subnet can be given a temporary address from the device menu with Set IP… (FORCEIP), and a permanent one from the Camera panel of the Diagnostics tab. Discovery requests broadcast acknowledgements, so devices on another subnet can still appear with a Different subnet label. The label does not prohibit a connection through a configured route.
  • USB3 Vision cameras are found by USB enumeration. On Linux your user needs permission to open the device (a udev rule).

Studio talks to the camera directly. It can also run against cameras that viva-service exposes over the network (remote mode).

Connection loss and recovery

In direct mode, Studio watches the GigE control connection even while no image is being acquired. If the camera disappears, the viewer closes its old stream and Studio looks for the same camera by MAC address for up to 30 seconds. The camera may return with another IP address. Its XML and feature controls are loaded again; configuration values are not automatically written back.

Acquisition remains stopped after recovery. Check the current settings and press Start Acq when ready. Cancel reconnect abandons the search, and connecting another camera also cancels it. If recovery expires, reconnect from the device menu.

When the transport reports lost control while the camera is still reachable, Studio keeps the session read-only and displays Camera control lost. It does not repeatedly try to reclaim control. Use Reconnect with control when the other controller has finished. On a camera that does not identify its controller, a takeover may become visible only after a refused write. A disconnected USB3 Vision camera requires manual reconnection from the device menu.

Watching another application’s stream

In a direct GigE Monitor session, feature controls, commands and persistent IP changes are read-only. Watch stream joins the multicast destination already configured by the controller; it does not start acquisition or change packet size, timing, destination or trigger settings. A stream sent by unicast to another host cannot be watched this way. Configure multicast and start acquisition in the controlling application first.

Stop watching, Disconnect and closing Studio only end this viewer’s reception. The controller and camera keep acquiring. After a monitor connection is recovered, it remains a monitor and its viewer stays stopped until you choose Watch stream again. Packet-size controls are disabled because the controller owns those settings. A lost-control banner also offers Open as monitor for a direct GigE camera; this is always an explicit choice.

macOS local-network access

On macOS 15 or later, allow Viva Studio access to the local network when macOS asks. This permission is separate from opening an unsigned download. To check it later, open System Settings → Privacy & Security → Local Network and find Viva Studio. Close and reopen Studio after changing the permission.

Check this setting when Studio cannot contact a GigE camera or a remote service, even if viva-camctl works from Terminal: macOS treats command-line tools and apps differently. A network error such as Broken pipe alone does not prove that permission is the cause; report it if access is allowed and the connection still fails. Apple’s local-network privacy guide describes the distinction.

Features

The Features tab shows the camera’s feature tree as its GenApi XML describes it: categories on the left, features on the right, with search and an editor for each feature type. A feature the camera currently refuses — read only, locked by another feature, or unavailable — is shown as such and cannot be edited. Load XML… opens a GenApi XML file with no camera attached, for browsing a camera’s description offline.

The sidebar groups the features most sessions need — acquisition control, exposure and gain, image format, trigger, user sets, transport layer, auto functions and colour processing — showing only those your camera has, and the packet size of a GigE stream.

Expand Image preview in the Features tab for a compact, fit-to-view canvas while changing settings. It starts collapsed and remembers your preference. Acquisition still starts from Start Acq; with the preview expanded, Start keeps the Features tab visible. The canvas shares the Image tab’s preview connection, and only the visible canvas decodes frames.

Register nodes

A <Register> node is a block of raw bytes — a vendor’s user data area, a lookup table, a file-transfer buffer. Selected while a camera is connected, it shows its bytes as a hex dump: the offset, sixteen bytes to a row in hexadecimal, and the same bytes as ASCII. Refresh reads it again. Studio reads the whole register but draws only its first 4096 bytes; Copy to editor copies all of them into the editor.

To write one, type or paste the new bytes in hexadecimal — spaces, :, - and , between bytes are fine — and press Write. A register is written whole: Studio refuses anything but exactly its length, rather than padding or cutting it. After the write it reads the register back, and re-reads any feature the write may have changed. A read-only register has no editor, a write-only one no dump, and a read-only session writes nothing. Offline, with only the XML, a register has no bytes to show.

Images

The Image sidebar puts acquisition rate, exposure and gain above the statistics for quick adjustment. Controls use the camera’s declared limits, units and access restrictions, including older names such as ExposureTimeAbs and AcquisitionFrameRateAbs. A raw gain or exposure value keeps its camera units; it is not converted to dB or microseconds. After automatic remote reconnection, Studio refreshes the feature graph and controls from the replacement session.

The Image tab shows the live stream once you press Start Acq. The toolbar zooms to fit or to exactly one screen pixel per camera pixel, and opens a histogram, a line profile and an ROI tool. Freeze for native pixel analysis holds one frame for the pixel inspector, histogram and line profile. They use the camera’s original sample values, including 10-, 12- and 16-bit formats. Resume live preview returns to the stream; freezing the viewer does not stop acquisition. The header shows the frame rate and, once any are lost, how many frames were lost — the first sign of a network that cannot keep up.

Save snapshot saves a PNG at the source bit depth. While frozen, it saves the frame being inspected; while live, it requests one recent frame. Bayer inspection measures the sensor mosaic, while the PNG contains demosaiced colour. Formats without a supported native conversion report an error and leave the live preview available.

Native capture supports images up to 16 Mi pixels. Remote mode carries each frame’s row stride, so padded rows and supported odd-width packed images use the same conversion as embedded mode. Update the service and Studio together: this requires service API version 8 or later and frame-header version 3; older frame headers are rejected.

The Statistics section of the Image tab counts every frame the camera sent: received complete, incomplete, missed, dropped by the host, and for GigE Vision the packets and resends behind them, or for USB3 Vision the transfers. These are frames received. Live preview targets 30 frames a second (15 in remote mode), decoding only in the visible Image tab or expanded Features preview, so the Image status bar’s “display” rate and the Displayed count stay low at a high camera rate; that is the preview, not a loss. The counters keep their last values after Stop.

Diagnostics and reports

The Diagnostics tab shows the camera’s identity, its IP configuration, its configuration file (Saving a camera’s configuration), the events it sends (Camera events), action commands (Action commands), the declarations in its XML that the library could not turn into features, and a log of what Studio did.

Generate report writes the same report as viva-camctl report (Reporting a camera we can’t open): your system, what discovery heard, the camera’s identity and, by default, its XML. Save it or copy it, and attach it to an issue. It is the most useful thing you can send us.

Saving a camera’s configuration

Configuration in the Diagnostics tab saves every feature the camera’s XML marks as streamable to a file, and loads one back — the same file viva-camctl save and load use, in the layout GenApi’s own tools write. A feature behind a selector, such as Gain behind GainSelector, is saved under each of its entries. Save to file… picks the file and shows how many values it saved, and under Left out, and why each feature it could not, with the reason: not available, locked by another feature, and the like. Stop acquisition before saving: features the camera locks while streaming are left out otherwise, and the panel says so while the camera acquires.

Load from file… writes the values back in the order the camera’s features depend on one another, and lists each value the camera refused, with its reason. A file saved from another camera model, or another version of its XML, still loads, with a warning. Afterwards Studio reads every feature on screen again. Neither is available in a read-only session: loading writes features, and saving sets selectors to read each entry. In remote mode the service saves and loads on its camera, and the file stays on your computer.

Action commands

A GigE Vision action command makes several cameras act at once — trigger an exposure, say — from one broadcast. It is addressed by keys, not by camera: every camera that receives it compares the device key, group key and group mask with its own ActionDeviceKey, ActionGroupKey and ActionGroupMask, and the ones that match act on it and acknowledge. Action command in the Diagnostics tab sends one, as viva-camctl action does.

Studio fills in the connected camera’s keys when the camera lets them be read; ActionDeviceKey is often write-only, and then you enter the key the camera was given. The destination is the broadcast address of the network the camera is on, or 255.255.255.255 with no camera connected; a camera’s own address reaches that camera only. A scheduled time, in the cameras’ timestamp ticks, makes the cameras act at that time instead of at once — only cameras that support scheduled actions accept it. Studio shows how many devices acknowledged within the timeout, and each device that refused, with the status it answered. The command reaches every device on the network, not only the connected camera. Action commands are sent in direct mode only.

Frame timestamps and chunks

Expand Frame metadata in the Image tab to inspect the displayed frame’s ID, raw device ticks, completeness, and any chunk IDs and values decoded from the camera’s XML. Host time (ns) is available only when the device clock has been calibrated; Studio does not substitute the frame’s reception time. IDs and timestamps retain their full precision.

Freeze keeps these values with the same captured image used for pixel inspection, histogram and PNG saving. Resume returns to live frames. Missing or unreadable chunk data and metadata truncation are shown explicitly.

If the camera exposes standard chunk settings, Chunk Data offers ChunkModeActive, ChunkSelector and ChunkEnable through the normal camera controls. Enable the desired selector explicitly, following the camera’s access restrictions; Studio does not enable chunks on connect or recovery. Monitor access remains read-only. Chunk values add processing work, so leave chunk mode off when it is unnecessary for high-rate acquisition.

In remote mode, update Studio and the camera services together: this feature uses image wire version 3 / API 8 or later. A bare preview from an older local streamer can still be displayed, but has no per-frame metadata.

Camera events

A camera can tell you when something happens on it — an exposure ended, a trigger was missed — with an event: a GigE Vision message or a USB3 Vision event. Camera events in the Diagnostics tab lists the events the camera offers (its EventSelector entries). Tick the ones you want and press Start; each event appears in the list as it arrives, newest first, with its name and ID, its raw device ticks and, for GigE Vision, the block it concerns. Expand an event to see the values the camera’s XML reads from it, such as EventExposureEndFrameID; a value that could not be read shows its error. Host time is available only once the device clock has been calibrated; Studio never substitutes the time the event arrived. The list keeps the newest 500 events.

Most cameras send events only while they acquire: start acquisition too.

Starting changes the camera’s event settings. Stop, disconnecting and closing Studio put back exactly what starting changed. When something cannot be put back — the camera was unplugged, another application took control, a write was refused — the panel says which setting, rather than reporting a clean stop. A read-only session cannot start events. In remote mode the service does the same, and Studio and the service need API version 9 or later.

A camera whose XML has no EventSelector has no events Studio can turn on, and the panel says so.

Remote mode

Instead of opening cameras itself, Studio can show cameras that viva-service (GigE Vision) or viva-service-u3v (USB3 Vision) serve over Zenoh: for a camera on another machine, or several viewers of one camera. viva-service is in the viva-genicam-<version>-<platform> archive on each GitHub release; viva-service-u3v runs from a clone of the repository.

Both sides need a Zenoh configuration, and neither loads one by itself. The repository’s studio/config/ holds a pair for one machine: the service listens on tcp/127.0.0.1:7447 (zenoh-local.json5) and Studio connects there (zenoh-studio.json5). For a service on another machine, put that machine’s address in both.

  1. Start the service with its configuration, naming the network interface the cameras are on:

    viva-service --iface eth0 --zenoh-config /path/to/zenoh-local.json5
    
  2. Start Studio with the ZENOH_CONFIG environment variable set to the absolute path of its configuration:

    # macOS
    open -a "Viva Studio" --env ZENOH_CONFIG=/path/to/zenoh-studio.json5
    # Linux, the AppImage
    ZENOH_CONFIG=/path/to/zenoh-studio.json5 ./viva-studio-….AppImage
    

    On Windows, set ZENOH_CONFIG as a user environment variable, then start Studio; remove the variable to go back to direct mode.

The chip in Studio’s header reads Remote or Embedded (direct mode). Without ZENOH_CONFIG Studio runs in direct mode; a ZENOH_CONFIG it cannot load is reported as an error, not ignored.

Trying it without a camera

From a clone of the repository, a fake GigE Vision camera on loopback stands in for a real one (Testing without hardware):

# Terminal 1: the fake camera
cargo run -p viva-fake-gige

# Terminal 2: the service, on the loopback interface (lo0 on macOS, lo on Linux)
cargo run -p viva-service -- --iface lo0 --zenoh-config studio/config/zenoh-local.json5

# Terminal 3: Studio in remote mode, as in step 2, with an absolute path
open -a "Viva Studio" --env ZENOH_CONFIG=$(pwd)/studio/config/zenoh-studio.json5

Studio lists the fake camera, shows its features, and streams a gradient image. For USB3 Vision the service hosts a fake of its own, which replaces the first two terminals:

cargo run -p viva-service-u3v -- --fake --zenoh-config studio/config/zenoh-local.json5

A fake camera appears only in remote mode: direct mode does not look for cameras on loopback, so without ZENOH_CONFIG the device list stays empty.

The services and their wire protocol are described in the repository’s docs/studio/zenoh-api.md.

Not there yet

  • Signed and notarised bundles, and automatic updates.
  • Recording and playback.
  • More than one camera at a time.

FAQ & Troubleshooting

Short answers to questions that come up often when using viva-genicam or bringing up a new camera. Each one links to the chapter that covers it in full.


“Discovery finds no cameras. What do I check first?”

Run viva-camctl list. If nothing appears, check in this order: the link LEDs, that the host NIC and the camera share a subnet, that the firewall lets the discovery reply in, and — on a multi-NIC host — that you name the right interface:

cargo run -p viva-camctl -- list --iface 192.168.0.5   # host NIC by IPv4 address
cargo run -p viva-camctl -- list --iface eth0          # or by OS name

The full checklist is in Discovery → Troubleshooting checklist. If the camera’s address starts with 169.254., go to Networking → Link-local (APIPA) cameras instead. If none of it helps, send us the report bundle.


“The vendor viewer works but viva-genicam doesn’t. Why?”

Usually because the two tools differ in which host NIC they use, where the camera is told to stream, or the packet size and delay they set. See Networking → Vendor tool works, viva-genicam does not for what to compare.


“Does this work on Windows?”

Yes — Windows, Linux and macOS are all supported. On Windows the usual obstacles are the firewall prompt and NIC power-saving settings; see Networking → Windows. A USB3 Vision camera needs the WinUSB driver once; see USB3 Vision setup → Windows.


“How do I set exposure, gain, pixel format, etc.?”

By feature name, with viva-camctl set or Camera::set in Rust:

cargo run -p viva-camctl -- set --ip 192.168.0.10 --name ExposureTime --value 5000

Registers & features covers reading, writing, why a write can be refused, and the Rust side.


“What are selectors and why do my changes seem to disappear?”

A selector such as GainSelector chooses which channel a feature like Gain refers to. Setting Gain without first setting the selector changes whichever channel is currently selected. See Registers & features → Work with selectors.


“Do I need to care about the GenApi XML?”

For most applications, no: you use features by name and the NodeMap handles the mapping. Look at the XML when a feature behaves differently from its documentation, or when you are debugging selectors or SwissKnife formulas. See the GenApi XML tutorial and the viva-genapi chapter.


“How do I save frames and look at them?”

viva-camctl stream saves the first --save N frames (default 1) to the current directory as frame_0001.pgm (Mono8) or frame_0001.ppm (other formats, or always with --rgb):

cargo run -p viva-camctl -- stream \
  --ip 192.168.0.10 --iface 192.168.0.5 --save 100 --duration-s 10

Without --duration-s the stream runs until Ctrl+C. Both formats are plain 8-bit NetPBM, readable by most image viewers, OpenCV and Pillow. For a camera with more than 8 bits per sample, add --save-format png or --save-format tiff to keep them all in a 16-bit file (Streaming → Saving frames). Event-vision cameras produce block_NNNN.evt3 / .evt21 files instead; see Streaming → Event-vision cameras.


“Where should I report bugs or ask questions?”

If a camera does not work, start with Reporting a camera we can’t open — it gives you two commands that collect everything we need.

What is known not to work yet is listed in issue #191. For anything else, open an issue on GitHub with what you ran and what happened, your OS and camera model, and logs from RUST_LOG=debug or viva-camctl -vv.

Reporting a camera we can’t open

If viva-genicam cannot discover, open, or read your camera, that is worth reporting even if you have a workaround. This page explains what to send and why it matters more than it might look.

Why your camera is the evidence

This project is a clean-room implementation of the GenICam standards. We can test it against a specification, against a fake camera, and against a corpus of real vendor XML documents — and we do. None of that is the same as a device.

Real cameras are routinely non-conformant, internally inconsistent, or at odds with their own documentation, and the goal is to work with the hardware that exists, not the hardware the standard describes. When a camera and the spec disagree, we accommodate the camera. So a device we have never seen is the one thing that can settle a question no amount of reading will.

Two of the worst bugs this project has shipped — a camera that could not be opened at all in #35, and another in #45 — were each a single vendor XML construct we had never encountered. Both reached users before they reached us. Both were fixed from an XML document a reporter attached to the issue, and both documents are now in the test corpus, so that class of bug has something watching for it.

What to send

Two commands. Neither needs the camera to open: xml never parses the document, and report records a parse or nodemap failure in the bundle instead of stopping. So both work on a camera we cannot open — which is the only camera anyone reports.

# Everything: environment, interfaces, discovery, bootstrap registers, XML
viva-camctl report --ip <CAMERA-IP> --out viva-report.txt

# Just the GenApi XML
viva-camctl xml --ip <CAMERA-IP> --out camera.xml

If the error mentions the XML ZIP archive, the document could not be unpacked. Send the archive exactly as the camera serves it:

viva-camctl xml --raw --ip <CAMERA-IP> --out camera-xml.zip

If discovery itself is what fails, drop --ip — the report still records your interfaces and what discovery did or did not hear:

viva-camctl report --out viva-report.txt

For a USB3 Vision camera, name it by its place in viva-camctl list-usb:

viva-camctl report --usb 0 --out viva-report.txt

A USB3 Vision report also lists the camera’s bootstrap registers, decoded and as raw bytes, and still does when its XML cannot be read. USB3 Vision has run on one camera so far, so those bytes are exactly what we need to see.

The .txt extension is not cosmetic: GitHub rejects .xml attachments, so the bundle is written as text you can drag onto an issue. Zip the raw XML if you send it separately.

Both commands ship with the Python package too, so there is nothing to build from source:

pip install viva-genicam
viva-camctl report --ip <CAMERA-IP> --out viva-report.txt

In Viva Studio, the Diagnostics tab’s Save report… writes the same bundle for the connected camera — the same library code (viva_genicam::report).

What is in the bundle

Sections, in order:

SectionContents
Environmentviva-camctl version, host OS and architecture
Network interfacesEvery interface as the library sees it, with index and IPv4 addresses
DiscoveryEach camera that answered: IP, MAC, manufacturer, model, version, serial, user name
USB3 Vision devicesEach USB3 Vision camera on the host: vendor and product, bus position, manufacturer, model, serial, link speed
CameraWhich device the rest of the report is about
Bootstrap registersThe GVCP standard register block, decoded (GigE Vision only)
GenApiXML size, schema version, node and feature counts, and any node that was dropped
GenApi XMLThe document itself

The interface list is there because an interface missing from it is invisible to discovery no matter what the OS reports elsewhere, and that is not obvious from any other output.

A section that fails says so and the report continues — a camera that refuses the control channel still produces everything up to that point.

Before you attach it

The bundle describes your machine: interface names, every IPv4 address on the host, and the camera’s MAC and serial. None of it is secret, but if any of it is sensitive in your environment, edit the file before attaching — it is plain text, and we would rather have a redacted report than none. Say what you redacted so we do not read a blank as a missing value.

Use --no-xml to leave the GenApi document out, or --stdout to look at the bundle before writing it anywhere.

Where to send it

Open an issue at github.com/VitalyVorobyev/viva-genicam/issues. Useful alongside the bundle:

  • What you ran and what happened, quoted rather than paraphrased.
  • Output with RUST_LOG=debug, or viva-camctl -vv.
  • Whether a vendor tool works on the same camera and host — that separates a library bug from a network or camera configuration problem.
  • A packet capture, if you can take one. tcpdump -i <iface> -w capture.pcap udp port 3956 covers control traffic. A capture shows exactly what the camera sent, which can answer wire-level questions that documentation alone cannot.

What happens to it

The XML goes into the vendor corpus — a set of real device descriptions that a scheduled job parses and evaluates, building a full nodemap from each and exercising every node. Adding yours means the construct that broke your camera is watched from then on.

The corpus job runs weekly and on demand rather than on every pull request: the documents are fetched from third-party repositories, and an upstream rename or a network hiccup must not be able to block an unrelated merge. So a fix will not appear on the day you report it, but a regression will not go unnoticed either.

The documents are vendor copyright, published for interoperability by third-party projects, so the repository fetches them rather than redistributing them; the fetch script is scripts/fetch-xml-corpus.sh. Contributed documents are fetched from the issue you attach them to — which is why those issue threads are kept rather than closed quickly.

You can run the same check against your own camera without waiting for us. Point VIVA_GENICAM_XML_CORPUS at a directory holding your XML:

mkdir -p ~/mycorpus
viva-camctl xml --ip <CAMERA-IP> --out ~/mycorpus/mycam.xml

git clone https://github.com/VitalyVorobyev/viva-genicam && cd viva-genicam
VIVA_GENICAM_XML_CORPUS=~/mycorpus \
  cargo test -p viva-genapi-xml --test vendor_corpus -- --nocapture   # parses
VIVA_GENICAM_XML_CORPUS=~/mycorpus \
  cargo test -p viva-genapi     --test vendor_corpus -- --nocapture   # + evaluates

The second stage is the one that matters. Parsing a document only proves the XML is well-formed; building a nodemap from it and evaluating every node is what exercises the formula language, the address model and the numeric codecs — where the defects behind #35 all lived, invisible to the parser.

Cameras that have run viva-genicam

Each camera below has run the library, as an issue or pull request shows; the link is the evidence, and nothing here goes beyond it. Reported is what the person with the camera said they saw. Inferred is what we concluded from what they sent us: an XML file, a log, a capture. A fix that was never run again on the camera says so.

What does not work yet, on any camera, is issue #191. If your camera is missing here, or does something this page does not say, tell us: a report from your camera is how this list grows.

GigE Vision

Anonymous six-sensor GigE device

GigE Vision 1.2; the manufacturer, model and unique identifiers are private. Maintainer test on macOS/Apple silicon, 1 Gb/s Ethernet, MTU 1500. One stream contains six side-by-side Mono8 images. The initial run exposed reversed controller IP/port register contents; the transport accepts that layout only when both values match its socket. Short runs delivered six full 720 × 540 images at 30 FPS without reported loss. Each sensor’s test pattern was checked in its own image tile. C GenTL and Harvesters each received 1000 complete frames. Faster minimum-ROI runs and Python delivery showed host backpressure drops; this is not a loss-free maximum-FPS or endurance claim. Events, chunks and metric 3D are not advertised by this interface. The fixes and tests are recorded in #224. The 2026-10-27 follow-up also verified Studio quick controls, compact preview, near-cap display pacing and remote controls after a software reset. Preloading NumPy avoided the measured Python startup drops. A larger delivery queue then passed short production CLI checks at the minimum ROI and full six-sensor ROI; this is not endurance qualification. Detailed scope and restoration are in the bench record.

Allied Vision Manta G-125B

Firmware 00.01.44.28514, GigE Vision 1.2; macOS on Apple silicon, through a USB Ethernet adapter at MTU 1500. Run by the maintainer, so everything here is what was seen on the camera, with verbose logs. The 2026-10-25 run could not capture packets because access to the host’s BPF devices was denied.

  • Discovery, including of the camera configured for another subnet, FORCEIP and persistent IP configuration (#215).
  • Control and exclusive access, a second application refused while one holds control, a read-only monitor receiving another application’s multicast stream, commands, a saved configuration loaded back to the same 98 values, chunks in its GigE Vision 1.x layout, and events (#216).
  • Streaming in every pixel format it offers, a 300 s stream at 30.9 fps with no frame lost, packet resend, packet pacing, multicast with a monitor, acquisition modes and software triggers, event timing, action commands (which it does not implement) and its clock (#217).
  • A two-hour endurance run: 222,375 complete frames, one incomplete frame, no missed frames or delivery backpressure; resident memory stayed bounded and 15 files remained open. A separate ten-minute run delivered 18,531 complete frames without loss. These are measurements, not a loss-free eight-hour qualification.
  • On 2026-10-25, all 24 hardware tests passed again. The C GenTL consumer and Harvesters each acquired ten complete 1292 × 964 Mono8 frames; Python discovery, feature reads, command execution and three NumPy-backed image captures passed.
  • The service published 92 image messages in three seconds and resumed acquisition after an expired heartbeat and temporary IP change. A native Studio debug bundle discovered this camera but failed to claim control with Broken pipe; its cause remains unconfirmed. The eight-hour follow-up started on 2026-10-25 and is still pending.
  • The recovery and surface checks above are recorded in #218; its eight-hour endurance result is pending.
  • The hardware smoke suite, crates/viva-genicam/tests/gige_hardware.rs, passes on it (#216, #217).

JAI FS-3200T-10GE-NNC

Windows 11 and Linux, link-local (APIPA) addressing; run by a user. Some threads call it a Vieworks FS3200T: the reporter wrote “JAI / Vieworks FS-3200T-10GE”, and discovery reports JAI Corporation.

  • Reported: discovery on Windows after the fix in #64, and FORCEIP, with a capture we parsed and found to match (#57).
  • Reported: on Linux, discovery, the XML download, 1 065 features loaded and streaming once the firewall let GVSP in (#57).
  • Reported: 15 s of streaming on Windows through viva-camctl, 46 frames and none dropped (#72); a later run on main, 31 frames and none dropped, which we identified as this camera from its MAC address (#70).
  • Reported: live frames in Viva Studio’s embedded mode (#87), and viva-service discovering and connecting on Windows by address and by adapter GUID (#109).
  • Reported: the automatic packet size gave no frames in Studio, and the cause was a switch on the path (#112). The fixes that followed have not been run on the camera; reads of its event registers refused with BAD_ALIGNMENT are still open there.

JAI GOX-2450SC-5GE

Windows 11, Viva Studio; run by a user. Reported: discovery, connection and its features in Studio. Acquisition failed on a host-side defect, since fixed, and has not been reported on this camera since (#70).

Micro-Epsilon scanCONTROL 8500-50

A GigE Vision laser profile scanner, firmware 3.0.0; run by a contributor.

  • Reported: discovery with viva-camctl (#95).
  • Reported: streaming its Coord3D_ABC32f profiles through the library, 755 568 frames with none dropped (#93).
  • Reported: how it answers control-channel reads while a command is pending (PENDING_ACK) and when its 5 s heartbeat expires, and, on the published 0.8.0 crates, a 5.1 MB file download (#163).

LUCID Triton2 EVS TRT009S-E

An event-vision camera (Sony IMX636); run by a contributor, on Linux as we read from its interface name.

  • Reported: control through the library (#138), and streaming its EVT event data with viva-camctl stream --raw-out (#154).
  • Reported: “Works”, with its GenApi XML, which is now in the vendor corpus (#138). The report does not say which version or command it ran.
  • The EVT decoder’s tests use bytes captured from this camera (#139).

Basler a2A4096-44g5m

NixOS (Linux), the 0.9.0 crates; run by a user (#210).

  • Reported: discovery, connection, writing PixelFormat and AcquisitionMode, and one 4096 × 3000 Mono8 image, saved through the reporter’s own workaround for the stream port.
  • Reported: TriggerSelector failed to resolve on 0.9.0 and worked on main; TriggerMode still could not be read. The fix in 0.10.0 was checked against the camera’s XML only.

Hikrobot MV-CS050-10GC

Arch Linux; run by a user. Reported: discovery, and a connection — XML fetched and its node map built — after three fixes to how its XML is read (#35). Streaming was not reported.

FLIR Blackfly S BFS-PGE-31S4C-C

macOS, link-local addressing, the Python package; run by a user.

  • Reported: the camera connects on 0.3.0 after it had failed to open (#45).
  • Reported: discovery and opening with viva-camctl on 0.4.1 (#120). Writing ExposureTime was refused as unavailable; the fix in 0.5.0 rests on its XML and has not been run on the camera.

FLIR Blackfly (model not stated)

Run by a user. Reported: one of its PTP registers sometimes failed to read on 0.5.0, and the fix worked on the camera (#140).

The Imaging Source DMK 33GP2000e

Ubuntu 24.04; run by a user. Reported: discovery and the XML download on 0.4.1, then a failure to parse the XML (#122); the fix in 0.5.0 has not been reported run on the camera. On 0.6.0, a capture of a “dmk camera” showed every packet-size write sent as WRITEREG (#136).

Cameras whose model was not given

  • Viva Studio’s embedded mode on Ubuntu, against an unnamed camera: no more refused reads on 0.6.0 (#135).
  • Several identical cameras told apart by serial on 0.6.0 (#137).

USB3 Vision

MATRIX VISION mvBlueFOX3-2004G

macOS on Apple silicon over a USB 2 (High Speed) link behind a hub, and Windows; run by the maintainer.

  • Bootstrap registers, streaming, chunks, events, the host clock, the cable pulled mid-stream, viva-service-u3v rescanning while it holds the camera, and the Python package (#205).
  • String and <pLength> features, enumeration entries it does not offer, a saved configuration loaded back, and the USB3 Vision hardware suite (#206).
  • On Windows, after WinUSB was installed on the camera’s first interface, acquisition and Viva Studio (#208).

Crates overview

Every crate, and the layer it implements, is on How the library fits together. This part of the book says which one to reach for, and goes deeper into three of them.


When to use which crate

I just want to use my camera from Rust

Use viva-genicam.

Typical tasks:

  • Enumerate cameras on a NIC
  • Open a device, read/write features by name
  • Start a GVSP stream, iterate over frames, look at stats
  • Subscribe to events or send action commands

Start with the examples under crates/viva-genicam/examples/ and the Tutorials: they go from discovery to frames in memory, and show how to query and set features by name, and why a write can be refused.


I want a command-line tool for daily work

Use viva-camctl.

Typical tasks:

  • Discovery: list all cameras on a given interface
  • Register/feature inspection and configuration
  • Quick streaming tests and stress benchmarks
  • Enabling/disabling chunk data, configuring events

This is also a good reference for how to structure a “real” application on top of viva-genicam.


I want to use my camera from software that loads GenTL producers

Use viva_gentl.cti, built from the viva-gentl crate and attached to each release: Harvesters and other GenTL consumers load it as they load a vendor’s .cti (Use viva from other tools).


I need to touch GigE Vision packets / low-level transport

Use viva-gige (and viva-gencp as needed).

Example reasons:

  • You want to experiment with MTU, packet delay, or custom stats
  • You’re debugging interoperability with a weird device and need raw GVCP/GVSP
  • You want to build a non-GenApi tool that only tweaks vendor-specific registers

The viva-gige chapter goes into more detail on discovery, streaming, events, actions, and tuning.


I want to understand how a feature becomes register access

Read the viva-genapi chapter: addressing, selectors, SwissKnife formulas, access modes and caching. If a feature misbehaves, the rule of thumb is:

  • “XML can’t be parsed” → viva-genapi-xml
  • “Feature exists but behaves wrong” → viva-genapi
  • “Device returns odd data / status codes” → viva-gige or viva-gencp

Crate deep dives

viva-gencp — GenCP message primitives

viva-gencp is the smallest crate in the stack: one lib.rs with GenCP’s vocabulary — opcodes, command ids, flags and status codes — and the decoding of an acknowledgement, and nothing else. No sockets, no retries, no async, no device state.

GigE Vision and USB3 Vision both control a camera with GenCP-style register reads and writes, but they do not put the same bytes on the wire:

GigE Vision (GVCP)USB3 Vision (GenCP proper)
Read / write memoryopcodes 0x0084 / 0x0086command ids 0x0800 / 0x0802
Register commands0x0080 / 0x0082none: a register is a 4-byte memory access
“Answer me” flagbit 0 of the flag bytebit 14 of the 16-bit flags
Byte orderbig-endianlittle-endian

What they share is a core of status codes and the pending-acknowledge mechanism. This crate holds both tables: OpCode is GVCP’s, and command_id and ccd_flags are GenCP’s (GenCP 1.2, Tables 4 and 7). Until 0.8 the USB3 Vision transport sent GVCP’s opcodes, which no USB3 Vision camera understands.


What is actually in it

ItemPurpose
OpCodeGVCP’s ReadRegister, WriteRegister, ReadMem, WriteMem
command_idGenCP’s command ids: READMEM_CMD 0x0800 … EVENT_ACK 0x0C01
ccd_flagsGenCP’s REQUEST_ACK (bit 14) and COMMAND_RESEND (bit 15)
StatusCodeThe status codes GVCP and GenCP share; each transport wraps it in its own type
AckHeaderGVCP’s 8-byte acknowledgement header, its status as the wire value
GenCpAckHeader plus payload
decode_ackParses a GVCP acknowledgement; viva-gige uses it
GenCpErrorDecode failures
HEADER_SIZE, PENDING_ACK_COMMAND8 and 0x0805

OpCode::command_code() gives GVCP’s wire value (0x0080, 0x0082, 0x0084, 0x0086); StatusCode::from_raw / to_raw convert a shared status code.


Request → acknowledge

Every command carries a request id, and the acknowledgement echoes it. The transport is responsible for matching them and for discarding stale acks — a late reply to a timed-out request must not be accepted as the answer to the next one.

Callers do not usually touch this crate. GigeDevice and U3vDevice build the commands, and NodeMap sits above those, so an application reads ExposureTime and the register transactions happen underneath.


Status codes

The table matters more than it looks, because a status is often the only thing a user sees when something fails. StatusCode holds the codes both protocols define, with the same meaning: 0x0000, 0x8001–0x8007, 0x800E, 0x800F and 0x8FFF.

CodeMeaningRetry?
SuccessCompleted—
NotImplementedDevice does not implement this commandNo
InvalidParameterParameter invalid or out of rangeNo
InvalidAddressNo such address on the deviceNo
WriteProtectRegister is read-onlyNo — permanent
BadAlignmentAccess not aligned as the transport requiresNo
AccessDeniedRefused this write: a GenApi lock, or control privilege not heldOnly after fixing the cause
BusyDevice busyYes — the only one worth retrying
InvalidHeaderThe command’s header is invalidNo
WrongConfigThe device’s configuration does not allow the commandNo
GenericErrorDevice reported an error with nothing more specific—

Beyond that the two tables part, and at 0x800B they disagree: GVCP’s NO_MSG, GenCP’s MSG_TIMEOUT. So each transport decodes a status with a type of its own that wraps this one — viva_gige::GigeStatus (with GVCP’s packet-resend codes) and viva_u3v::U3vStatus (with USB3 Vision’s 0xA0xx codes) — and keeps Unknown(u16) for a code neither table names. Each prints the name and the hex value together, ACCESS_DENIED (0x8006).

The distinction between WriteProtect and AccessDenied is worth keeping in mind when debugging: the first means the register never accepts writes, the second means it would but not right now.

Pending acknowledge

GenCP lets a device say “still working” rather than answering immediately. It signals that with a command id — PENDING_ACK_COMMAND, 0x0805 — not with a status code, so a transport has to check the acknowledge’s command id before it interprets the status. Confusing the two turns an access-denied answer into a pending acknowledge, or the other way round.


Using it directly

You would only do this for diagnostics. decode_ack turns the bytes of a GVCP acknowledgement into a GenCpAck:

use viva_gige::GigeStatus;
use viva_gencp::{StatusCode, decode_ack};

let ack = decode_ack(&buf)?;        // -> GenCpAck

// `AckHeader::status` is the wire value: decode it with the transport's type,
// which names GVCP's own codes as well as the shared ones.
match GigeStatus::from_raw(ack.header.status) {
    GigeStatus::Common(StatusCode::Success) => { /* ack.payload */ }
    GigeStatus::Common(StatusCode::Busy) => { /* the one status worth retrying */ }
    other => return Err(format!("device reported {other}").into()),
}

ack.header.request_id is what the transport matches against the request it sent, and OpCode::ack_code() (command_code() + 1) is the opcode it should have come back with.

To send commands, use the layers that build them correctly: viva_gige::GigeDevice::{read_register, write_register, read_mem, write_mem}, or Camera::{get, set} above them.


Endianness and alignment

GenCP leaves the byte order to the transport, but requires it to match the device’s bootstrap registers (GenCP 1.2 §2.3): GVCP is big-endian, USB3 Vision little-endian. decode_ack is GVCP’s and handles the big-endian side; viva-u3v encodes its own little-endian packets. The structs hold host-order values. Register widths must match the address alignment, and devices do return BadAlignment when they do not — which is why that status has a name of its own rather than being folded into InvalidParameter.


See also

  • viva-gige — GenCP over GVCP, plus GVSP streaming
  • viva-genapi — the NodeMap that turns feature names into these messages

viva-gige — GigE Vision transport (GVCP/GVSP)

viva-gige implements the GigE Vision transport on Windows, Linux and macOS: discovery and control over GVCP, image data over GVSP, plus interface enumeration, event and action messages, and device-timestamp mapping.

It sits below viva-genapi — this crate moves bytes, the NodeMap decides which bytes. Applications normally reach it through viva-genicam.


What it exports

The modules are private; everything public is at the crate root, and viva_gige::consts holds the protocol’s vocabulary.

AreaItems
Discovery and control (GVCP)discover, discover_on_interface, discover_all, discover_ip, discover_with, force_ip, DeviceInfo, GigeDevice, GvcpCapability, GigeError, GigeStatus
Streaming (GVSP)Zero-copy packet parsing (parse_packet_ref, parse_header), StreamDest, StreamConfig, StreamParams, chunk extraction (parse_chunks), encode_packet_resend
InterfacesIface, IfaceSelector, mtu, best_packet_size
Actions and eventssend_action, ActionParams, AckSummary; EventSocket, EventPacket
TimeTimeSync — device ticks to host time
constsGVCP opcodes, flags, bootstrap register addresses and protocol limits

Selecting the local interface

On a multi-NIC host, bind to the NIC that reaches the camera. Iface offers four ways to get one, and they are easy to confuse:

use viva_gige::Iface;

Iface::from_system("eth0")?;                  // by interface name
Iface::from_ipv4("192.168.0.5".parse()?)?;    // by *host* address
Iface::from_remote_ipv4("192.168.0.10".parse()?)?; // by the *camera's* address
Iface::list()?;                               // everything the library can see

from_ipv4 takes an address on this host. from_remote_ipv4 takes the camera’s address and probes the routing table for the interface that reaches it — which is what you want when all you have is the camera’s IP. Passing a camera address to from_ipv4 is an easy mistake to miss, because it works against the loopback fake camera, where the two addresses coincide, and fails against real hardware.

Iface::list() is also a diagnostic. It reports interfaces as the library sees them, which is not always the set the OS shows, and an interface missing from this list is invisible to discovery no matter what ipconfig or ip addr says. IfaceSelector parses either spelling a user might type — an IPv4 address or an OS interface name — and resolve() turns it into an Iface.


Discovery (GVCP)

A broadcast command — to each interface’s subnet and to 255.255.255.255 — then replies collected for a timeout window. Each reply becomes a DeviceInfo with IP, MAC, manufacturer, model, version, serial, user-defined name, subnet and gateway; shares_subnet_with_host() says whether the camera can be reached from the interface that heard it. discover_ip asks one address directly, and discover_with takes DiscoveryOptions (Networking → Using –iface and discovery quirks).

    // `discover` broadcasts on the interfaces the library can see; naming one
    // pins it to that NIC, which is what you want on a multi-homed host.
    // `IfaceSelector` takes either spelling — `--iface 192.168.0.5` or
    // `--iface eth0` — so the flag means the same thing here as in
    // `viva-camctl` and `viva-service`.
    let devices = if let Some(selector) = iface.as_ref() {
        let iface = selector.resolve()?;
        viva_genicam::gige::discover_on_interface(timeout, iface.name()).await?
    } else {
        viva_genicam::gige::discover(timeout).await?
    };

    if devices.is_empty() {
        println!("No cameras found.");
        return Ok(());
    }

    println!("{:<16} {:<17} {:<20} Model", "IP", "MAC", "Manufacturer");
    for dev in devices {
        println!(
            "{:<16} {:<17} {:<20} {}",
            dev.ip,
            format_mac(&dev.mac),
            dev.manufacturer.as_deref().unwrap_or("-"),
            dev.model.as_deref().unwrap_or("-"),
        );
    }

discover, discover_on_interface and discover_all differ in which interfaces they scan; the table in Discovery → Discover from Rust lists them. An interface that cannot be bound or broadcast on is skipped with a warning rather than failing the whole call.

From the CLI:

cargo run -p viva-camctl -- list --iface 192.168.0.5

Control (GVCP)

GigeDevice owns one control channel:

use viva_gige::{GigeDevice, GVCP_PORT};

let mut device = GigeDevice::open(SocketAddr::new(camera_ip.into(), GVCP_PORT)).await?;
device.claim_control().await?;

let value = device.read_register(0x0a00).await?;
device.write_register(0x0a00, value | 1).await?;

let bytes = device.read_mem(0x0200, 512).await?;

read_register/write_register are 32-bit at a 32-bit address; read_mem/write_mem take a 64-bit address and a length, and chunk the transfer to fit the transport.

Control privilege and the heartbeat

claim_control() takes the Control Channel Privilege. A device revokes it if no GVCP command arrives within GevHeartbeatTimeout — 3 000 ms is typical — and GVSP image traffic does not count towards that timer. A camera can therefore be streaming at full rate while the control channel times out, and the next write fails with AccessDenied.

You do not have to manage this. GigeRegisterIo in viva-genicam owns a keepalive: it reads the device’s own GevHeartbeatTimeout and pings at a quarter of it, so holding a Camera is enough. heartbeat_timeout_ms() and ping_control_channel() are here for anyone driving GigeDevice directly. Dropping the transport stops the keepalive and waits for any request it has in flight, so keep the Tokio runtime alive until the Camera is gone.

A request whose acknowledgement is slow — a file operation the device answers with PENDING_ACK — holds the device for the whole wait, and the keepalive cannot get in. GigeDevice therefore sends its own CCP reads while it waits, with separate request IDs, and drains their replies (ADR-0023). GigeRegisterIo sets the probe period from the heartbeat window; a raw GigeDevice opts in with set_inflight_keepalive_period. Each wait lasts set_control_timeout (500 ms by default) unless the device asks for more.

IP configuration

force_ip assigns a temporary address to a camera identified by MAC — useful when a camera is on the wrong subnet and otherwise unreachable. write_persistent_ip and enable_persistent_ip make it survive a power cycle.

cargo run -p viva-camctl -- set-ip --mac DE:AD:BE:EF:CA:FE --ip 192.168.1.100 --force

Events and actions

  • Events are device-to-host notifications on the message channel (exposure end, and vendor-defined ones). set_message_destination points the device at a host socket; EventSocket acknowledges each message as it arrives, so a slow reader costs the camera no retransmission, and keeps up to EVENT_QUEUE_CAPACITY events for the application, dropping the oldest past that; stats() counts what it received and dropped. viva_genicam::EventStream presents the result.
  • Actions are host-to-many-devices: send_action broadcasts an action command so several cameras trigger together, optionally at a scheduled timestamp. AckSummary reports which devices acknowledged, and which answered with an error status instead (refusals).

Both are vendor-variable. If you schedule actions, keep the time bases consistent — see TimeSync below.


Streaming (GVSP)

This crate parses GVSP: parse_packet_ref reads one datagram without copying it — the standard 8-byte header or the 20-byte extended-ID one, and the payload type as all 16 bits, so 0x4001 (image with extended chunks) keeps its chunk bit. The receive engine in viva-genicam assembles the blocks, on a thread of its own per stream, with up to three blocks in flight and a timeout counted from each block’s last packet (ADR-0025).

Application code opens streams through viva-genicam, not this crate directly:

    // Connect to camera (fetches XML, builds nodemap).
    let mut camera = connect_gige(&device).await?;

    // Open the stream: destination, packet size, socket, and a receive engine
    // sized by the camera's PayloadSize.
    let mut options = StreamOptions::new().iface(iface.clone());
    if let Some(group) = args.multicast {
        options = options.multicast(group);
    }
    if let Some(port) = args.port {
        options = options.destination_port(port);
    }
    options = match args.packet_size {
        Some(size) => options.packet_size(size),
        None => options.auto_packet_size(),
    };
    let mut frame_stream = camera.open_stream(options)?;

    // Start acquisition.
    camera.acquisition_start()?;

Camera::open_stream takes a StreamOptions (iface, packet_size, auto_packet_size, multicast, destination_port, packet_delay, resend, rcvbuf_bytes). The lower-level StreamBuilder (in viva_genicam::stream) adds dest, target_mtu, probe and channel, for a stream built on a GigeDevice of your own; FrameStream::new then starts the receive engine on it.

Either way the socket is bound first, to a port the operating system picks unless destination_port names one, and that port is what the stream channel is pointed at; GevSCPD is written only for a packet_delay, in the camera’s timestamp ticks; a channel at or beyond GevNumberOfStreamChannels is refused before anything is written; and the stream accepts datagrams only from the camera’s address.

Packet size and MTU

GevSCPSPacketSize is the size of the transmitted IP packet, so it must fit the path MTU end to end. StreamBuilder chooses it in one of three modes:

  • Preserve (the default) — start from the camera’s current value and never raise it.
  • Auto — auto_packet_size() starts from a size derived from the host interface’s MTU (target_mtu can cap that MTU).
  • Explicit — packet_size(n) starts from n, treated as a ceiling.

In every mode a GVSP test-packet probe can then lower the size when the path drops it; probe(false) disables it. Streaming → Packet size and MTU explains the modes, the probe and camera-side clamping in full. Two details belong to this layer:

  • StreamBuilder::build reads the register back through GigeDevice::get_stream_packet_size and puts the effective size in StreamParams, so reassembly follows the camera rather than the request. A device that will not answer the read-back keeps the requested value and logs a warning.
  • On a large-MTU link the requested size must still be clamped to the IPv4 maximum. Linux loopback reports MTU 65536, which would produce a 65 508-byte datagram against the 65 507-byte limit — every send_to fails. An explicitly configured size above 65 535 is refused rather than truncated: GevSCPSPacketSize holds the size in 16 bits, so writing 70 000 would configure 4 464.

Resend

encode_packet_resend builds PACKETRESEND_CMD (0x0040): 12 bytes of stream channel, 16-bit block id and 24-bit first and last packet ids, or 20 bytes with extended ids (flag 0x10): channel, a reserved half-word, 32-bit packet ids and the 64-bit block id. It asks for no acknowledgement — the answer is the packets themselves. The receive engine sends it from the stream socket to the camera’s control port, when GigeDevice::gvcp_capability has bit 0x4 set; GigeStatus names the statuses a camera answers with when it cannot (PACKET_UNAVAILABLE and the rest of GVCP’s own range), and parse_header reads such an answer, which is a header and nothing else. When and how often the engine asks is in Streaming → Packet resend.

Chunk data

With ChunkModeActive set, a frame’s payload is a run of chunks: the image first, then one chunk per enabled value, each its data followed by an 8-byte tag — chunk ID and length, 32-bit big-endian. parse_chunks reads them from the end of the payload and reports a malformed layout with the offset where it went wrong. This crate does not decode the values: viva-genicam splits each frame into its image and its chunks, and the camera’s XML says what each chunk holds — see Chunks and events.

Statistics

A stream’s counters are viva_genicam::StreamStats: every block counted once as complete, incomplete, missed (a block-id gap) or dropped to backpressure, plus what became of the packets — see Streaming → What the statistics tell you.


Timestamp mapping

Devices report a tick counter, not wall-clock time. TimeSync maintains a linear mapping from device ticks to host SystemTime, calibrated by latching the device timestamp against a host reading. Without that calibration there is no origin to map from — so treat an uncalibrated host timestamp as absent rather than as data. Given the device’s tick frequency, the mapping’s slope is that frequency and only the offset is fitted; the device’s clock still drifts from the host’s (an Allied Vision Manta G-125B’s by 31 ms in 20 minutes), so calibrate again to stay within a few milliseconds over a long run.


Logging

RUST_LOG=info,viva_gige=debug,viva_genicam=debug cargo run -p viva-camctl -- stream --ip 192.168.0.10

viva-camctl maps -v to debug and -vv to trace if you would rather not set the variable. Useful targets: viva_gige::gvcp (binds, discovery, register ops), viva_gige::nic (interface enumeration and socket binding), viva_gige::gvsp (packet parsing), and viva_genicam::stream (stream setup, packet-size negotiation and frame reassembly).


Platform notes

Windows. Firewall profiles, jumbo frames and NIC power settings are covered in Networking → Windows.

Linux. With firewalld, GVCP replies arrive from source port 3956 and the GVSP port needs its own rule — see Letting the reply back in. net.core.rmem_max caps the socket receive buffer; the stream warns when it gets less than half of what it asked for.

Link-local. GigE Vision cameras fall back to 169.254.0.0/16 when no DHCP server answers. That works, but the host needs an address in the same range and the firewall usually needs telling — the same networking chapter covers it.


See also

viva-genapi — the NodeMap

viva-genapi turns the XmlModel produced by viva-genapi-xml into a NodeMap: the thing that knows what ExposureTime means, where it lives, what it depends on, and whether you are allowed to write it right now.

It has no transport of its own. Every accessor takes a &dyn RegisterIo, which is the whole coupling between this crate and the wire:

pub trait RegisterIo {
    fn read(&self, addr: u64, len: usize) -> Result<Vec<u8>, GenApiError>;
    fn write(&self, addr: u64, data: &[u8]) -> Result<(), GenApiError>;
}

Two implementations ship with the stack: GigeRegisterIo and U3vRegisterIo in viva-genicam, and NullIo here — which returns zeroes for reads and discards writes. NullIo is not a placeholder: it is how a GenApi document is browsed with no camera attached, which is what Viva Studio and the WASM build do. Values that depend only on the XML — SwissKnife expressions over constants, enum entry lists, ranges, the category tree — come out correct; anything backed by a real register comes out zero, so read structure from it, not data.


Node kinds

VariantGenICam name
Node::IntegerInteger, IntReg, MaskedIntReg
Node::FloatFloat, FloatReg
Node::EnumEnumeration
Node::BooleanBoolean
Node::CommandCommand
Node::CategoryCategory
Node::SwissKnifeSwissKnife, IntSwissKnife
Node::ConverterConverter
Node::IntConverterIntConverter
Node::StringStringReg, String (a <Value>, or delegating through <pValue>)
Node::RegisterRegister (a <Length>, or a <pLength> read each time)

Node::kind_name() returns the GenICam name, name() the feature name, and access_mode() the declared mode — which is not the same as the effective one, see below.


Reading and writing

The accessors are typed, and each takes the transport:

let width  = nodemap.get_integer("Width", &io)?;
let expo   = nodemap.get_float("ExposureTime", &io)?;
let fmt    = nodemap.get_enum("PixelFormat", &io)?;
let on     = nodemap.get_bool("ReverseX", &io)?;
let serial = nodemap.get_string("DeviceSerialNumber", &io)?;

nodemap.set_integer("Width", 640, &io)?;
nodemap.exec_command("AcquisitionStart", &io)?;

Camera in viva-genicam wraps these behind string-valued get/set, which is what most application code should use — see Registers & features.

Limits

A write is checked against the feature’s Min, Max and Inc before anything is sent — and before it is forwarded through <pValue>, so a limit declared on Width binds even though the register behind it declares none. Many cameras report their limits at run time instead (<pMin>, <pMax>, <pInc> pointing at other nodes); those are read when the write happens. A feature that declares no limit of its own takes the one of the node it delegates to. A value outside them is GenApiError::Range.

NodeMap::feature_state reports the same limits — the bounds in force now — and a <Converter> reports its raw node’s range mapped through its formula, in the order its <Slope> says (a Decreasing converter turns the raw maximum into its minimum).

An <Integer> with a <Value> and nothing behind it is a floating value: writing it changes what it reads, within its limits, and nothing reaches the camera. Selectors on several cameras (AVT’s TriggerSelector, Sony’s UserSetSelector) are built this way.

Commands

exec_command writes the value the command’s XML names — a constant <CommandValue>, or the current value of the node <pCommandValue> points at (Hikrobot’s UserSetSave writes the selected user set’s number) — after checking the command’s own pIsAvailable and pIsLocked. It returns when the write is acknowledged. is_done(name, &io) is GenICam’s IsDone: a command whose register is write-only is done at once; otherwise the register is read from the camera, past every cache, and the command is done when it no longer holds the command value. Camera::execute_and_wait polls it.

Addressing

A node’s address is not always a constant. It can be:

  • Fixed — an <Address> in the XML.
  • Computed — a sum of <Address>, <pAddress> (another node’s value) and <Integer> offsets, resolved at access time.
  • Delegated — <pValue> pointing at another node, which may itself delegate. The declaration you are reading is often not the one holding the data.

This matters because it is where the interesting bugs live. A parser can accept a document perfectly and the address model still be wrong, which is why the vendor corpus test does not stop at parsing: it builds a NodeMap from each real document and evaluates every node.

Selectors

When a feature is selector-dependent (Gain behind GainSelector), the selector’s current value takes part in resolving the address. Writing the selector invalidates the cached values of everything that depends on it, so the next read of Gain returns the newly selected channel rather than a stale value.

SwissKnife and Converter

SwissKnife nodes compute a value from other nodes with a formula — arithmetic, comparisons, bitwise operators, and a ternary. Converter and IntConverter run a formula in both directions, so they are writable: the FROM expression maps a user value back to the raw one. Evaluation is transparent — you call get_float and the inputs are read or computed first.


Access mode is evaluated, not declared

AccessMode in the XML is a starting point. The effective mode also depends on predicates the device answers at runtime:

  • pIsImplemented — the feature is absent on this model.
  • pIsAvailable — present but not currently applicable.
  • pIsLocked — writable in principle, locked right now.

effective_access_mode, is_implemented, is_available and available_enum_entries expose this. Writes go through it: a locked node is refused locally, with GenApiError::Locked { name, locked_by } naming the feature that holds the lock — because “access denied” leaves a caller nowhere to go, whereas “ExposureTime is locked by ExposureTime_Lck” says what to change first.


Introspection

Built for consumers that need to render a feature tree rather than read one value:

MethodReturns
node_names()Every feature name
node(name)The Node, or None
categories()Category name → its members
dependents(name)Which nodes are invalidated when this one changes
nodes_at_visibility(level)Beginner / Expert / Guru / Invisible filtering
version()The document’s schema version
skipped()Nodes that could not be built
ignored()Child elements of the nodes that were built, read past without interpretation

skipped() is the important one. A construct this crate cannot handle does not fail the whole document — it lands here, and the parser’s own losses (XmlModel::skipped) are carried along with it, so a consumer sees both. The camera still opens, minus the features that could not be built.

ignored() lists the smaller losses: an element of a node that loaded, which the parser read past. Most are documentation (<Extension>, an entry’s <ToolTip>); one that changes a value is worth reporting, as a skipped node is. viva-camctl report prints both.


Caching and invalidation

Values are cached and invalidated by dependency: writing a node clears the cached values of everything dependents() lists for it, including through pValue delegation and selectors — a selector names the features it selects in <pSelected>, and writing it clears them and the registers behind them. Cache correctness is a conformance question, not an optimisation — a stale Width after a selector change is a wrong answer, not a slow one.


Errors

GenApiError is specific on purpose; the variant usually says what to do next. It is #[non_exhaustive], so a match on it needs a wildcard arm.

VariantMeans
NodeNotFound(name)No such feature in this camera’s document
Type { name, kind, expected }Asked for the wrong type — get_float on an Integer
Access { name, refused }The node’s access mode forbids the read or write refused names
Locked { name, locked_by }pIsLocked is engaged; locked_by is the feature to change
InvalidText { name, expected, text }Text that is not a value of the feature’s type
Range { name, value, violation }Value below Min, above Max, or off Inc
Unavailable(name)pIsImplemented or pIsAvailable says the feature cannot be used now
NoValueSource { name }The node declares no register, <pValue> or <Value> to read
Io(source)The transport failed; source is the transport’s error (GigeError, U3vError)
RegisterEncoding { name, width, problem }The register’s bytes do not convert — the camera’s answer, not the XML
Declaration { name, problem }The XML declares the node in a way that cannot be evaluated
ExprParse / ExprEval / UnknownVariableA SwissKnife formula failed to parse, evaluate, or resolve a reference
EnumValueUnknown / EnumNoSuchEntryRaw value maps to no entry, or no entry has that name
BadIndirectAddresspAddress resolved to something impossible
BitfieldOutOfRange / ValueTooWideBitfield metadata exceeds the register, or the value exceeds the field
NotAttached { node, port }A chunk or event feature read with no frame or event attached to its port
PortNotWritable { node, port }A write to a chunk or event port, which holds data the camera sent
PortOutOfRangeA chunk or event register reaches past the data attached to its port

See also

API reference

The API reference is generated with cargo doc and published alongside this book. Note that rustdoc uses the crate name, with underscores — viva_gige, not viva-gige. What each crate is for is in How the library fits together.

The Python API is documented separately in Python bindings → API reference; it does not appear in rustdoc.

Glossary

TermDefinition
GenICamGeneric Interface for Cameras – an EMVA standard for camera control
GenApiGeneric API – the XML-based feature description layer of GenICam
GenCPGeneric Control Protocol – transport-agnostic register read/write
GVCPGigE Vision Control Protocol – UDP-based control channel
GVSPGigE Vision Streaming Protocol – UDP-based image data channel
SFNCStandard Feature Naming Convention – standard camera feature names
PFNCPixel Format Naming Convention – standard pixel format codes
CCPControl Channel Privilege – exclusive camera access token
GenTLGeneric Transport Layer – shared library interface for camera transport
NodeMapIn-memory representation of GenApi features parsed from XML
RegisterIoTrait abstracting register read/write over any transport

License

viva-genicam is licensed under the MIT License; the LICENSE file in the repository root has the full text.

MIT covers the project’s code, including commercial use; it does not grant third-party trademark rights or certify standards compliance. Dependencies keep their own licenses and notices. GenICam is a trademark of EMVA; GigE Vision and USB3 Vision are trademarks of A3 (Association for Advancing Automation). This project is independent and claims no A3 registration or certification. The licensing and provenance review records unresolved standards-related distribution questions separately from MIT.

The Python package is MIT too. Up to 0.8 its wheel linked libusb (LGPL-2.1-or-later) for USB3 Vision; since 0.9 USB goes through nusb, which is pure Rust, and no C USB library is linked anywhere.

Developing viva-genicam

This book is for people using viva-genicam. The documentation for working on it lives in the repository, next to the code:

  • CONTRIBUTING.md — building, the checks CI runs, the test suites, the vendor XML corpus, and pull requests.
  • docs/ — the design and its tenets, the standards and which crate implements which, decision records, the roadmap and the backlog.
  • studio/README.md — building Viva Studio from source.

The most useful contribution needs no code: a report from a camera we have not seen yet (Reporting a camera we can’t open).