fix(simulation): prevent unbounded memory growth in GstCameraSystem (#27873) (#29591)

* fix(simulation): prevent unbounded memory growth in GstCameraSystem

Each CameraStream pushed camera frames into an appsrc with no queue
bound (block=false, enough-data unhandled) and never read the pipeline
bus, so when the pipeline stalled the frames accumulated silently at
frame_size x fps (~110 MB/s per camera at 1280x960@30) until the host
froze. The stall is guaranteed on modern NVIDIA drivers because the
nvh264enc path sets legacy NVENC properties they reject, killing caps
negotiation before data ever flows, while set_state() only being
checked for FAILURE (pipelines with sinks return ASYNC) hid the error.

Bound the appsrc queue (max-buffers=3, leaky-type=downstream) so a
stalled pipeline drops frames instead of hoarding them, surface bus
errors/warnings through gzerr/gzwarn, verify the async transition to
PLAYING, retry once with software x264 when the NVIDIA encoder fails,
drop the driver-incompatible encoder properties, and guard the frame
memcpy against undersized frames. Also make ~CameraStream() call
stop() unconditionally: after a pipeline failure (_running == false)
the streaming thread could still be joinable, and destroying a
joinable std::thread terminates the process.



* fix(simulation): end the camera stream loop on stop during pipeline setup

stop() can run before runPipeline() sets _running, which then overwrote the cleared flag; the frame loop never checked _stopRequested, so join() blocked gz shutdown. The pipeline cleanup in stop() was unreachable: runPipeline() releases the pipeline on every return.

Assisted-by: Claude:claude-opus-5-5

* fix(simulation): retry the camera stream with x264 only after an NVENC failure

The retry fired on any pipeline error, including runs where the NVIDIA element was never created and x264 was already in use, so it rebuilt the same pipeline under a misleading warning.

Assisted-by: Claude:claude-opus-5-5

* fix(simulation): drop the PLAYING wait from the camera stream start

It cannot see an encoder failure, which happens on the first frame, and with rtmpsink it blocked for the full 5 s because the sink cannot preroll until this thread pushes a frame. The bus loop reports both kinds of failure.

Assisted-by: Claude:claude-opus-5-5

* fix(simulation): warn once about undersized camera frames

The warning fired on every frame at the camera rate. GST_MESSAGE_SRC_NAME also handles a bus message without a source.

Assisted-by: Claude:claude-opus-5-5

---------



(cherry picked from commit 4b1ac1879d)

Signed-off-by: PasinJ <porh8pasin@gmail.com>
Signed-off-by: jiakun <53556221+ddwolf87@users.noreply.github.com>
Co-authored-by: porh <155837075+porhJ@users.noreply.github.com>
Co-authored-by: Jacob Dahl <dahl.jakejacob@gmail.com>
This commit is contained in:
authored and GitHub committed 2026-11-03 12:14:03 -07:00
1 parent 5b22d9ed66
commit fe1bd3e03a
2 files changed
+107 -42

No files matched your search

@@ -176,8 +176,7 @@ void GstCameraSystem::PostUpdate(const gz::sim::UpdateInfo &_info,
return;
}
// New cameras appeared (for example, spawned new vehicle instance in
// multi-vehicle simulation)
// New cameras appeared
_ecm.EachNew<gz::sim::components::Camera, gz::sim::components::Name,
gz::sim::components::ParentEntity>(
[&](const gz::sim::Entity & entity, const gz::sim::components::Camera *,
@@ -249,27 +248,18 @@ void CameraStream::start()
/////////////////////////////////////////////////
void CameraStream::stop()
{
_stopRequested = true;
_running = false;
if (_gstLoop) {
g_main_loop_quit(_gstLoop);
}
if (_gstThread.joinable()) {
_gstThread.join();
}
if (_pipeline) {
gst_element_set_state(_pipeline, GST_STATE_NULL);
gst_object_unref(_pipeline);
}
}
CameraStream::~CameraStream()
{
if (_running) {
stop();
}
// Always stop: a failed pipeline can leave the thread joinable, and destroying a joinable std::thread terminates the process.
stop();
}
//////////////////////////////////////////////////
@@ -315,20 +305,33 @@ void CameraStream::gstThreadFunc()
{
gzdbg << "Starting GStreamer thread" << std::endl;
_gstLoop = g_main_loop_new(nullptr, FALSE);
bool tryCuda = _useCuda;
if (!_gstLoop) {
gzerr << "Failed to create GStreamer main loop" << std::endl;
return;
while (!_stopRequested) {
bool usedNvenc = false;
const bool error = runPipeline(tryCuda, usedNvenc);
// NVENC can be present but fail on the first frame. Any other failure would recur with x264.
if (error && usedNvenc && !_stopRequested) {
gzwarn << "GStreamer pipeline failed with NVIDIA encoder; retrying with software (x264) encoder" << std::endl;
tryCuda = false;
continue;
}
break;
}
gzdbg << "GStreamer thread stopped" << std::endl;
}
//////////////////////////////////////////////////
bool CameraStream::runPipeline(bool useCuda, bool &usedNvenc)
{
_pipeline = gst_pipeline_new(nullptr);
if (!_pipeline) {
gzerr << "Failed to create GStreamer pipeline" << std::endl;
g_main_loop_unref(_gstLoop);
_gstLoop = nullptr;
return;
return true;
}
// Create elements
@@ -351,8 +354,9 @@ void CameraStream::gstThreadFunc()
GstElement *encoder;
if (_useCuda) {
if (useCuda) {
encoder = gst_element_factory_make("nvautogpuh264enc", nullptr);
usedNvenc = (encoder != nullptr);
if (encoder) {
// Higher quality NVIDIA encoder settings
@@ -419,10 +423,8 @@ void CameraStream::gstThreadFunc()
!payloader || !sink) {
gzerr << "Failed to create one or more GStreamer elements" << std::endl;
gst_object_unref(_pipeline);
g_main_loop_unref(_gstLoop);
_pipeline = nullptr;
_gstLoop = nullptr;
return;
return true;
}
// Configure source
@@ -431,10 +433,16 @@ void CameraStream::gstThreadFunc()
_width, "height", G_TYPE_INT, _height, "framerate", GST_TYPE_FRACTION,
(unsigned int)_rate, 1, NULL);
// Bound the appsrc queue so a stalled pipeline drops frames instead of
// buffering every one (~110 MB/s at 1280x960@30) until the host OOMs.
g_object_set(G_OBJECT(_source), "caps", sourceCaps, "is-live", TRUE,
"do-timestamp", TRUE, "stream-type", GST_APP_STREAM_TYPE_STREAM,
"format", GST_FORMAT_TIME, "min-latency", 0, "max-latency", 0,
"emit-signals", TRUE, NULL);
"emit-signals", TRUE,
"max-bytes", (guint64)0,
"max-buffers", (guint64)3,
"leaky-type", GST_APP_LEAKY_TYPE_DOWNSTREAM,
NULL);
gst_caps_unref(sourceCaps);
@@ -455,21 +463,18 @@ void CameraStream::gstThreadFunc()
queue2, encoder, payloader, sink, nullptr)) {
gzerr << "Failed to link GStreamer elements" << std::endl;
gst_object_unref(_pipeline);
g_main_loop_unref(_gstLoop);
_pipeline = nullptr;
_gstLoop = nullptr;
return;
return true;
}
// Start pipeline
if (gst_element_set_state(_pipeline, GST_STATE_PLAYING) ==
GST_STATE_CHANGE_FAILURE) {
gzerr << "Failed to set GStreamer pipeline to playing state" << std::endl;
gst_element_set_state(_pipeline, GST_STATE_NULL);
gst_object_unref(_pipeline);
g_main_loop_unref(_gstLoop);
_pipeline = nullptr;
_gstLoop = nullptr;
return;
return true;
}
gzdbg << "GStreamer pipeline started, streaming to "
@@ -477,15 +482,70 @@ void CameraStream::gstThreadFunc()
: (_udpHost + ":" + std::to_string(_udpPort)))
<< std::endl;
// Watch the bus so async pipeline errors are surfaced, not dropped.
GstBus *bus = gst_element_get_bus(_pipeline);
_running = true;
bool pipelineError = false;
bool warnedUndersized = false;
// Not _running: a stop() during pipeline setup clears it before it is set above.
while (!_stopRequested && !pipelineError) {
// Drain pending bus messages
if (bus) {
GstMessage *busMsg;
while ((busMsg = gst_bus_pop_filtered(bus,
(GstMessageType)(GST_MESSAGE_ERROR | GST_MESSAGE_WARNING))) != nullptr) {
GError *gerr = nullptr;
gchar *dbgInfo = nullptr;
if (GST_MESSAGE_TYPE(busMsg) == GST_MESSAGE_ERROR) {
gst_message_parse_error(busMsg, &gerr, &dbgInfo);
gzerr << "GStreamer pipeline error from ["
<< GST_MESSAGE_SRC_NAME(busMsg) << "]: "
<< (gerr ? gerr->message : "unknown")
<< (dbgInfo ? (std::string(" (") + dbgInfo + ")") : "")
<< std::endl;
pipelineError = true;
} else {
gst_message_parse_warning(busMsg, &gerr, &dbgInfo);
gzwarn << "GStreamer warning from ["
<< GST_MESSAGE_SRC_NAME(busMsg) << "]: "
<< (gerr ? gerr->message : "unknown")
<< std::endl;
}
if (gerr) {
g_error_free(gerr);
}
g_free(dbgInfo);
gst_message_unref(busMsg);
}
}
// Process frames
while (_running) {
std::unique_lock<std::mutex> lock(_frameMutex);
if (_newFrameAvailable) {
if (_newFrameAvailable && !pipelineError) {
// Push RGB data directly - we configured the caps to accept RGB
const guint size = _width * _height * 3; // RGB is 3 bytes per pixel
// Skip undersized frames: the memcpy below would read OOB.
if (_currentFrame.data().size() < size) {
if (!warnedUndersized) {
gzwarn << "Skipping camera frames: got " << _currentFrame.data().size()
<< " bytes, expected " << size << std::endl;
warnedUndersized = true;
}
_newFrameAvailable = false;
lock.unlock();
std::this_thread::sleep_for(std::chrono::milliseconds(5));
continue;
}
GstBuffer *buffer = gst_buffer_new_allocate(nullptr, size, nullptr);
if (buffer) {
@@ -532,13 +592,17 @@ void CameraStream::gstThreadFunc()
}
// Cleanup
_running = false;
if (bus) {
gst_object_unref(bus);
}
gst_element_set_state(_pipeline, GST_STATE_NULL);
gst_object_unref(_pipeline);
g_main_loop_unref(_gstLoop);
_pipeline = nullptr;
_gstLoop = nullptr;
gzdbg << "GStreamer thread stopped" << std::endl;
return pipelineError;
}
// Register this plugin
@@ -81,11 +81,11 @@ private:
std::atomic<bool> _newFrameAvailable{};
// GStreamer elements
GMainLoop *_gstLoop{};
GstElement *_pipeline{};
GstElement *_source{};
std::thread _gstThread;
std::atomic<bool> _running{};
std::atomic<bool> _stopRequested{};
// stream params
int _width{0};
@@ -101,6 +101,9 @@ private:
void onImage(const gz::msgs::Image &msg);
void gstThreadFunc();
// Returns true on error, false on a normal stop.
bool runPipeline(bool useCuda, bool &usedNvenc);
};
@@ -139,9 +142,7 @@ private:
std::string _rtmpLocation;
bool _useCuda = true;
// methods below are used to maintain consistency in udp ports when restarting instances. For example, if we have
// instance 1 streaming on port 5601 we also want it to stream to the same port if we shutdown and restart the
// instance
// methods below are used to maintain consistency in udp ports when restarting instances.
std::unordered_set<int> _usedUdpPorts;
int getAvailableUdpPort()