Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion src/service-maker/includes/buffer.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,10 @@ class Buffer {
BatchMetadata getBatchMetadata();

/**
* @brief create a tensor object with the buffer data
* @brief Create a tensor referencing a filled RGB surface in the buffer.
* The tensor retains the backing buffer until destruction.
* @return An owned tensor, or nullptr for an invalid buffer, unfilled/out-of-range
* batchId, unsupported format/memory layout, or failed EGL mapping.
*
*/
virtual Tensor* extract(unsigned int batchId);
Expand Down
146 changes: 93 additions & 53 deletions src/service-maker/sources/core/src/buffer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -81,41 +81,54 @@ static std::vector<int> extract_chunk_ids_from_buffer(GstBuffer* buffer)
class GstBufferTensorContext : public Tensor::Context {
public:
GstBufferTensorContext(GstBuffer *buffer) : buffer_(buffer) {
// gst_buffer_ref(buffer_);
gst_buffer_ref(buffer_);
}
virtual ~GstBufferTensorContext() {
// gst_buffer_unref(buffer_);
gst_buffer_unref(buffer_);
}
protected:
GstBuffer* buffer_;
};

class TegraGstBufferTensorContext : public Tensor::Context
class TegraGstBufferTensorContext : public GstBufferTensorContext
{
public:
TegraGstBufferTensorContext(GstBuffer *buffer, unsigned int batchId, CUgraphicsResource& cuGrphRes) : buffer_(buffer), batchId_(batchId), cuGrphRes_(cuGrphRes)
TegraGstBufferTensorContext(GstBuffer *buffer, unsigned int batchId,
CUgraphicsResource cuGrphRes, CUcontext context)
: GstBufferTensorContext(buffer), batchId_(batchId), cuGrphRes_(cuGrphRes), context_(context)
{
}
virtual ~TegraGstBufferTensorContext()
~TegraGstBufferTensorContext() override
{
GstMapInfo map = GST_MAP_INFO_INIT;
gst_buffer_map(buffer_, &map, GST_MAP_READ);
NvBufSurface *surface_batch = (NvBufSurface *)map.data;
if (NvBufSurfaceUnMapEglImage(surface_batch, batchId_) != 0) {
printf("Error: Failed to unmap EGL image\n");
// Tensor destruction may happen on a different thread from extraction.
if (cuCtxPushCurrent(context_) != CUDA_SUCCESS) {
g_printerr("Failed to restore CUDA context for EGL cleanup\n");
return;
}
if (cuCtxSynchronize() != CUDA_SUCCESS) {
g_printerr("Failed to synchronize CUDA before EGL cleanup\n");
}
cuCtxSynchronize();
CUresult status = cuGraphicsUnregisterResource(cuGrphRes_);
if (status != CUDA_SUCCESS) {
printf("Error: Failed to unregister CUDA graphics resource \n");
g_printerr("Failed to unregister CUDA graphics resource\n");
} else {
GstMapInfo map = GST_MAP_INFO_INIT;
if (gst_buffer_map(buffer_, &map, GST_MAP_READ)) {
if (map.data && map.size == sizeof(NvBufSurface) &&
NvBufSurfaceUnMapEglImage((NvBufSurface*)map.data, batchId_) != 0) {
g_printerr("Failed to unmap EGL image\n");
}
gst_buffer_unmap(buffer_, &map);
}
}
gst_buffer_unmap(buffer_, &map);
CUcontext previous;
cuCtxPopCurrent(&previous);
}

protected:
GstBuffer *buffer_;
private:
unsigned int batchId_;
CUgraphicsResource cuGrphRes_;
CUcontext context_;
};

static void
Expand Down Expand Up @@ -295,58 +308,85 @@ Tensor* Buffer::extract(unsigned int batchId) {
Tensor* tensor = nullptr;
if (buffer_) {
GstMapInfo map = GST_MAP_INFO_INIT;
gst_buffer_map(buffer_, &map, GST_MAP_READ);
auto buf_size = map.size;
if (!gst_buffer_map(buffer_, &map, GST_MAP_READ)) {
return nullptr;
}
if (map.data == nullptr || map.size != sizeof(NvBufSurface)) {
gst_buffer_unmap(buffer_, &map);
return nullptr;
}
NvBufSurface *surface_batch = (NvBufSurface*) map.data;
if (surface_batch->surfaceList == nullptr ||
batchId >= surface_batch->batchSize || batchId >= surface_batch->numFilled) {
gst_buffer_unmap(buffer_, &map);
return nullptr;
}
NvBufSurfaceParams &surface = surface_batch->surfaceList[batchId];
if (buf_size == sizeof(NvBufSurface)) {
if (surface_batch->memType == NVBUF_MEM_CUDA_DEVICE ||
surface_batch->memType == NVBUF_MEM_CUDA_PINNED ||
surface_batch->memType == NVBUF_MEM_CUDA_UNIFIED ||
surface_batch->memType == NVBUF_MEM_DEFAULT) {
if (surface.colorFormat == NVBUF_COLOR_FORMAT_RGB) {
int64_t shape[] = {surface.height, surface.width, 3};
int64_t strides[] = {surface.pitch, 3, 1};
auto* ctx = new GstBufferTensorContext(buffer_);
tensor = new Tensor(3, Tensor::UNSIGNED, 8, shape, strides, surface.dataPtr, "HWC", surface_batch->gpuId, Tensor::DeviceType::GPU, ctx);
} else {
g_printerr("Only RGB format is supported for being extracted as a tensor\n");
}
if (surface_batch->memType == NVBUF_MEM_CUDA_DEVICE ||
surface_batch->memType == NVBUF_MEM_CUDA_PINNED ||
surface_batch->memType == NVBUF_MEM_CUDA_UNIFIED ||
surface_batch->memType == NVBUF_MEM_DEFAULT) {
if (surface.colorFormat == NVBUF_COLOR_FORMAT_RGB) {
int64_t shape[] = {surface.height, surface.width, 3};
int64_t strides[] = {surface.pitch, 3, 1};
auto* ctx = new GstBufferTensorContext(buffer_);
tensor = new Tensor(3, Tensor::UNSIGNED, 8, shape, strides, surface.dataPtr, "HWC", surface_batch->gpuId, Tensor::DeviceType::GPU, ctx);
} else {
g_printerr("Only RGB format is supported for being extracted as a tensor\n");
}
#if defined(__aarch64__)
else if (surface_batch->memType == NVBUF_MEM_SURFACE_ARRAY || surface_batch->memType == NVBUF_MEM_HANDLE)
}
#if defined(__aarch64__)
else if (surface_batch->memType == NVBUF_MEM_SURFACE_ARRAY)
{
if (surface.colorFormat == NVBUF_COLOR_FORMAT_RGB)
{
if (surface.colorFormat == NVBUF_COLOR_FORMAT_RGB)
{
int64_t shape[] = {surface.height, surface.width, 3};
int64_t strides[] = {surface.pitch, 3, 1};
CUeglFrame eglFrame;
CUgraphicsResource cuGrphRes;
CUresult cuStatus = CUDA_SUCCESS;
if (NvBufSurfaceMapEglImage(surface_batch, batchId) != 0)
g_printerr("EGL Image Map Failed\n");
cuStatus = cuGraphicsEGLRegisterImage(&cuGrphRes, surface.mappedAddr.eglImage, CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE);
if (cuStatus != CUDA_SUCCESS)
g_printerr("EGL Reguster Image Failed\n");
cuGraphicsResourceGetMappedEglFrame(&eglFrame, cuGrphRes, batchId, 0);
tensor = new Tensor(3, Tensor::UNSIGNED, 8, shape, strides, eglFrame.frame.pPitch[0], "HWC", surface_batch->gpuId, Tensor::DeviceType::GPU, new TegraGstBufferTensorContext(buffer_, batchId, cuGrphRes));
CUeglFrame eglFrame{};
CUgraphicsResource cuGrphRes = nullptr;
CUcontext context = nullptr;
if (cuCtxGetCurrent(&context) != CUDA_SUCCESS || context == nullptr) {
g_printerr("No current CUDA context for EGL extraction\n");
gst_buffer_unmap(buffer_, &map);
return nullptr;
}
if (NvBufSurfaceMapEglImage(surface_batch, batchId) != 0) {
g_printerr("EGL image map failed\n");
gst_buffer_unmap(buffer_, &map);
return nullptr;
}
CUresult cuStatus = cuGraphicsEGLRegisterImage(
&cuGrphRes, surface.mappedAddr.eglImage, CU_GRAPHICS_MAP_RESOURCE_FLAGS_NONE);
if (cuStatus != CUDA_SUCCESS) {
g_printerr("EGL image registration failed\n");
NvBufSurfaceUnMapEglImage(surface_batch, batchId);
gst_buffer_unmap(buffer_, &map);
return nullptr;
}
else
{
g_printerr("Only RGB format is supported for being extracted as a tensor\n");
auto ctx = std::make_unique<TegraGstBufferTensorContext>(buffer_, batchId, cuGrphRes, context);
// The resource is one EGL image already selected by batchId. CUDA's
// index selects a cubemap face, not a DeepStream batch slot.
cuStatus = cuGraphicsResourceGetMappedEglFrame(&eglFrame, cuGrphRes, 0, 0);
if (cuStatus == CUDA_SUCCESS && eglFrame.frameType == CU_EGL_FRAME_TYPE_PITCH &&
eglFrame.planeCount == 1 && eglFrame.frame.pPitch[0] != nullptr) {
int64_t shape[] = {eglFrame.height, eglFrame.width, 3};
int64_t strides[] = {eglFrame.pitch, 3, 1};
tensor = new Tensor(3, Tensor::UNSIGNED, 8, shape, strides,
eglFrame.frame.pPitch[0], "HWC", surface_batch->gpuId,
Tensor::DeviceType::GPU, ctx.release());
} else {
g_printerr("Failed to obtain a pitched RGB EGL frame\n");
}
}
#endif
else
{
g_printerr("Only Buffer Surface Memory types are supported for being extracted as a tensor");
g_printerr("Only RGB format is supported for being extracted as a tensor\n");
}
}
#endif
else
{
g_printerr("We only support extracting buffer surface as a tensor\n");
g_printerr("Only Buffer Surface Memory types are supported for being extracted as a tensor");
}
gst_buffer_unmap(buffer_, &map);
gst_buffer_unmap(buffer_, &map);
}

return tensor;
Expand Down
3 changes: 2 additions & 1 deletion src/service-maker/sources/python/src/bindings/buffer.h
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,8 @@ void module_buffer_bind(py::module &m) {
return self.chunkId(id);
}, pydeepstreamdoc::buffer::BufferDoc::get_chunk_id)
.def("extract", [](Buffer& self, unsigned int id) {
return make_unique<TensorWrapper>(self.extract(id));
auto* tensor = self.extract(id);
return tensor ? make_unique<TensorWrapper>(tensor) : nullptr;
},
py::call_guard<py::gil_scoped_release>(),
pydeepstreamdoc::buffer::BufferDoc::extract, py::arg("batch_id")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,10 +47,11 @@ namespace pydeepstreamdoc
:arg batch_id: Batch id of the buffer
:returns: Chunk id of the buffer)pydeepstream";
constexpr const char* extract = R"pydeepstream(
Extract data from the buffer in the batch with given id to a tensor
Extract a filled RGB surface as a tensor. Other formats are unsupported.
The tensor retains its backing buffer. EGL extraction requires pitched memory.

:arg batch_id: *int* Batch id of the buffer
:returns: :class:`Tensor` Buffer data as tensor)pydeepstream";
:arg batch_id: *int* Nonnegative frame batch id (use frame metadata, not batch capacity)
:returns: :class:`Tensor`, or None for invalid buffers, unfilled/out-of-range ids, or unsupported surfaces)pydeepstream";
}

namespace FeederDoc
Expand Down
83 changes: 83 additions & 0 deletions src/service-maker/sources/python/tests/test_extract.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""GPU extraction regression tests; isolate native crashes and hangs in subprocesses."""

import subprocess
import sys

import pytest


@pytest.mark.parametrize("format_name", ["RGB", "RGBA", "NV12"])
@pytest.mark.parametrize("batched", [False, True])
def test_extract(format_name: str, batched: bool) -> None:
result = subprocess.run(
[sys.executable, __file__, format_name, str(int(batched))],
capture_output=True, text=True, timeout=60,
)
assert result.returncode == 0, result.stdout + result.stderr


def run_case(format_name: str, batched: bool) -> None:
from pyservicemaker import Buffer, BufferOperator, Pipeline, Probe

pipeline = Pipeline("extract-regression")
assert Buffer().extract(0) is None
assert Buffer([1, 2, 3]).extract(0) is None

class Inspect(BufferOperator):
def __init__(self) -> None:
super().__init__()
self.results = []
self.errors = []
self.tensors = []

def handle_buffer(self, buffer: Buffer) -> bool:
# Never let test assertions escape a streaming-thread callback (#100).
try:
tensor = buffer.extract(0)
if format_name == "RGB":
assert tensor is not None
assert tensor.shape == (48, 64, 3)
assert tensor.__dlpack_device__()[0] == 2
assert tensor.__dlpack__() is not None
self.tensors.append(tensor)
else:
assert tensor is None
# In a capacity-four batch only slot zero holds a frame.
for index in (1, 3, 4, 2**32 - 1):
assert buffer.extract(index) is None, f"Unexpected tensor for slot {index}"
self.results.append(True)
except Exception as error:
self.errors.append(repr(error))
return True

inspector = Inspect()
pipeline.add("videotestsrc", "source", {"num-buffers": 1, "is-live": True})
pipeline.add("capsfilter", "input_caps", {"caps": "video/x-raw,format=RGBA,width=64,height=48"})
pipeline.add("nvvideoconvert", "upload", {})
pipeline.add("capsfilter", "nvmm", {"caps": "video/x-raw(memory:NVMM),format=RGBA"})
pipeline.link("source", "input_caps", "upload", "nvmm")
upstream = "nvmm"
if batched:
pipeline.add("nvstreammux", "mux", {"batch-size": 4, "width": 64, "height": 48, "batched-push-timeout": 10000})
pipeline.link(("nvmm", "mux"), ("", "sink_0"))
upstream = "mux"
pipeline.add("nvvideoconvert", "convert", {})
pipeline.add("capsfilter", "output_caps", {"caps": f"video/x-raw(memory:NVMM),format={format_name}"})
pipeline.add("fakesink", "sink", {"sync": False, "async": False})
pipeline.link(upstream, "convert", "output_caps", "sink")
pipeline.attach("output_caps", Probe("inspect", inspector))
pipeline.start().wait()
assert not inspector.errors, inspector.errors
assert inspector.results, "No frames reached extraction probe"
# Extracted tensors keep their GstBuffer alive after pipeline teardown.
for tensor in inspector.tensors:
copied = tensor.clone()
assert copied is not None
assert copied.shape == (48, 64, 3)


if __name__ == "__main__":
run_case(sys.argv[1], bool(int(sys.argv[2])))