Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/cpp/.dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ __pycache__
**/*.pyc
**/*.so
build
demo
media
.local
*.log
Expand Down
11 changes: 0 additions & 11 deletions src/cpp/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,3 @@ EXPOSE 8000
HEALTHCHECK --interval=30s --timeout=3s --start-period=60s \
CMD python -c "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8000/health', timeout=2)" || exit 1
CMD ["uvicorn", "rkapi.app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1", "--limit-concurrency", "16"]

# The catalog selects weights and adapter; no Dockerfile edit per new model.
FROM build AS package
COPY rkapi /source/rkapi
COPY tools/models.py /source/tools/models.py
COPY models /source/models
ARG MODEL_ID
RUN python3 tools/models.py prepare --model "$MODEL_ID" --output /model-package

FROM runtime AS model
COPY --from=package /model-package/ /opt/model/
3 changes: 3 additions & 0 deletions src/cpp/Dockerfile.video
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ARG RUNTIME_IMAGE=rockchip-cv-runtime:local
FROM ${RUNTIME_IMAGE}
ADD --link video.tar /
77 changes: 38 additions & 39 deletions src/cpp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,12 +107,12 @@ if metadata["model"]["task"] == "detection":
## Models

YOLO26 ships in sizes `n`, `s`, and `m` for RK3576 and RK3588, with
INT8 and FP16 builds for all seven tasks. Each image serves one model.
INT8 and FP16 builds for all seven tasks. Each image serves one model and includes a short demo video.
The catalog contains 84 variants across 21 image names.

All images built from the same code revision share the same ARM64 operating
system, dependencies, C++ engine, HTTP API, and browser code. Only the final
filesystem layer contains model-specific files. The common entrypoint loads
system, dependencies, C++ engine, HTTP API, and browser code. The final filesystem layer contains model-specific files. A separate layer contains
the selected demo video and its attribution. The common entrypoint loads
the model manifest bundled at `/opt/model/package.json`.

Image names below use the prefix `ghcr.io/seeed-projects/recomputer-rk-cv/`.
Expand Down Expand Up @@ -208,9 +208,9 @@ the client to include transport and response delivery.
| Environment variable | Default | Purpose |
| --- | --- | --- |
| `RK_NMS` | Model setting | Enable or disable server NMS with `on` or `off` |
| `RK_SOURCE` | Unset | RTSP URL, mounted video file, or H.264 V4L2 device |
| `RK_LOOP_VIDEO` | `0` | Set to `1` for the browser-rendered local MP4 detection demo |
| `RK_WORKERS` | `0` | Automatic live worker count, or `1` for a single context |
| `RK_SOURCE` | Bundled demo video | Override with an RTSP URL, mounted video file, or H.264 V4L2 device. Set to an empty string to disable live preview. |
| `RK_LOOP_VIDEO` | `1` for the bundled demo, otherwise `0` | Set to `1` for looping, browser-rendered playback of a local MP4 |
| `RK_WORKERS` | `0` | Use all NPU cores with dedicated workers, two on RK3576 and three on RK3588. Set to `1` for one context. |
| `RK_MAX_UPLOAD_MB` | `128` | Maximum upload size in MB |
| `RK_CLASSES` | Packaged labels | Override labels with one class per line |
| `RK_PACKAGE` | `/opt/model/package.json` | Model package manifest path |
Expand All @@ -224,22 +224,24 @@ provide a usable frame.

## Video

For continuous prediction, add `-e RK_SOURCE=rtsp://192.168.1.10/live` to
the Docker run command. For a local video, pass
`-v "$PWD/media:/media:ro" -e RK_SOURCE=/media/input.mp4`.
An H.264 V4L2 camera can use `-e RK_SOURCE=/dev/video0`.

Continuous H.264/H.265 sources use MPP hardware decoding. Once a frame is
ready, open `http://<board-ip>:8000` to watch the annotated feed and
adjust confidence and NMS IoU. Threshold changes also update the container's
API defaults. Use a detection image such as `yolo26n:rk3576-int8` for the live preview.

For smooth playback of a mounted H.264 MP4 with an object detection model,
also pass `-e RK_LOOP_VIDEO=1`. The board loops the file and publishes
timestamped detection results. The browser plays the original MP4 and draws
boxes on a canvas, so playback can run at the video's frame rate even when
inference produces fewer results. The MP4 should use landscape or portrait
dimensions encoded directly, without a rotation tag.
Open `http://<board-ip>:8000` to play the bundled clip and view the model's
output. The first live-stream subscriber starts the decoder and NPU workers.
The last disconnect stops them. Reading the page or checking `/health` does
not start inference. Image or video-frame uploads still run on demand.
`/health` reports whether the pipeline is active, the subscriber count, and
the worker count and core masks when running.

| Tasks | Bundled clip |
| --- | --- |
| Detection, classification, instance segmentation, semantic segmentation, depth | Street traffic with moving vehicles and foreground/background separation |
| Pose | A full-body squat demonstration |
| Oriented boxes | Aerial footage of boats at different angles |

The browser plays the H.264 MP4 and draws model results on a canvas. For a
custom clip, pass `-v "$PWD/input.mp4:/media/input.mp4:ro"` with
`-e RK_SOURCE=/media/input.mp4 -e RK_LOOP_VIDEO=1`. Use a browser-compatible
MP4 without a rotation tag. RTSP and H.264 V4L2 sources still use the MJPEG
preview with the source selected through `RK_SOURCE`.

With a YOLO26 split scores-and-boxes model, the browser applies confidence
filtering and per-class NMS locally. The board sends every valid decoded
Expand All @@ -255,37 +257,27 @@ six `float32` values per proposal in the order `x1, y1, x2, y2, confidence,
class_id`. Box coordinates are in source-image pixels. Use the label list
from `GET /api/metadata`.

Call `curl -fsS -X POST "$API/api/predict"` for the latest result or use
`/api/video_feed` directly for the 10 FPS MJPEG preview. Local files follow
media timestamps from container startup and retain the last result at EOF
when looping is disabled.
Call `curl -fsS -X POST "$API/api/predict"` for the latest result while a
preview stream is subscribed. `/api/video_feed` serves the 10 FPS MJPEG
preview and holds a live-source subscription.

## Build and publish

### Build locally

Run these commands in `src/cpp` on an ARM64 Docker host. Inference requires
the matching Rockchip board.
the matching Rockchip board. Leave out `--model` to build the full catalog.

```sh
python3 tools/models.py list

docker build --platform linux/arm64 --target model \
--build-arg MODEL_ID=yolo26n-rk3588-int8 \
-t yolo26n:rk3588-int8 .
```

Set `IMAGE=yolo26n:rk3588-int8` in the quick-start command to run the local
image. To build several model images from exactly the same local runtime, use
the same packaging script as CI. Leave out `--model` to build the full catalog.

```sh
docker build --platform linux/arm64 --target runtime -t rockchip-cv-runtime:local .
python3 -m pip install PyYAML
python3 tools/build_images.py --runtime rockchip-cv-runtime:local \
--repository rockchip-cv-local --model yolo26n-rk3588-int8
```

Set `IMAGE=rockchip-cv-local/yolo26n:rk3588-int8` in the quick-start command.

### GitHub Actions

The [C++ Rockchip model images workflow](../../.github/workflows/cpp-model-images.yml)
Expand All @@ -297,7 +289,10 @@ or the full catalog when left empty. Manual runs on `main` publish images.
The workflow saves one shared runtime per source commit under
`runtime:<commit-sha>`. Each model uses it as the base, verifies the model
package and native module imports, and checks that its layer list matches the
runtime plus exactly one model layer. Each model is published with a
runtime plus one independent video layer and one model layer. Models that
use the same clip must have the same video layer ID. The workflow builds each video layer once from a deterministic archive.
BuildKit's `ADD --link` keeps the video layer independent so code-only
rebuilds can reuse it. Each model is published with a
`<chip>-<precision>` tag and a `<chip>-<precision>-<commit-sha>` tag.

Each manifest points to an immutable Hugging Face revision. The build
Expand All @@ -314,3 +309,7 @@ The model packages use weights and conversion metadata from
[HanzoHuang/YOLO26-RKNN2](https://huggingface.co/HanzoHuang/YOLO26-RKNN2).
Model manifests and metadata record provenance, license information, and the
SHA-256 checksums used during packaging.

The bundled clips were excerpted or resized and converted to H.264 without
audio. Attributions and license links are included in each image at
`/opt/demo/ATTRIBUTION.txt` and in the [demo directory](demo/).
1 change: 1 addition & 0 deletions src/cpp/demo/.gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.mp4 -filter -diff -merge -text
Binary file added src/cpp/demo/exercise.mp4
Binary file not shown.
5 changes: 5 additions & 0 deletions src/cpp/demo/exercise.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Squat exercise demonstration by FitnessScape.
Source: https://commons.wikimedia.org/wiki/File:Squat_-_exercise_demonstration_video.webm
Original: https://www.youtube.com/watch?v=0I6q9NqK9tM
License: https://creativecommons.org/licenses/by/3.0/
Changes: resized and converted to H.264 MP4 without audio.
Binary file added src/cpp/demo/harbor.mp4
Binary file not shown.
4 changes: 4 additions & 0 deletions src/cpp/demo/harbor.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Aerial view of sea and boats.
Source: https://commons.wikimedia.org/wiki/File:Aerial_view_of_sea_and_boats.webm
License: https://creativecommons.org/publicdomain/zero/1.0/
Changes: excerpted, resized and converted to H.264 MP4 without audio.
Binary file added src/cpp/demo/street.mp4
Binary file not shown.
5 changes: 5 additions & 0 deletions src/cpp/demo/street.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
Street traffic in San Francisco by Editor.
Source: https://commons.wikimedia.org/wiki/File:Street_traffic.webm
Original: https://www.youtube.com/watch?v=_7sCYyxw4Ic
License: https://creativecommons.org/licenses/by/3.0/
Changes: excerpted, resized and converted to H.264 MP4 without audio.
4 changes: 3 additions & 1 deletion src/cpp/native/bindings.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,7 @@ class Predictor
}

std::string description() const { return detector_.description.dump(); }
bool supports_candidates() const { return detector_.supports_candidates(); }
};

class Live
Expand Down Expand Up @@ -324,7 +325,8 @@ PYBIND11_MODULE(_native, m)
py::class_<Predictor>(m, "Predictor")
.def(py::init<const std::string &, const std::string &>(), py::arg("model"), py::arg("options") = "{}")
.def("predict", &Predictor::image, py::call_guard<py::gil_scoped_release>())
.def("description", &Predictor::description);
.def("description", &Predictor::description)
.def("supports_candidates", &Predictor::supports_candidates);
py::class_<Live>(m, "Live")
.def(py::init<const std::string &, const std::string &, int, const std::string &, bool>(),
py::arg("source"), py::arg("model"), py::arg("workers") = 0, py::arg("options") = "{}",
Expand Down
38 changes: 28 additions & 10 deletions src/cpp/rkapi/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from pathlib import Path
from time import perf_counter

from anyio import CancelScope
import cv2
import numpy as np
from fastapi import FastAPI, File, Form, HTTPException, Request, UploadFile
Expand Down Expand Up @@ -214,16 +215,33 @@ def decode():
await upload.close()


class LiveResponse(StreamingResponse):
"""Hold one live-source lease until the HTTP stream disconnects."""

def __init__(self, runtime, content, **kwargs):
super().__init__(content, **kwargs)
self.runtime = runtime

async def __call__(self, scope, receive, send):
acquired = False
try:
with CancelScope(shield=True):
await run_in_threadpool(self.runtime.acquire_live)
acquired = True
await super().__call__(scope, receive, send)
except SourceUnavailable as error:
raise HTTPException(503, str(error)) from error
except UnsupportedOperation as error:
raise HTTPException(501, str(error)) from error
finally:
if acquired:
with CancelScope(shield=True):
await run_in_threadpool(self.runtime.release_live)


@app.get("/api/video_feed")
async def video_feed():
rt = app.state.runtime
try:
await run_in_threadpool(rt.preview)
except SourceUnavailable as error:
raise HTTPException(503, str(error)) from error
except UnsupportedOperation as error:
raise HTTPException(501, str(error)) from error

async def frames():
previous = None
while True:
Expand All @@ -243,7 +261,7 @@ async def frames():
break
await asyncio.sleep(.05)

return StreamingResponse(frames(), media_type="multipart/x-mixed-replace; boundary=frame",
return LiveResponse(rt, frames(), media_type="multipart/x-mixed-replace; boundary=frame",
headers={"Cache-Control": "no-store"})


Expand Down Expand Up @@ -276,7 +294,7 @@ async def events():
yield "data: " + json.dumps(result, separators=(",", ":")) + "\n\n"
await asyncio.sleep(.015)

return StreamingResponse(events(), media_type="text/event-stream",
return LiveResponse(rt, events(), media_type="text/event-stream",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})


Expand All @@ -299,7 +317,7 @@ async def frames():
previous, data = packet
yield data

return StreamingResponse(frames(), media_type="application/octet-stream",
return LiveResponse(rt, frames(), media_type="application/octet-stream",
headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})


Expand Down
6 changes: 6 additions & 0 deletions src/cpp/rkapi/backends/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,12 @@ def image(self, image, conf, iou, source):
in the returned dictionary, not in the shared HTTP layer.
"""

def acquire_live(self):
raise UnsupportedOperation("this backend does not support live inference")

def release_live(self):
pass

def source_status(self):
return None

Expand Down
Loading