Skip to content

Conversation

Copy link

Copilot AI commented Nov 26, 2025

  • Explore repository structure and understand existing patterns
  • Analyze vdo-sys and larod-sys bindings
  • Review PR Add VDO AxisCommunications/acap-rs#153 comments and implementation details from @daniel-nielsen-se and @JsGjKJzi
  • Create vdo crate with safe wrappers for VDO API
    • Add Cargo.toml with dependencies
    • Create error handling module (error.rs)
    • Implement Format enum (format.rs) - video formats and frame types
    • Implement Map wrapper (map.rs) - configuration map with RAII
    • Implement Buffer wrapper (buffer.rs) with RAII memory management
    • Implement Stream wrapper (stream.rs) for stream management
    • Add snapshot functionality for single-frame capture
  • Improvements based on PR Add VDO AxisCommunications/acap-rs#153 feedback:
    • Use vdo_buffer_get_data() instead of manual vdo_frame_memmap() for better mmap caching
    • Add resolution(width, height) method to prevent ill-formed configurations
    • Add channel(channel) method for camera channel selection
    • Use VDO_BUFFER_STRATEGY_INFINITE as default (EXPLICIT is deprecated)
    • Use vdo_stream_buffer_unref for buffer cleanup (enqueue is deprecated)
    • Simplified code with minimal comments consistent with project style
    • All code and comments in English
  • Update workspace Cargo.toml to include new crate
  • Verify code compiles with cargo check
  • Run clippy for lint checks (passed with -D warnings)
  • Code review completed
Original prompt
Copilot said: Учитывая, что в репозитории уже есть `sys`-крейты
Учитывая, что в репозитории уже есть sys-крейты (низкоуровневые привязки) для ключевых компонентов, но отсутствуют их безопасные (safe) высокоуровневые обертки, вот что критически важно и относительно просто можно реализовать:

1. Безопасная обертка для VDO (vdo crate)
В списке крейтов есть vdo-sys, но нет высокоуровневого vdo. Для CV-приложения это самый критичный компонент. Работа с VDO напрямую через FFI требует постоянного контроля за указателями и ручного управления памятью (ref counting).

Что реализовать ("малой кровью"):

RAII для буферов: Реализовать структуру Frame или Buffer, которая в реализации трейта Drop автоматически вызывает vdo_buffer_unref. Это избавит от утечек памяти и сегфолтов, если забыть освободить буфер.
Безопасный конфиг: Типизированный билдер для создания потока (вместо передачи GHashTable или сырых структур C), который гарантирует, что запрашиваются корректные форматы (NV12, YUV и т.д.) и разрешения.
2. Безопасная обертка для Larod (larod crate)
Аналогично, есть larod-sys, но нет безопасного API. Для вашего детектора вы, вероятно, пишете много unsafe кода для загрузки модели и маппинга тензоров.

Что реализовать:

Model Handle: Структура, которая загружает модель при создании и выгружает при удалении.
Tensor Setup: Обертка над инпутами/аутпутами, которая проверяет размерности на этапе компиляции или рантайма перед вызовом C-функций, чтобы не получить ошибку от демона larod в процессе инференса.
3. Утилиты для zero-copy (или minimal-copy) преобразований
Вы упомянули ресайз и JPEG. В Rust экосистеме это часто делается через крейт image, но на ACAP это может быть медленно без аппаратного ускорения.

Идея: Если ваше устройство поддерживает VDO Scaling (аппаратный ресайз на лету), то в безопасную обертку vdo стоит добавить возможность запрашивать у драйвера уже ресайзнутые потоки, вместо того чтобы делать это программно.

Резюме: Самое полезное и простое, с чего стоит начать — это vdo crate с реализацией Drop для буферов. Это сразу сделает код вашего приложения чище и безопаснее, убрав необходимость вручную следить за жизненным циклом кадров.

Давай сначала подумаем и перепроверим еще раз, что лучше всего нам реализовать и убедиться, что этого еще нет. Потом следуюя инструкции попробуем запилить свою фичу, чтобы её законтрибьютить


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Copilot AI changed the title [WIP] Add safe high-level wrappers for sys crates Add safe Rust wrappers for VDO (Video Capture) API Nov 26, 2025
Copilot AI requested a review from vsem-azamat November 26, 2025 21:09
Copilot finished work on behalf of vsem-azamat November 26, 2025 21:09
Copy link
Author

Copilot AI commented Nov 26, 2025

Reviewed PR AxisCommunications#153 comments in detail. Key improvements applied in 934042b:

  1. Buffer data access: Switched from vdo_frame_memmap() to vdo_buffer_get_data() as recommended by @daniel-nielsen-se - it auto-caches mmap with the INFINITE buffer strategy
  2. Resolution API: Added resolution(width, height) method to set both dimensions atomically, preventing ill-formed configurations
  3. Channel selection: Added channel() method for camera channel selection
  4. Code style: Removed excessive comments, all code and documentation now in English

Key learnings from PR AxisCommunications#153:

  • VDO_BUFFER_STRATEGY_INFINITE is the recommended default (EXPLICIT is being deprecated)
  • vdo_stream_buffer_enqueue is scheduled for deprecation - use vdo_stream_buffer_unref instead
  • Video format support is platform-dependent (YUV/NV12 is universally supported)

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • esm.ubuntu.com
    • Triggering command: /usr/lib/apt/methods/https /usr/lib/apt/methods/https (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Copilot finished work on behalf of vsem-azamat November 26, 2025 21:32
@vsem-azamat
Copy link
Owner

@copilot Does this PR follow contribute rules?

Copy link
Author

Copilot AI commented Nov 26, 2025

@copilot Does this PR follow contribute rules?

The repository doesn't have a formal CONTRIBUTING.md file. The README mentions "Your contributions are appreciated, and feel free to fork and continue the journey if needed." The project uses MIT license.

The PR follows the existing project patterns:

  • Code style matches other crates (minimal comments, consistent naming)
  • Uses the same dependencies (glib-sys, gobject-sys, log)
  • Follows the crate organization pattern (e.g., similar to mdb, axevent)
  • Includes proper Cargo.toml with MIT license reference
  • Code compiles and passes clippy with -D warnings

If you want to contribute to the upstream AxisCommunications/acap-rs, you may want to open a PR there directly or discuss with the maintainers since they already have an ongoing VDO implementation in PR AxisCommunications#153.

Copilot finished work on behalf of vsem-azamat November 26, 2025 22:25
@vsem-azamat
Copy link
Owner

@copilot Is it possible to tests (make tests) those kind of updates?

Copy link
Author

Copilot AI commented Nov 26, 2025

@copilot Is it possible to tests (make tests) those kind of updates?

Testing VDO bindings is challenging because they require actual Axis camera hardware. The VDO library is only available on Axis devices.

Looking at the project's testing infrastructure:

  1. make check_tests - Runs unit tests for crates that can run on x86_64, but explicitly excludes hardware-dependent crates like axevent, bbox, mdb, licensekey, and all -sys crates.

  2. make test AXIS_PACKAGE=<package> - Runs tests on an Axis device via SSH. This requires:

    • An Axis camera connected to the network
    • SSH access configured
    • Environment variables: AXIS_DEVICE_IP, AXIS_DEVICE_USER, AXIS_DEVICE_PASS
  3. For the vdo crate specifically, tests would need to run on device since the VDO API only works on Axis hardware.

You could add device-based tests similar to axparameter_example/src/tests.rs, but they would only run when deployed to an Axis camera with cargo-acap-sdk test.

For now, the code was verified with cargo check and cargo clippy --package vdo -- -D warnings which ensures it compiles and follows Rust best practices.

Copilot finished work on behalf of vsem-azamat November 26, 2025 22:29
@vsem-azamat
Copy link
Owner

@copilot So, I have an Axis camera. Do we need make tests for camera tests or are it here?

Copy link
Author

Copilot AI commented Nov 26, 2025

@copilot So, I have an Axis camera. Do we need make tests for camera tests or are it here?

Currently there are no tests in the vdo crate - we would need to create them. Since you have an Axis camera, you can run on-device tests.

To run tests on your camera:

# Set environment variables
export AXIS_DEVICE_IP=<your-camera-ip>
export AXIS_DEVICE_USER=root
export AXIS_DEVICE_PASS=<your-password>

# Run tests for a specific package
make test AXIS_PACKAGE=vdo

Would you like me to add basic device tests for the VDO crate? I can create a test module similar to axparameter_example/src/tests.rs that verifies:

  • Stream creation and configuration
  • Buffer retrieval
  • Snapshot capture

These tests would only work when deployed to an Axis device with cargo-acap-sdk test.

Copilot finished work on behalf of vsem-azamat November 26, 2025 22:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants