# Debugging Guide Source: https://imsdkdocs.qualcomm.com/advanced/debugging Developer guide for debugging, profiling, and tracing QIM SDK GStreamer pipelines. This guide covers practical debugging techniques for QIM SDK AI pipelines — from enabling verbose logs to measuring per-stage latency, tracing buffers, and diagnosing camera or performance issues. *** ## 1. Enable Debug Logs QIM SDK uses the standard GStreamer debug system. Pass `--gst-debug=` to `gst-launch-1.0`, or set the `GST_DEBUG` environment variable for Python/C++ apps. ### Debug Levels | Level | Name | Description | | - | - | - | | 0 | none | No debug information is output. | | 1 | ERROR | Logs all fatal errors. These are errors that do not allow the core or elements to perform the requested action. The application can still recover if programmed to handle the conditions that triggered the error. | | 2 | WARNING | Logs all warnings. Typically these are non-fatal, but user-visible problems are expected to happen. | | 3 | FIXME | Logs all "fixme" messages. Those typically that a codepath that is known to be incomplete has been triggered. It may work in most cases, but may cause problems in specific instances. | | 4 | INFO | Logs all informational messages. These are typically used for events in the system that only happen once, or are important and rare enough to be logged at this level. | | 5 | DEBUG | Logs all debug messages. These are general debug messages for events that happen only a limited number of times during an object's lifetime; these include setup, teardown, change of parameters, etc. | | 6 | LOG | Logs all log messages. These are messages for events that happen repeatedly during an object's lifetime; these include streaming and steady-state conditions. This is used for log messages that happen on every buffer in an element for example. | | 7 | TRACE | Logs all trace messages. Those are message that happen very very often. This is for example is each time the reference count of a GstMiniObject, such as a GstBuffer or GstEvent, is modified. | | 9 | MEMDUMP | Logs all memory dump messages. This is the heaviest logging and may include dumping the content of blocks of memory. | ### Global Level ```bash theme={null} gst-launch-1.0 --gst-debug=3 \ filesrc location=... ! ... ``` ### Per-Element Level Override the global level for a specific plugin — useful for isolating one stage without drowning in output from everything else: ```bash theme={null} # Global = 2 (warnings), but inference plugin = 6 (verbose) gst-launch-1.0 --gst-debug=2,qtimltflite:6 \ filesrc location=... ! ... ``` ### Common Starting Points | Flag | When to use | | - | - | | `--gst-debug=2` | Production runs — quiet, errors/warnings only | | `--gst-debug=2,qtimltflite:5` | Prints all ERROR and WARNING messages globally, plus ERROR, WARNING, INFO, and DEBUG messages specifically from the qtimltflite plugin | | `--gst-debug=2,qtimlvtransform:4,qtivcomposer:7` | Prints all ERROR and WARNING messages globally, ERROR, WARNING, and INFO messages from qtimlvtransform, and ERROR, WARNING, INFO, DEBUG, LOG, and TRACE messages from qtivcomposer | ### Python / C++ Apps ```bash theme={null} GST_DEBUG=3 python3 my_pipeline.py ``` ```bash theme={null} GST_DEBUG=5 ./my_pipeline_app ``` ### Redirect to File ```bash theme={null} GST_DEBUG=5 GST_DEBUG_FILE=/data/gst.log GST_DEBUG_COLOR_MODE=off gst-launch-1.0 ... ``` *** ## 2. Measure Pipeline KPIs (Latency per Stage) Use the built-in GStreamer **latency tracer** to get per-element mean/min/max processing time for every stage — no custom instrumentation required. ### Enable Tracing ```bash theme={null} GST_TRACERS="latency(flags=pipeline+element)" \ GST_DEBUG="GST_TRACER:7" \ gst-launch-1.0 -e \ qtimlvconverter name=stage_01_preproc \ qtimltflite name=stage_01_inference \ model=$HOME/Downloads/qimsdk_samples/models/$MODEL_NAME \ delegate=external external-delegate-path=libQnnTFLiteDelegate.so \ external-delegate-options="QNNExternalDelegate,backend_type=htp,log_level=(string)1;" \ qtimlpostprocess name=stage_01_postproc module=yolov8 \ labels=$HOME/Downloads/qimsdk_samples/labels/$LABELS_NAME \ settings="{\"confidence\": 51.0}" \ filesrc location=$HOME/Downloads/qimsdk_samples/media/$SRC_VIDEO_NAME ! qtdemux ! h264parse ! \ v4l2h264dec capture-io-mode=4 output-io-mode=4 ! video/x-raw,format=NV12 ! queue ! \ tee name=t ! qtimetamux name=obj_mux ! qtivoverlay ! \ fpsdisplaysink name=display sync=false text-overlay=false \ video-sink="waylandsink" \ t. ! queue ! stage_01_preproc. stage_01_preproc. ! queue ! \ stage_01_inference. stage_01_inference. ! queue ! \ stage_01_postproc. stage_01_postproc. ! text/x-raw ! queue ! obj_mux. \ 2> /tmp/trace.log ``` ### Parse Results ```bash theme={null} gst-stats-1.0 /tmp/trace.log ``` ### Reading the Output ``` Element Latency Statistics: stage_01_preproc.src: mean=2.19ms min=1.24ms max=12.2ms ← preprocessing stage_01_inference.src: mean=5.71ms min=4.95ms max=6.78ms ← inference (NPU) stage_01_postproc.src: mean=0.24ms min=0.12ms max=0.44ms ← postprocessing obj_mux.src: mean=0.76ms min=0.14ms max=2.03ms ← metadata sync ``` > [!NOTE] > > At 30 fps (33 ms budget per frame), the typical AI pipeline uses \~37% of the frame budget, leaving headroom for additional stages. ### Measure FPS Live (On-Screen) Add `fpsdisplaysink` in place of `waylandsink` to see FPS on the display in real time: ```bash theme={null} ... ! qtivoverlay ! fpsdisplaysink sync=false video-sink="waylandsink sync=false" ``` *** ## 3. Measure Inference Performance ### GST\_TRACER (inferences/sec) From the [tracer output](/advanced/debugging#enable-tracing), calculate inferences/sec: ``` inferences/sec = 1 / mean_inference_latency ``` Example: `mean = 5.71 ms` → `1 / 0.00571 ≈ 175 inferences/sec` ### pidstat (CPU/Memory alongside inference) ```bash theme={null} # Run in a second terminal while the pipeline is running pidstat -u -r -p $(pgrep gst-launch-1.0) 1 ``` This reports per-second CPU (`%usr`, `%sys`) and memory (`RSS`, `VSZ`) for the pipeline process. *** ## 4. Debug Performance Issues ### Frame Drops Frame drops manifest as: * Stuttering on the display * `queue` elements reporting overflows in debug logs (`--gst-debug=4`) * Tracer showing high `max` latency on inference (`stage_01_inference`) **Check for queue overflows:** ```bash theme={null} gst-launch-1.0 --gst-debug=4,queue:5 ... ``` Look for lines like: ``` WARN queue gstqueue.c:... overrun ... ``` **Fix:** Add `max-size-time=0 max-size-bytes=0 max-size-buffers=3` to queues around inference: ```bash theme={null} ... ! queue max-size-buffers=3 ! stage_01_preproc. ... ``` ### Slow Throughput If end-to-end latency is higher than expected: 1. Run the [latency tracer](/advanced/debugging#2-measure-pipeline-kpis-latency-per-stage) to find which stage is the bottleneck. 2. Check if the inference delegate is correct — GPU delegate is much slower than HTP (NPU): ```bash theme={null} # Slow — GPU qtimltflite delegate=gpu ... # Fast — NPU via HTP qtimltflite delegate=external \ external-delegate-path=libQnnTFLiteDelegate.so \ external-delegate-options="QNNExternalDelegate,backend_type=htp;" ``` 3. Check model quantization — W8A8 (quantized) is significantly faster on the NPU than float32. ### Memory Copies Unnecessary buffer copies add latency. To detect them, enable memory tracing: ```bash theme={null} GST_DEBUG=4,GST_BUFFER:5 gst-launch-1.0 ... 2>&1 | grep -i "copy\|memcpy\|alloc" ``` Use `capture-io-mode=4 output-io-mode=4` on decoder/encoder elements to enable zero-copy DMA buffer passing: ```bash theme={null} v4l2h264dec capture-io-mode=4 output-io-mode=4 ``` *** ## 5. Trace Buffers Buffer tracing lets you follow a specific buffer through the pipeline to diagnose where it is dropped, delayed, or corrupted. ### Enable Buffer Tracing ```bash theme={null} GST_DEBUG=GST_SCHEDULING:5 gst-launch-1.0 ... 2>&1 | head -200 ``` Each line shows a buffer's `PTS` (presentation timestamp), `DTS`, `size`, and which pad it passed through. ### Check for PTS Discontinuities If frames are out of order or the pipeline stalls, look for timestamp jumps: ```bash theme={null} GST_DEBUG=GST_SCHEDULING:5 gst-launch-1.0 ... 2>&1 | grep -i "pts\|discont\|gap" ``` ### Use the Dot Graph (Pipeline Visualization) Dump the pipeline as a `.dot` file to visually inspect element connections: ```bash theme={null} GST_DEBUG_DUMP_DOT_DIR=/tmp gst-launch-1.0 -e ... & # After pipeline is running: dot -Tpng /tmp/*.dot -o pipeline.png ``` *** ## 6. Debug Camera Issues ### Common Errors **QMMF Recorder StartCamera Failed:** ``` ERROR qticamsrc qmmf_source_context.cc: QMMF Recorder StartCamera Failed! WARN qticamsrc qmmf_source.c: error: Failed to Open Camera! ``` **Fix:** Kill and restart the camera server: ```bash theme={null} sudo killall cam-server ``` Then re-run the pipeline. The camera server restarts automatically on the next `gst-launch-1.0` invocation. ### Enable Camera Server Debug Logs ```bash theme={null} GST_DEBUG=2,qticamsrc:6 gst-launch-1.0 \ qticamsrc name=camsrc ! video/x-raw,format=NV12,width=1920,height=1080,framerate=30/1 ! \ waylandsink fullscreen=true sync=false ``` ### Camera Not Detected ```bash theme={null} # List available V4L2 devices v4l2-ctl --list-devices # Check camera capabilities v4l2-ctl -d /dev/video0 --all ``` ### ISP Camera (Config #2 / qticamsrc) To switch from libcamera (Config #1) to `qticamsrc` (Config #2), write `"camx"` to the EFI variable: ```bash theme={null} echo -n "camx" > /var/data efivar -n 882f8c2b-9646-435f-8de5-f208ff80c1bd-VendorDtbOverlays -w -f /var/data sync && reboot ``` ### Verify Camera Stream is Running ```bash theme={null} # Quick sanity check — should show frames on display gst-launch-1.0 \ qticamsrc name=camsrc ! video/x-raw,format=NV12,width=1920,height=1080,framerate=30/1 ! \ waylandsink fullscreen=true sync=false ``` *** ## 7. Quick Diagnostic Checklist Run this sequence when a pipeline doesn't work: ```bash theme={null} # Step 1 — Check GStreamer can see the plugins gst-inspect-1.0 qtimltflite gst-inspect-1.0 qtimlvconverter gst-inspect-1.0 qticamsrc # Step 2 — Run with level 3 logs gst-launch-1.0 --gst-debug=3 [your pipeline] 2>&1 | grep -E "ERROR|WARN|FIXME" # Step 3 — Check camera server sudo killall cam-server # reset if camera errors appear # Step 4 — Add latency tracing GST_TRACERS="latency(flags=pipeline+element)" GST_DEBUG="GST_TRACER:7" \ gst-launch-1.0 [your pipeline] 2> /tmp/trace.log gst-stats-1.0 /tmp/trace.log ``` *** ## 8. Report an Issue When filing a bug or asking for help, include: 1. **Platform** — Device model (e.g. RB3 Gen 2), OS (Ubuntu / Qualcomm Linux), QIM SDK version 2. **Full pipeline command** — the exact `gst-launch-1.0` or Python script 3. **Debug log** — captured with `--gst-debug=5 2> debug.log` 4. **Tracer output** — from `gst-stats-1.0` if a performance issue 5. **Error message** — the exact error line from the log 6. **Expected vs actual behaviour** File the issue through the [Qualcomm Support](https://www.qualcomm.com/support) portal. ```bash theme={null} # Collect everything in one command GST_DEBUG=5 GST_TRACERS="latency(flags=pipeline+element)" GST_DEBUG_FILE=/tmp/debug.log \ gst-launch-1.0 [your pipeline] gst-stats-1.0 /tmp/debug.log >> /tmp/debug.log # Attach /tmp/debug.log to your issue ``` # QIM SDK Docker Source: https://imsdkdocs.qualcomm.com/advanced/docker Build, configure, and run the QIM SDK Docker container on Qualcomm platforms. ## Overview Containers are lightweight, isolated environments that package everything needed to run an application — code, dependencies, and system libraries — so it behaves consistently across platforms. Advantages of containerization include: * **Consistency:** Containers provide a consistent environment across multiple platforms and operating systems. Developers can create images that transform into containers when deployed, ensuring uniformity regardless of the underlying infrastructure. * **Automation:** Containerization supports automated tasks. Developers can schedule actions without manual intervention, reducing repetitive work. * **Stability:** Containers are based on Linux, with the Linux kernel present in every container. This stability extends to systems and devices, including when containers run on macOS or Windows. * **Space efficiency:** Unlike traditional virtual machines, which consume significant server space and memory, containers include only application code and dependencies. They can run entirely in the cloud and minimize resource requirements. ![Container architecture overview](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/containers.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=38d6618346b5163a2fdb597b140d3bf7) ## QIM SDK in Docker QIM SDK in a Docker container means the full Qualcomm multimedia and AI software stack is delivered as containerized environments instead of being manually installed directly on a host or target system. In practice, a build container compiles and assembles all required components, including cross-compiled artifacts for Qualcomm ARM64 targets. The build then produces a deploy container that contains only the runtime pieces needed on the device. **Key benefits of this approach:** * **Reproducible builds:** Use the same toolchain, package versions, and scripts across developers and CI. Reduces "works on my machine" failures. * **Build and runtime separation:** Use a heavy build image to compile artifacts and a lean deploy image that contains only runtime essentials. * **Efficient cross-compilation:** Build on the host and target ARM64 Qualcomm devices reliably, faster than compiling directly on the target. * **Secure runtime posture:** Run as a non-root user by default, avoid broad privileged-container dependencies, and use CDI-based explicit hardware passthrough for GPU, camera, and media devices. * **Operational consistency:** Use versioned images that are testable, promotable, and rollback-friendly, with a predictable deployment flow using environment and CDI configuration on the target. ### Features * **Debian (Trixie) base:** Built on Debian Trixie for a streamlined and lightweight foundation. * **No platform dependencies:** Entirely self-sufficient — no eSDK or host platform content required to build or deploy. * **Self-contained dependencies:** All necessary dependencies are installed directly inside the container, minimizing host-container compatibility issues and simplifying deployment on edge devices. * **GStreamer 1.26:** Includes GStreamer 1.26 with the latest `gst-qti-oss-patches` for optimized performance on Qualcomm platforms. * **Broad target support:** Validated across QLI 2.x, Ubuntu Server, and Ubuntu Desktop. Supports IQ615, QCS6490, IQ8275, IQ9075, IQ-X5121 and IQ-X7181 platforms. ### Versions | Version | Status | | - | - | | 2.1.0 | Latest | This version of image targets only the following platforms. Support for more platforms & OS will be added in upcoming releases. **QLI 2.x** * QCS6490 * IQ-9075 * IQ-8275 * IQ-615 * IQ-X7181 * IQ-X5121 **Ubuntu 24.04** * QCS6490 * IQ-9075 * IQ-8275 **Ubuntu 26.04** * IQ-X7181 * IQ-X5121 ## Architecture The following diagram explains the build and deployment flow of the QIM SDK Docker image. ![QIM SDK Docker build and deployment flow](https://mintcdn.com/qimsdk/2ihxAnX-B-ATkWe4/advanced/images/imsdkcontainer.png?fit=max\&auto=format\&n=2ihxAnX-B-ATkWe4\&q=85\&s=aacb89bf5f1b7b2c75a25226e4a0adb8) * The host machine runs a development container that compiles all QIM SDK sources and dependencies into Debian artifacts. * The generated artifacts are transferred to a Debian-based deploy container with CDI-managed hardware access that runs on the Qualcomm device. ## Quick Start Guide > [!NOTE] > > Before getting started, ensure the device is set up by following the [Installation](/installation) guide. > [!WARNING] > > Camera is not supported in the container. ### Download configuration files Before setting up the device, download the CDI and environment files for the target chipset and OS. The CDI JSON file provides platform-specific device mountings; the environment file sets the required variables inside the container. Select your chipset to download the corresponding files: **QCS6490** | Target OS | CDI file | Environment file | | - | - | - | | QLI 2.x | [qcs6490\_qli\_2x\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs6490_qli_2x_qimsdk.json?inline=false) | [qcs6490\_qli\_2x\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs6490_qli_2x_qimsdk.env?inline=false) | | Ubuntu 24.04 Server | [qcs6490\_ubuntu\_server\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs6490_ubuntu_server_qimsdk.json?inline=false) | [qcs6490\_ubuntu\_server\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs6490_ubuntu_server_qimsdk.env?inline=false) | | Ubuntu 24.04 Desktop | [qcs6490\_ubuntu\_desktop\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs6490_ubuntu_desktop_qimsdk.json?inline=false) | [qcs6490\_ubuntu\_desktop\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs6490_ubuntu_desktop_qimsdk.env?inline=false) | **IQ-8275** | Target OS | CDI file | Environment file | | - | - | - | | QLI 2.x | [qcs8275\_qli\_2x\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs8275_qli_2x_qimsdk.json?inline=false) | [qcs8275\_qli\_2x\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs8275_qli_2x_qimsdk.env?inline=false) | | Ubuntu 24.04 Server | [qcs8275\_ubuntu\_server\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs8275_ubuntu_server_qimsdk.json?inline=false) | [qcs8275\_ubuntu\_server\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs8275_ubuntu_server_qimsdk.env?inline=false) | | Ubuntu 24.04 Desktop | [qcs8275\_ubuntu\_desktop\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs8275_ubuntu_desktop_qimsdk.json?inline=false) | [qcs8275\_ubuntu\_desktop\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs8275_ubuntu_desktop_qimsdk.env?inline=false) | **IQ-9075** | Target OS | CDI file | Environment file | | - | - | - | | QLI 2.x | [qcs9075\_qli\_2x\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs9075_qli_2x_qimsdk.json?inline=false) | [qcs9075\_qli\_2x\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs9075_qli_2x_qimsdk.env?inline=false) | | Ubuntu 24.04 Server | [qcs9075\_ubuntu\_server\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs9075_ubuntu_server_qimsdk.json?inline=false) | [qcs9075\_ubuntu\_server\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs9075_ubuntu_server_qimsdk.env?inline=false) | | Ubuntu 24.04 Desktop | [qcs9075\_ubuntu\_desktop\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs9075_ubuntu_desktop_qimsdk.json?inline=false) | [qcs9075\_ubuntu\_desktop\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs9075_ubuntu_desktop_qimsdk.env?inline=false) | **IQ-615** | Target OS | CDI file | Environment file | | - | - | - | | QLI 2.x | [qcs615\_qli\_2x\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/qcs615_qli_2x_qimsdk.json?inline=false) | [qcs615\_qli\_2x\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/qcs615_qli_2x_qimsdk.env?inline=false) | **IQ-X7181** | Target OS | CDI file | Environment file | | - | - | - | | QLI 2.x | [iqx7181\_qli\_2x\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/iqx7181_qli_2x_qimsdk.json?inline=false) | [iqx7181\_qli\_2x\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/iqx7181_qli_2x_qimsdk.env?inline=false) | | Ubuntu 26.04 Server | [iqx7181\_ubuntu\_server\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/iqx7181_ubuntu_server_qimsdk.json?inline=false) | [iqx7181\_ubuntu\_server\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/iqx7181_ubuntu_server_qimsdk.env?inline=false) | | Ubuntu 26.04 Desktop | [iqx7181\_ubuntu\_desktop\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/iqx7181_ubuntu_desktop_qimsdk.json?inline=false) | [iqx7181\_ubuntu\_desktop\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/iqx7181_ubuntu_desktop_qimsdk.env?inline=false) | **IQ-X5121** | Target OS | CDI file | Environment file | | - | - | - | | QLI 2.x | [iqx5121\_qli\_2x\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/iqx5121_qli_2x_qimsdk.json?inline=false) | [iqx5121\_qli\_2x\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/iqx5121_qli_2x_qimsdk.env?inline=false) | | Ubuntu 26.04 Server | [iqx5121\_ubuntu\_server\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/iqx5121_ubuntu_server_qimsdk.json?inline=false) | [iqx5121\_ubuntu\_server\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/iqx5121_ubuntu_server_qimsdk.env?inline=false) | | Ubuntu 26.04 Desktop | [iqx5121\_ubuntu\_desktop\_qimsdk.json](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/cdi/iqx5121_ubuntu_desktop_qimsdk.json?inline=false) | [iqx5121\_ubuntu\_desktop\_qimsdk.env](https://git.codelinaro.org/clo/le/sdk-tools/-/raw/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/env/iqx5121_ubuntu_desktop_qimsdk.env?inline=false) | ### Set up and run on the device **QLI 2.x** **1. SSH into the device** ```bash theme={null} ssh @ ``` **2. Create required directories** ```bash theme={null} mkdir -p /etc/cdi mkdir -p /etc/docker/env mkdir -p $HOME/Downloads/qimsdk_samples mkdir -p $HOME/Downloads/qimsdk_samples/media mkdir -p $HOME/Downloads/qimsdk_samples/models mkdir -p $HOME/Downloads/qimsdk_samples/labels ``` **3. Copy the downloaded configuration files to the device** ```bash theme={null} scp .json @:/etc/cdi/qimsdk.json scp .env @:/etc/docker/env/qimsdk.env ``` > **Additional step to configure nodes for video driver and USB camera** > > On platforms such as iq615, iqx7181, and iqx8121, the Qualcomm downstream video drivers (`video32` and `video33`) are unavailable. Therefore, the upstream video driver is used. Since the upstream driver may be assigned to any device node between `/dev/video0` and `/dev/video28`, an additional configuration step is required to determine and configure the appropriate video nodes. > > Run the following command to list the video devices: > > ```bash theme={null} > v4l2-ctl --list-devices > ``` > > Example: > > ```bash theme={null} > Qualcomm Venus video decoder (plat:aa00000.video-codec:dec): > /dev/video2 > > Qualcomm Venus video encoder (plat:aa00000.video-codec:enc): > /dev/video3 > > USB Camera (usb-0000:00:14.0-3): > /dev/video4 > /dev/video5 > ``` > > Identify the relevant video device nodes and add them to the cdi.json file that has been deployed to the target system before creating the container. > > ``` > "deviceNodes": [ > ... > { > "path": "/dev/video2", > "uid": 0, > "gid": 44 > }, > { > "path": "/dev/video3", > "uid": 0, > "gid": 44 > }, > { > "path": "/dev/video4", > "uid": 0, > "gid": 44 > }, > { > "path": "/dev/video5", > "uid": 0, > "gid": 44 > }, > ... > ] > ``` **4. Pull the container image** **Native Image** The QIM SDK native image is intended for native pipeline execution and includes all required runtime dependencies for QIM SDK applications. Python dependencies are intentionally excluded to keep the image lightweight and user can use the QIM SDK Python image for python support. ```bash theme={null} docker pull artifacts.codelinaro.org/iot-solutions-microservices/qimsdk:latest ``` Tag the image locally: ```bash theme={null} docker tag artifacts.codelinaro.org/iot-solutions-microservices/qimsdk:latest qimsdk:latest ``` **Python Image** The QIM SDK Python image includes all functionality available in the base image, along with Python support. ```bash theme={null} docker pull artifacts.codelinaro.org/iot-solutions-microservices/qimsdk-python:latest ``` Tag the image locally: ```bash theme={null} docker tag artifacts.codelinaro.org/iot-solutions-microservices/qimsdk-python:latest qimsdk-python:latest ``` **5. Run the container** > **Additional step for SE-Linux enabled builds** > > An additional step is required for SE-Linux enabled builds to provide access to cdi, env & media artifacts. > > ```bash theme={null} > # After pushing the CDI file to the device run the following command > restorecon -Rv /etc/cdi > > # To get access to wayland and pipewire sockets. > setsebool -P dockerd_connect_user_services on > > # To get access to the user Downloads directory > setsebool -P dockerd_mounton_xdg_downloads on > ``` > > ```bash theme={null} > # Run the following commands whenever new artifacts are uploaded to the paths below. > chcon -t xdg_downloads_t /var/roothome/Downloads > chcon -R -t xdg_downloads_t /var/roothome/Downloads/qimsdk_samples > ``` ```bash theme={null} # The following docker run command mounts $HOME/Downloads/qimsdk_samples # into the container for media assets and application artifacts. # Using this path is recommended to avoid potential SELinux permission issues. docker run -it -d \ --net host \ --env-file /etc/docker/env/qimsdk.env \ -v $HOME/Downloads/qimsdk_samples:/home/qimsdk/Downloads/qimsdk_samples \ --device qualcomm.com/device=qimsdk \ -h \ --name \ ``` After the container is running, execute a new terminal process in it: ```bash theme={null} docker exec -ti bash ``` **Ubuntu** **1. SSH into the device** ```bash theme={null} ssh @ ``` **2. Install docker** ```bash theme={null} sudo apt update sudo apt install docker.io sudo usermod -aG docker $USER # Log out and log back in for the group membership changes to take effect. ``` **3. Create required directories** ```bash theme={null} sudo mkdir -p /etc/cdi sudo mkdir -p /etc/docker/env mkdir -p $HOME/Downloads/qimsdk_samples mkdir -p $HOME/Downloads/qimsdk_samples/media mkdir -p $HOME/Downloads/qimsdk_samples/models mkdir -p $HOME/Downloads/qimsdk_samples/labels ``` **4. Copy the downloaded configuration files to the device** ```bash theme={null} scp .json @:/etc/cdi/qimsdk.json scp .env @:/etc/docker/env/qimsdk.env ``` > **Additional step to configure nodes for video driver and USB camera** > > On platforms such as iq615, iqx7181, and iqx8121, the Qualcomm downstream video drivers (`video32` and `video33`) are unavailable. Therefore, the upstream video driver is used. Since the upstream driver may be assigned to any device node between `/dev/video0` and `/dev/video28`, an additional configuration step is required to determine and configure the appropriate video nodes. > > Run the following command to list the video devices: > > ```bash theme={null} > sudo apt install v4l-utils > v4l2-ctl --list-devices > ``` > > Example: > > ```bash theme={null} > Qualcomm Venus video decoder (plat:aa00000.video-codec:dec): > /dev/video2 > > Qualcomm Venus video encoder (plat:aa00000.video-codec:enc): > /dev/video3 > > USB Camera (usb-0000:00:14.0-3): > /dev/video4 > /dev/video5 > ``` > > Identify the relevant video device nodes and add them to the cdi.json file that has been deployed to the target system before creating the container. > > ``` > "deviceNodes": [ > ... > { > "path": "/dev/video2", > "uid": 0, > "gid": 44 > }, > { > "path": "/dev/video3", > "uid": 0, > "gid": 44 > }, > { > "path": "/dev/video4", > "uid": 0, > "gid": 44 > }, > { > "path": "/dev/video5", > "uid": 0, > "gid": 44 > }, > ... > ] > ``` **5. Pull the container image** **Native Image** The QIM SDK native image is intended for native pipeline execution and includes all required runtime dependencies for QIM SDK applications. Python dependencies are intentionally excluded to keep the image lightweight and user can use the QIM SDK Python image for python support. ```bash theme={null} docker pull artifacts.codelinaro.org/iot-solutions-microservices/qimsdk:latest ``` Tag the image locally: ```bash theme={null} docker tag artifacts.codelinaro.org/iot-solutions-microservices/qimsdk:latest qimsdk:latest ``` **Python Image** The QIM SDK Python image includes all functionality available in the base image, along with Python support. ```bash theme={null} docker pull artifacts.codelinaro.org/iot-solutions-microservices/qimsdk-python:latest ``` Tag the image locally: ```bash theme={null} docker tag artifacts.codelinaro.org/iot-solutions-microservices/qimsdk-python:latest qimsdk-python:latest ``` **6. Run the container** ```bash theme={null} # The following docker run command mounts $HOME/Downloads/qimsdk_samples # into the container for media assets and application artifacts. # Using this path is recommended to avoid potential SELinux permission issues. # Automatically detect and pass the active Wayland display to the container, # as the WAYLAND_DISPLAY name may vary across systems and display configurations sudo docker run -it -d \ --net host \ -e WAYLAND_DISPLAY=$(basename \ $(ls ${XDG_RUNTIME_DIR}/wayland-* 2>/dev/null | head -n1) \ 2>/dev/null) \ --env-file /etc/docker/env/qimsdk.env \ -v $HOME/Downloads/qimsdk_samples:/home/qimsdk/Downloads/qimsdk_samples \ --device qualcomm.com/device=qimsdk \ -h \ --name \ ``` After the container is running, execute a new terminal process in it: ```bash theme={null} sudo docker exec -ti bash ``` Once inside the container, refer to the **Examples** section to run * [AI pipelines](/sample-pipelines/aipipelines) * [multimedia pipelines](/sample-pipelines/multimediapipelines) * [GStreamer C/C++ AI applications](/sample-application/ai-sample-applications) * [GStreamer C/C++ multimedia applications](/sample-application/multimedia-sample-applications) * [C++ App Builder](/app-builder/cpp-quickstart) * [Python App Builder](/app-builder/python-quickstart) ### Running GStreamer Sample applications inside container By default, sample application configuration files are installed under `/etc/configs`. However, this location cannot be mounted into the container due to SELinux restrictions. On the platform, copy the configuration files to `$HOME/Downloads/qimsdk_samples/configs`. Because `$HOME/Downloads/qimsdk_samples` is mounted into the container by the previous docker run command, the `configs` directory will be accessible from within the container. ```bash theme={null} mkdir -p $HOME/Downloads/qimsdk_samples/configs cp /etc/configs/* $HOME/Downloads/qimsdk_samples/configs chmod -R 0777 $HOME/Downloads/qimsdk_samples/configs ``` Inside the container, use `--config-file` argument to pass config file to sample app: ```bash theme={null} gst-ai-classification \ --config-file=$HOME/Downloads/qimsdk_samples/configs/config_classification.json ``` ## Build an QIM SDK container > [!NOTE] > > All steps in this section are performed on a Ubuntu 22.04 or 24.04 machine which can be x86 or ARM64. ### Prerequisites > **Ubuntu packages** > > Install prerequisite packages on the host (one time only). > > **ARM64** > > ```bash theme={null} > sudo apt install -y jq tofrodos > sudo wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq > sudo chmod +x /usr/bin/yq > ``` > > **x86** > > ```bash theme={null} > sudo apt install -y jq tofrodos qemu-user-static qemu-system-arm > sudo wget https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq > sudo chmod +x /usr/bin/yq > wget http://archive.ubuntu.com/ubuntu/pool/universe/q/qemu/qemu-user-static_6.2+dfsg-2ubuntu6_amd64.deb > sudo dpkg -i qemu-user-static_6.2+dfsg-2ubuntu6_amd64.deb > rm qemu-user-static_6.2+dfsg-2ubuntu6_amd64.deb > ``` > > > [!WARNING] > > > > Do **not** install `yq` via snap. If it was installed via snap, remove it and reinstall using the commands above: > > > > ```bash theme={null} > > sudo snap remove yq > > sudo systemctl stop snapd > > ``` > **File watcher limits** > > Increase the maximum user watches and instances on the host to prevent this error during development: > > ```text theme={null} > System limit for number of file watchers reached > ``` > > Add these lines to `/etc/sysctl.conf`: > > ```text theme={null} > fs.inotify.max_user_instances=8192 > fs.inotify.max_user_watches=542288 > ``` > > Save the file and reboot the host system. > **Swap image** > > To build Docker image files, the host system requires at least 64 GB of RAM and a swap image of at least half the available RAM plus a small reserve. > > For example, with 64 GB of RAM, the recommended swap size is at least 32 GB. With an 8 GB reserve, total RAM + swap + reserved memory is 104 GB. > > Check whether swap is enabled: > > ```bash theme={null} > sudo swapon --show > ``` > > If swap is missing or too small, create a new swap file: > > ```bash theme={null} > MEM_AVAIL=$(grep MemAvailable /proc/meminfo | awk '{printf "%.0f\n", $2/1024/1024}') > let MEM_SWAP="$MEM_AVAIL / 2 + 8" > sudo swapoff /swap.img > sudo fallocate -l "${MEM_SWAP}G" /swap.img > sudo chmod 600 /swap.img > sudo mkswap /swap.img > sudo swapon /swap.img > ``` > > Edit `/etc/default/grub` and set: > > ```text theme={null} > GRUB_CMDLINE_LINUX_DEFAULT="text cgroup_enable=memory swapaccount=1" > ``` > > Update GRUB: > > ```bash theme={null} > sudo update-grub > ``` > > Edit `/etc/fstab` and add this line at the end of the file: > > ```text theme={null} > /swap.img none swap sw 0 0 > ``` > > Save and close all opened system files, then reboot the host system. > > After rebooting, verify the swap image matches the expected size: > > ```bash theme={null} > sudo swapon --show > ``` > **Configure Docker** > > Docker must be configured on the host system once before building images. > > > **Remove old versions** > > > > Remove old Docker Desktop versions if present: > > > > ```bash theme={null} > > sudo apt remove docker-desktop > > rm -r ~/.docker/desktop > > sudo rm /usr/local/bin/com.docker.cli > > sudo apt purge docker-desktop > > ``` > > > **Set up the Docker repository** > > > > Install repository dependencies: > > > > ```bash theme={null} > > sudo apt-get update > > sudo apt-get install \ > > ca-certificates \ > > curl \ > > gnupg \ > > lsb-release > > ``` > > > > Create the Docker keyring directory: > > > > ```bash theme={null} > > sudo mkdir -p /etc/apt/keyrings > > ``` > > > > Add the Docker GPG key: > > > > ```bash theme={null} > > curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg > > ``` > > > > Add the Docker repository: > > > > ```bash theme={null} > > echo \ > > "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \ > > $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null > > ``` > > > **Install Docker Engine** > > > > ```bash theme={null} > > sudo apt-get update > > sudo apt-get install docker-ce docker-ce-cli > > ``` > > > **Add user to the Docker group** > > > > Add the user to the Docker group to run Docker commands without `sudo`: > > > > ```bash theme={null} > > sudo groupadd docker > > sudo usermod -aG docker $USER > > newgrp docker > > ``` > > > > > [!NOTE] > > > > > > Until the host is rebooted, run `newgrp docker` in every newly opened terminal. > > > **Add a registry mirror (optional)** > > > > > [!WARNING] > > > > > > Tabs, unexpected spaces, and other invisible whitespace characters can break JSON configuration files and may cause a `docker.service failed to start` error. > > > > Add the registry mirror configuration to `/etc/docker/daemon.json`: > > > > ```json theme={null} > > { > > "registry-mirrors": [""] > > } > > ``` > > > > Restart Docker: > > > > ```bash theme={null} > > sudo fromdos -f /etc/docker/daemon.json > > sudo systemctl daemon-reload > > sudo systemctl restart docker > > ``` > > > **Configure proxy (optional)** > > > > If network downloads require a proxy, add the proxy configuration to the Docker daemon. > > > > > [!WARNING] > > > > > > Tabs, unexpected spaces, and other invisible whitespace characters can break JSON configuration files and may cause a `docker.service failed to start` error. > > > > Add the proxy configuration to `/etc/docker/daemon.json`: > > > > ```json theme={null} > > { > > "proxies": { > > "http-proxy": "", > > "https-proxy": "", > > "no-proxy": "" > > } > > } > > ``` > > > > Restart Docker: > > > > ```bash theme={null} > > sudo fromdos -f /etc/docker/daemon.json > > sudo systemctl daemon-reload > > sudo systemctl restart docker > > ``` > > > > Set proxy environment variables before invoking Docker build commands: > > > > ```bash theme={null} > > export http_proxy= > > export https_proxy= > > export no_proxy= > > ``` > > > > This ensures that both the Docker daemon and build processes use the same proxy settings as the host system. > > > > > [!NOTE] > > > > > > Until the host is rebooted, run `newgrp docker` in every newly opened terminal. > > > **Test the Docker setup (optional)** > > > > Run the Docker hello-world container: > > > > ```bash theme={null} > > docker run hello-world > > ``` > > > **Move the Docker directory (optional)** > > > > If the build image script fails with a `No space left on device` error, move the Docker directory to `/local/mnt`. > > > > > [!WARNING] > > > > > > All containers must be restarted after moving the Docker directory because the Docker service is stopped during this procedure. > > > > Stop Docker: > > > > ```bash theme={null} > > service docker stop > > ``` > > > > Verify that no Docker process is running: > > > > ```bash theme={null} > > ps faux > > ``` > > > > Check the Docker directory structure: > > > > ```bash theme={null} > > sudo ls /var/lib/docker/ > > ``` > > > > Back up the current Docker directory: > > > > ```bash theme={null} > > tar -zcC /var/lib docker > /mnt/pd0/var_lib_docker-backup-$(date +%s).tar.gz > > ``` > > > > Move the Docker directory to the new partition: > > > > ```bash theme={null} > > mv /var/lib/docker /local/mnt/docker > > ``` > > > > Create a symlink to the Docker directory in the new partition: > > > > ```bash theme={null} > > ln -s /local/mnt/docker /var/lib/docker > > ``` > > > > Verify that the Docker directory structure is unchanged: > > > > ```bash theme={null} > > sudo ls /var/lib/docker/ > > ``` > > > > Start Docker: > > > > ```bash theme={null} > > service docker start > > ``` > > > > List container names: > > > > ```bash theme={null} > > docker ps -a > > ``` > > > > Start a listed container: > > > > ```bash theme={null} > > docker start > > ``` > **Configure system memory** > > Check that there are no active cgroup CPU and memory utilization restrictions on the host. The Docker service cgroup memory configuration entries should have `max` set as the value. > > ```bash theme={null} > sudo systemctl list-unit-files | grep -Ei docker > sudo systemctl status docker.service > cat /sys/fs/cgroup/system.slice/docker.service/ > cat /sys/fs/cgroup/system.slice/docker.service/memory.max > cat /sys/fs/cgroup/system.slice/docker.service/memory.swap.max > ``` > > > **Tune VM settings (optional)** > > > > If the host system has 64 GB RAM or less, tune system VM page swap and dentry and inode cache reclaim behavior. > > > > **`vm.swappiness`** > > > > Higher values cause more aggressive application memory page swapping; lower values favor keeping pages in memory longer. The default is usually `60` on recent Ubuntu and Debian versions, which may not fit the Docker build environment on systems with low available RAM. A value of `10` is recommended. > > > > **`vm.vfs_cache_pressure`** > > > > Intermittent high VFS pressure can result from creating many small temporary files during package installation, causing the OS to prematurely swap memory pages associated with cached dentries and inodes. The default is usually `100`. Setting it to `400` relaxes cache management by freeing cached pages earlier, reducing the chance of running out of memory during high multi-threaded load. > > > > **`vm.min_free_kbytes`** > > > > In heavy multi-stage Docker builds with many buildx threads, the host OS can exhaust available RAM quickly. The mandatory VM free memory watermark is controlled by `vm.min_free_kbytes`. Too low risks deadlocks under load; too high causes premature OOM kills. A value of `262144` KB better balances free memory under excessive load. > > > > Edit `/etc/sysctl.conf` and add: > > > > ```text theme={null} > > vm.swappiness=10 > > vm.vfs_cache_pressure=400 > > vm.min_free_kbytes=262144 > > ``` ### Build steps **1. Fetch the source code** Run the following commands on the host machine: ```bash theme={null} git clone https://git.codelinaro.org/clo/le/sdk-tools.git -b imsdk-tools.lnx.1.0 cd sdk-tools/qimsdk-debian/ git checkout fcc71f5f12791f77d8174cb5772eab6c785578d7 ``` **2. Build the image** **Native image** Build `qimsdk_deploy_arm64`, which contains the minimal set of runtime binaries needed to execute GStreamer use cases: ```bash theme={null} docker build \ --build-arg QIMSDK_ARG_QNP_VERSION= \ --build-arg QIMSDK_ARG_CAMERA_SERVICE_TAG= \ --build-arg QIMSDK_ARG_GST_PLUGINS_TAG=\ --build-arg QIMSDK_ARG_SOLUTIONS_MICROSERVICES_TAG= \ --build-arg QIMSDK_ARG_GST_QTI_OSS_PATCHES_TAG= \ --build-arg QIMSDK_ARG_MAX_JOBS= \ --target qimsdk_deploy_arm64 \ -t qimsdk \ . ``` For example: Docker build command for `2.1.0` release ```bash theme={null} docker build \ --build-arg QIMSDK_ARG_QNP_VERSION=2.50.0.260828 \ --build-arg QIMSDK_ARG_CAMERA_SERVICE_TAG=1.0.6 \ --build-arg QIMSDK_ARG_GST_PLUGINS_TAG=2.0.2 \ --build-arg QIMSDK_ARG_SOLUTIONS_MICROSERVICES_TAG=805fd443c8ffe75eed16ca54a68602535c80e232 \ --build-arg QIMSDK_ARG_GST_QTI_OSS_PATCHES_TAG=a4db6968a1f467875407a2008d7c13974a826fe4 \ --build-arg QIMSDK_ARG_MAX_JOBS=8 \ --target qimsdk_deploy_arm64 \ -t qimsdk \ . ``` **Python image** Build `qimsdk_deploy_py_arm64`, which contains the minimal set of runtime binaries needed to execute GStreamer use cases along with python support: ```bash theme={null} docker build \ --build-arg QIMSDK_ARG_QNP_VERSION= \ --build-arg QIMSDK_ARG_CAMERA_SERVICE_TAG= \ --build-arg QIMSDK_ARG_GST_PLUGINS_TAG=\ --build-arg QIMSDK_ARG_SOLUTIONS_MICROSERVICES_TAG= \ --build-arg QIMSDK_ARG_GST_QTI_OSS_PATCHES_TAG= \ --build-arg QIMSDK_ARG_MAX_JOBS= \ --target qimsdk_deploy_py_arm64 \ -t qimsdk-python \ . ``` For example: Docker build command for `2.1.0` release ```bash theme={null} docker build \ --build-arg QIMSDK_ARG_QNP_VERSION=2.50.0.260828 \ --build-arg QIMSDK_ARG_CAMERA_SERVICE_TAG=1.0.6 \ --build-arg QIMSDK_ARG_GST_PLUGINS_TAG=2.0.2 \ --build-arg QIMSDK_ARG_SOLUTIONS_MICROSERVICES_TAG=805fd443c8ffe75eed16ca54a68602535c80e232 \ --build-arg QIMSDK_ARG_GST_QTI_OSS_PATCHES_TAG=a4db6968a1f467875407a2008d7c13974a826fe4 \ --build-arg QIMSDK_ARG_MAX_JOBS=8 \ --target qimsdk_deploy_py_arm64 \ -t qimsdk-python \ . ``` #### Build Arguments | Argument | Description | Default | | - | - | - | | *QIMSDK\_ARG\_QNP\_VERSION* | Specifies the QAIRT SDK version to use. If not provided, the QNN and SNPE plugins are not built. | Not set | | *QIMSDK\_ARG\_CAMERA\_SERVICE\_TAG* | Commit ID or tag from the [Qualcomm Camera Service repository](https://github.com/qualcomm/camera-service) | `main` | | *QIMSDK\_ARG\_GST\_PLUGINS\_TAG* | Commit ID or tag from the [qimsdk](https://github.com/qualcomm/qimsdk) repository. | `main` | | *QIMSDK\_ARG\_SOLUTIONS\_MICROSERVICES\_TAG* | Commit ID or tag from the [solutions-microservices](https://git.codelinaro.org/clo/le/solutions-microservices/) repository. | `iot-solutions.lnx.1.0` | | *QIMSDK\_ARG\_GST\_QTI\_OSS\_PATCHES\_TAG* | Commit ID or tag from the [gst-qti-oss-patches](https://github.com/qualcomm/gst-qti-oss-patches) repository. | `1.26.2` | | *QIMSDK\_ARG\_MAX\_JOBS* | Limits the maximum number of parallel build jobs used during image creation. Valid values range from `1` to the number of available CPU cores (`nproc`). | All available CPU cores | > [!NOTE] > > See [qimsdk-debian/README.md](https://git.codelinaro.org/clo/le/sdk-tools/-/blob/fcc71f5f12791f77d8174cb5772eab6c785578d7/qimsdk-debian/README.md) for more information about the Docker image composition and workflow. **3. Save the image** Save the built image as a tar file: ```bash theme={null} docker save -o .tar ``` **4. Copy and load the image on the device** Copy the tar file to the device: ```bash theme={null} scp .tar @:~/Downloads/ ``` Load the image on the device: ```bash theme={null} docker load -i ~/Downloads/.tar ``` > [!NOTE] > > The home directory (\~) varies by platform: > > * QLI 2.x: /root > * Ubuntu Noble: /home/ubuntu > * Ubuntu Resolute: /home/qcom **5. Run the container on the device** With the image copied to the device, follow the [Set up and run on the device](#set-up-and-run-on-the-device) steps to configure CDI and start the container. ## Install additional packages inside the container Use this procedure to install packages into an already running `qimsdk-debian` deploy container. The container must have been started with the `--net host` option. The following steps use vi as an example. **1. Execute a shell in the container as root** ```bash theme={null} docker exec -ti qimsdk sh ``` **2. Install apt packages** In the root shell, install the required packages: ```bash theme={null} apt-get update DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC \ apt-get install -y --no-install-recommends vi apt -y upgrade apt-get autoremove -y apt-get clean ``` After installing the vi package in the previous step, it can be launched from any new shell session started as the `qimsdk` user: ```bash theme={null} docker exec -ti qimsdk bash ``` ## Debugging The following techniques apply to the QIM SDK container running on the Qualcomm device. ### Check container logs **1. Stream live logs** ```bash theme={null} docker logs -f ``` **2. Print the last 100 lines and follow** ```bash theme={null} docker logs --tail 100 -f ``` ### Inspect container state **1. List all containers and their status** ```bash theme={null} docker ps -a ``` **2. Inspect container metadata** Inspect detailed container metadata including environment variables, mounts, and network settings: ```bash theme={null} docker inspect ``` ### Restart a container **1. Stop the container** ```bash theme={null} docker stop ``` **2. Start the container** ```bash theme={null} docker start ``` # Technology Overview Source: https://imsdkdocs.qualcomm.com/advanced/technologyoverview Qualcomm Technology components used in by QIM SDK # GStreamer plugin architecture The QIM SDK encapsulates hardware complexity within a modular plugin architecture, freeing developers from the burden of managing low-level platform libraries or hardware-specific details that vary across Qualcomm chipsets and generations. Each [QIM SDK plugin](../plugin-reference/introduction) in the SDK maps directly to a dedicated hardware accelerator — including video encode/decode, camera ISP, GPU, display, and AI/ML accelerators — giving developers a clean, unified API surface to build sophisticated multimedia and AI pipelines with minimal integration overhead ![Figure:Qualcomm QIM SDK GStreamer plugin architecture](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/pluginarch.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=9cd247e0283f0a2f6f329e45ace74e8a) ## Camera Architecture The QIM SDK abstracts the underlying camera driver and hardware through a client-server architecture, shielding developers from the complexities of low-level camera management and enabling rapid construction of single-stream, multi-stream, multi-client, and multi-camera applications. At its core, the [`qticamsrc`](../plugin-reference/qticamsrc) GStreamer element operates as a client to the le-camera service — a system-level service responsible for managing the camera HAL, stream lifecycle, buffer allocation, and capture control. This separation of responsibilities allows [`qticamsrc`](../plugin-reference/qticamsrc) to surface the full camera capability set to the GStreamer pipeline through a developer-friendly interface of source pads, camera properties, and control signals. At runtime, [`qticamsrc`](../plugin-reference/qticamsrc) performs the following on behalf of the pipeline: * Opens and configures the target camera device * Creates and manages video and image output streams * Receives captured frames from the le-camera service * Wraps camera buffers as GstBuffer objects and pushes them downstream through the corresponding source pads * Returns buffers to the camera service upon downstream consumption This architecture enables zero-copy camera output by retaining buffer ownership and stream resources within the service layer — maximizing pipeline throughput while minimizing memory overhead. ![Camera pipeline](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/camera.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=c906f31fca5f574f80ba6495775679bb) ### Related Information [Camera use cases](../sample-pipelines/multimediapipelines#1-camera) ## AI Inference Architecture The QIM SDK provides end-to-end support for AI/ML video and audio analytics pipelines, covering the full processing chain from raw media ingestion through model inference to real-time result visualization. AI pipelines in QIM SDK are built around a tensor-based, three-stage processing model: preprocessing, inference, and postprocessing. Each stage is handled by a dedicated plugin and executes in parallel across consecutive frames — source capture at frame N-2, preprocessing at N-1, inference at N, and postprocessing at N+1 — delivering maximum pipeline throughput and optimal hardware utilization. The pipeline source can be live camera frames via [`qticamsrc`](../plugin-reference/qticamsrc) (YUV) or offline media via `filesrc` (with format conversion); the sink can be an on-screen display via [`waylandsink`](../plugin-reference/waylandsink) or local storage via `filesink`. The [`qtimlvconverter`](../plugin-reference/qtimlvconverter) preprocessing plugin converts raw video frames into normalized tensors by performing color space conversion, resizing, and mean subtraction. It queries tensor dimensions and format requirements directly from the downstream inference plugin at runtime, making it a fully generic, model-agnostic preprocessing stage compatible with all inference backends. All inference plugins operate in tensor-in / tensor-out mode and share the same [`qtimlvconverter`](../plugin-reference/qtimlvconverter) for preprocessing. QIM SDK supports the following inference engines, each with hardware delegate support for acceleration across Qualcomm's neural processing subsystems: | Plugin | Engine | | - | - | | [`qtimltflite`](../plugin-reference/qtimltflite) | LiteRT / TensorFlow Lite | | [`qtimlsnpe`](../plugin-reference/qtimltflite) | Snapdragon Neural Processing Engine (SNPE) | | [`qtimlqnn`](../plugin-reference/qtimlqnn) | Qualcomm Neural Network (QNN) | | [`qtimlonnx`](../plugin-reference/qtimlonnx) | ONNX Runtime | Inference output tensors are passed directly to task-specific postprocessing plugins that decode multi-dimensional tensor data — bounding boxes, class labels, segmentation masks, and keypoints — into structured ML metadata. The postprocessing layer follows a modular sub-module architecture, allowing developers to author custom postprocessing modules to support proprietary or non-standard model architectures. Finally, the [`qtivoverlay`](../plugin-reference/qtivoverlay) plugin consumes the structured ML metadata and renders inference results directly onto the video buffer in real time. The annotated stream can then be rendered to a display, encoded and stored locally, or streamed over a network. ![Figure:AI Inference Architecture](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/mlpipeline.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=f4b4c8f398eddc9c679a2cecc11e4fa9) ### Related information [Run AI/ML use cases](../sample-pipelines/aipipelines) ## Video Architecture The QIM SDK provides hardware-accelerated video encode and decode through V4L2-based plugins that interface directly with the Qualcomm multimedia engine. Video encoding and decoding are performed entirely on the dedicated VPU (Video Processing Unit), offloading this work from the CPU and allowing concurrent camera capture, AI inference, and video processing without resource contention. The architecture supports AVC (H.264) and HEVC (H.265) formats for both encode and decode paths. Encoded output can be written to file via a multiplexer or streamed over the network. Decoded output is delivered as DMA-buf-backed NV12 frames, compatible with all downstream QIM SDK plugins including AI preprocessing and display. ### Encode Video frames captured from the camera via [`qticamsrc`](../plugin-reference/qticamsrc) are passed directly to the hardware encoder. The encoded bitstream is parsed and multiplexed into an MP4 or MPEGTS container before being written to file or transmitted over the network. ![Video encode pipeline](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/videoencode.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=4676fbaa3271dc2867343480e4bd834e) | Component | Description | | - | - | | [`qticamsrc`](../plugin-reference/qticamsrc) | Captures video streams from the ISP camera. See [Camera Architecture](/advanced/technologyoverview#camera-architecture). | | [`v4l2h264enc`](../plugin-reference/v4l2h264enc) | Encodes the video stream to AVC (H.264) format using the V4L2 driver. | | [`v4l2h265enc`](../plugin-reference/v4l2h265enc) | Encodes the video stream to HEVC (H.265) format using the V4L2 driver. | | `h264parse` / `h265parse` | Parses the encoded bitstream and inserts headers required for downstream muxing or streaming. | | `mp4mux` / `mpegtsmux` | Multiplexes the encoded stream into an MP4 or MPEGTS container. | | `filesink` | Writes the muxed container to the file system. | ### Decode A video file is demultiplexed, the elementary stream is parsed, and the hardware decoder produces raw NV12 frames for display or downstream AI processing. Decode parameters are exposed as GStreamer element properties for direct application control. ![Video decode pipeline](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/videodecode.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=a47a31d06e6520cfaaa82f62756303f1) | Component | Description | | - | - | | `filesrc` | Reads the video container from the file system. | | `qtdemux` | Demultiplexes the container into separate elementary streams. | | `h264parse` / `h265parse` | Parses the encoded elementary stream before decoding. | | [`v4l2h264dec`](../plugin-reference/v4l2h264dec) | Decodes the AVC (H.264) video stream to raw NV12 frames using the V4L2 driver. | | [`v4l2h265dec`](../plugin-reference/v4l2h265dec) | Decodes the HEVC (H.265) video stream to raw NV12 frames using the V4L2 driver. | | [`waylandsink`](../plugin-reference/waylandsink) | Receives decoded NV12 frames as GBM buffers and submits them to the Weston compositor for display. | ### Related Information [Video encode and decode use cases](../sample-pipelines/multimediapipelines#2-camera-and-video-encode) [Video playback use cases](../sample-pipelines/multimediapipelines#5-video-playback-use-cases) ## Audio Architecture Audio capture and playback in QIM SDK are handled through the `pulsesrc` and `pulsesink` GStreamer plugins, which interface with the system-level PulseAudio server. The PulseAudio server in turn communicates with the ALSA driver to interact with the underlying audio hardware. Audio encode and decode use open-source GStreamer plugins (such as `flacenc`, `flacparse`, `flacdec`, `lamemp3enc`, `mpegaudioparse`, `mpg123audiodec`) combined with the PulseAudio integration, enabling a complete audio pipeline without requiring custom hardware-specific code. ### Capture The `pulsesrc` plugin captures raw PCM audio from the microphone and passes it to the PulseAudio server, which handles hardware interaction via the ALSA driver. The PCM stream can then be encoded or written directly to file. ![Audio capture pipeline](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/audio.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=cdfecca737cd454321448fa2ab877566) | Component | Description | | - | - | | `pulsesrc` | Captures PCM audio samples from the microphone via the PulseAudio server. | | PulseAudio server | Interfaces with the ALSA driver to acquire audio data from the hardware. | | Encode / `filesink` | Optionally encodes and writes the captured audio to a file. | ### Playback The `pulsesink` plugin receives PCM audio data and routes it through the PulseAudio server for hardware playback. It supports both live audio sources and pre-encoded audio files after decoding. ![Audio playback pipeline](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/playback.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=1d2850d76c96ecc8568fd449b2932d55) | Component | Description | | - | - | | `filesrc` | Reads audio data from a file. | | Decode | Decodes encoded audio (e.g., MP3, FLAC, WAV) to raw PCM using open-source decoder plugins. | | `pulsesink` | Sends PCM audio data to the PulseAudio server for playback on the audio hardware. | | PulseAudio server | Interfaces with the ALSA driver to route audio to the hardware output. | ### Encode Captured PCM audio is encoded using an open-source encoder, parsed, and multiplexed into a container before being written to file. ![Audio encoding pipeline](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/audioencode.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=09fa609b79032aee93f8ba08facf4d5d) | Component | Description | | - | - | | `pulsesrc` | Captures PCM audio from the microphone. | | PulseAudio server | Interacts with the ALSA driver to supply raw audio data. | | Encode | Encodes PCM to a compressed format (MP3, FLAC, AAC) using open-source plugins. | | Parse | Parses the encoded bitstream before muxing. | | `mp4mux` / `mpegtsmux` | Multiplexes the encoded audio into an MP4 or MPEGTS container. | | `filesink` | Writes the container to the file system. | ### Decode An encoded audio file is read, demultiplexed, decoded back to PCM, and played back through `pulsesink`. ![Audio decode pipeline](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/audiodecode.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=62fcf272a3f0818ee8d5f008cee16f80) | Component | Description | | - | - | | `filesrc` | Reads the audio container from the file system. | | `qtdemux` | Demultiplexes the container to extract the audio elementary stream. | | Decode | Decodes the compressed audio to raw PCM using open-source decoder plugins. | | `pulsesink` | Sends the decoded PCM to the PulseAudio server for playback. | | PulseAudio server | Interfaces with the ALSA driver to route audio to the hardware output. | ### Related Information [Audio use cases](../sample-pipelines/multimediapipelines#6-audio-use-cases) ## Graphics and Display Architecture The QIM SDK uses the Wayland display protocol with the Weston compositor to manage display composition and output. Weston runs as an independent process and handles all display composition using OpenGL ES, communicating with the display hardware through the DRM/KMS subsystem. QIM SDK plugins deliver video buffers as GBM-backed DMA-buf handles. Weston receives these buffers via the Wayland protocol and composites them directly onto the display without intermediate CPU copies, maintaining the zero-copy path from camera capture or video decode through to the screen. ![Weston/Wayland architecture](https://mintcdn.com/qimsdk/p8bRJ_K0_Mx14HV0/advanced/images/wayland.png?fit=max\&auto=format\&n=p8bRJ_K0_Mx14HV0\&q=85\&s=d36710a57d31d5843087a1fe6eb5ba63) | Component | Description | | - | - | | Wayland/GLES client | GStreamer plugins such as [`waylandsink`](../plugin-reference/waylandsink) implement the Wayland client protocol to submit video buffers to Weston. | | Weston server | Implements the Wayland compositor. Uses KMS to configure the display and OpenGL ES with DRM for hardware-accelerated compositing. | | SDM back-end | Display hardware abstraction layer (HAL) that provides the DRM/KMS platform implementation for Weston. | | libGBM | Buffer allocation and sharing library. Provides a DMA-backed allocator enabling zero-copy buffer sharing between the GPU, display, and other hardware blocks. | | EGL sub-driver | Interface between GBM/EGL and the Wayland protocol, allowing GStreamer elements to share hardware-allocated buffers with the Weston compositor. | ### Related Information [Display and composition use cases](../sample-pipelines/multimediapipelines) # Test Automation Source: https://imsdkdocs.qualcomm.com/advanced/test-automation Automated testing strategies and tools for QIM SDK pipelines. > [!NOTE] > > This section is coming soon. Content will cover automated pipeline testing, regression frameworks, and CI/CD integration for QIM SDK. # Ubuntu platform Source: https://imsdkdocs.qualcomm.com/advanced/ubuntu-build This section explains how to compile QIM SDK plugins for Ubuntu platform. **On-device Compilation** This section explains how to compile QIM SDK plugins directly on the **target device** running Ubuntu. ## Prerequisites Before you begin, ensure the following: * You have access to a Qualcomm development kit running Ubuntu Linux. * You have administrative privileges (sudo access) for installing packages. * Internet connectivity for downloading packages and source code. ## Steps to Compile and Install To download the source code and compile the sample applications, run the following commands on the Qualcomm development kit. **1. Update user permissions for your session** ```bash theme={null} theme={null} sudo su ``` **2. Configure Ubuntu package manager to download source code** ```bash theme={null} theme={null} apt-add-repository -s ppa:ubuntu-qcom-iot/qcom-ppa ``` **3. Build the dependencies** ```bash theme={null} theme={null} apt build-dep gst-plugins-qti-oss ``` **4. Change directory to home folder** ```bash theme={null} theme={null} cd /home/ubuntu ``` **5. Download the sources of the QIM Package** ```bash theme={null} theme={null} apt source gst-plugins-qti-oss ``` **6. Go to QIM root folder** For example: ```bash theme={null} theme={null} cd gst-plugins-qti-oss-1.8.1+ubuntu3 ``` **7. Run CMake to build and install** ```bash theme={null} theme={null} cmake -B build -S . \ -DCMAKE_INSTALL_PREFIX=/usr \ -DCMAKE_INSTALL_INCLUDEDIR=include \ -DENABLE_GST_PLUGIN_BASE=1 \ -DENABLE_GST_IMSDK_PLUGINS=1 \ -DENABLE_GST_PLUGIN_QMMFSRC=1 \ -DENABLE_GST_PYTHON_EXAMPLES=1 \ -DENABLE_GST_SAMPLE_APPS=1 \ -DENABLE_GST_TEST_FRAMEWORK=1 \ -DENABLE_GST_PLUGIN_TOOLS=1 \ -DENABLE_GST_PLUGIN_MLACLASSIFICATION=1 \ -DENABLE_GST_PLUGIN_MLVCLASSIFICATION=1 \ -DENABLE_GST_PLUGIN_MLVDETECTION=1 \ -DENABLE_GST_PLUGIN_MLVPOSE=1 \ -DENABLE_GST_PLUGIN_MLVSEGMENTATION=1 \ -DENABLE_GST_PLUGIN_MLVSUPERRESOLUTION=1 \ && cmake --build build \ && cmake --install build ``` > [!NOTE] > > After modifying any part of the source code, re-run step 7 to rebuild and reinstall your changes. ## Steps to build custom application Go through the [prerequisites](#prerequisites) and [Steps to Compile and Install](#steps-to-compile-and-install) section before starting this. **1. Create a subdirectory in gst-sample-apps** ```bash theme={null} theme={null} cd gst-plugins-qti-oss-1.8.1+ubuntu3/gst-sample-apps && mkdir gst- ``` **2. Build application** Follow [Step 7: Run CMake to build and install](#steps-to-compile-and-install) **On-host Compilation** > [!NOTE] > > On-host compilation for Ubuntu is not yet available in this documentation. Please refer to the on-device compilation instructions. # Yocto platform Source: https://imsdkdocs.qualcomm.com/advanced/yocto-build This section explains how to compile QIM SDK plugins for Yocto platform. **On-host Compilation** This section explains how to compile QIM SDK plugins directly on a x86 and Arm host machine running Ubuntu. ## Prerequisites Before you begin, ensure the following: * Internet connectivity for downloading packages and source code. * Sufficient space on the host to download the SDK. Upto \~5GB. ## Download and install the sdk. **1. Download SDK** **x86 Host** ```bash theme={null} theme={null} wget -O sdk.zip https://artifacts.codelinaro.org/artifactory/qli-ci/flashable-binaries/meta-qcom/qcom-distro/qcom-armv8a/x64-qli-2.0-qimsdk-2.0.0-standardsdk.zip ``` **Arm Host** ```bash theme={null} theme={null} wget -O sdk.zip https://artifacts.codelinaro.org/artifactory/qli-ci/flashable-binaries/meta-qcom/qcom-distro/qcom-armv8a/arm-qli-2.0-qimsdk-2.0.0-standardsdk.zip ``` **2. Extract and Install the SDK** ```bash theme={null} theme={null} unzip sdk.zip && cd images/qcom-armv8a/sdk/ ``` **x86 Host** ```bash theme={null} theme={null} bash qcom-distro-x86_64-qcom-multimedia-proprietary-image-armv8a-qcom-armv8a-toolchain-2.0.sh -d -y ``` **Arm Host** ```bash theme={null} theme={null} bash qcom-distro-aarch64-qcom-multimedia-proprietary-image-armv8a-qcom-armv8a-toolchain-2.0.sh -d -y ``` **3. Source the cross-compilation toolchain environment** ```bash theme={null} theme={null} source /environment-setup-armv8a-qcom-linux ``` > [!NOTE] > > Each time you wish to use the SDK in a new shell session, you need to source the environment setup script in Step 3 ## Steps to Compile To download the source code and compile the sample applications, run the following commands. **1. Clone the sources from github** ```bash theme={null} theme={null} git clone https://github.com/qualcomm/qimsdk.git cd qimsdk ``` **2. Compile base libraries** ```bash theme={null} theme={null} cmake -B build-base -S . \ -DCMAKE_INSTALL_PREFIX=/usr \ -DENABLE_GST_PLUGIN_BASE=1 \ && cmake --build build-base ``` **3. Install base libraries to SDK sysroot path** ```bash theme={null} theme={null} DESTDIR="${SDKTARGETSYSROOT}" cmake --install build-base --prefix /usr ``` **4. Compile plugins and app builders sample apps with updated base libraries** ```bash theme={null} theme={null} cmake -B build -S . \ -DCMAKE_INSTALL_PREFIX=/usr \ -DENABLE_GST_IMSDK_PLUGINS=1 \ -DENABLE_GST_PLUGIN_MLTFLITE=1 \ -DENABLE_GST_PYTHON_EXAMPLES=1 \ -DENABLE_GST_SAMPLE_APPS=1 \ -DENABLE_GST_SAMPLE_APPS_CAMERA=1 \ -DENABLE_GST_PLUGIN_TOOLS=1 \ -DENABLE_GST_CAMERA_PLUGINS=1 \ -DENABLE_APP_BUILDER_CPP=1 \ -DENABLE_APP_BUILDER_PYTHON=1 \ && cmake --build build ``` > [!NOTE] > > After modifying any part of the source code, re-run step 4 to rebuild your changes. > The corresponding libs from build directory can then be copied on to device. ## Steps to build custom application Go through the [prerequisites](#prerequisites) and [Steps to Compile](#steps-to-compile) section before starting this. **GStreamer Sample App** **1. Create a subdirectory in gst-sample-apps** ```bash theme={null} theme={null} cd qimsdk/gstreamer/gst-sample-apps && mkdir gst- ``` **2. Build the application** Follow [Steps to Compile](#steps-to-compile) **3. Copy the binary to target device** ```bash theme={null} theme={null} #The application will be found in the below location qimsdk/build/gstreamer/gst-sample-apps/gst-/ ``` **C++ App Builder** **1. Create a subdirectory in cpp reference-apps** ```bash theme={null} theme={null} cd qimsdk/cpp/examples/reference-apps/ && mkdir ``` **2. Build the application** Follow [Steps to Compile](#steps-to-compile) **3. Copy the binary to target device** ```bash theme={null} theme={null} #The application will be found in the below location qimsdk/build/cpp/examples/reference-apps// ``` **On-device Compilation** > [!NOTE] > > On-device compilation for Yocto is not yet available in this documentation. Please refer to the on-host compilation instructions. # Coding Agent Source: https://imsdkdocs.qualcomm.com/app-builder-coding-agent Generate QIM SDK applications with AI coding agent skills QIM SDK provides AI coding skills that generate complete applications from a natural-language description of your pipeline. Pick the coding agent that matches your development path, then follow its guide to generate your first application with an AI coding agent (Claude Code, Cursor, Codex, etc) > **[GStreamer App Builder](/app-builder/gstreamer-coding-agent)** > > Generate GStreamer C apps and gst-launch scripts using QIM SDK plugins. > > [Go to Coding Agent →](/app-builder/gstreamer-coding-agent) > **[C++ App Builder](/app-builder/cpp-coding-agent)** > > Generate high-performance C++ applications on the QIM SDK C++ API. > > [Go to Coding Agent →](/app-builder/cpp-coding-agent) > **[Python App Builder](/app-builder/python-coding-agent)** > > Generate Python applications on the QIM SDK Python API for prototyping. > > [Go to Coding Agent →](/app-builder/python-coding-agent) The skills are available at [qimsdk-agentic-skills](https://github.com/qualcomm/qimsdk-agentic-skills/) # Quickstart Source: https://imsdkdocs.qualcomm.com/app-builder-quickstart Choose a development path and jump into its quickstart guide QIM SDK supports three ways to build AI and multimedia applications. Pick the path that best fits your workflow, then follow its quickstart guide to build your first pipeline. > **[GStreamer App Builder](/quickstart)** > > Build pipelines with native GStreamer elements and QIM SDK plugins. > > [Go to Quickstart →](/quickstart) > **[C++ App Builder](/app-builder/cpp-quickstart)** > > Build high-performance applications with the fluent C++ App Builder API. > > [Go to Quickstart →](/app-builder/cpp-quickstart) > **[Python App Builder](/app-builder/python-quickstart)** > > Build applications quickly with the high-level Python App Builder API. > > [Go to Quickstart →](/app-builder/python-quickstart) # Sample Applications Source: https://imsdkdocs.qualcomm.com/app-builder-sample-applications Explore ready-to-run sample applications for each development path QIM SDK provides ready-to-run sample applications for each development path. Pick the path that matches your workflow to browse its applications, or go to GitHub to view the source code. > **[GStreamer App Builder](/sample-application/ai-sample-applications)** > > Sample applications built with the GStreamer App Builder. > > [View applications →](/sample-application/ai-sample-applications) > > [View source on GitHub →](https://github.com/qualcomm/qimsdk/tree/main/gstreamer/gst-sample-apps) > **[C++ App Builder](/app-builder/cpp-reference-applications)** > > Reference applications built with the C++ App Builder API. > > [View applications →](/app-builder/cpp-reference-applications) > > [View source on GitHub →](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps) > **[Python App Builder](/app-builder/python-reference-applications)** > > Reference applications built with the Python App Builder API. > > [View applications →](/app-builder/python-reference-applications) > > [View source on GitHub →](https://github.com/qualcomm/qimsdk/tree/main/python/examples/reference-apps) # SDK Architecture and API Reference Source: https://imsdkdocs.qualcomm.com/app-builder/cpp-architecture-api-reference Design and API details of the QIM SDK Pipeline SDK (C++ and Python) ## Pipeline SDK Design **Overview** This SDK delivers a streamlined, modern interfaces, engineered to facilitate the rapid development, execution, and management of sophisticated multimedia pipelines. By implementing a high-level abstraction layer, the SDK encapsulates complex underlying GStreamer based mechanisms — including element negotiation, signal management, event loops, and state transitions — allowing engineers to prioritize core application logic over boilerplate framework intricacies. **Key Capabilities** The wrapper empowers developers to architect advanced multimedia and AI-enhanced workflows with precision and efficiency. It supports the seamless integration of diverse components, such as video capture sources, signal processing nodes, machine learning inference engines, graphical overlays, and rendering outputs. Uniquely designed to decouple implementation from the underlying framework, the SDK eliminates the need for deep GStreamer expertise or compile-time dependencies on GStreamer headers, ensuring a clean, robust, and accessible development experience. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/imsdk_overview.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=a927e3a6ea23ccab4080d3e28b88c18d) ## APIs **Public APIs:** * `Pipeline` — build & control pipelines fluently. * `Element` — generic element wrapper with variadic property setting, and state control. \[it can be instantiated at create time as well as at runtime to update the pipeline.] Some element has special functions which can be controlled by dedicated elements types. Those elements derived from `Element` can be use as `Element` if special functions are not used. * `AppSrc` — app-facing source for zero-copy buffer pull. \[Providing the buffer from application to pipeline using standard lambdas, push APIs, EOS etc] * `AppSink` — app-facing sink for zero-copy buffer push \[Providing the buffer from pipeline to application with zero copy] * `CamSrc` - Build-in camera element which expose API for capture images \[provides functionality to take snapshots at runtime] * `MLVConverter` - ML video converter (`qtimlvconverter`). Expose API for custom pre-processing implementation at application utilizing standard lambdas. * `MLPostprocess` - ML postprocess element (`qtimlpostprocess`). Expose API for custom post-processing implementation at application utilizing standard lambdas. The callback is typed per ML task (classification, object detection, pose estimation, depth estimation, segmentation, raw tensors). * `MLVideoONNXBin` - ONNX inference bin (`qtimlvideoonnxbin`). Expose API for custom pre-processing and post-processing implementation at application utilizing standard lambdas. * `MLVideoQNNBin` - QNN inference bin (`qtimlvideoqnnbin`). Expose API for custom pre-processing and post-processing implementation at application utilizing standard lambdas. * `MLVideoSNPEBin` - SNPE inference bin (`qtimlvideosnpebin`). Expose API for custom pre-processing and post-processing implementation at application utilizing standard lambdas. * `MLVideoTFLiteBin` - TFLite inference bin (`qtimlvideotflitebin`). Expose API for custom pre-processing and post-processing implementation at application utilizing standard lambdas. * `Buffer` — opaque buffer that bridges Native Buffer with timestamp helpers and zero-copy paths. * `StreamFilter` and derived concrete stream helpers: `VideoFilter` (all RAW formats - YUV, RGB, bayer), `H264Filter`, `TensorFilter`, `TextFilter`, `AudioFilter`, `ImageFilter`. these filters are used to set characteristics of the streams. * Logging controls — `SetImsdkLogLevel()` and `SetImsdkGstLogMode()` select the SDK's log verbosity and whether GStreamer's output is simplified or passed through raw. See [Logging and Diagnostics](/app-builder/cpp-logging). **Reference flows** ### Pipeline **Purpose** A convenient, exception-safe wrapper around a `GstPipeline` that: * Builds pipelines using element factory names or pre-constructed wrapper elements. * Manages pipeline lifecycle and execution state. * Performs delayed linking for dynamic/request-pad elements automatically via `pad-added`. **Key Responsibilities** * Create and own the underlying `GstPipeline` instance. * Add elements, assign properties, and insert caps filters. * Link elements (immediately when possible, deferred otherwise). * Manage the full pipeline lifecycle (`prepare`, `start`, `wait`, `stop`). * Install bus watches to handle `ERROR`, `EOS`, and state transitions. * Integrate with runtime shutdown notifications. **A minimal pipeline** Add the elements in the order data flows through them, then run: ```cpp theme={null} Pipeline pipeline("my-pipeline"); pipeline .add("filesrc", "src", "location", "/home/user/media/video.mp4") .add("qtdemux", "demux") .add("h264parse", "parse") .add("v4l2h264dec", "decoder", "output-io-mode", 4, "capture-io-mode", 4) .add_stream_filter("vf", VideoFilter().format("NV12")) .add("waylandsink", "display", "fullscreen", true) .execute(); ``` `execute()` starts the pipeline, blocks until EOS/error/termination, and tears it down. > [!TIP] > > **Adjacent elements are linked in add order.** In the example above `src` → `demux` → `parse` → `decoder` → `vf` → `display` are linked simply because that is the order of the `add()` calls, so a linear graph needs no explicit linking. Use [`link()`](#branching-with-explicit-links) when the graph is not linear — a `tee` splitting into a display branch and an inference branch, or a `qtimetamux` rejoining them. > [!NOTE] > > `qtdemux` is an example of the delayed linking described above: its src pads appear only once the container has been parsed, so the `demux` → `parse` link is completed automatically when the pad shows up. No `pad-added` handling is needed in application code. **Building the pipeline** | Method | Description | | - | - | | `Pipeline(const std::string &name)` | Creates an empty pipeline. `name` is the `GstPipeline` name, used in log messages. | | `Pipeline(const std::string &name, const std::string &config)` | Builds a complete pipeline from a YAML description. `config` is the YAML **content**, not a path. See [Describing a pipeline in YAML](#describing-a-pipeline-in-yaml). | | `Pipeline &add(String factory, String name, ...)` | Creates an element from the factory name and adds it under a unique instance name. Trailing arguments are property key/value pairs, applied immediately. | | `Pipeline &add(const Element &element)` | Adds an externally constructed element. Required for the specialized wrappers (`AppSrc`, `AppSink`, `CamSrc`, `MLVConverter`, `MLPostprocess`, the ML bins) so callbacks can be attached before the element joins the pipeline. | | `Pipeline &add_stream_filter(String name, const StreamFilter &filter)` | Inserts a caps filter between the previous and next element. When neighbouring elements have several formats in common, this fixates the one you want instead of leaving the choice to caps negotiation. See [StreamFilter](#streamfilter). | | `Pipeline &link(names...)` | Links the named elements in the given order. Needed only for non-linear graphs. | The optional key/value pairs passed to `add()` are the element's properties, and they are validated as soon as the element is added. Setting a property the element does not have throws `std::invalid_argument` naming the property, the element instance, and the element type — so a typo surfaces immediately at that `add()` call instead of being silently ignored: ```cpp theme={null} // "fulscreen" is not a waylandsink property -> throws std::invalid_argument pipeline.add("waylandsink", "display", "fulscreen", true); ``` **Branching with explicit links** Add order cannot express a branch, so name the chains explicitly. Element instance names are the identifiers. ```cpp theme={null} pipeline .add("filesrc", "src", "location", path) .add("qtdemux", "demux") .add("h264parse", "parse") .add("v4l2h264dec", "decoder", "output-io-mode", 4, "capture-io-mode", 4) .add_stream_filter("vf", VideoFilter().format("NV12")) .add("tee", "split") .add("queue", "q1") .add("qtimlvconverter", "preprocessing") .add("qtimltflite", "inferencing", "model", model_path) .add("qtimlpostprocess", "postprocessing", "module", "yolov8") .add_stream_filter("mlf", TextFilter()) .add("qtimetamux", "mlmuxer") .add("qtivoverlay", "overlay") .add("waylandsink", "display", "fullscreen", true) // trunk, up to the tee .link("src", "demux", "parse", "decoder", "vf", "split") // branch 1: raw video to the metadata muxer .link("split", "mlmuxer") // branch 2: inference path, rejoining at the muxer .link("split", "q1", "preprocessing", "inferencing", "postprocessing", "mlf", "mlmuxer", "overlay", "display"); ``` > [!TIP] > > Elements whose src pads are `SOMETIMES` or `REQUEST` — `qtdemux`, `tsdemux`, `tee`, `qtivsplit` — cannot be linked at construction time, because the pads do not exist yet. The pipeline detects this from the pad templates, defers the link, and completes it from a `pad-added` handler it installs itself. Request pads on the sink side (for example `qtimetamux`, `qtivcomposer`) are requested and released automatically. No `pad-added` callback is needed in application code. > [!NOTE] > > A link between two elements that both have only static pads and no common caps fails immediately with `std::runtime_error` naming both elements. A deferred link that never resolves surfaces at run time instead; on error the pipeline logs which pads stayed unlinked. **Running the pipeline** A pipeline is always in one of three states, and the lifecycle methods are the transitions between them: ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/pipeline_states.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=ca50232408e58a030b9f1693f14feb07) | State | Meaning | | - | - | | `NULL` | No resources allocated. Initial state, and the state after `stop()`. Devices are closed, buffer pools released. | | `PAUSED` | Elements are allocated and caps are negotiated between linked pads, but the clock is not running and no data flows. Sinks have pre-rolled. This is the state in which elements can be added, removed, or relinked. | | `PLAYING` | The clock is running and buffers flow through the graph. | `execute()` performs the whole `NULL → PLAYING → NULL` cycle, so most applications never call the individual transitions. `prepare()`, `activate()`, and `deactivate()` — the transitions through `PAUSED` shown above — are covered in [Advanced state control](#advanced-state-control). | Method | Description | | - | - | | `void execute()` | `start()`, `wait()`, `stop()` in sequence. The normal entry point. | | `Pipeline &start()` | Sets the pipeline to `PLAYING`. Non-blocking: the state change is asynchronous and this returns without waiting for it. Throws `std::runtime_error` if the transition fails. | | `Pipeline &wait()` | Blocks until the pipeline is done: `EOS` on the bus, `ERROR` on the bus, `stop()` from another thread, or `SIGINT`/`SIGTERM`. | | `Pipeline &stop()` | Sets the pipeline to `NULL` and releases resources. Blocks until teardown completes. | | `Pipeline &eos(bool enabled)` | When enabled, `stop()` first sends an end-of-stream event through the pipeline and waits for it to come back from the sinks, so that data already inside the pipeline is processed before teardown. Off by default. See [Draining the pipeline on shutdown](#draining-the-pipeline-on-shutdown). | > [!WARNING] > > `start()` is non-blocking, so it must be paired with `wait()` (or your own blocking logic). A `main()` that calls `start()` and returns destroys the pipeline before buffers flow. To run the pipeline while the application does other work, split `execute()` apart: ```cpp theme={null} pipeline.start(); // returns immediately // ... application work, runtime property changes, snapshots ... pipeline.wait(); // block until EOS / error / Ctrl+C pipeline.stop(); ``` **Draining the pipeline on shutdown** By default `stop()` tears the pipeline down as fast as it can. Every element goes to `NULL` immediately and whatever buffers are still in flight — queued between elements, held inside an encoder, not yet written by a sink — are discarded. This is usually what you want: the pipeline stops without delay. Some pipelines must not lose those buffers, and for them `eos(true)` changes the shutdown sequence. Instead of stopping straight away, `stop()` sends an end-of-stream event into the pipeline. The event travels downstream element by element; each element finishes processing the data it has already accepted, passes the event on, and the sinks report it back on the bus. Only once that end-of-stream notification comes back does `stop()` tear the pipeline down. Nothing that had already entered the pipeline is dropped. The trade-off is shutdown latency: `stop()` now blocks until the last buffer has made it through the whole graph, which takes as long as the remaining data needs. Use `eos(true)` when the tail of the stream is part of the result: * **Muxed recordings.** Containers such as MP4 and MKV are written by a muxer (`mp4mux`, `matroskamux`) that writes its index and header metadata — the `moov` atom, in MP4's case — only on end-of-stream. Cut it off early and the file is left incomplete, often unplayable rather than merely short. * **Encoders with buffered frames.** Encoders keep several frames in flight for B-frames, lookahead, and similar optimizations. End-of-stream is what makes the encoder flush those frames downstream; without it the tail of the recording is simply missing. * **Any sink where losing the final buffered data is unacceptable** — file sinks, muxed outputs, and applications that expect to receive every frame through `AppSink`. Not every sink needs draining, though. A live network stream can usually just be cut off, and a receiver will not care that the last few buffers never arrived. The question is not whether a sink writes somewhere, but whether anything downstream depends on the data still sitting in the pipeline. Leave `eos()` off (the default) when the newest data is all that matters and stopping promptly is preferable — live preview to a display, a camera feed on screen, or writing self-contained files where each buffer is already complete on its own (JPEG frames through `multifilesink`, for example, which needs no finalization). ```cpp theme={null} Pipeline pipeline("cam-encoder-pipeline"); pipeline .add("qtiqmmfsrc", "source") .add_stream_filter("vf", VideoFilter().format("NV12") .resolution(1920, 1080) .framerate(30)) .add("v4l2h264enc", "encoder", "output-io-mode", "dmabuf-import", "capture-io-mode", "dmabuf") .add("h264parse", "parser") .add("mp4mux", "muxer") .add("filesink", "sink", "location", HOME_PATH + "/media/output.mp4") .eos(true) // drain, so mp4mux can finalize the container .execute(); ``` > [!NOTE] > > If the pipeline has already reached end-of-stream on its own — a file source that ran out of data, for instance — `stop()` detects it and tears down immediately instead of sending a second event and waiting again. Enabling `eos(true)` therefore costs nothing for pipelines that end naturally; it only matters when you stop a pipeline that is still running. **Advanced state control** For reconfiguring a loaded pipeline — adding, removing, or relinking elements without returning to `NULL`. | Method | Description | | - | - | | `Pipeline &prepare()` | `NULL` → `PAUSED`. Allocates resources and negotiates caps without running the clock. Blocking. | | `Pipeline &activate()` | `PAUSED` → `PLAYING`. | | `Pipeline &deactivate()` | `PLAYING` → `PAUSED`. Resources stay allocated. | **Accessing elements at run time** | Method | Description | | - | - | | `Element get(String name)` | Returns a wrapper for the named element, for runtime property changes and per-pad configuration. Throws `std::runtime_error` if the name is not in the pipeline. | | `T get(String name)` | Returns a typed wrapper, exposing that type's element-specific API — for example `get("source")` for the image-capture calls. Use it when the element was added by factory name but its specialized interface is needed. | **Runtime property and per-pad configuration** — `get()` reaches any element by name while the pipeline is loaded or playing: ```cpp theme={null} // Change a property at run time. pipeline.get("display").set("fullscreen", false); // Per-pad properties on a request pad of qtivcomposer. pipeline.get("composer").input(1).set("alpha", 0.5); ``` **Typed access to an element's own API** — `get()` returns the specialized wrapper, so element-specific calls become available on an element that was added by factory name: ```cpp theme={null} // qtiqmmfsrc was added as "source"; CamSrc exposes its capture API. auto cam = pipeline.get("source"); cam.image_capture(); ``` See the sample applications for complete image-capture pipelines. > [!NOTE] > > `get()` returns an element wrapper **by value**; each call yields a new wrapper referencing the same `GstElement`. Bind it with `auto`, not `auto&`. **Describing a pipeline in YAML** The graph — elements, properties, stream filters, and links — can be described in YAML instead of in code. This separates *what the pipeline is* from *what the application does with it*: the same binary can run a different topology, a different model, or a different source by pointing it at another configuration file. That makes it useful where the pipeline is not fixed at build time: * **Deploying one binary across variants** — the same application against a built-in camera, a USB camera, or an RTSP stream, switching source and format per device. * **Tuning without rebuilding** — resolution, framerate, model path, or delegate changed on the target, which matters when a rebuild means a full cross-compile and reflash. * **Keeping topology under review** — the pipeline shape lives in a file that can be diffed and versioned on its own. Loading from YAML does not give up application logic: the elements are ordinary pipeline members afterwards, so `get()` and `get()` reach them as usual. ```yaml theme={null} pipeline: elements: - type: filesrc name: src location: ~/media/video.mp4 - type: qtdemux name: demux - type: h264parse name: parse - type: v4l2h264dec name: decoder output-io-mode: 4 capture-io-mode: 4 - type: filter name: videofilter video: format: NV12 - type: waylandsink name: display fullscreen: true ``` Everything lives under a single root key, `pipeline:`, which takes three independent child keys: ```yaml theme={null} pipeline: eos: true # optional — EOS-on-shutdown, same as eos(true) in code elements: # required — the elements, in add order - type: ... links: # optional — explicit links, for non-linear graphs - [ ... ] ``` | Key | Required | Description | | - | - | - | | `eos` | No | Boolean. Equivalent to calling [`eos(bool)`](#draining-the-pipeline-on-shutdown). Defaults to false when omitted. | | `elements` | Yes | Sequence of elements. Add order is link order, exactly as with `add()`. | | `links` | No | Sequence of chains, each a list of element names. Equivalent to one `link()` call per entry. Omit it for linear pipelines. | Within `elements:`, each entry needs `type` (the factory name) and `name` (the instance name); every remaining key is applied as a property of that element. An entry with `type: filter` inserts a stream filter instead, described by a `video:`, `image:`, `h264:`, `tensor:`, `text:`, `audio:`, or raw `caps:` block. Any of those blocks may carry an `add:` sequence of `key=value` strings, appended to the filter's caps through [`add()`](#videofilter) — the same escape-hatch the typed filters expose in code. It is accepted both inside the filter block and alongside it: ```yaml theme={null} - type: filter name: videofilter video: format: NV12 add: - colorimetry=bt709 ``` `links:` mirrors [`link()`](#branching-with-explicit-links) — one sequence per chain, so the branching pipeline shown earlier becomes: ```yaml theme={null} links: - [split, mlmuxer] - [source, videostream, split, q1, preprocessing, inferencing, postprocessing, mlf, mlmuxer, overlay, display] ``` The constructor takes the YAML content, so read the file first: ```cpp theme={null} std::ifstream input(config_path); std::ostringstream buffer; buffer << input.rdbuf(); Pipeline pipeline("demo-pipeline", buffer.str()); pipeline.execute(); ``` The names in the configuration are the handles the application uses afterwards. Given a config that declares a `qtimlpostprocess` element named `postprocessing`, the application can claim its post-processing without the topology being hard-coded: ```cpp theme={null} Pipeline pipeline("demo-pipeline", buffer.str()); auto postprocessing = pipeline.get("postprocessing"); postprocessing.set_handler([](const MLFrame& frame, const MLParam& params, MLDetections& detections) { return decode_detection(frame, params, detections); }); pipeline.execute(); ``` ### Element **Purpose** Generic wrapper around a `GstElement` with fluent, variadic property setting. Can be instantiated at create time or used at runtime to update a live pipeline. Serves as the base class for all specialized element types. **Key Responsibilities** * Create GStreamer elements from a factory name. * Provide fluent, variadic property setting for all common types and `StreamFilter` (caps). * Implement pad linking/unlinking with error checking. * Support state publication to pipeline (`sync`, `deactivate`, `stop`). * Expose per-pad configuration through `Port`. * Serve as the base class for specialized wrappers. ```cpp theme={null} Element display("waylandsink", "display"); display.set("fullscreen", true); display.set("sync", false); ``` Any element can be constructed directly and handed to `Pipeline::add()`, or reached later by name with `Pipeline::get()`. Elements cannot be copied — only moved — so pass them by reference or move them where ownership has to change. | `qti::Element` | Description | | - | - | | `Element(const std::string &factory, const std::string &name = {})` | Creates the element from a GStreamer factory name. The instance name is optional but recommended, since it is how the element is addressed in `link()`, `get()`, and log messages. | | `Element &set(String prop, Value value, ...)` | Sets one or more properties. Accepts any number of key/value pairs in a single call and returns `*this`, so calls can be chained. | | `Element &link(Element &downstream, String src_pad = "src", String sink_pad = "sink")` | Links this element's src pad to `downstream`'s sink pad. Throws `std::runtime_error` naming both pads if the link fails. | | `Element &unlink(Element &downstream, String src_pad = "src", String sink_pad = "sink")` | Unlinks the named pad pair between this element and `downstream`. | | `Element &unlink(String src_pad = "src")` | Unlinks whatever is connected to the given src pad, without naming the peer. | | `Element &sync()` | Synchronizes the element's state with its parent pipeline's state. Call this after adding an element to a pipeline that is already running. | | `Element &deactivate()` | Moves the element to `PAUSED`. | | `Element &stop()` | Moves the element to `NULL`. | | `Port input(unsigned int id)` | Returns the sink pad at the given index, for per-pad configuration. | | `Port input(String name_or_type, unsigned int id)` | Returns the sink pad matching a pad-template name and index. | | `Port output(unsigned int id)` | Returns the src pad at the given index. | | `Port output(String name_or_type, unsigned int id)` | Returns the src pad matching a pad-template name and index. | **Setting properties** `set()` is variadic, so a whole configuration can go in one call, and property names are validated immediately — an unknown property throws `std::invalid_argument` naming the property and the element type rather than being silently ignored: ```cpp theme={null} Element decoder("v4l2h264dec", "decoder"); decoder.set("output-io-mode", 4, "capture-io-mode", 4); ``` Besides the usual scalar types and strings, `set()` accepts a `StreamFilter` wherever an element takes a caps property, and plain enums (converted to their underlying integer): ```cpp theme={null} AppSrc appsrc("appsrc"); appsrc.set("caps", VideoFilter().format("NV12") .resolution(1920, 1080) .framerate(30)); ``` **Per-pad configuration with Port** Some elements are configured per pad rather than per element — a compositor's inputs each have their own position, size, and alpha. `input()` and `output()` return a `Port` for one pad, which carries the same fluent, validated `set()`: ```cpp theme={null} // Second input of qtivcomposer: blend at 50% alpha. pipeline.get("composer").input(1).set("alpha", 0.5); ``` | `qti::Port` | Description | | - | - | | `Port &set(String prop, Value value, ...)` | Sets one or more pad properties. Validated like `Element::set()`, and additionally accepts `std::vector` and `{a, b}` initializer lists for array-valued pad properties such as positions and dimensions. | The `id` selects which pad, and `name_or_type` narrows it to a pad template when an element has several families of pads. A template containing `%u` is formatted with the index (`"image_%u"` with `id` 0 gives `image_0`); otherwise the name and index are joined with an underscore (`"sink"` with `id` 1 gives `sink_1`). Without a name, the pad is matched by numeric suffix first and by position among same-direction pads second. An unresolvable pad throws `std::runtime_error`. > [!NOTE] > > A `Port` refers to a pad of a live element and cannot be copied, only moved. Get it, set the properties, and let it go — as in the one-liner above — rather than storing it beyond the lifetime of the element. **Runtime changes** Because `Pipeline::get()` returns an `Element` for any element in the pipeline, the same `set()` works while the pipeline is playing: ```cpp theme={null} pipeline.get("display").set("fullscreen", false); ``` `sync()`, `deactivate()`, and `stop()` exist for reconfiguring a live pipeline. An element added to an already-running pipeline starts in `NULL` while the pipeline is `PLAYING`, so it will not process data until its state is brought up to match — that is what `sync()` does. `deactivate()` and `stop()` take a single element down without touching the rest of the graph. > [!NOTE] > > Runtime relinking is an advanced use of the API. Pad linking, unlinking, and per-element state changes on a live pipeline must respect GStreamer's rules about when pads may be changed; the wrappers report failures as exceptions but do not remove the need to get the sequence right. ### AppSrc **Purpose** `AppSrc` wraps the `appsrc` element, the entry point for feeding application-produced buffers into a pipeline. It manages the `need-data`/`enough-data` signal plumbing so the application only has to supply buffers, either from a callback or by pushing them directly. **Key Responsibilities** * Validate that the wrapped element is indeed an `appsrc`. * Register and dispatch the underlying `need-data` and `enough-data` signals. * Let the application supply buffers on demand through `set_buffer_producer()`, or push them directly with `push_buffer()`. * Signal end-of-stream on this element's output. * Manage lifetime of the connected signal handlers. ```cpp theme={null} AppSrc appsrc("src"); appsrc.set("is-live", true) .set("block", true) .set("format", AppSrc::Format::TIME) .set("do-timestamp", true) .set("caps", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)); ``` | `qti::AppSrc` | Description | | - | - | | `AppSrc(const std::string &name = {})` | Creates an `appsrc` element with an optional instance name. | | `AppSrc &set(String prop, Value value, ...)` | Sets one or more properties, same as `Element::set()`. | | `AppSrc &set_buffer_producer(std::function producer)` | Registers a callback invoked whenever appsrc needs more data. Fill the buffer and return `true` to push it, `false` to skip this round. | | `AppSrc &set_enough_handler(std::function enough)` | Registers a callback invoked when appsrc reports it is holding enough queued data. | | `bool push_buffer(qti::Buffer &buffer)` / `bool push_buffer(qti::Buffer &&buffer)` | Pushes a buffer into the stream directly, outside the `need-data` callback. Returns `true` once it is accepted downstream. | | `void end_of_stream()` | Sends an end-of-stream event on this element's output. | `AppSrc::Format` mirrors appsrc's own `format` property (`DEFAULT`, `BYTES`, `TIME`, `BUFFERS`, `PERCENT`); `TIME`, used above, is the usual choice for timestamped media. > [!NOTE] > > `push_buffer()` transfers a buffer's underlying `GstBuffer` without copying when the `Buffer` already owns one — which is exactly the case for a buffer just pulled from an `AppSink`. A `Buffer` filled with raw data instead (as inside a `set_buffer_producer()` callback) is copied into a new `GstBuffer` on push. ### AppSink **Purpose** `AppSink` wraps the `appsink` element, the exit point that delivers pipeline output back to application code. It pulls samples through appsink's action signals and hands them to the application as `Buffer`. **Key Responsibilities** * Validate that the wrapped element is indeed an `appsink`. * Pull samples via appsink's action signals and convert them into `Buffer`. * Deliver each buffer to the application through `set_buffer_consumer()`. * Deliver the first (preroll) sample separately through `set_preroll_handler()`. * Notify the application of end-of-stream through `set_eos_handler()`. * Manage lifetime of the connected signal handlers. ```cpp theme={null} AppSink appsink("sink"); appsink.set("emit-signals", true) .set("max-buffers", 5) .set("drop", true) .set_buffer_consumer([](Buffer buf) { // consume buf.data(), buf.size(), buf.pts() }); ``` | `qti::AppSink` | Description | | - | - | | `AppSink(const std::string &name = {})` | Creates an `appsink` element with an optional instance name. | | `AppSink &set(String prop, Value value, ...)` | Sets one or more properties, same as `Element::set()`. | | `AppSink &set_buffer_consumer(std::function consumer)` | Registers a callback invoked for every buffer pulled from the pipeline. | | `AppSink &set_preroll_handler(std::function preroll)` | Registers a callback invoked for the first (preroll) sample only; return `false` to report an error instead of accepting it. | | `AppSink &set_eos_handler(std::function eos)` | Registers a callback invoked when appsink receives end-of-stream. | **Bridging two pipelines** Because `AppSink` and `AppSrc` are ordinary elements, they can sit in two independent `Pipeline` objects and be wired together in application code — useful when one graph produces frames (say, from a camera) and another consumes them (say, encoding or display) on its own clock: ```cpp theme={null} AppSrc appsrc("src"); appsrc.set("is-live", true) .set("block", true) .set("format", AppSrc::Format::TIME) .set("do-timestamp", true) .set("caps", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)); AppSink appsink("sink"); appsink.set("emit-signals", true) .set("max-buffers", 5) .set("drop", true) .set_buffer_consumer([&](Buffer b) { appsrc.push_buffer(std::move(b)); }); Pipeline pipeline1("p1"); pipeline1.add("videotestsrc", "testsrc", "is-live", true, "pattern", "ball") .add_stream_filter("videostream", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)) .add(appsink); Pipeline pipeline2("p2"); pipeline2.add(appsrc) .add("waylandsink", "display", "fullscreen", true); ``` Each buffer handed to `set_buffer_consumer()` on `pipeline1` is pushed straight into `pipeline2` through `appsrc.push_buffer()`, without a copy. ### CamSrc **Purpose** `CamSrc` wraps the `qtiqmmfsrc` camera source element and exposes its still/burst image-capture action signals as ordinary method calls, so an application can trigger a snapshot without touching GStreamer signals directly. **Key Responsibilities** * Validate that the wrapped element is indeed a `qtiqmmfsrc`. * Trigger still or burst image capture through `image_capture()`. * Cancel any pending capture request through `cancel_capture()`. | `qti::CamSrc` | Description | | - | - | | `CamSrc(const std::string &name = {})` | Creates a `qtiqmmfsrc` element with an optional instance name. | | `bool image_capture(unsigned int count = 1)` | Captures `count` still images. | | `bool image_capture(CaptureMode mode, unsigned int count = 1)` | Captures `count` images using `CaptureMode::kStill` or `CaptureMode::kBurst`. | | `bool image_capture(CaptureMode mode, unsigned int count, const std::vector &metadata_ptrs)` | Same as above, attaching a per-request metadata payload to each capture. | | `bool cancel_capture()` | Cancels any capture requests still pending. | A running pipeline built from a plain factory name still has a `qtiqmmfsrc` element in it; use `Pipeline::get()` to reach it as a `CamSrc` and call its capture API: ```cpp theme={null} auto cam = pipeline.get("source"); cam.image_capture(); ``` See `examples/test_camera_and_capture` for a complete pipeline that branches a `qtiqmmfsrc` into a live display and a `multifilesink` for captured images. ### MLVConverter **Purpose** `MLVConverter` wraps the `qtimlvconverter` element, which converts raw video frames into the input tensor format expected by a model. Beyond the properties available on the generic `Element`, it lets the application replace the built-in conversion with its own implementation through a lambda. **Key Responsibilities** * Validate that the wrapped element is a `qtimlvconverter`. * Convert incoming video frames into model input tensors. * Optionally delegate the conversion to an application-supplied pre-process callback. * Provide fluent, variadic property setting that returns `MLVConverter&` for chaining. **Pre-process callback** The callback receives the source frames as `MLVideoBlits` (each entry carries the image planes plus the source quadrilateral, destination rectangle, alpha and rotation) and must fill the tensors of the `MLFrame` output. Returning `false` marks the conversion as failed. ```cpp theme={null} using TensorsPreprocessCallback = std::function; ``` > [!NOTE] > > Set `engine` to `none` to disable the internal pre-processing path when you supply your own callback — otherwise the built-in conversion runs instead. **Usage** ```cpp theme={null} MLVConverter preprocessing("preprocessing"); // engine=none disables internal preprocessing path in qtimlvconverter. preprocessing.set("engine", "none"); preprocessing.set_handler( [](const MLVideoBlits& blits, MLFrame& output) { if (blits.entries.empty() || output.tensors.empty()) return false; const MLVideoBlit& blit = blits.entries.front(); return convert_nv12_to_nhwc_i8(blit.image, &blit, output.tensors.front()); }); pipeline.add(preprocessing); ``` | `qti::MLVConverter` | Description | | - | - | | `MLVConverter(const std::string &name = {})` | Creates a `qtimlvconverter` element with an optional instance name. | | `MLVConverter &set(String prop, Value value, ...)` | Sets one or more properties, same as `Element::set()`. | | `MLVConverter &set_handler(TensorsPreprocessCallback handler)` | Registers the external pre-process callback. Requires `engine=none` to take effect. | ### MLPostprocess **Purpose** `MLPostprocess` wraps the `qtimlpostprocess` element, which decodes model output tensors into ML metadata attached to the frame. It lets the application replace the built-in decoding module with its own implementation through a lambda. **Key Responsibilities** * Validate that the wrapped element is a `qtimlpostprocess`. * Decode output tensors into ML metadata (classifications, detections, poses, depth maps, segmentations), or pass the raw tensors through for a further stage. * Optionally delegate the decoding to an application-supplied post-process callback. * Select the callback type automatically from the lambda's third parameter. * Provide fluent, variadic property setting that returns `MLPostprocess&` for chaining. **Post-process callbacks** `set_handler()` is overloaded once per ML task. The overload is selected by the type of the third parameter of the callback, so the same method name registers any of the supported result types. Each callback receives the model output tensors as `MLFrame`, the element parameters as `MLParam`, and an output container to fill. Returning `false` marks the frame as failed. | Callback type | Signature | Output | | - | - | - | | `ClassificationPostprocessCallback` | `bool(const MLFrame&, const MLParam&, MLClassifications&)` | Class name, confidence, color | | `ObjectDetectionPostprocessCallback` | `bool(const MLFrame&, const MLParam&, MLDetections&)` | Bounding boxes, confidence, landmarks | | `PoseEstimationPostprocessCallback` | `bool(const MLFrame&, const MLParam&, MLPoses&)` | Keypoints and keypoint links | | `DepthEstimationPostprocessCallback` | `bool(const MLFrame&, const MLParam&, MLDepthMaps&)` | Per-cell depth values and colors | | `SegmentationPostprocessCallback` | `bool(const MLFrame&, const MLParam&, MLSegmentations&)` | Per-cell labels and colors | | `TensorsPostprocessCallback` | `bool(const MLFrame&, const MLParam&, MLFrame&)` | Raw output tensors, for daisy-chaining into a next stage | > [!TIP] > > Use `MLParam::get()` to read element parameters inside the callback. For example `params.get("input-tensor-region", region)` returns the `Region` the frame was scaled into, which is needed to map model coordinates back to frame coordinates. **Usage** ```cpp theme={null} static const std::vector labels = load_labels(HOME_PATH + "/labels/resnet101.json"); MLPostprocess postprocessing("postprocessing"); postprocessing .set("results", 1) .set_handler([](const MLFrame& frame, const MLParam& params, MLClassifications& classifications) { return decode_top1_classification(frame, params, labels, classifications, /*confidence_threshold=*/51.0f, ""); }); pipeline.add(postprocessing); ``` | `qti::MLPostprocess` | Description | | - | - | | `MLPostprocess(const std::string &name = {})` | Creates a `qtimlpostprocess` element with an optional instance name. | | `MLPostprocess &set(String prop, Value value, ...)` | Sets one or more properties, same as `Element::set()`. | | `MLPostprocess &set_handler(ClassificationPostprocessCallback handler)` | Registers a callback that decodes tensors into classifications. | | `MLPostprocess &set_handler(ObjectDetectionPostprocessCallback handler)` | Registers a callback that decodes tensors into detections. | | `MLPostprocess &set_handler(PoseEstimationPostprocessCallback handler)` | Registers a callback that decodes tensors into poses. | | `MLPostprocess &set_handler(DepthEstimationPostprocessCallback handler)` | Registers a callback that decodes tensors into depth maps. | | `MLPostprocess &set_handler(SegmentationPostprocessCallback handler)` | Registers a callback that decodes tensors into segmentations. | | `MLPostprocess &set_handler(TensorsPostprocessCallback handler)` | Registers a callback that produces raw output tensors, for chaining into another ML stage. | ### ML inference bins **Purpose** The ML video bins wrap a full pre-process → inference → post-process chain into a single element, so a whole AI branch can be added to the pipeline as one node instead of being assembled from separate elements and queues. Four bins are available, one per inference runtime: | QIM SDK C++ class | GStreamer element | Runtime | | - | - | - | | `MLVideoONNXBin` | `qtimlvideoonnxbin` | ONNX Runtime | | `MLVideoQNNBin` | `qtimlvideoqnnbin` | Qualcomm® AI Engine Direct (QNN) | | `MLVideoSNPEBin` | `qtimlvideosnpebin` | Snapdragon® Neural Processing Engine (SNPE) | | `MLVideoTFLiteBin` | `qtimlvideotflitebin` | LiteRT (TensorFlow Lite) | All four expose an identical API and differ only in the wrapped element and the runtime-specific properties. Each inherits from both the pre-process and the post-process base, so it accepts a custom pre-process callback, a custom post-process callback, or both. **Key Responsibilities** * Validate that the wrapped element matches the expected bin factory. * Run pre-processing, inference, and post-processing inside a single element. * Optionally delegate pre-processing to an application-supplied callback via `set_preprocess_handler()`. * Optionally delegate post-processing to an application-supplied callback via `set_postprocess_handler()`. * Provide fluent, variadic property setting that returns the concrete bin type for chaining. **Properties** Because the bin embeds several stages, its properties are prefixed by the stage they configure — `preprocess-*`, `inference-*`, and `postprocess-*`. For example `inference-model` on the bin corresponds to `model` on a standalone inference element, and `postprocess-labels` corresponds to `labels` on a standalone `qtimlpostprocess`. > [!NOTE] > > Set `preprocess-engine` to `none` to disable the internal pre-processing path when you supply your own pre-process callback. **Usage** **Custom post-processing** — the bin handles pre-processing and inference internally, the application decodes the output tensors. ```cpp theme={null} static const std::vector labels = load_labels(HOME_PATH + "/labels/yolov8.json"); MLVideoTFLiteBin mlbin("mlbin"); mlbin .set("inference-delegate", "external", "inference-external-delegate-path", "libQnnTFLiteDelegate.so", "inference-external-delegate-options", "QNNExternalDelegate,backend_type=htp;", "inference-model", HOME_PATH + "/models/yolov8_det_quantized.tflite") .set_postprocess_handler( [&](const MLFrame& frame, const MLParam& params, MLDetections& detections) { return decode_detection(frame, detections, params, labels, /*confidence_threshold=*/0.70f); }); Pipeline pipeline("mlbin-external-detection"); pipeline .add("filesrc", "src", "location", HOME_PATH + "/media/video.mp4") .add("qtdemux", "demux") .add("h264parse", "parse") .add("v4l2h264dec", "decoder", "output-io-mode", 4, "capture-io-mode", 4) .add_stream_filter("vf", VideoFilter().format("NV12")) .add(mlbin) .add("qtivoverlay", "overlay") .add("waylandsink", "display", "fullscreen", true); pipeline.execute(); ``` **Custom pre-processing** — the application converts frames into input tensors, the bin runs inference and its built-in post-process module. ```cpp theme={null} MLVideoTFLiteBin mlbin("mlbin"); // preprocess-engine=none disables internal preprocessing path in mlbin. mlbin.set("preprocess-engine", "none"); mlbin.set("inference-delegate", "external"); mlbin.set("inference-external-delegate-path", "libQnnTFLiteDelegate.so"); mlbin.set("inference-external-delegate-options", "QNNExternalDelegate,backend_type=htp;"); mlbin.set("inference-model", HOME_PATH + "/models/yolov8_det_quantized.tflite"); mlbin.set("postprocess-module", "yolov8"); mlbin.set("postprocess-labels", HOME_PATH + "/labels/yolov8.json"); mlbin.set_preprocess_handler( [](const MLVideoBlits& blits, MLFrame& output) { if (blits.entries.empty() || output.tensors.empty()) return false; const MLVideoBlit& blit = blits.entries.front(); return convert_nv12_to_nhwc_i8(blit.image, &blit, output.tensors.front()); }); ``` Swapping runtimes is a matter of changing the class and the runtime-specific properties; the callback registration is unchanged. ```cpp theme={null} MLVideoQNNBin qnn_bin("mlbin"); // qtimlvideoqnnbin MLVideoSNPEBin snpe_bin("mlbin"); // qtimlvideosnpebin MLVideoONNXBin onnx_bin("mlbin"); // qtimlvideoonnxbin ``` **APIs** The table below applies to each of `MLVideoONNXBin`, `MLVideoQNNBin`, `MLVideoSNPEBin`, and `MLVideoTFLiteBin`; substitute the concrete class name for ``. | `qti::` | Description | | - | - | | `(const std::string &name = {})` | Creates the corresponding `qtimlvideo*bin` element with an optional instance name. | | ` &set(String prop, Value value, ...)` | Sets one or more properties, same as `Element::set()`. Properties are stage-prefixed: `preprocess-*`, `inference-*`, `postprocess-*`. | | ` &set_preprocess_handler(TensorsPreprocessCallback handler)` | Registers the external pre-process callback. Requires `preprocess-engine=none` to take effect. | | ` &set_postprocess_handler(Callback handler)` | Registers the external post-process callback. Accepts the same task-specific callback types as `MLPostprocess::set_handler()`. | > [!NOTE] > > The bins cannot be copied, only moved — the same as the other element wrappers. ### Buffer **Purpose** Unified buffer abstraction over native GStreamer memory. Provides read/write access, timestamp metadata (pts, dts, duration), resize support, and zero-copy transfer between AppSink and AppSrc. **Key Responsibilities** * Own and manage mapping/unmapping of underlying `GstBuffer` or `GstSample`. * Provide read/write access to buffer memory. * Support resizing and writable allocation for AppSrc. * Carry timestamps (PTS/DTS/duration) and apply them back to `GstBuffer`. * Enable zero-copy extraction using `take_gst_buffer()`. ```cpp theme={null} appsink.set_buffer_consumer([](Buffer buf) { auto* data = buf.data(); auto pts = buf.pts(); }); ``` A `Buffer` arrives either from an `AppSink` — wrapping the sample the pipeline just produced — or is allocated by the application to be filled and pushed through an `AppSrc`. Which of the two it is determines whether the payload is writable: samples coming out of the pipeline are read-only. **APIs** | `qti::Buffer` | Description | | - | - | | `Buffer()` | Creates an empty wrapper, referencing no data. `valid()` returns `false` until it is filled. | | `Buffer(size_t size)` | Allocates a writable buffer with a payload of `size` bytes, for pushing into an `AppSrc`. | | `static Buffer from_readable_sample(void *gst_sample_opaque)` | Wraps an existing `GstSample` and exposes its payload and metadata as a `Buffer`. | | `uint8_t *data()` / `const uint8_t *data() const` | Returns a pointer to the payload. The non-const overload requires a writable buffer. | | `size_t size() const` | Returns the payload size in bytes. | | `void resize(size_t n)` | Resizes the payload storage. | | `void set_pts(uint64_t ns)` / `void set_dts(uint64_t ns)` / `void set_duration(uint64_t ns)` | Sets the presentation timestamp, decode timestamp, or duration, in nanoseconds. | | `uint64_t pts() const` / `uint64_t dts() const` / `uint64_t duration() const` | Reads the corresponding timestamp field, in nanoseconds. | | `bool is_writable() const` | Returns `true` when the underlying memory can be modified in place. | | `bool is_readonly() const` | Returns `true` when the buffer came from an `AppSink` and its memory cannot be modified. | | `bool valid() const` | Returns `true` when the wrapper currently references valid data. | | `void *take_gst_buffer()` | Transfers ownership of the underlying `GstBuffer` to the caller and clears this wrapper. This is the zero-copy hand-off path used by `AppSrc::push_buffer()`. | | `void refill_for_appsrc(size_t n)` | Prepares the buffer's storage for reuse inside an `AppSrc` producer callback, resizing it to `n` bytes. | > [!NOTE] > > Like the element wrappers, a `Buffer` cannot be copied, only moved — ownership of the underlying memory is unique. Pass it by reference, or `std::move()` it where ownership has to change, as in the `AppSink` → `AppSrc` bridge above. ### StreamFilter **Purpose** StreamFilter describes the characteristics of a media stream between two pipeline stages so they can negotiate concrete parameters rather than relying on defaults. Without explicit parameters, adjacent components may fall back to suboptimal formats, trigger implicit conversions, or produce mismatched configurations. Specialized subtypes provide fluent, type-safe setters for each domain. Raw caps strings are also accepted for cases not covered by typed setters or when copying directly from gst-launch output. **When to Use StreamFilter** * When two adjacent stages can interoperate in multiple ways, and you want to select explicit parameters instead of relying on defaults. * When you need to optimize latency or performance by avoiding implicit conversions (e.g., choose a hardware-friendly pixel format). * When you want predictable behavior across platforms (e.g., lock color range/primaries/transfer/matrix). * When you integrate tensors for AI/ML and must precisely specify dimensions and element types. * When you need a human-readable summary of the stream parameters for logs and debugging. A `StreamFilter` is not an `Element` and is never added to a pipeline with `add()`. It is always attached between stages with `Pipeline::add_stream_filter(unique_name, filter)`, which internally creates a `capsfilter` element and applies the filter's caps to it. The base `StreamFilter` class itself only exposes a raw-caps-string constructor and `to_string()`; the fluent per-domain setters (`.format()`, `.resolution()`, `.framerate()`, ...) live on the typed subclasses such as `VideoFilter`. **Usage** **Typed subclass** ```cpp theme={null} Pipeline pipeline("video-pipeline"); pipeline.add("videotestsrc", "src", "pattern", "ball") .add_stream_filter("filter", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)) .add("waylandsink", "sink") .execute(); ``` **Raw caps string** ```cpp theme={null} Pipeline pipeline("video-pipeline-streamfilter-string"); pipeline.add("videotestsrc", "src", "pattern", "ball") .add_stream_filter("filter", qti::StreamFilter( "video/x-raw,format=NV12,width=1920,height=1080,framerate=30/1")) .add("waylandsink", "sink") .execute(); ``` **APIs** | `qti::StreamFilter` | Description | | - | - | | `StreamFilter()` | Creates an empty filter expression. | | `StreamFilter(const std::string &caps_or_mediatype)` | Creates a filter from a raw caps or media-type string, e.g. `"video/x-raw,format=NV12"`. | | `std::string to_string() const` | Serializes the current filter expression to a caps string, for logging/debugging. | ### VideoFilter **Purpose** Configures a raw video stream (YUV, RGB, Bayer) between a camera source and any downstream processing or display element. Supports format, resolution, framerate, colorimetry, interlace mode, and pixel aspect ratio. **Key Responsibilities** * Produce caps with standard raw video attributes: format, resolution, framerate, colorimetry, interlace mode, pixel aspect ratio, etc. **APIs** | Member | Description | | - | - | | `format(const std::string &fmt)` / `format(Format fmt)` | Sets the stream's pixel format, for example `NV12`, `YUY2`, `RGB`, `RGBA`. Determines how pixel data is laid out in memory; essential for hardware compatibility and color-conversion paths. Accepts a string or a `VideoFilter::Format` enumerator. | | `resolution(int width, int height)` | Specifies the frame dimensions in pixels. | | `framerate(int num, int den = 1)` / `framerate(float num)` | Sets the frame rate as a fraction, for example `30/1` or `30000/1001` frames-per-second. Pass a single value when you do not need a fractional frame rate, like `30.0` fps. | | `colorimetry(const std::string &value)` | Defines the colorimetry standard, for example `bt601`, `bt709`, `bt2020`. | | `range(const std::string &value)` | Selects the quantization range, `full` or `limited`. | | `interlace(const std::string &mode)` | Sets the interlacing mode, for example `progressive` or `interleaved`. Progressive is standard for modern pipelines; interlaced is still used in some camera/legacy systems. | | `pixel_aspect_ratio(int num, int den = 1)` | Specifies the pixel aspect ratio, also called PAR. Normally `1/1`; used for anamorphic or non-square-pixel formats. | | `add(const std::string &expr)` | Appends an arbitrary custom caps field using a `key=value` expression. Escape-hatch for advanced/experimental fields not covered by the typed API. | `VideoFilter::Format` enumerates the raw video formats (`video/x-raw`), `JPEG` (`image/jpeg`), and the Bayer patterns (`video/x-bayer`: `BGGR`, `RGGB`, `GBRG`, `GRBG`, `MONO`). **Usage** We can achieve the same results in three different ways: **Typed (enum) API** - if you want compile-time safety, IDE autocompletion, and guardrails against typos. Ideal for SDK consumers and most production code. ```cpp theme={null} auto v1 = VideoFilter() .format(VideoFilter::Format::NV12) .resolution(1920, 1080) .framerate(30) .colorimetry("bt709") .range("limited") .interlace("progressive"); ``` **String API** - if you need quick iteration or to pass values not (yet) covered by enums — e.g., enabling a freshly added GStreamer value on a target platform without immediately updating headers. ```cpp theme={null} auto v2 = VideoFilter() .format("NV12") .resolution(1920, 1080) .framerate(30) .colorimetry("bt709") .range("limited") .interlace("progressive"); ``` **Raw caps string** - very useful for setting arbitrary stream (caps) filter or you want to lift an existing caps line from logs, gst-launch, or a pad template and drop it as-is — great for debugging, prototyping, or reproducing pipelines exactly. ```cpp theme={null} auto v3 = StreamFilter("video/x-raw,format=NV12,width=1920,height=1080,framerate=30/1,colorimetry=bt709,range=limited"); ``` ### H264Filter **Purpose** Configures an encoded H.264 stream between an encoder and a downstream parser or muxer. Supports resolution, framerate, stream-format, alignment, profile, and level. **Key Responsibilities** * Specify resolution, framerate, stream-format, alignment, profile, level. * Insert `codec_data` buffers. * Attach arbitrary name/value string properties. **APIs** | Member | Description | | - | - | | `resolution(int width, int height)` | Specifies the frame dimensions in pixels. | | `framerate(int num, int den = 1)` / `framerate(float num)` | Sets the frame rate as a fraction, or as a single value when a fractional rate is not needed. | | `profile(const std::string &p)` | Sets the H.264 profile caps field, for example `baseline`, `main`, `high`. | | `level(const std::string &lvl)` | Sets the H.264 level caps field. | | `stream_format(const std::string &f)` | Sets the H.264 stream-format caps field, for example `byte-stream`, `avc`. | | `alignment(const std::string &a)` | Sets the H.264 alignment caps field, for example `au`, `nal`. | | `codec_data(const std::string &bytes)` | Sets the H.264 `codec_data` caps field from a byte string. | | `set(const std::string &key, const std::string &val)` | Shorthand for `add(key + "=" + val)`. | | `add(const std::string &expr)` | Appends an arbitrary custom caps field using a `key=value` expression. | **Usage** ```cpp theme={null} auto h264f = H264Filter().resolution(1920, 1080) .framerate(30) .profile("baseline") .stream_format("byte-stream") .alignment("au"); Pipeline pipeline("h264-pipeline"); pipeline.add_stream_filter("h264f", h264f); ``` ### TensorFilter **Purpose** Configures an ML tensor stream with explicit data type and shape (e.g., UINT8, NHWC). Not needed in a full inference pipeline — when preprocess, inference, and postprocess elements are all present, tensor parameters are negotiated automatically. Use TensorFilter when: * The preprocessing stage does not have model dimension information * You need exact tensor data output from the inference plugin **Key Responsibilities** * Declare element type (e.g., `UINT8`, `FLOAT32`) for tensors. * Specify shape (dimensions). Supports: * Single tensor: a 1D list (e.g., `1, 520, 520, 3`). * Multiple tensors: array-of-arrays (e.g., `{ {1,3,H,W}, {1,32} }`) when needed. **APIs** | Member | Description | | - | - | | `type(const std::string &t)` / `type(Type t)` | Specifies the tensor data type, for example `UINT8` or `FLOAT32`. Accepts a string or a `TensorFilter::Type` enumerator (`UINT8`, `UINT16`, `UINT32`, `INT8`, `INT16`, `INT32`, `FLOAT16`, `FLOAT32`). | | `dimensions(UInts... dims)` | Specifies a single tensor's dimensions as a variadic list of integers, for example `dimensions(1, 520, 520, 3)`. | | `dimensions(const std::vector &one_tensor_dims)` | Specifies a single tensor's dimensions as a vector. | | `dimensions(const std::vector> &many_tensors_dims)` | Specifies several tensors at once, one inner vector per tensor. | | `add(const std::string &expr)` | Appends an arbitrary custom caps field using a `key=value` expression. Escape-hatch for advanced/experimental fields not covered by the typed API. | **Usage** We can achieve the same results in three different ways: **Typed (enum) API** - if you want compile-time safety, IDE autocompletion, and guardrails against typos. Ideal for SDK consumers and most production code. ```cpp theme={null} auto t1 = TensorFilter() .type(TensorFilter::Type::UINT8) .dimensions(1, 520, 520, 3); // NHWC, for example ``` **String API** - if you need quick iteration or to pass values not (yet) covered by enums — e.g., enabling a freshly added GStreamer value on a target platform without immediately updating headers. ```cpp theme={null} auto t2 = TensorFilter() .type("FLOAT32") .dimensions(1, 3, 640, 640); // NCHW, for example ``` **Raw caps string** - very useful for setting arbitrary stream (caps) filter or you want to lift an existing caps line from logs, gst-launch, or a pad template and drop it as-is — great for debugging, prototyping, or reproducing pipelines exactly. ```cpp theme={null} auto t3 = StreamFilter("neural-network/tensors,type=UINT8,dimensions=<<1,520,520,3>>"); ``` ### TextFilter **Purpose** Configures a raw text stream (text/x-raw) for pipelines that carry textual data such as metadata, subtitles, or logs. Minimal by design — attach only the fields you need using .add("key=value"). **Key Responsibilities** * Provide a lightweight caps descriptor for text (`text/x-raw`) without enforcing a schema. * Let callers attach arbitrary properties (e.g., encoding/charset, language, packetization hints) using `.add("key=value")`. **APIs** | Member | Description | | - | - | | `add(const std::string &expr)` | Appends an arbitrary custom caps field using a `key=value` expression. Escape-hatch for advanced/experimental fields not covered by the typed API. | **Usage** ```cpp theme={null} auto txt = TextFilter().add("charset=utf8"); ``` ### ImageFilter **Overview** Used exclusively with CamSrc (qtiqmmfsrc) to enable and link its dedicated image capture pad. Without ImageFilter, the image pad is not requested, not activated, and produces no buffers. It is a structural enabler, not a processing stage — it is not intended for general image processing or frame extraction from video sources. `ImageFilter` is used to: * Enable the image output pad exposed by `CamSrc` (`qtiqmmfsrc`) * Attach that pad to the pipeline so the source can activate image capture * Provide a concrete sink target required by GStreamer for pad activation It is not intended for: * Generic image processing * Frame extraction from arbitrary video sources * Replacement of `VideoFilter` or `AppSink` **Relationship to CamSrc (qtiqmmfsrc)** * `CamSrc` (`qtiqmmfsrc`) exposes a dedicated image pad that remains inactive unless linked. * `ImageFilter` explicitly exists to satisfy this requirement. * Without `ImageFilter`, the image pad: * Will not be requested * Will not be activated * Will not produce buffers This makes `ImageFilter` a structural enabler, not a processing stage. **APIs** | Member | Description | | - | - | | `format(const std::string &fmt)` | Sets the image format for the capture pad, for example `JPEG`. | | `resolution(int width, int height)` | Specifies the captured image dimensions in pixels. | | `framerate(int num, int den = 1)` / `framerate(float num)` | Sets the capture pad's frame rate. | | `add(const std::string &expr)` | Appends an arbitrary custom caps field using a `key=value` expression. | **Usage** ```cpp theme={null} auto imagefilter1 = ImageFilter() .format("JPEG") .resolution(3840, 2160); ``` ### AudioFilter **Purpose** Configures a raw PCM audio stream with sample format, channel count, sample rate, and layout. Use this to ensure audio converters and sinks negotiate exactly the format your hardware supports rather than inserting an implicit resampler. **Key Responsibilities** * Set audio sample format (e.g., `S16LE`, `F32LE`) to match HW/SW capabilities. * Define channels and rate for correct resampling/mixing. * Choose layout (`interleaved` vs `non-interleaved`) to align with downstream expectations. **APIs** | Member | Description | | - | - | | `format(const std::string &fmt)` / `format(Format f)` | Sets the audio sample format, for example `S16LE`, `F32LE`. Accepts a string or an `AudioFilter::Format` enumerator. | | `channels(int n)` | Specifies the number of audio channels. | | `rate(int hz)` | Specifies the audio sample rate in Hz. | | `layout(const std::string &l)` / `layout(Layout l)` | Specifies the audio layout. Accepts a string or `AudioFilter::Layout::INTERLEAVED` / `NON_INTERLEAVED`. | | `add(const std::string &expr)` | Appends an arbitrary custom caps field using a `key=value` expression. Escape-hatch for advanced/experimental fields not covered by the typed API. | `AudioFilter::Format` covers the signed/unsigned integer formats (`S8` through `U32BE`, including the packed 18/20/24-bit variants) and the float formats `F32LE`, `F32BE`, `F64LE`, `F64BE`. **Usage** We can achieve the same results in three different ways: **Typed (enum) API** - if you want compile-time safety, IDE autocompletion, and guardrails against typos. Ideal for SDK consumers and most production code. ```cpp theme={null} auto a1 = AudioFilter() .format(AudioFilter::Format::S16LE) .rate(48000) .channels(2) .layout(AudioFilter::Layout::INTERLEAVED); ``` **String API** - if you need quick iteration or to pass values not (yet) covered by enums — e.g., enabling a freshly added GStreamer value on a target platform without immediately updating headers. ```cpp theme={null} auto a2 = AudioFilter() .format("F32LE") .rate(44100) .channels(1) .layout("non-interleaved"); ``` **Raw caps string** - very useful for setting arbitrary stream (caps) filter or you want to lift an existing caps line from logs, gst-launch, or a pad template and drop it as-is — great for debugging, prototyping, or reproducing pipelines exactly. ```cpp theme={null} auto a3 = StreamFilter("audio/x-raw,format=S16LE,rate=48000,channels=2,layout=interleaved"); ``` ### Logging The SDK can either simplify GStreamer's log stream into a compact, uniform format or step aside and let GStreamer log raw, with `GST_DEBUG` fully in control. Both modes, the verbosity levels, and the ordering constraint on configuring them are covered in [Logging and Diagnostics](/app-builder/cpp-logging). ## QIM SDK Nodes All nodes are executed by GStreamer elements under the hood. Most elements are handled through the `Element` base class. However, elements that provide additional functionality — such as application buffer interfaces in appsink and appsrc, or image-capture signals in camera sources like `qtiqmmfsrc` — require extended interfaces. If you do not need these extra capabilities (for example, image capture), you can still use these elements via the generic `Element` base class without any limitations for standard data processing. Below is a table listing all supported elements and the corresponding QIM SDK wrapper classes used to work with them. **Sources** | GStreamer | QIM SDK C++ Class | | - | - | | `qtiqmmfsrc` | `qti::CamSrc` (also usable as `qti::Element`) | | `v4l2src` | `qti::Element` | | `filesrc` | `qti::Element` | | `multifilesrc` | `qti::Element` | | `appsrc` | `qti::AppSrc` | | `appsink` | `qti::AppSink` | | `qtisocketsrc` | `qti::Element` | **AI** | GStreamer | QIM SDK C++ Class | | - | - | | `qtimlaconverter` | `qti::Element` | | `qtimlvconverter` | `qti::MLVConverter` (also usable as `qti::Element`) | | `qtimlqnn` | `qti::Element` | | `qtimlsnpe` | `qti::Element` | | `qtimltflite` | `qti::Element` | | `qtimlpostprocess` | `qti::MLPostprocess` (also usable as `qti::Element`) | | `qtimlvideoonnxbin` | `qti::MLVideoONNXBin` (also usable as `qti::Element`) | | `qtimlvideoqnnbin` | `qti::MLVideoQNNBin` (also usable as `qti::Element`) | | `qtimlvideosnpebin` | `qti::MLVideoSNPEBin` (also usable as `qti::Element`) | | `qtimlvideotflitebin` | `qti::MLVideoTFLiteBin` (also usable as `qti::Element`) | | `qtimlaic` | `qti::Element` | | `qtimetamux` | `qti::Element` | | `qtimlmetaextractor` | `qti::Element` | | `qtimlmetaparser` | `qti::Element` | | `qtimldemux` | `qti::Element` | | `qtimetatransform` | `qti::Element` | | `mlonnx` | `qti::Element` | **Multimedia** | GStreamer | QIM SDK C++ Class | | - | - | | `qtiobjtracker` | `qti::Element` | | `qtismartvencbin` | `qti::Element` | | `qtivoverlay` | `qti::Element` | | `qtivsplit` | `qti::Element` | | `qtivcomposer` | `qti::Element` | | `qtibatch` | `qti::Element` | | `qticamreproc` | `qti::Element` | | `qtic2adec` | `qti::Element` | | `qtic2aenc` | `qti::Element` | | `qtic2vdec` | `qti::Element` | | `qtic2venc` | `qti::Element` | | `qtijpegenc` | `qti::Element` | | `qtivtransform` | `qti::Element` | | `qticvimgpyramid` | `qti::Element` | | `qticvoptclflow` | `qti::Element` | | `qtidfs` | `qti::Element` | | `v4l2h264dec` | `qti::Element` | | `v4l2h264enc` | `qti::Element` | | `v4l2h265dec` | `qti::Element` | | `v4l2h265enc` | `qti::Element` | | `tee` | `qti::Element` | | `h264parse` | `qti::Element` | | `rtpptdemux` | `qti::Element` | | `rtph264depay` | `qti::Element` | | `queue` | `qti::Element` | | `qtdemux` | `qti::Element` | | `tsdemux` | `qti::Element` | ## Common Application Design ### Create pipeline with config file The SDK supports fully declarative pipeline construction using YAML. A YAML pipeline describes elements and links between them, which are translated at runtime into a GStreamer pipeline. **TopLevel Structure** A YAML pipeline file has a single top-level key: ```yaml theme={null} pipeline: elements: [...] links: [...] ``` **Elements Section** `elements` is an ordered list of pipeline elements. Each element entry defines: * The GStreamer element type * A unique name used for linking * Optional properties * Optional filter configuration **Common Fields** ```yaml theme={null} - type: name: : ``` * `type`: GStreamer element factory name, or `filter` * `name`: Unique identifier within the pipeline * properties: Any remaining key/value pairs are passed directly to the element as GStreamer properties **Filter Elements** Filters are declared using `type: filter` and are further specialized by their configuration block. **Stream Filter** ```yaml theme={null} - type: capsfilter name: raw_caps caps: "video/x-raw,format=NV12,width=1280,height=720,framerate=30/1" ``` **Video Filter** ```yaml theme={null} - type: filter name: vf video: format: NV12 width: 1920 height: 1080 framerate: 30 ``` **Links Section** `links` defines explicit connection paths between elements. Each entry is an ordered list of element names. Elements are linked sequentially from left to right. ```yaml theme={null} links: - [src, demux, parse, decoder, vf, split] ``` **Example yaml files** **YAML config file** ```yaml theme={null} pipeline: elements: - type: qtiqmmfsrc name: source camera: "0" - type: filter name: filter video: format: NV12 width: 1920 height: 1080 framerate: 30.0 - type: tee name: split - type: qtimlvconverter name: preprocessing - type: qtimltflite name: inferencing delegate: gpu model: /etc/models/model.tflite - type: qtimlpostprocess name: postprocessing - type: qtimetamux name: mlmuxer - type: qtivoverlay name: overlay - type: waylandsink name: display sync: true async: true fullscreen: true links: - [source, filter, split, preprocessing, inferencing, postprocessing, mlmuxer, overlay, display] - [split, mlmuxer] ``` ### Multi-Model Daisy Chain Below is shown a logical diagram of an AI daisy chain pipeline with sequential and parallel inferencing. The same could be handled by a straight sequential pipeline of inference bins. But we must set manually the source for every inference bin. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/ai_daisy_chain.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=34d7ff5c88a84de892097767fa85ab23) > **Try me** > > > [!NOTE] > > > > Several `.add(...)` calls in this example had missing/mismatched quotes in the source PDF (e.g. a stray closing paren instead of a closing quote, or a missing leading quote). These have been corrected below where unambiguous. One inline comment truncated at the page margin was completed using the identical sentence found in the prose above. > > ```cpp theme={null} > Element ml_car("qtimlvideotflitebin", "car") > .add("performance-profile", "high-performance") > .add("inference-delegate", "dsp") > .add("inference-model", "/opt/car_detect.dlc") > .add("inference-layers", "< /model.22/Mul_2, /model.22/Sigmoid >") > .add("postprocess-threshold", 60.0) > .add("postprocess-results", 4) > .add("postprocess-module", "yolov8") > .add("postprocess-labels", "/opt/car_detect_model.labels"); > // The same could be handle by straight sequential pipeline of inference bins. But we must set manually source to every inference bin. > > Element ml_plate("qtimlvideotflitebin", "plated") > .add("source", 1) > .add("image-disposition", "centre") > .add("performance-profile", "high-performance") > .add("inference-delegate", "dsp") > .add("inference-model", "/opt/plate_detect.dlc") > .add("inference-layers", "< /model.22/Mul_2, /model.22/Sigmoid >") > .add("postprocess-threshold", 40.0) > .add("postprocess-results", 1) > .add("postprocess-module", "yolov8") > .add("postprocess-labels", "/opt/plate_detect_model.labels"); > > Element ml_anpr("qtimlvideotflitebin", "anpr") > .add("source", 2) > .add("image-disposition", "centre") > .add("inference-delegate", "dsp") > .add("inference-model", "/opt/anpr.dlc") > .add("inference-layers", "< /decode_head2/classifier/Conv, /decode_head/classifier/Conv >") > .add("postprocess-threshold", 15.0) > .add("postprocess-results", 1) > .add("postprocess-module", "anpr") > .add("postprocess-labels", "/opt/anpr_model.labels"); > > Element ml_siglip("qtimlvideotflitebin", "siglip") > .add("source", 1) > .add("image-disposition", "centre"); > .add("inference-delegate", "dsp"); > .add("inference-model", "/opt/car_make_model.dlc"); > .add("inference-layers", "< /classifier/Gemm >"); > .add("postprocess-threshold", 15.0); > .add("postprocess-results", 1); > .add("postprocess-module", "mobilenet"); > .add("postprocess-labels", "/opt/car_make_model.labels"); > > Pipeline pipeline("SmartVehicleIdentification"); > pipeline.add("camsrc", "source", "camera", "0") > .add_stream_filter("filter", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)) > .add(ml_car) > .add(ml_plate) > .add(ml_anpr) > .add(ml_siglip) > .add("qtivoverlay", "overlay") > .add("waylandsink", "display", "sync", "true", "async", "true", "fullscreen") > .execute(); > ``` ### Custom Postprocessing with YOLOv8 (Detection) QIM SDK implements AI model post-processing through dedicated modules that take tensors as input and produce predictions. All remaining complexity — such as batching, daisy-chaining, image mask support — is encapsulated within the post-processing plugin. This makes the post-processing module API an ideal integration point for application-specific post-processing logic. As a result, applications do not need to handle batching, chaining, image masks, or ML metadata themselves. We will implement a specialized post-processing module to manage bindings with the application. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/custom_post.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=e58d0809d197ae3c2aa92815907df9fa) Custom postprocessing callback is attached to a [`qtimlpostprocess`](/plugin-reference/qtimlpostprocess) element via [`MLPostprocess::set_handler(...)`](/plugin-reference/qtimlpostprocess). Typical pipeline segment: 1. Preprocess frame/tensors ([`qtimlvconverter`](/plugin-reference/qtimlvconverter)) 2. Run ML inference ([`qtimltflite`](/plugin-reference/qtimltflite)) 3. Convert raw tensors in custom callback ([`qtimlpostprocess`](/plugin-reference/qtimlpostprocess)) **Supported callback types** * `ClassificationPostprocessCallback` * `ObjectDetectionPostprocessCallback` * `PoseEstimationPostprocessCallback` * `DepthEstimationPostprocessCallback` * `SegmentationPostprocessCallback` * `TensorsPostprocessCallback` **Minimal usage** ```cpp theme={null} MLPostprocess postprocessing("postprocessing"); postprocessing.set_handler(my_callback); pipeline.add("qtimltflite", "inferencing", ...) .add(postprocessing) .add_stream_filter("mlf", TextFilter()) ...; ``` **Input and output explained** `MLFrameView` (read-only model tensors) Used by classification/detection/pose/depth/segmentation callbacks. Each `TensorView` contains: * `type`: tensor element type (`MLTensorType`) * `dimensions`: tensor shape * `data`: raw tensor memory (`const uint8_t*`) * `size`: tensor bytes Common access pattern: ```cpp theme={null} const auto& t = frame.tensors[0]; const float* data = static_cast(t.data); ``` `MLParam` (runtime metadata and context) `MLParam` carries key/value fields provided by pipeline and preprocessing/postprocess context. Commonly used keys: * `input-tensor-width` * `input-tensor-height` * `input-tensor-region` (mapped to `Region {x, y, width, height}`) Example: ```cpp theme={null} float source_width = 0.0f; float source_height = 0.0f; Region region; params.get("input-tensor-width", source_width); params.get("input-tensor-height", source_height); params.get("input-tensor-region", region); ``` **Callback signatures** * Callbacks (`ClassificationPostprocessCallback`, `ObjectDetectionPostprocessCallback`, `PoseEstimationPostprocessCallback`, `DepthEstimationPostprocessCallback`, `SegmentationPostprocessCallback`) fill the provided output metadata container (`MLClassifications`, `MLDetections`, `MLPoses`, `MLDepthMaps`, `MLSegmentations`). * Tensor callback (`TensorsPostprocessCallback`) fills `MLFrame& output` for downstream tensor stages. * Input `MLFrameView` is read-only and must not be modified. **Classification callback** ```cpp theme={null} using ClassificationPostprocessCallback = std::function; ``` Output: fill `MLClassifications` with `MLClassification` items. Field meanings: * `name`: class label text * `confidence`: prediction confidence * `color`: optional UI/overlay color * `extra`: optional metadata map **Object detection callback** ```cpp theme={null} using ObjectDetectionPostprocessCallback = std::function; ``` Output: fill `MLDetections` with `MLDetection` items. Field meanings: * `left`, `top`, `right`, `bottom`: normalized box coordinates * `name`, `confidence`, `color`: class info * `landmarks`: optional keypoints * `extra`: optional metadata map Implemented example includes confidence thresholding, region coordinate transform, and NMS. **Segmentation callback** ```cpp theme={null} using SegmentationPostprocessCallback = std::function; ``` Input parameters * `frame` (`const MLFrameView&`): read-only model output tensors. * `params` (`const MLParam&`): runtime metadata (for example: `input-tensor-width`, `input-tensor-height`, `input-tensor-region`). * `segmentations` (`MLSegmentations&`): output container to fill. Output contract (`MLSegmentation`) * `labels`: per-pixel semantic labels. * `colors`: per-pixel colors; index-aligned with `labels`. * `n_rows`, `n_columns`: segmentation map dimensions. * `extra`: optional metadata fields. **Pose estimation callback** ```cpp theme={null} using PoseEstimationPostprocessCallback = std::function; ``` Output: fill `MLPoses` with `MLPose` items. Field meanings: * `keypoints`: list of `MLKeypoint` (`name`, `x`, `y`, `confidence`, `color`) * `links`: list of `MLKeypointLink` describing skeleton connections * `name`, `confidence`, `extra`: pose-level metadata **Depth estimation callback** ```cpp theme={null} using DepthEstimationPostprocessCallback = std::function; ``` Output: fill `MLDepthMaps` with one or more `MLDepthMap` items. Field meanings: * `values`: per-pixel depth values (`double`) * `colors`: per-pixel pseudo-color values (`uint32_t`) * `n_rows`, `n_columns`: depth map shape * `extra`: optional metadata map **Tensor-to-tensor callback** ```cpp theme={null} using TensorsPostprocessCallback = std::function; ``` output is owned and writable; callback typically: 1. validates input tensors from `frame` 2. copies/selects required tensors into output 3. updates output tensor dimensions/order if needed **Semantic callbacks** (`classification`, `detection`, `pose`, `depth`, `segmentation`) ```cpp theme={null} bool callback(const MLFrameView& frame, const MLParam& params, OutputType& output) ``` * `frame`: input tensors from inference (read-only) * `params`: runtime metadata (input sizes, region, etc.) * `output`: semantic objects to be filled by callback * return `true` on valid output * return `false` on validation/decode failure **Tensor callback** ```cpp theme={null} bool callback(const MLFrameView& frame, const MLParam& params, MLFrame& output) ``` * `frame`: input tensors from inference (read-only) * `params`: runtime metadata/context * `output`: writable output tensors for downstream tensor stage * return `true` on valid output * return `false` on validation/decode failure **Copy-ready callback skeletons** Classification ```cpp theme={null} ClassificationPostprocessCallback cb = [](const MLFrameView& frame, const MLParam& params, MLClassifications& out) { // decode tensors -> classes return true; }; ``` Detection ```cpp theme={null} ObjectDetectionPostprocessCallback cb = [](const MLFrameView& frame, const MLParam& params, MLDetections& out) { // decode tensors -> detections return true; }; ``` Pose estimation ```cpp theme={null} PoseEstimationPostprocessCallback cb = [](const MLFrameView& frame, const MLParam& params, MLPoses& out) { // decode tensors -> poses return true; }; ``` Depth estimation ```cpp theme={null} DepthEstimationPostprocessCallback cb = [](const MLFrameView& frame, const MLParam& params, MLDepthMaps& out) { // decode tensors -> depthmaps return true; }; ``` Segmentation ```cpp theme={null} SegmentationPostprocessCallback cb = [](const MLFrameView& frame, const MLParam& params, MLSegmentations& out) { // decode tensors -> segmentations return true; }; ``` Tensors ```cpp theme={null} TensorsPostprocessCallback cb = [](const MLFrameView& frame, const MLParam& params, MLFrame& output) { // map/copy selected tensors from frame -> output return true; }; ``` > **Try me** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_external_postprocess_detection_yolov8`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_external_postprocess_detection_yolov8) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_external_postprocess_detection_yolov8` > > #### Download Required Files > > | File | Save as | > | - | - | > | [Model](https://aihub.qualcomm.com/iot/models/yolov8_det) | yolov8\_det\_quantized.tflite | > | [yolov8.json](../labels/yolov8.json) | yolov8.json | > | [ai\_demo\_sample.mp4](https://github.com/qualcomm/sample-apps-for-qualcomm-linux/blob/main/qualcomm-linux/artifacts/videos/demo_samples/ai_demo_sample.mp4) | ai\_demo\_sample.mp4 | > > > [!NOTE] > > > > If the downloaded model file is a `.zip` archive, extract it on your host machine before copying: `unzip filename.zip` > > > > Some AI Hub models require running the AI Hub export/optimize step for your target runtime before the downloaded file is usable — download alone isn't always sufficient. > > **1. Copy Files to Device** > > ```bash SCP (SSH) theme={null} > # Replace and with your device credentials. > # ~ resolves automatically to the correct home directory on the device (/root on QLI, /home/ubuntu on Ubuntu). > > ssh @ "mkdir -p ~/Downloads/qimsdk_samples/{models,labels,media}" > scp yolov8_det_quantized.tflite @:~/Downloads/qimsdk_samples/models/ > scp yolov8.json @:~/Downloads/qimsdk_samples/labels/ > scp ai_demo_sample.mp4 @:~/Downloads/qimsdk_samples/media/ > ``` > > **2. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_external_postprocess_detection_yolov8 > ``` > > The application runs inference on the video file and uses the custom, application-defined postprocessing callback to decode detections, which are then overlaid and displayed fullscreen. > > To stop the application, press **CTRL + C**. # Coding Agent Source: https://imsdkdocs.qualcomm.com/app-builder/cpp-coding-agent Use the QIM SDK C++ App Builder skill to generate C++ pipeline apps with an AI coding agent. ## What is the C++ App Builder Skill? The **QIM SDK C++ App Builder** is an AI coding skill that generates C++ applications using the `QIM SDK C++ API`. You describe the pipeline behavior and configuration in natural language, and the agent produces a ready-to-build `main.cc` and `CMakeLists.txt` built on the `QIM SDK C++ API` — along with a `README.md` that documents the information about the generated application. **Flow** ![QIM SDK coding agent workflow](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/qimsdk-coding-agent-flow.jpg?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=23b4e6ec57deb071b36a9ce0b39c01e8) **What it generates** For each request, the agent produces an artifact folder named `qimsdk-cpp-/` containing: * **`main.cc`** — a complete, buildable C++ application using the QIM SDK C++ API, including pipeline construction, element wiring, stream filters, and ML inference configuration * **`CMakeLists.txt`** — the build script that compiles `main.cc` and links against `qimsdk-app-builder` * **`README.md`** — a detailed document covering: * Purpose and pipeline behavior summary * Configuration placeholders (input, model, labels, output paths) * A step-by-step pipeline flow (text summary + Mermaid diagram) * Steps to compile and run the app on device * **`A YAML config file`** — only when you request declarative YAML pipeline mode **Supported use cases:** | Category | Details | | - | - | | **AI pipelines** | Object detection, image classification, semantic segmentation, face detection, pose estimation, super resolution, depth estimation, audio classification, object tracking, gesture recognition | | **Inputs** | ISP camera, USB camera, file source (MP4/H.264), RTSP stream | | **Outputs** | HDMI display, encoded file (MP4), RTSP stream, Redis/MQTT metadata | | **ML backends** | TFLite, QNN, SNPE, QAIRT, ONNX Runtime | | **Pipeline patterns** | Single-stream, multi-stream, daisy-chained models, ML-bin fused inference, custom pre/post-processing, AppSrc/AppSink bridges, YAML config mode | ## Prerequisites ### For generating code > [!NOTE] > > Qualcomm dev kits are not needed for code generation. **Host Machine**: Any PC with internet access **Coding Agent**: Any AI coding agent installed (Claude Code, Cursor, Codex, etc.) which supports skills — the skills provided are agent-agnostic. > [!NOTE] > > This skill is designed to work well even with low-reasoning / smaller models. > > Eg: A Sonnet 4.5 model is sufficient. ### For deploying and running apps The target devices where QIM SDK is supported (see [QIM SDK Installation Guide](/installation)) ## How to Use ### Step 1: Get the skill Choose one installation method: **Install Skill** Clone the skill repository and copy the **QIM SDK C++ App Builder** and **qimsdk-deploy** skills into your coding agent's skills directory: ```bash theme={null} git clone https://github.com/qualcomm/qimsdk-agentic-skills # The following commands are for Claude Code. # Set this to your coding agent's skills directory. cp -r qimsdk-agentic-skills/skills/qimsdk-cpp-app-builder ~/.claude/skills cp -r qimsdk-agentic-skills/skills/qimsdk-deploy ~/.claude/skills ``` The skills directory is agent-specific. Check your coding agent's documentation for its skills location. Restart or reload your coding agent after installation. Verify that `qimsdk-cpp-app-builder` and `qimsdk-deploy` are available with `/skills`. **Install Plugin** **Claude Code** — run inside a Claude Code session: ```text theme={null} /plugin marketplace add https://github.com/qualcomm/qimsdk-agentic-skills.git /plugin install qimsdk-agentic-skills@qimsdk-marketplace /reload-plugins ``` **Codex** — run in your terminal: ```bash theme={null} codex plugin marketplace add https://github.com/qualcomm/qimsdk-agentic-skills.git codex plugin add qimsdk-agentic-skills@qimsdk-marketplace ``` *** ### Step 2: Generate the application Describe your pipeline to the agent. It will automatically activate the skill and generate a complete `main.cc`, `CMakeLists.txt`, and `README.md`. #### Sample Prompt **Prompt format — describe pipeline behavior and configuration:** ``` Create a QIM SDK C++ app for single-stream YOLOX object detection from an MP4 file, encoding the result to a file. ## Pipeline Behavior - Decode an MP4 file using Qualcomm hardware decoder - Run YOLOX object detection on full frames using TFLite external delegate on HTP/NPU - Merge metadata with the video stream before overlay - Overlay bounding boxes and labels - Encode the overlaid video and save to an output MP4 file ## Configuration - Input: ~/Downloads/qimsdk_samples/media/ai_demo_sample.mp4 - Model: ~/Downloads/qimsdk_samples/models/yolox_w8a8.tflite - Labels: ~/Downloads/qimsdk_samples/labels/yolov8.json - Backend: TFLite external delegate, HTP/NPU - Confidence: 51.0 - Output: ~/Downloads/qimsdk_samples/media/obj_detect_out.mp4 ``` More sample prompts can be found in the [Available Sample Prompts](#available-sample-prompts) section below. #### Generated `README.md` The README documents the generated app in full: * **Purpose** — a plain-English summary of what the pipeline does * **Files** — lists `main.cc`, `CMakeLists.txt`, and `README.md` with descriptions * **Assumptions** — codec format, quantization requirements, camera defaults, output directory pre-conditions * **Configuration** — all user-supplied paths (input, model, labels, output) with instructions on where to change them * **Placeholders to Fill** — any values you still need to supply, or a note that none remain when the request was fully specified * **Pipeline Flow** — a `Text Summary` walkthrough of every element plus a `Mermaid Diagram` of the full pipeline * **Steps to compile** — how to build the app against the QIM SDK with CMake * **Steps to Run** — exact commands to run on device, including any setup (e.g. `mkdir -p` for output directories) > **README.md** > > # QIM SDK C++ App — Single-Stream YOLOX Object Detection (MP4 → MP4) > > ## Purpose > > Decode an MP4 file with the Qualcomm hardware decoder, run **YOLOX** object > detection on full frames using the **TFLite external delegate on the HTP/NPU**, > merge the detection metadata with the video stream, overlay bounding boxes and > class labels, then hardware-encode the annotated video to an output MP4 file. > Headless (no display branch). > > ## Files > > * `main.cc` — the qimsdk C++ pipeline app > * `CMakeLists.txt` — build target (`qimsdk-cpp-yolox-obj-detect-encode`) > * `README.md` — this file > > ## Assumptions > > * Input is H.264-in-MP4, decoded with `v4l2h264dec` (`capture-io-mode=4`, > `output-io-mode=4` — file source decoded through the hardware decoder). > * YOLOX (`yolox_w8a8.tflite`) uses the `yolov8` postprocess module with the > `yolov8.json` labels, per the model catalog. > * Confidence threshold is applied as inline postprocess settings > `{"confidence": 51.0}`. > * No display: the annotated stream is normalized back to NV12 > (`render_vf`), encoded (`v4l2h264enc`, `capture/output-io-mode=4/4`, the > correct pairing for a transform/decoder-produced NV12 buffer), parsed, > muxed (`mp4mux`), and written to the output MP4 (`filesink`). > * `pipeline.eos(true)` is set so `mp4mux` finalizes the container on EOS. > * `HOME` is resolved once in C++ (`std::getenv("HOME")` with an unset/empty > check) and prepended to every file path, because C++ string literals do not > expand `$HOME`. > > ## Configuration (fixed constants in `main.cc`) > > | Value | Path | > | - | - | > | Input | `$HOME/Downloads/qimsdk_samples/media/ai_demo_sample.mp4` | > | Model | `$HOME/Downloads/qimsdk_samples/models/yolox_w8a8.tflite` | > | Labels | `$HOME/Downloads/qimsdk_samples/labels/yolov8.json` | > | Output | `$HOME/Downloads/qimsdk_samples/media/obj_detect_out.mp4` | > > ## Placeholders to Fill > > None. All paths, model, labels, confidence, and delegate options are concrete. > `${QIMSDK_BINDIR}` is expected to be defined by the parent SDK build. > > ## Pipeline Flow > > ### Text Summary > > `filesrc` reads the MP4 and `qtdemux` extracts the H.264 elementary stream, > which `h264parse` prepares and `v4l2h264dec` hardware-decodes. A `queue` > (`q_dec`) decouples the decoder thread, then a `VideoFilter` (`vf`) constrains > the stream to NV12. A `tee` (`split`) branches: > > * **Passthrough / video branch** → `qtimetamux` (`metamux`). > * **AI branch** → `queue` (`q_ai`) → `qtimlvconverter` (`pre`, preprocess to > model tensor) → `qtimltflite` (`infer`, YOLOX, external delegate, HTP/NPU) → > `qtimlpostprocess` (`post`, `module=yolov8`, labels, `{"confidence": 51.0}`) → > `TextFilter` (`mlf`) → `qtimetamux` (`metamux`). > > `qtimetamux` merges the detection metadata back onto the video frames, > `qtivoverlay` draws the bounding boxes and class labels, a `VideoFilter` > (`render_vf`) normalizes the overlaid frames to NV12 for the encoder, and the > stream is hardware-encoded by `v4l2h264enc`, parsed by `h264parse` > (`h264parser`), muxed by `mp4mux`, and written by `filesink` to the output MP4. > > ### Mermaid Diagram > > ```mermaid theme={null} > flowchart TD > SRC[filesrc] --> DEMUX[qtdemux] > DEMUX --> PARSE[h264parse] > PARSE --> DEC[v4l2h264dec] > DEC --> QDEC[queue q_dec] > QDEC --> NV12[NV12 VideoFilter vf] > NV12 --> SPLIT[tee split] > SPLIT -->|passthrough| MUX[qtimetamux metamux] > SPLIT -->|AI| QAI[queue q_ai] > QAI --> PRE[qtimlvconverter pre] > PRE --> INFER[qtimltflite YOLOX HTP] > INFER --> POST[qtimlpostprocess module=yolov8] > POST --> TEXT[TextFilter mlf] > TEXT --> MUX > MUX --> OVL[qtivoverlay] > OVL --> RENDER[NV12 VideoFilter render_vf] > RENDER --> ENC[v4l2h264enc] > ENC --> PARSEOUT[h264parse h264parser] > PARSEOUT --> MP4[mp4mux] > MP4 --> SINK[filesink] > ``` > > ## Steps to Compile > > Yocto: [https://imsdkdocs.qualcomm.com/advanced/yocto-build#steps-to-build-custom-application](https://imsdkdocs.qualcomm.com/advanced/yocto-build#steps-to-build-custom-application) > > ## Steps to Run > > First ensure all referenced files — the input MP4, the `yolox_w8a8.tflite` > model, and the `yolov8.json` labels — are already present on the device at the > paths configured in `main.cc`. > > ```bash theme={null} > # Copy the app to device > scp qimsdk-cpp-yolox-obj-detect-encode @:~/ > > # SSH into device and run > ssh @ > chmod +x ~/qimsdk-cpp-yolox-obj-detect-encode > ./qimsdk-cpp-yolox-obj-detect-encode > ``` > > The input MP4 must exist at > `$HOME/Downloads/qimsdk_samples/media/ai_demo_sample.mp4` on the device, and the > output directory (`$HOME/Downloads/qimsdk_samples/media/`) must be writable so > the app can create `obj_detect_out.mp4`. The app runs to end-of-file, finalizes > the MP4, and exits. #### Generated `main.cc` * The generated application constructs a tee-split pipeline: decoded frames are split into a passthrough branch and an AI branch. * The AI branch runs `qtimlvconverter` (preprocess) → `qtimltflite` (YOLOX inference via HTP/NPU) → `qtimlpostprocess` → `TextFilter`, then merges back into `qtimetamux` with the passthrough video. * `qtivoverlay` draws bounding boxes, and the result is hardware-encoded and written to an MP4 file via `filesink`. * Pipeline construction and `.execute()` live inside `create_and_execute_pipeline()`; `main()` sets up logging, wraps the call in a try/catch, and returns a non-zero exit code on error. * All paths are `$HOME`-relative and resolved once via a checked `std::getenv("HOME")` helper — C++ string literals do not expand shell variables. > **main.cc** > > ```cpp theme={null} > #include > #include > #include > > #include > > using namespace qti; > > // C++ string literals never expand $HOME; resolve it once at startup with an > // explicit unset/empty check so HOME-relative paths fail loudly if HOME is unset. > const std::string HOME_PATH = [] { > const char* home = std::getenv("HOME"); > if (home == nullptr || *home == '\0') { > throw std::runtime_error("HOME is not set; cannot resolve filesystem paths"); > } > return std::string(home); > }(); > > // Example pipeline: > // > // filesrc -> qtdemux -> h264parse -> v4l2h264dec -> [vf NV12] -> tee > // tee (passthrough) -> qtimetamux -> qtivoverlay -> [render vf NV12] -> encoder -> parser -> muxer -> filesink > // tee (AI branch) -> qtimlvconverter -> qtimltflite (YOLOX, HTP external delegate) > // -> qtimlpostprocess (module=yolov8, labels, confidence=51.0) > // -> [TextFilter] -> qtimetamux > // > // The pipeline reads an MP4/H.264 file, decodes it with the hardware decoder, > // runs YOLOX object detection on full frames via the HTP/NPU (TFLite external > // delegate), merges the detection metadata back with the video, overlays > // bounding boxes and class labels on each frame, encodes the overlaid video > // with the hardware H.264 encoder, and writes the result to an output MP4 file. > > void create_and_execute_pipeline() { > > // Reads the input media file as raw bytes. > Element src("filesrc", "src"); > src.set("location", HOME_PATH + "/Downloads/qimsdk_samples/media/ai_demo_sample.mp4"); > > // Extracts elementary streams from the MP4 container. > // Dynamic pad-added linking is handled internally by the SDK. > Element demux("qtdemux", "demux"); > > // Prepares the H.264 bitstream for the decoder. > Element parse("h264parse", "parse"); > > // Decodes the compressed H.264 stream into raw video frames. > // > // The I/O mode is configured to enforce DMA buffer usage, > // avoiding unnecessary buffer copies. > Element decoder("v4l2h264dec", "decoder"); > decoder.set("output-io-mode", 4); > decoder.set("capture-io-mode", 4); > > // Queue immediately after the hardware decoder before any filter/tee. > Element q_dec("queue", "q_dec"); > > // Normalizes decoded output to NV12 before branching/AI preprocessing. > auto vf = VideoFilter().format("NV12"); > > // Splits the normalized video into a passthrough (main video) branch and > // an AI inference branch. > Element split("tee", "split"); > > // Queue to isolate the AI branch from the tee. > Element q_ai("queue", "q_ai"); > > // Converts raw video frames into normalized tensors for inference. > Element preprocess("qtimlvconverter", "pre"); > > // Runs YOLOX object detection via the TFLite HTP/NPU external delegate. > Element infer("qtimltflite", "infer"); > infer.set("delegate", "external"); > infer.set("external-delegate-path", "libQnnTFLiteDelegate.so"); > infer.set("external-delegate-options", > "QNNExternalDelegate,backend_type=htp,log_level=(string)1;"); > infer.set("model", HOME_PATH + "/Downloads/qimsdk_samples/models/yolox_w8a8.tflite"); > > // Decodes YOLOX output tensors into bounding boxes + class labels. > // module=yolov8 is the documented compatibility mapping for YOLOX detection. > // The confidence threshold (51.0) is applied as inline JSON settings. > Element post("qtimlpostprocess", "post"); > post.set("module", "yolov8"); > post.set("labels", HOME_PATH + "/Downloads/qimsdk_samples/labels/yolov8.json"); > post.set("settings", "{\"confidence\": 51.0}"); > > // Serialized detection metadata bus feeding qtimetamux. > auto mlf = TextFilter(); > > // Synchronizes AI detection metadata with the original video buffer. > Element metamux("qtimetamux", "metamux"); > > // Draws bounding boxes and class labels on the video frame. > Element overlay("qtivoverlay", "overlay"); > > // Encoder requires NV12 raw video input. > auto render_vf = VideoFilter().format("NV12"); > > // Encodes the overlaid raw video frames into H.264. > // > // File/decode source path: driver manages both encoder input and output > // buffers via dmabuf, so both io-modes are 4. > Element encoder("v4l2h264enc", "encoder"); > encoder.set("output-io-mode", 4); > encoder.set("capture-io-mode", 4); > > // Parses the encoded H.264 bitstream for muxing. > Element h264parser("h264parse", "h264parser"); > > // Muxes the encoded stream into an MP4 container. > Element muxer("mp4mux", "muxer"); > > // Writes the muxed MP4 stream to the output file. > Element sink("filesink", "sink"); > sink.set("location", HOME_PATH + "/Downloads/qimsdk_samples/media/obj_detect_out.mp4"); > > // Creates the pipeline, adds and links elements, and executes it. > // > // Explicit linking is applied for the tee/metamux branches. > // eos(true) lets mp4mux finalize the container correctly on EOS. > Pipeline pipeline("qimsdk-cpp-yolox-obj-detect-encode"); > pipeline.add(src) > .add(demux) > .add(parse) > .add(decoder) > .add(q_dec) > .add_stream_filter("vf", vf) > .add(split) > .add(metamux) > .add(q_ai) > .add(preprocess) > .add(infer) > .add(post) > .add_stream_filter("mlf", mlf) > .add(overlay) > .add_stream_filter("render_vf", render_vf) > .add(encoder) > .add(h264parser) > .add(muxer) > .add(sink) > .eos(true) > .link("src", "demux", "parse", "decoder", "q_dec", "vf", "split") > .link("split", "metamux") > .link("split", "q_ai", "pre", "infer", "post", "mlf", "metamux") > .link("metamux", "overlay", "render_vf", "encoder", "h264parser", "muxer", "sink") > .execute(); > } > > int main() { > // Route GStreamer logs through the IMSDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > > try { > create_and_execute_pipeline(); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > > return 0; > } > ``` #### Generated `CMakeLists.txt` * Defines a single executable target (`qimsdk-cpp-yolox-obj-detect-encode`) built from `main.cc`. * Links against `qimsdk-app-builder` — no direct GStreamer package dependency. * Installs the binary to `${QIMSDK_BINDIR}` (defined by the parent SDK build) with standard executable permissions. > **CMakeLists.txt** > > ```cmake theme={null} > cmake_minimum_required(VERSION 3.8.2) > > set(TEST_TARGET qimsdk-cpp-yolox-obj-detect-encode) > > add_executable(${TEST_TARGET} > main.cc > ) > > target_link_libraries(${TEST_TARGET} PRIVATE > qimsdk-app-builder > ) > > install( > TARGETS ${TEST_TARGET} > RUNTIME DESTINATION ${QIMSDK_BINDIR} > PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ > GROUP_EXECUTE GROUP_READ > WORLD_EXECUTE WORLD_READ > ) > ``` *** ### Step 3: Running the applications **1. Download Required Files** | File | Download | Save as | | - | - | - | | YOLOX W8A8 model | [Qualcomm AI Hub — YOLOX](https://aihub.qualcomm.com/iot/models/yolox) | `yolox_w8a8.tflite` | | Detection labels | [yolov8.json](../labels/yolov8.json) | `yolov8.json` | | Sample video | [Input video](https://github.com/qualcomm/sample-apps-for-qualcomm-linux/raw/refs/heads/main/qualcomm-linux/artifacts/videos/demo_samples/) | `ai_demo_sample.mp4` | > [!NOTE] > > If the downloaded model file is a `.zip` archive, extract it on your host machine before copying: `unzip filename.zip` **2. Copy the assets to the device** The input video, model, and labels must be present on the device before running — regardless of how you build and run the app. Copy them to the paths `main.cc` expects: ```bash theme={null} # Replace and with your device credentials. ssh @ "mkdir -p ~/Downloads/qimsdk_samples/media ~/Downloads/qimsdk_samples/models ~/Downloads/qimsdk_samples/labels" # Copy the assets to device (paths must match main.cc) scp ai_demo_sample.mp4 @:~/Downloads/qimsdk_samples/media/ scp yolox_w8a8.tflite @:~/Downloads/qimsdk_samples/models/ scp yolov8.json @:~/Downloads/qimsdk_samples/labels/ ``` **3. Build and run the application** The C++ app must be compiled before it can run. With the assets in place, you have two options to build and run the agent-generated app: **Option A — Use the QIM SDK Deploy skill (Recommended):** The `qimsdk-deploy` skill builds the app on your host against the Yocto SDK, then pushes the compiled binary to the device and runs it over SSH. It handles only the app build and binary transfer — the assets from the previous step must already be on the device. **Option B — Follow the generated README:** Follow the steps in the [`README.md`](#generated-readme-md) to compile the app, then push the binary to the device and run it: 1. **Compile the app** by following the steps at [Yocto Build](/advanced/yocto-build). 2. **Push the compiled binary to the device and run it:** ```bash theme={null} # Copy the built binary to device scp qimsdk-cpp-yolox-obj-detect-encode @:~/ # SSH into device and run ssh @ chmod +x ~/qimsdk-cpp-yolox-obj-detect-encode ./qimsdk-cpp-yolox-obj-detect-encode ``` On completion (EOS), the annotated video is written to `~/Downloads/qimsdk_samples/media/obj_detect_out.mp4`. *** ## Available Sample Prompts | # | Prompt | | - | - | | 1 | [Camera YOLOv8 object detection using fused TFLite ML-bin](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_01_mlbin_yolov8_camera_overlay.md) | | 2 | [Two-stage PPE daisy-chain — person detection → PPE detection → overlay display](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_02_mlbin_ppe_daisy_chain_display.md) | | 3 | [Object detection with custom C++ postprocess placeholder](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_03_custom_postprocess_detection_placeholder.md) | | 4 | [Pose estimation with custom C++ postprocess placeholder](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_04_custom_postprocess_pose_placeholder.md) | | 5 | [Inference app with tensor output via custom callback placeholder](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_05_tensor_dump_callback_placeholder.md) | | 6 | [YOLOv8 object detection pipeline with generated YAML config](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_06_yaml_yolov8_generated_config.md) | | 7 | [Object detection with custom C++ preprocess placeholder](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_07_custom_preprocess_detection_placeholder.md) | | 8 | [Object detection with TFLite ML-bin custom preprocess placeholder](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_08_mlbin_custom_preprocess_detection_placeholder.md) | | 9 | [Load existing YOLOv8 detection pipeline from external YAML config](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_09_yaml_yolov8_external_config.md) | | 10 | [Single-stream YOLOX object detection from MP4, encoded to file](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_10_single_stream_object_detection.md) | | 11 | [AI wall — four parallel AI inference streams composed into a 2×2 grid display](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_11_ai_wall.md) | | 12 | [Four-stage gesture recognition daisy-chain pipeline](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_12_gesture_recognition.md) | | 13 | [Audio classification — classify audio events from video and overlay results](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/AI_13_audio_classification.md) | | 14 | [Two pipelines bridged through application-managed buffers (AppSrc/AppSink)](https://github.com/qualcomm/qimsdk-agentic-skills/blob/main/sample-prompts/qimsdk-cpp-app-builder/MM_01_appsrc_appsink_bridge.md) | # Demo Applications Source: https://imsdkdocs.qualcomm.com/app-builder/cpp-demo-applications Ready-to-run C++ App Builder demo applications The table below lists the C++ App Builder demo applications built on top of the [C++ App Builder](/app-builder/cpp-app-builder) SDK. | # | Application | Source Code | Description | | - | - | - | - | | 1 | [Product Counting Application](/blogs/product-counting-application) | [demo\_product\_counting/main.cc](https://github.com/qualcomm/qimsdk/blob/main/cpp/examples/demo-apps/demo_product_counting/main.cc) | A YOLOv8-based object detection pipeline that counts products crossing a center region of interest in real time. | | 2 | [Smart Board Application](/blogs/smart-board-application) | [demo\_smartboard/main.cc](https://github.com/qualcomm/qimsdk/blob/main/cpp/examples/demo-apps/demo_smartboard/main.cc) | A touchless virtual whiteboard controlled entirely by hand gestures, supporting freehand drawing, shape recognition, erasing, and dragging content via a two-stage palm detection and hand landmark pipeline. | | 3 | [Touchless Wrist Steering Car Game](/blogs/touchless-wrist-steering-car-game) | [demo\_car\_game/main.cc](https://github.com/qualcomm/qimsdk/blob/main/cpp/examples/demo-apps/demo_car_game/main.cc) | A two-stage palm detection and hand landmark pipeline turns wrist movement into a virtual steering wheel for a real-time, touchless split-screen driving game. | # Quick start guide Source: https://imsdkdocs.qualcomm.com/app-builder/cpp-quickstart A Quick demonstration of C++ SDK for building AI application on Qualcomm platforms ## What is the QIM SDK C++ App Builder? ### Overview The **QIM SDK C++ App Builder** is a modern C++ SDK for building, running, and managing multimedia and AI pipelines on Qualcomm platforms. It sits as a high-level abstraction layer on top of GStreamer, taking care of framework-level concerns such as element negotiation, pad linking, signal management, event loops, and state transitions, so developers can stay focused on application logic instead of framework boilerplate. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/imsdk_overview.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=a927e3a6ea23ccab4080d3e28b88c18d) ### Key Capabilities * **No GStreamer expertise required** — the SDK manages all underlying GStreamer mechanics internally, with no compile-time dependency on GStreamer headers. * **Less code, no GStreamer boilerplate** — a fluent, high-level API bundles away the pipeline construction, element linking, and state management that GStreamer's native API would otherwise require, so a functional camera-to-display pipeline can be written in just a few lines of C++. * **Custom pre/post-processing** — plug in your own pre- and post-processing logic around the built-in ML bins without writing a custom GStreamer element. * **AI inference support** — built-in ML bins for TFLite, QNN, SNPE, and ONNX models. * **Broad multimedia support** — video capture, signal processing, ML inference, overlay rendering, and display output. ### API Reference
API Description API Code Reference
**Pipeline** Builds, links, and manages the full lifecycle of a GStreamer pipeline. Supports both programmatic (C++ fluent API) and declarative (YAML) pipeline definition. Key methods: `add()`, `link()`, `add_stream_filter()`, `execute()`, `prepare()`, `start()`, `stop()`, `get()`. ```cpp theme={null} Pipeline p("cam-pipeline"); p.add("qtiqmmfsrc", "src").add("waylandsink", "sink").execute(); ```
**Element** Generic wrapper around a GStreamer element. Supports fluent property setting, either at creation time or at runtime, to update a live pipeline. ```cpp theme={null} Element sink("waylandsink", "display"); sink.set("fullscreen", true); sink.set("sync", false); ```
**Buffer** Unified buffer abstraction over native GStreamer memory. Provides read/write access, timestamp metadata, and zero-copy transfer paths. Key methods: `data()`, `size()`, `resize()`, `pts()`, `dts()`, `duration()`. ```cpp theme={null} sink.setBufferConsumer([](Buffer buf) { auto* data = buf.data(); auto pts = buf.pts(); }); ```
**AppSrc** App-facing source. Feeds buffers from application code into the pipeline using lambda callbacks or a push API. ```cpp theme={null} AppSrc src(pipeline.get("src")); src.setBufferProducer([](Buffer& buf) { // fill buf.data() return true; }); ```
**AppSink** App-facing sink. Delivers pipeline output buffers to application code with zero-copy. ```cpp theme={null} AppSink sink(pipeline.get("sink")); sink.setBufferConsumer([](Buffer buf) { // consume buf.data() }); ```
**CamSrc** Built-in ISP camera source. Exposes an API for runtime image capture and snapshots. ```cpp theme={null} CamSrc cam(pipeline.get("source")); cam.captureImage("snapshot.jpg"); ```
**MLPreProcess** Attaches a custom C++ lambda for pre-processing input frames before ML inference. ```cpp theme={null} MLPreProcess pre(pipeline.get("preproc")); pre.set_handler([](Buffer& buf) { // transform input frame }); ```
**MLPostProcess** Attaches a custom C++ lambda for post-processing raw inference tensor output. ```cpp theme={null} MLPostProcess pp(pipeline.get("postproc")); pp.set_handler([](Buffer& buf) { // parse inference output }); ```
**MLVideoTFLiteBin** / **MLVideoQNNBin** / **MLVideoSNPEBin** / **MLVideoONNXBin** All-in-one preprocess + inference + postprocess bins. Supports TFLite, QNN, SNPE, and ONNX models. ```cpp theme={null} pipeline.add("MLVideoTFLiteBin", "ml", "model", "/models/model.tflite", "delegate", "htp"); ```
**VideoFilter** / **AudioFilter** / **ImageFilter** / **H264Filter** / **TensorFilter** / **TextFilter** Fluent caps builders for `add_stream_filter()`. Describes stream characteristics for caps negotiation between pipeline stages. ```cpp theme={null} pipeline.add_stream_filter("vf", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)); ```
*** ## Build your application > [!NOTE] > > Ensure you have QIM SDK installed. See [QIM SDK Installation Guide](../installation) Before running any of the applications below, create the sample directory tree on the target device: ```bash theme={null} # ~ resolves automatically to the correct home directory on the device (/root on QLI, /home/ubuntu on Ubuntu). ssh @ "mkdir -p ~/Downloads/qimsdk_samples/{media,models,labels}" ``` This is required even for apps that don't download any media, model, or label files (such as the camera capture and recording apps), since they still write their output under this path. ### USB Camera Source USB (UVC) cameras are handled by the `v4l2src` node. Each USB camera comes with its own format and frame constraints. Because of this, we always place `qtivtransform` right after the USB camera to ensure that the rest of the pipeline receives a hardware-friendly NV12 (Semi-planar YUV420) video format. `qtivtransform` automatically operates in passthrough mode if the USB camera already supports NV12, so you don't need to worry about any performance overhead. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/usb_cam_src.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=2eb0a04e674fbfb4ee468483a076bad3) **Explicit coding style** > [!NOTE] > > Check application source code on GitHub: [`qimsdk_ref_usb_camera`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_usb_camera) > > Pre-built application on device: `/usr/bin/qimsdk_ref_usb_camera` ```cpp theme={null} #include #include using namespace qti; // Example pipeline: // // source → transform → [videofilter] → display // // The pipeline reads frames from a USB (V4L2) camera, rotates them, restricts // the stream to NV12/1080p/30fps, and displays the result through Wayland. void create_and_execute_pipeline(const std::string &device) { // Captures frames from the USB camera source. Element source("v4l2src", "source"); source.set("device", device); // Applies geometric transforms to video frames. Element transform("qtivtransform", "transform"); // Stream filters used in branch links. // They define specific stream characteristics from the supported options. auto videofilter = VideoFilter().format("NV12").resolution(1920, 1080).framerate(30); // Render video stream on display. // // sync=false disables strict rendering synchronization to the pipeline clock. // fullscreen=true renders the output fullscreen on the target display. Element display("waylandsink", "display"); display.set("sync", false); display.set("fullscreen", true); // Creates the pipeline, adds elements, links them explicitly, and executes it. Pipeline pipeline("usb-cam-pipeline"); pipeline.add(source) .add(transform) .add_stream_filter("videofilter", videofilter) .add(display) .link("source", "transform", "videofilter", "display") .execute(); } int main(int argc, char **argv) { // Route GStreamer logs through the QIM SDK logger and enable debug output. qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); // V4L2 device node to capture from, defaults to /dev/video2. Pass -d/--device to override. std::string device = "/dev/video2"; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if ((arg == "-d" || arg == "--device") && i + 1 < argc) { device = argv[++i]; } } try { create_and_execute_pipeline(device); } catch (const std::exception &ex) { std::cerr << "Exception: " << ex.what() << std::endl; return 1; } return 0; } ``` **1. Connect a USB camera** Connect a USB (UVC) camera to the target device and verify it is exposed as `/dev/video2` (update the pipeline's `device` property if your camera is exposed on a different node). **2. Run the application** ```bash theme={null} /usr/bin/qimsdk_ref_usb_camera --input-config /dev/video2 ``` **3. Expected Output** The live camera feed is rotated and rendered fullscreen on the display in NV12 format at 1080p/30fps. ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/usb-camera-preview.jpeg?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=2ed060f58a450ceb48de22da1d5cf295) To stop the application, press **CTRL + C**. **4. Customize application** * **Source code:** [`qimsdk_ref_usb_camera`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_usb_camera) * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) **Implicit coding style** > [!NOTE] > > Check application source code on GitHub: [`qimsdk_ref_usb_camera_impl`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_usb_camera_impl) > > Pre-built application on device: `/usr/bin/qimsdk_ref_usb_camera_impl` ```cpp theme={null} #include #include using namespace qti; // Example pipeline: // // source → transform → [videofilter] → display // // The pipeline reads frames from a USB (V4L2) camera, rotates them, restricts // the stream to NV12/1080p/30fps, and displays the result through Wayland. void create_and_execute_pipeline(const std::string &device) { // Creates the pipeline, adds and links elements, and executes it. // // Elements are created on the fly as they are added, and linking is // implicit, following the order in which elements are added. // // sync=false disables strict rendering synchronization to the pipeline clock. // fullscreen=true renders the output fullscreen on the target display. Pipeline pipeline("usb-cam-pipeline"); pipeline.add("v4l2src", "source", "device", device) .add("qtivtransform", "transform") .add_stream_filter("videofilter", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)) .add("waylandsink", "display", "sync", false, "fullscreen", true) .execute(); } int main(int argc, char **argv) { // Route GStreamer logs through the QIM SDK logger and enable debug output. qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); // V4L2 device node to capture from, defaults to /dev/video2. Pass -d/--device to override. std::string device = "/dev/video2"; for (int i = 1; i < argc; ++i) { std::string arg = argv[i]; if ((arg == "-d" || arg == "--device") && i + 1 < argc) { device = argv[++i]; } } try { create_and_execute_pipeline(device); } catch (const std::exception &ex) { std::cerr << "Exception: " << ex.what() << std::endl; return 1; } return 0; } ``` **1. Connect a USB camera** Connect a USB (UVC) camera to the target device and verify it is exposed as `/dev/video2` (update the pipeline's `device` property if your camera is exposed on a different node). **2. Run the application** ```bash theme={null} /usr/bin/qimsdk_ref_usb_camera_impl --input-config /dev/video2 ``` **3. Expected Output** The live camera feed is rotated and rendered fullscreen on the display in NV12 format at 1080p/30fps. ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/usb-camera-preview.jpeg?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=2ed060f58a450ceb48de22da1d5cf295) To stop the application, press **CTRL + C**. **4. Customize application** * **Source code:** [`qimsdk_ref_usb_camera_impl`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_usb_camera_impl) * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) **YAML config style** > [!NOTE] > > See the full YAML configuration here: [qimsdk\_ref\_usb\_camera.yaml](https://github.com/qualcomm/qimsdk/blob/main/tools/appbuilders-configs/qimsdk_ref_usb_camera.yaml) > > Check application source code on GitHub: [qimsdk\_ref\_yml](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_yml) > > Pre-built application on device: `/usr/bin/qimsdk_ref_yml` > > YAML configuration saved on device: `/etc/qimsdk/qimsdk_ref_usb_camera.yaml` ```yaml theme={null} pipeline: elements: - type: v4l2src name: source device: /dev/video2 - type: qtivtransform name: transform - type: filter name: videostream video: format: NV12 width: 1920 height: 1080 framerate: 30 - type: waylandsink name: display sync: false fullscreen: true ``` **1. Connect a USB camera** Connect a USB (UVC) camera to the target device and verify it is exposed as `/dev/video2` (update the pipeline's `device` property if your camera is exposed on a different node). **2. Run the application** ```bash theme={null} qimsdk_ref_yml /etc/qimsdk/qimsdk_ref_usb_camera.yaml ``` **3. Expected Output** The live camera feed is rotated and rendered fullscreen on the display in NV12 format at 1080p/30fps. ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/usb-camera-preview.jpeg?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=2ed060f58a450ceb48de22da1d5cf295) To stop the application, press **CTRL + C**. **4. Customize application** * **Source code:** [qimsdk\_ref\_yml](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_yml) * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) ### Object Detection This pipeline captures from a built-in camera, runs an object detection model through an ML inference bin, renders bounding box overlays on the output frames, and displays the result. The ML bin handles preprocessing, inference, and postprocessing internally. The stream filter pins the input video format expected by the model. The overlay element draws detection results on each frame before display. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/object_det.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=5c252d39d2b0070fd2b02a8ee3dd3454) **Explicit coding style** > [!NOTE] > > Check application source code on GitHub: [`qimsdk_ref_camera_yolov8`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera_yolov8) > > Pre-built application on device: `/usr/bin/qimsdk_ref_camera_yolov8` **1. Download Required Files** | File | Download | Save as | | - | - | - | | YOLOv8 detection model | [Qualcomm AI Hub — YOLOv8](https://aihub.qualcomm.com/iot/models/yolov8_det) | `yolov8_det_quantized.tflite` | | Detection labels | [yolov8.json](../labels/yolov8.json) | `yolov8.json` | > [!NOTE] > > If the downloaded model file is a `.zip` archive, extract it on your host machine before copying: `unzip filename.zip` > > Some AI Hub models require running the AI Hub export/optimize step for your target runtime before the downloaded file is usable — download alone isn't always sufficient. **2. Copy the assets to the device** The model and labels must be present on the device before running. Copy them to the paths the application expects: ```bash theme={null} # Replace and with your device credentials. # ~ resolves automatically to the correct home directory on the device (/root on QLI, /home/ubuntu on Ubuntu). ssh @ "mkdir -p ~/Downloads/qimsdk_samples/models ~/Downloads/qimsdk_samples/labels" # Copy the assets to device scp yolov8_det_quantized.tflite @:~/Downloads/qimsdk_samples/models/ scp yolov8.json @:~/Downloads/qimsdk_samples/labels/ ``` **3. Connect an IMX camera** This application uses the built-in ISP camera. On platforms without an onboard ISP camera (e.g. IQ9), attach an external IMX camera (e.g. from RB3 Gen2) before running the application — see [ISP Camera (Config #2 / qticamsrc)](/advanced/debugging#isp-camera-config-2--qticamsrc) for the procedure to switch from `libcamera` to `qticamsrc`. **4. Run the application** ```bash theme={null} /usr/bin/qimsdk_ref_camera_yolov8 ``` **5. Expected Output** The live camera feed is rendered fullscreen on the display with YOLOv8 bounding boxes and class labels overlaid on each detected object in real time. ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/object-det-live.jpeg?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=9e1969d7993f5be0c0e9e8b6dacb2095) To stop the application, press **CTRL + C**. **6. Customize application** * **Source code:** [`qimsdk_ref_camera_yolov8`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera_yolov8) * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) ### Custom Post-Processing The QIM SDK implements AI model post-processing through dedicated modules that take tensors as input and produce predictions. All underlying complexity — batching, daisy-chaining, image mask support, and ML metadata handling — is encapsulated within the post-processing plugin. This makes `MLPostProcess` the ideal integration point for application-specific logic, since the application does not need to handle any of that complexity directly. A specialized post-processing module manages the bindings between the pipeline and the application. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/custom_post.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=e58d0809d197ae3c2aa92815907df9fa) **Explicit coding style** > [!NOTE] > > Check application source code on GitHub: [`qimsdk_ref_external_postprocess_mlbin_yolov8`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_external_postprocess_mlbin_yolov8) > > Pre-built application on device: `/usr/bin/qimsdk_ref_external_postprocess_mlbin_yolov8` **1. Download Required Files** | File | Download | Save as | | - | - | - | | YOLOv8 detection model | [Qualcomm AI Hub — YOLOv8](https://aihub.qualcomm.com/iot/models/yolov8_det) | `yolov8_det_quantized.tflite` | | Detection labels | [yolov8.json](../labels/yolov8.json) | `yolov8.json` | | Sample video | [Input video](https://github.com/qualcomm/sample-apps-for-qualcomm-linux/raw/refs/heads/main/qualcomm-linux/artifacts/videos/demo_samples/) | `ai_demo_sample.mp4` | > [!NOTE] > > If the downloaded model file is a `.zip` archive, extract it on your host machine before copying: `unzip filename.zip` > > Some AI Hub models require running the AI Hub export/optimize step for your target runtime before the downloaded file is usable — download alone isn't always sufficient. **2. Copy the assets to the device** The input video, model, and labels must be present on the device before running. Copy them to the paths the application expects: ```bash theme={null} # Replace and with your device credentials. # ~ resolves automatically to the correct home directory on the device (/root on QLI, /home/ubuntu on Ubuntu). ssh @ "mkdir -p ~/Downloads/qimsdk_samples/media ~/Downloads/qimsdk_samples/models ~/Downloads/qimsdk_samples/labels" # Copy the assets to device scp ai_demo_sample.mp4 @:~/Downloads/qimsdk_samples/media/ scp yolov8_det_quantized.tflite @:~/Downloads/qimsdk_samples/models/ scp yolov8.json @:~/Downloads/qimsdk_samples/labels/ ``` **3. Run the application** ```bash theme={null} /usr/bin/qimsdk_ref_external_postprocess_mlbin_yolov8 ``` **4. Expected Output** The video plays back with YOLOv8 bounding boxes and class labels decoded by the custom postprocessing callback, overlaid and rendered fullscreen on the display. ![Expected Output](https://mintcdn.com/qimsdk/WywR0vqVkL-AO2Rd/app-builder/images/expected-output-object-detect.png?fit=max\&auto=format\&n=WywR0vqVkL-AO2Rd\&q=85\&s=0765f511db9b649cbac010ebc9861230) To stop the application, press **CTRL + C**. **5. Customize application** * **Source code:** [`qimsdk_ref_external_postprocess_mlbin_yolov8`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_external_postprocess_mlbin_yolov8) * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) *** ## Benefits of QIM SDK C++ App Builder * Significantly reduced source code * Improved readability * Internal GStreamer state transition handling * Hidden End-of-Stream handling * Automatic error and state event handling * Automatic resource cleanup * Simplified AppSink/AppSrc interaction using lambda functions * SDK-managed buffer mapping and queries * Simplified buffer access anywhere in the pipeline using wrapped GST probes * YAML-based pipeline description # Reference Applications Source: https://imsdkdocs.qualcomm.com/app-builder/cpp-reference-applications Reference C++ App Builder pipeline examples ## Multimedia Pipeline Before running any of the applications below, create the sample directory tree on the target device: ```bash theme={null} # ~ resolves automatically to the correct home directory on the device (/root on QLI, /home/ubuntu on Ubuntu). ssh @ "mkdir -p ~/Downloads/qimsdk_samples/{media,models,labels}" ``` This is required even for apps that don't download any media, model, or label files (such as the camera capture and recording apps), since they still write their output under this path. ### USB Camera Preview USB (UVC) cameras are handled by the `v4l2src` node. Each USB camera comes with its own format and frame constraints. Because of this, we always place `qtivcomposer` right after the USB camera to ensure that the rest of the pipeline receives a hardware-friendly NV12 (Semi-planar YUV420) video format. However, `qtivcomposer` will automatically operate in passthrough mode if the USB camera already supports NV12, so you don't need to worry about any performance overhead. > [!NOTE] > > Some USB webcams (e.g. Logitech Brio 4K) may render a green/garbled frame at 30fps depending on platform/build. If this happens, lower the pipeline's framerate (e.g. to 15fps) as a workaround. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/usb_cam_src.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=2eb0a04e674fbfb4ee468483a076bad3) > **Try me** > > **Explicit coding style** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_usb_camera`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_usb_camera) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_usb_camera` > > ```cpp theme={null} > #include > #include > using namespace qti; > // Example pipeline: > // > // source → transform → [videofilter] → display > // > // The pipeline reads frames from a USB (V4L2) camera, rotates them, restricts > // the stream to NV12/1080p/30fps, and displays the result through Wayland. > void create_and_execute_pipeline(const std::string &device) { > // Captures frames from the USB camera source. > Element source("v4l2src", "source"); > source.set("device", device); > > // Applies geometric transforms to video frames. > Element transform("qtivtransform", "transform"); > > // Stream filters used in branch links. > // They define specific stream characteristics from the supported options. > auto videofilter = VideoFilter().format("NV12").resolution(1920, 1080).framerate(30); > > // Render video stream on display. > // > // sync=false disables strict rendering synchronization to the pipeline clock. > // fullscreen=true renders the output fullscreen on the target display. > Element display("waylandsink", "display"); > display.set("sync", false); > display.set("fullscreen", true); > > // Creates the pipeline, adds elements, links them explicitly, and executes it. > Pipeline pipeline("usb-cam-pipeline"); > pipeline.add(source) > .add(transform) > .add_stream_filter("videofilter", videofilter) > .add(display) > .link("source", "transform", "videofilter", "display") > .execute(); > } > int main(int argc, char **argv) { > // Route GStreamer logs through the QIM SDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > // V4L2 device node to capture from, defaults to /dev/video2. Pass -d/--device to override. > std::string device = "/dev/video2"; > for (int i = 1; i < argc; ++i) { > std::string arg = argv[i]; > if ((arg == "-d" || arg == "--device") && i + 1 < argc) { > device = argv[++i]; > } > } > try { > create_and_execute_pipeline(device); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **1. Connect a USB camera** > > Connect a USB (UVC) camera to the target device and verify it is exposed as `/dev/video2` (update the pipeline's `device` property if your camera is exposed on a different node). > > **2. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_usb_camera --input-config /dev/video2 > ``` > > The application connects to the USB camera, restricts the stream to NV12/1080p/30fps, and renders it fullscreen on the display. > > **3. Expected Output** > > The live USB camera feed is rendered fullscreen on the display. > > ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/usb-camera-preview.jpeg?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=2ed060f58a450ceb48de22da1d5cf295) > > To stop the application, press **CTRL + C**. > > **4. Customize application** > > * **Source code:** [`qimsdk_ref_usb_camera`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_usb_camera) > * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) > > **Implicit coding style** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_usb_camera_impl`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_usb_camera_impl) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_usb_camera_impl` > > ```cpp theme={null} > #include > #include > using namespace qti; > // Example pipeline: > // > // source → transform → [videofilter] → display > // > // The pipeline reads frames from a USB (V4L2) camera, rotates them, restricts > // the stream to NV12/1080p/30fps, and displays the result through Wayland. > void create_and_execute_pipeline(const std::string &device) { > // Creates the pipeline, adds and links elements, and executes it. > // > // Elements are created on the fly as they are added, and linking is > // implicit, following the order in which elements are added. > // > // sync=false disables strict rendering synchronization to the pipeline clock. > // fullscreen=true renders the output fullscreen on the target display. > Pipeline pipeline("usb-cam-pipeline"); > pipeline.add("v4l2src", "source", "device", device) > .add("qtivtransform", "transform") > .add_stream_filter("videofilter", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)) > .add("waylandsink", "display", "sync", false, "fullscreen", true) > .execute(); > } > int main(int argc, char **argv) { > // Route GStreamer logs through the QIM SDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > // V4L2 device node to capture from, defaults to /dev/video2. Pass -d/--device to override. > std::string device = "/dev/video2"; > for (int i = 1; i < argc; ++i) { > std::string arg = argv[i]; > if ((arg == "-d" || arg == "--device") && i + 1 < argc) { > device = argv[++i]; > } > } > try { > create_and_execute_pipeline(device); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **1. Connect a USB camera** > > Connect a USB (UVC) camera to the target device and verify it is exposed as `/dev/video2` (update the pipeline's `device` property if your camera is exposed on a different node). > > **2. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_usb_camera_impl --input-config /dev/video2 > ``` > > The application connects to the USB camera, restricts the stream to NV12/1080p/30fps, and renders it fullscreen on the display. > > **3. Expected Output** > > The live USB camera feed is rendered fullscreen on the display. > > ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/usb-camera-preview.jpeg?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=2ed060f58a450ceb48de22da1d5cf295) > > To stop the application, press **CTRL + C**. > > **4. Customize application** > > * **Source code:** [`qimsdk_ref_usb_camera_impl`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_usb_camera_impl) > * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) > > **YAML config style** > > > [!NOTE] > > > > See the full YAML configuration here: [qimsdk\_ref\_usb\_camera.yaml](https://github.com/qualcomm/qimsdk/blob/main/tools/appbuilders-configs/qimsdk_ref_usb_camera.yaml) > > > > Check application source code on GitHub: [qimsdk\_ref\_yml](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_yml) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_yml` > > > > YAML configuration saved on device: `/etc/qimsdk/qimsdk_ref_usb_camera.yaml` > > ```yaml theme={null} > pipeline: > elements: > - type: v4l2src > name: source > device: /dev/video2 > > - type: qtivtransform > name: transform > > - type: filter > name: videostream > video: > format: NV12 > width: 1920 > height: 1080 > framerate: 30 > > - type: waylandsink > name: display > sync: false > fullscreen: true > ``` > > **1. Connect a USB camera** > > Connect a USB (UVC) camera to the target device and verify it is exposed as `/dev/video2` (update the pipeline's `device` property if your camera is exposed on a different node). > > **2. Run the application** > > ```bash theme={null} > qimsdk_ref_yml /etc/qimsdk/qimsdk_ref_usb_camera.yaml > ``` > > The application connects to the USB camera, restricts the stream to NV12/1080p/30fps, and renders it fullscreen on the display. > > **3. Expected Output** > > The live USB camera feed is rendered fullscreen on the display. > > ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/usb-camera-preview.jpeg?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=2ed060f58a450ceb48de22da1d5cf295) > > To stop the application, press **CTRL + C**. > > **4. Customize application** > > * **Source code:** [qimsdk\_ref\_yml](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_yml) > * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) ### Built-in Camera Preview This pipeline includes a built-in camera node, a stream filter, and a display node. If the device has more than one built-in camera, you can specify which one to use by providing the camera's unique ID. The stream filter defines the camera's output format, resolution, and framerate. You can also configure the display settings, such as enabling fullscreen rendering. > [!NOTE] > > IQ9 has no onboard ISP camera. You can attach an external IMX camera (e.g. from RB3 Gen2) instead — see [ISP Camera (Config #2 / qticamsrc)](/advanced/debugging#isp-camera-config-2--qticamsrc) for the procedure to switch from `libcamera` to `qticamsrc`. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/built_in_cam_src.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=e777745704666adec46efa79f2a7b461) > **Try me** > > **Explicit coding style** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_camera`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_camera` > > ```cpp theme={null} > #include > #include > using namespace qti; > // Example pipeline: > // > // source → [videostream] → display > // > // The pipeline reads camera frames, runs ML inference and postprocessing, > // and displays the result through Wayland. > void create_and_execute_pipeline() { > // Captures frames from the camera source. > Element source("qtiqmmfsrc", "source"); > > // Render video stream on display. > // > // async=false enforce state transition to ensure the buffers are returned on time. > // sync=false disables strict rendering synchronization to the pipeline clock. > // fullscreen=true renders the output fullscreen on the target display. > Element display("waylandsink", "display"); > display.set("sync", false); > display.set("fullscreen", true); > > // Stream filters used in branch links. > // They define specific stream characteristics from the supported options. > auto videostream = VideoFilter().format("NV12").resolution(1920, 1080).framerate(30); > > // Creates the pipeline, adds and links elements, and executes it. > // > // Linking is implicit and follows the order in which elements are added. > Pipeline pipeline("cam-pipeline"); > pipeline.add(source) > .add_stream_filter("videostream", videostream) > .add(display) > .execute(); > } > int main() { > // Route GStreamer logs through the QIMSDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > try { > create_and_execute_pipeline(); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **Implicit coding style** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_camera_impl`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera_impl) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_camera_impl` > > ```cpp theme={null} > #include > #include > using namespace qti; > void create_and_execute_pipeline() { > Pipeline pipeline("cam-pipeline"); > pipeline.add("qtiqmmfsrc", "source") > .add_stream_filter("videostream", VideoFilter().format("NV12").resolution(1920, 1080).framerate(30)) > .add("waylandsink", "display", "sync", false, "fullscreen", true) > .execute(); > } > int main() { > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > try { > create_and_execute_pipeline(); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **1. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_camera > ``` > > The application captures live camera frames and renders them fullscreen on the display. > > **2. Expected Output** > > A live preview of the camera feed is rendered fullscreen on the display. > > To stop the application, press **CTRL + C**. > > **3. Customize application** > > * **Source code:** [`qimsdk_ref_camera`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera), [`qimsdk_ref_camera_impl`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera_impl) > * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) ### Built-in Camera Preview with Still Capture > [!NOTE] > > The application captures a still image a few seconds after starting and then stops automatically — this is expected behavior, not a hang. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/img_cap_isp.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=82ba5616eae28f1ac42df27be89a9b1b) > **Try me** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_camera_and_capture`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera_and_capture) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_camera_and_capture` > > ```cpp theme={null} > #include > #include > #include > #include > using namespace qti; > static const std::string home_path = > std::getenv("HOME") ? std::getenv("HOME") : ""; > // Example pipeline: > // > // source → [vf] → display → [if] → imagesink > // > // The pipeline reads camera frames, runs ML inference and postprocessing, > // and displays the result through Wayland. > void create_and_execute_pipeline() { > // Captures frames from the camera source. > Element source("qtiqmmfsrc", "source"); > > // Render video stream on display. > // > // async=false enforce state transition to ensure the buffers are returned on time. > // sync=false disables strict rendering synchronization to the pipeline clock. > // fullscreen=true renders the output fullscreen on the target display. > Element display("waylandsink", "display"); > display.set("async", false); > display.set("sync", false); > display.set("fullscreen", true); > > // Writes output buffers to files. > Element imagesink("multifilesink", "imagesink"); > imagesink.set("enable-last-sample", false); > imagesink.set("location", home_path + "/Downloads/qimsdk_samples/media/image_%d.jpeg"); > > // Stream filters used in branch links. > // They define specific stream characteristics from the supported options. > auto vf = VideoFilter().format("NV12").resolution(1920, 1080).framerate(30); > auto image_filter = ImageFilter().format("jpeg").resolution(3840, 2160); > > // Creates the pipeline, adds and links elements, and executes it. > // > // Explicit linking is applied > Pipeline pipeline("cam-pipeline"); > pipeline.add(source) > .add_stream_filter("vf", vf) > .add(display) > .add_stream_filter("if", image_filter) > .add(imagesink) > .link("source", "vf", "display") > .link("source", "if", "imagesink") > .start(); > > std::this_thread::sleep_for(std::chrono::seconds(2)); > > auto cam = pipeline.get("source"); > cam.image_capture(); > > std::this_thread::sleep_for(std::chrono::seconds(2)); > > pipeline.stop(); > } > int main() { > if (home_path.empty()) { > std::cerr << "Error: HOME environment variable is not set." << std::endl; > return 1; > } > // Route GStreamer logs through the QIMSDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > try { > create_and_execute_pipeline(); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **1. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_camera_and_capture > ``` > > The application displays a live preview and captures a still JPEG image a few seconds after starting, saving it under `~/media/image_%d.jpeg`. > > **2. Expected Output** > > A live preview is rendered, followed by a still JPEG image saved to `~/Downloads/qimsdk_samples/media/image_%d.jpeg`. The application then stops automatically. > > **3. Customize application** > > * **Source code:** [`qimsdk_ref_camera_and_capture`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera_and_capture) > * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) ### Camera Recording to MP4 This pipeline captures frames from the built-in camera, encodes them into an H.264 stream using the hardware encoder, parses the bitstream, muxes it into an MP4 container, and writes the resulting file to disk. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/camera-encoder.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=3facf40df2e33b24c695a56c41e08223) > **Try me** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_camera_encoder`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera_encoder) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_camera_encoder` > > ```cpp theme={null} > #include > #include > #include > using namespace qti; > static const std::string home_path = > std::getenv("HOME") ? std::getenv("HOME") : ""; > // Example pipeline: > // > // source -> [vf] -> encoder -> parser -> muxer -> sink > // > // The pipeline reads camera frames, encodes them with H.264, muxes into MP4, > // and writes the output to disk. > void create_and_execute_pipeline() { > // Captures frames from the camera source. > Element source("qtiqmmfsrc", "source"); > // Encodes raw video frames into H.264 stream. > Element encoder("v4l2h264enc", "encoder"); > encoder.set("output-io-mode", "dmabuf-import"); > encoder.set("capture-io-mode", "dmabuf"); > // Parses H.264 bitstream for downstream muxing. > Element parser("h264parse", "parser"); > // Muxes encoded stream into MP4 container. > Element muxer("mp4mux", "muxer"); > // Writes output stream to a file. > Element sink("filesink", "sink"); > sink.set("location", home_path + "/Downloads/qimsdk_samples/media/encoder_output.mp4"); > // Stream filters used in branch links. > // They define specific stream characteristics from the supported options. > auto vf = VideoFilter().format("NV12").resolution(1920, 1080).framerate(30); > // Creates the pipeline, adds and links elements, and executes it. > // > // Explicit linking is applied. > Pipeline pipeline("cam-encoder-pipeline"); > pipeline.add(source) > .add_stream_filter("vf", vf) > .add(encoder) > .add(parser) > .add(muxer) > .add(sink) > .eos(true) > .execute(); > } > int main() { > if (home_path.empty()) { > std::cerr << "Error: HOME environment variable is not set." << std::endl; > return 1; > } > // Route GStreamer logs through the QIMSDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > try { > create_and_execute_pipeline(); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **1. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_camera_encoder > ``` > > The application records camera frames encoded as H.264 into an MP4 file saved to `~/Downloads/qimsdk_samples/media/encoder_output.mp4`. > > **2. Expected Output** > > The recorded MP4 file is written to `~/Downloads/qimsdk_samples/media/encoder_output.mp4` and can be played back to verify the camera recording. > > To stop the application, press **CTRL + C**. > > **3. Customize application** > > * **Source code:** [`qimsdk_ref_camera_encoder`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_camera_encoder) > * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) ### MP4 File Playback This pipeline ingests an MP4 file, demultiplexes it to extract the video track, decodes the compressed stream (e.g., H.264/H.265) into raw frames, converts (or directly negotiates) the output to NV12 — a hardware-friendly YUV 4:2:0 semi-planar format — and then renders the frames to the display using a sink that supports zero-copy or hardware buffers. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/offline_video_src.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=22f1d4b65ef60c1a7e1561843da9a5ee) > **Try me** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_qtdemux_decode_display`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_qtdemux_decode_display) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_qtdemux_decode_display` > > ```cpp theme={null} > #include > #include > #include > using namespace qti; > static const std::string home_path = > std::getenv("HOME") ? std::getenv("HOME") : ""; > // Example pipeline: > // > // src → demux → parse → decoder → [videofilter] → display > // > // The pipeline reads an MP4/H.264 file, decodes it through the hardware decoder, > // overlays detected objects, and displays the result through Wayland. > void create_and_execute_pipeline() { > // Reads the input media file as raw bytes. > Element src("filesrc", "src"); > src.set("location", home_path + "/Downloads/qimsdk_samples/media/ai_demo_sample.mp4"); > > // Extracts elementary streams from the MP4 container. > Element demux("qtdemux", "demux"); > > // Prepares the H.264 bitstream for the decoder. > Element parse("h264parse", "parse"); > > // Decodes the compressed H.264 stream into raw video frames. > // > // The I/O mode is configured to enforce DMA buffer usage, > // avoiding unnecessary buffer copies. > Element decoder("v4l2h264dec", "decoder"); > decoder.set("output-io-mode", 4); > decoder.set("capture-io-mode", 4); > > // Render video stream on display. > // > // async=false enforce state transition to ensure the buffers are returned on time. > // sync=true keeps rendering synchronized to the pipeline clock. > // fullscreen=true renders the output fullscreen on the target display. > Element display("waylandsink", "display"); > display.set("fullscreen", true); > > // Stream filters used in branch links. > // They define specific stream characteristics from the supported options. > auto videofilter = VideoFilter().format("NV12"); > > // Creates the pipeline, adds and links elements, and executes it. > // > // Linking is implicit and follows the order in which elements are added. > Pipeline pipeline("video-pipeline"); > pipeline.add(src) > .add(demux) > .add(parse) > .add(decoder) > .add_stream_filter("videofilter", videofilter) > .add(display); > pipeline.start().wait().stop(); > } > int main() { > if (home_path.empty()) { > std::cerr << "Error: HOME environment variable is not set." << std::endl; > return 1; > } > // Route GStreamer logs through the QIMSDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > try { > create_and_execute_pipeline(); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **1. Download Required Files** > > | File | Download | Save as | > | - | - | - | > | Sample video | [ai\_demo\_sample.mp4](https://github.com/qualcomm/sample-apps-for-qualcomm-linux/blob/main/qualcomm-linux/artifacts/videos/demo_samples/ai_demo_sample.mp4) | `ai_demo_sample.mp4` | > > You can also use your own MP4 (H.264) file, or update the pipeline's `location` property to point to it. > > **2. Copy the video file to the device** > > ```bash theme={null} > # ~ resolves automatically to the correct home directory on the device (/root on QLI, /home/ubuntu on Ubuntu). > > ssh @ "mkdir -p ~/Downloads/qimsdk_samples/media" > scp ai_demo_sample.mp4 @:~/Downloads/qimsdk_samples/media/ > ``` > > **3. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_qtdemux_decode_display > ``` > > The application decodes the video file and renders it fullscreen on the display. > > **4. Expected Output** > > The MP4 video plays back fullscreen on the display. > > ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/video-play-back.png?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=3e0d2e8fcff29d3d3ed1778114b86df7) > > To stop the application, press **CTRL + C**. > > **5. Customize application** > > * **Source code:** [`qimsdk_ref_qtdemux_decode_display`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_qtdemux_decode_display) > * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) ### Transport Stream (.ts) File Playback This pipeline is similar to the Offline Video Source pipeline, but ingests an MPEG transport stream (`.ts`) file instead of an MP4 container. It demultiplexes the transport stream using `tsdemux` to extract the video track, decodes the compressed H.264 stream into raw frames, converts (or directly negotiates) the output to NV12, and renders the frames to the display. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/transport-stream-video-source.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=d82a97ad8232ad92d41ae13f30ea397e) > **Try me** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_tsdemux_decode_display`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_tsdemux_decode_display) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_tsdemux_decode_display` > > ```cpp theme={null} > #include > #include > #include > using namespace qti; > static const std::string home_path = > std::getenv("HOME") ? std::getenv("HOME") : ""; > // Example pipeline: > // > // src → demux → [vf1] → parse → decoder → [vf2] → display > // > // The pipeline reads an MPEG transport stream (.ts) file, demultiplexes it, > // decodes the H.264 stream through the hardware decoder, and displays the > // result through Wayland. > void create_and_execute_pipeline() { > // Reads a sequence of input files as stream data. > Element src("multifilesrc", "src"); > src.set("location", home_path + "/Downloads/qimsdk_samples/media/ai_demo_sample.ts"); > src.set("stop-index", 0); > // Extracts elementary streams from the transport stream. > Element demux("tsdemux", "demux"); > // Prepares the H.264 bitstream for the decoder. > Element parse("h264parse", "parse"); > // Decodes the compressed H.264 stream into raw video frames. > // > // The I/O mode is configured to enforce DMA buffer usage, > // avoiding unnecessary buffer copies. > Element decoder("v4l2h264dec", "decoder"); > decoder.set("output-io-mode", 4); > decoder.set("capture-io-mode", 4); > // Render video stream on display. > // > // async=false enforce state transition to ensure the buffers are returned on time. > // sync=true keeps rendering synchronized to the pipeline clock. > // fullscreen=true renders the output fullscreen on the target display. > Element display("waylandsink", "display"); > display.set("fullscreen", true); > auto vf1 = H264Filter().framerate(30); > // Stream filters used in branch links. > // They define specific stream characteristics from the supported options. > auto vf2 = VideoFilter().format("NV12"); > // Creates the pipeline, adds and links elements, and executes it. > // > // Linking is implicit and follows the order in which elements are added. > Pipeline pipeline("video-pipeline"); > pipeline.add(src) > .add(demux) > .add_stream_filter("vf1", vf1) > .add(parse) > .add(decoder) > .add_stream_filter("vf2", vf2) > .add(display); > pipeline.start().wait().stop(); > } > int main() { > if (home_path.empty()) { > std::cerr << "Error: HOME environment variable is not set." << std::endl; > return 1; > } > // Route GStreamer logs through the QIMSDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > try { > create_and_execute_pipeline(); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **1. Download Required Files** > > | File | Download | Save as | > | - | - | - | > | Sample transport stream | [ai\_demo\_sample.ts](https://github.com/qualcomm/sample-apps-for-qualcomm-linux/raw/refs/heads/main/qualcomm-linux/artifacts/videos/demo_samples/ai_demo_sample.ts) | `ai_demo_sample.ts` | > > **2. Copy the transport stream file to the device** > > ```bash theme={null} > # ~ resolves automatically to the correct home directory on the device (/root on QLI, /home/ubuntu on Ubuntu). > > ssh @ "mkdir -p ~/Downloads/qimsdk_samples/media" > scp ai_demo_sample.ts @:~/Downloads/qimsdk_samples/media/ > ``` > > **3. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_tsdemux_decode_display > ``` > > The application decodes the transport stream file and renders it fullscreen on the display. > > **4. Expected Output** > > The transport stream video plays back fullscreen on the display. > > ![Expected Output](https://mintcdn.com/qimsdk/vM1cbKMfLRcPD7xl/app-builder/images/video-play-back.png?fit=max\&auto=format\&n=vM1cbKMfLRcPD7xl\&q=85\&s=3e0d2e8fcff29d3d3ed1778114b86df7) > > To stop the application, press **CTRL + C**. > > **5. Customize application** > > * **Source code:** [`qimsdk_ref_tsdemux_decode_display`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_tsdemux_decode_display) > * **Build instructions:** [Steps to build custom application](/advanced/yocto-build#steps-to-build-custom-application) ### Synthetic Test Pattern (VideoFilter API) This pipeline generates synthetic test video frames using `videotestsrc` (a bouncing ball pattern), instead of reading from a camera or file. The frames are restricted to NV12/1080p/30fps, rotated 180 degrees by [`qtivtransform`](/plugin-reference/qtivtransform), downscaled to 1280x720 by a second stream filter, and rendered to the display. This is a useful pipeline for testing display and transform stages without any camera or media file dependency. ![Introduction](https://mintcdn.com/qimsdk/QarSxH4rrv0vwi-l/app-builder/images/video-test-source-with-video-filter.png?fit=max\&auto=format\&n=QarSxH4rrv0vwi-l\&q=85\&s=d61e04032b475dd2ee014d28ed1a7fa8) > **Try me** > > > [!NOTE] > > > > Check application source code on GitHub: [`qimsdk_ref_videotestsrc_videofilter_display`](https://github.com/qualcomm/qimsdk/tree/main/cpp/examples/reference-apps/qimsdk_ref_videotestsrc_videofilter_display) > > > > Pre-built application on device: `/usr/bin/qimsdk_ref_videotestsrc_videofilter_display` > > ```cpp theme={null} > #include > #include > using namespace qti; > // Example pipeline: > // > // src → [vf1] → transform → [vf2] → sink > // > // The pipeline generates synthetic test video frames, rotates them, restricts > // the stream to NV12/1080p/30fps, downscales to 720p, and displays the result > // through Wayland. > void create_and_execute_pipeline() { > // Generates synthetic test video frames. > Element src("videotestsrc", "src"); > src.set("pattern", "ball"); > // Applies geometric transforms to video frames. > Element transform("qtivtransform", "transform"); > transform.set("rotate", "180"); > // Render video stream on display. > Element sink("waylandsink", "sink"); > sink.set("fullscreen", true); > // Stream filters used in branch links. > // They define specific stream characteristics from the supported options. > auto vf1 = qti::VideoFilter().format("NV12").resolution(1920, 1080).framerate(30); > auto vf2 = qti::VideoFilter().resolution(1280, 720); > // Creates the pipeline, adds and links elements, and executes it. > // > // Linking is implicit and follows the order in which elements are added. > Pipeline pipeline("video-pipeline"); > pipeline.add(src) > .add_stream_filter("vf1", vf1) > .add(transform) > .add_stream_filter("vf2", vf2) > .add(sink) > .execute(); > } > int main() { > // Route GStreamer logs through the QIMSDK logger and enable debug output. > qti::SetImsdkGstLogMode(qti::ImsdkGstLogMode::ImsdkLog); > qti::SetImsdkLogLevel(qti::ImsdkLogLevel::Debug); > try { > create_and_execute_pipeline(); > } catch (const std::exception &ex) { > std::cerr << "Exception: " << ex.what() << std::endl; > return 1; > } > return 0; > } > ``` > > **1. Run the application** > > ```bash theme={null} > /usr/bin/qimsdk_ref_videotestsrc_videofilter_display > ``` > > The application generates a synthetic bouncing-ball test pattern, rotates and rescales it, and renders it fullscreen on the display. > > **2. Expected Output** > > A rotated, rescaled bouncing-ball test pattern is rendered fullscreen on the display. > >