pipeline: virtual: Simplify streams handling when processing request
diff mbox series

Message ID 20261203061326.532856-1-laurent.pinchart@ideasonboard.com
State New
Headers show
Series
  • pipeline: virtual: Simplify streams handling when processing request
Related show

Commit Message

Laurent Pinchart Dec. 3, 2026, 6:13 a.m. UTC
Stream configurations are stored in a vector of StreamConfig structures
that group a stream and a frame generator. This data structure results
in complex lookup when processing requests. The processRequest()
function first iterates over streams in the request, and for each stream
looks up the corresponding entry in the StreamConfiguration vector and
stores it in a local array. It then iterates over the array to generate
frames for each stream.

This can be simplified by turning the data storage into an std::map
indexed by stream pointers. The streams need to be stored in a separate
vector, but the resulting code is still simpler.

While adapting the pipeline handler to this new structure, standardize
the naming of the variables that iterate over the sream configurations
map to "streamConfig", and drop the null frame generator check in
initFrameGenerator() as the condition can't occur.

Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
---
 src/libcamera/pipeline/virtual/virtual.cpp | 88 +++++++++-------------
 src/libcamera/pipeline/virtual/virtual.h   |  5 +-
 2 files changed, 38 insertions(+), 55 deletions(-)


base-commit: 5944ea56612caf61c814ddede241922c2d0e332a

Comments

Barnabás Pőcze Dec. 3, 2026, 8:10 a.m. UTC | #1
2026. 12. 03. 7:13 keltezéssel, Laurent Pinchart írta:
> Stream configurations are stored in a vector of StreamConfig structures
> that group a stream and a frame generator. This data structure results
> in complex lookup when processing requests. The processRequest()
> function first iterates over streams in the request, and for each stream
> looks up the corresponding entry in the StreamConfiguration vector and
> stores it in a local array. It then iterates over the array to generate
> frames for each stream.
> 
> This can be simplified by turning the data storage into an std::map
> indexed by stream pointers. The streams need to be stored in a separate
> vector, but the resulting code is still simpler.
> 
> While adapting the pipeline handler to this new structure, standardize
> the naming of the variables that iterate over the sream configurations
> map to "streamConfig", and drop the null frame generator check in
> initFrameGenerator() as the condition can't occur.
> 
> Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com>
> ---
>   src/libcamera/pipeline/virtual/virtual.cpp | 88 +++++++++-------------
>   src/libcamera/pipeline/virtual/virtual.h   |  5 +-
>   2 files changed, 38 insertions(+), 55 deletions(-)
> 
> diff --git a/src/libcamera/pipeline/virtual/virtual.cpp b/src/libcamera/pipeline/virtual/virtual.cpp
> index 72a07eef410b..762d2df8a128 100644
> --- a/src/libcamera/pipeline/virtual/virtual.cpp
> +++ b/src/libcamera/pipeline/virtual/virtual.cpp
> @@ -106,7 +106,7 @@ private:
>   		return static_cast<VirtualCameraData *>(camera->_d());
>   	}
>   
> -	bool initFrameGenerator(Camera *camera);
> +	void initFrameGenerator(Camera *camera);
>   	void bufferCompleted(FrameBuffer *buffer);
>   
>   	DmaBufAllocator dmaBufAllocator_;
> @@ -130,7 +130,7 @@ VirtualCameraData::VirtualCameraData(PipelineHandler *pipe,
>   			{ Rectangle(config_.maxResolutionSize) });
>   
>   	/* \todo Support multiple streams and pass multi_stream_test */
> -	streamConfigs_.resize(kMaxStream);
> +	streams_.resize(kMaxStream);
>   
>   	moveToThread(this);
>   }
> @@ -144,38 +144,27 @@ void VirtualCameraData::processRequest(Request *request,
>   	 * completed and managed by the application, so iterating its buffer
>   	 * map directly is not safe.
>   	 */
> -	std::array<std::pair<StreamConfig *, FrameBuffer *>, kMaxStream> buffers;
> -	size_t bufferCount = 0;
> +	Request::BufferMap buffers = request->buffers();

Unfortunately I'm no fan of this copy per frame. :( Looking at this again,
I'm wondering if things might be better off with a single signal at the end
of the processing, and then the handler completes all buffers and the request.
Yes, this would mean the "bufferCompleted" signals from the camera would emitted
at effectively the same time, but not sure how big of a practical issue that
really is.


> +
>   	const auto targetTime = std::chrono::steady_clock::time_point{
>   		std::chrono::nanoseconds(targetTimestamp)
>   	};
>   	std::this_thread::sleep_until(targetTime);
>   
> -	for (const auto &[stream, buffer] : request->buffers()) {
> -		bool found = false;
> -		for (auto &streamConfig : streamConfigs_) {
> -			if (stream == &streamConfig.stream) {
> -				buffers[bufferCount++] = { &streamConfig, buffer };
> -				found = true;
> -				break;
> -			}
> -		}
> -		ASSERT(found);
> -	}
> -
> -	for (size_t i = 0; i < bufferCount; i++) {
> -		const auto &[stream, buffer] = buffers[i];
> +	for (const auto &[stream, buffer] : buffers) {
> +		StreamConfig &config = streamConfigs_[stream];
>   		FrameMetadata &fmd = buffer->_d()->metadata();
>   
>   		fmd.status = FrameMetadata::Status::FrameSuccess;
> -		fmd.sequence = stream->seq++;
> +		fmd.sequence = config.seq++;
>   		fmd.timestamp = targetTimestamp;
>   
>   		std::span<const FrameBuffer::Plane> planes = buffer->planes();
>   		for (const auto [j, p] : utils::enumerate(planes))
>   			fmd.planes()[j].bytesused = p.length;
>   
> -		if (stream->frameGenerator->generateFrame(stream->stream.configuration(), buffer))
> +		if (config.frameGenerator->generateFrame(stream->configuration(),
> +							 buffer))
>   			fmd.status = FrameMetadata::Status::FrameError;
>   
>   		bufferCompleted.emit(buffer);
> [...]
> diff --git a/src/libcamera/pipeline/virtual/virtual.h b/src/libcamera/pipeline/virtual/virtual.h
> index e4a3fd085430..aaa04a0e86e5 100644
> --- a/src/libcamera/pipeline/virtual/virtual.h
> +++ b/src/libcamera/pipeline/virtual/virtual.h
> @@ -7,6 +7,7 @@
>   
>   #pragma once
>   
> +#include <map>
>   #include <string>
>   #include <variant>
>   #include <vector>
> @@ -41,7 +42,6 @@ public:
>   		std::vector<int64_t> frameRates;
>   	};
>   	struct StreamConfig {
> -		Stream stream;
>   		std::unique_ptr<FrameGenerator> frameGenerator;
>   		unsigned int seq = 0;
>   	};
> @@ -67,7 +67,8 @@ public:
>   
>   	Configuration config_;
>   
> -	std::vector<StreamConfig> streamConfigs_;
> +	std::vector<Stream> streams_;
> +	std::map<const Stream *, StreamConfig> streamConfigs_;

I have a local change that makes `StreamConfig` derive from `Stream`, and
then the pointer to `Stream` can be down-cast to pointer to `StreamConfig`
without any extra lookup.


>   	Signal<FrameBuffer *> bufferCompleted;
>   
>   	int64_t targetFrameDuration_;
> 
> base-commit: 5944ea56612caf61c814ddede241922c2d0e332a

Patch
diff mbox series

diff --git a/src/libcamera/pipeline/virtual/virtual.cpp b/src/libcamera/pipeline/virtual/virtual.cpp
index 72a07eef410b..762d2df8a128 100644
--- a/src/libcamera/pipeline/virtual/virtual.cpp
+++ b/src/libcamera/pipeline/virtual/virtual.cpp
@@ -106,7 +106,7 @@  private:
 		return static_cast<VirtualCameraData *>(camera->_d());
 	}
 
-	bool initFrameGenerator(Camera *camera);
+	void initFrameGenerator(Camera *camera);
 	void bufferCompleted(FrameBuffer *buffer);
 
 	DmaBufAllocator dmaBufAllocator_;
@@ -130,7 +130,7 @@  VirtualCameraData::VirtualCameraData(PipelineHandler *pipe,
 			{ Rectangle(config_.maxResolutionSize) });
 
 	/* \todo Support multiple streams and pass multi_stream_test */
-	streamConfigs_.resize(kMaxStream);
+	streams_.resize(kMaxStream);
 
 	moveToThread(this);
 }
@@ -144,38 +144,27 @@  void VirtualCameraData::processRequest(Request *request,
 	 * completed and managed by the application, so iterating its buffer
 	 * map directly is not safe.
 	 */
-	std::array<std::pair<StreamConfig *, FrameBuffer *>, kMaxStream> buffers;
-	size_t bufferCount = 0;
+	Request::BufferMap buffers = request->buffers();
+
 	const auto targetTime = std::chrono::steady_clock::time_point{
 		std::chrono::nanoseconds(targetTimestamp)
 	};
 	std::this_thread::sleep_until(targetTime);
 
-	for (const auto &[stream, buffer] : request->buffers()) {
-		bool found = false;
-		for (auto &streamConfig : streamConfigs_) {
-			if (stream == &streamConfig.stream) {
-				buffers[bufferCount++] = { &streamConfig, buffer };
-				found = true;
-				break;
-			}
-		}
-		ASSERT(found);
-	}
-
-	for (size_t i = 0; i < bufferCount; i++) {
-		const auto &[stream, buffer] = buffers[i];
+	for (const auto &[stream, buffer] : buffers) {
+		StreamConfig &config = streamConfigs_[stream];
 		FrameMetadata &fmd = buffer->_d()->metadata();
 
 		fmd.status = FrameMetadata::Status::FrameSuccess;
-		fmd.sequence = stream->seq++;
+		fmd.sequence = config.seq++;
 		fmd.timestamp = targetTimestamp;
 
 		std::span<const FrameBuffer::Plane> planes = buffer->planes();
 		for (const auto [j, p] : utils::enumerate(planes))
 			fmd.planes()[j].bytesused = p.length;
 
-		if (stream->frameGenerator->generateFrame(stream->stream.configuration(), buffer))
+		if (config.frameGenerator->generateFrame(stream->configuration(),
+							 buffer))
 			fmd.status = FrameMetadata::Status::FrameError;
 
 		bufferCompleted.emit(buffer);
@@ -355,9 +344,10 @@  int PipelineHandlerVirtual::configure(Camera *camera,
 {
 	VirtualCameraData *data = cameraData(camera);
 	for (auto [i, c] : utils::enumerate(*config)) {
-		c.setStream(&data->streamConfigs_[i].stream);
+		Stream *stream = &data->streams_[i];
+		c.setStream(stream);
 		/* Start reading the images/generating test patterns */
-		data->streamConfigs_[i].frameGenerator->configure(c.size);
+		data->streamConfigs_[stream].frameGenerator->configure(c.size);
 	}
 
 	return 0;
@@ -393,8 +383,8 @@  int PipelineHandlerVirtual::start(Camera *camera, const ControlList *controls)
 
 	data->targetTimestamp_ = 0;
 
-	for (auto &s : data->streamConfigs_)
-		s.seq = 0;
+	for (auto &[stream, config] : data->streamConfigs_)
+		config.seq = 0;
 
 	data->bufferCompleted.connect(this, &PipelineHandlerVirtual::bufferCompleted);
 	data->start();
@@ -477,17 +467,13 @@  bool PipelineHandlerVirtual::match([[maybe_unused]] DeviceEnumerator *enumerator
 	/* Configure and register cameras with configData */
 	for (auto &data : configData) {
 		std::set<Stream *> streams;
-		for (auto &streamConfig : data->streamConfigs_)
-			streams.insert(&streamConfig.stream);
+		for (auto &stream : data->streams_)
+			streams.insert(&stream);
+
 		std::string id = data->config_.id;
 		std::shared_ptr<Camera> camera = Camera::create(std::move(data), id, streams);
 
-		if (!initFrameGenerator(camera.get())) {
-			LOG(Virtual, Error) << "Failed to initialize frame "
-					    << "generator for camera: " << id;
-			continue;
-		}
-
+		initFrameGenerator(camera.get());
 		registerCamera(std::move(camera));
 	}
 
@@ -496,30 +482,26 @@  bool PipelineHandlerVirtual::match([[maybe_unused]] DeviceEnumerator *enumerator
 	return true;
 }
 
-bool PipelineHandlerVirtual::initFrameGenerator(Camera *camera)
+void PipelineHandlerVirtual::initFrameGenerator(Camera *camera)
 {
-	auto data = cameraData(camera);
-	auto &frame = data->config_.frame;
-	std::visit(utils::overloaded{
-			   [&](TestPattern &testPattern) {
-				   for (auto &streamConfig : data->streamConfigs_) {
-					   if (testPattern == TestPattern::DiagonalLines)
-						   streamConfig.frameGenerator = std::make_unique<DiagonalLinesGenerator>();
-					   else
-						   streamConfig.frameGenerator = std::make_unique<ColorBarsGenerator>();
-				   }
-			   },
-			   [&](ImageFrames &imageFrames) {
-				   for (auto &streamConfig : data->streamConfigs_)
-					   streamConfig.frameGenerator = ImageFrameGenerator::create(imageFrames);
-			   } },
-		   frame);
+	VirtualCameraData *data = cameraData(camera);
 
-	for (auto &streamConfig : data->streamConfigs_)
-		if (!streamConfig.frameGenerator)
-			return false;
+	using Generator = std::function<std::unique_ptr<FrameGenerator>()>;
 
-	return true;
+	Generator generator = std::visit(utils::overloaded{
+		[](TestPattern &testPattern) -> Generator {
+			if (testPattern == TestPattern::DiagonalLines)
+				return []() { return std::make_unique<DiagonalLinesGenerator>(); };
+			else
+				return []() { return std::make_unique<ColorBarsGenerator>(); };
+		},
+		[](ImageFrames &imageFrames) -> Generator {
+			return [&imageFrames]() { return ImageFrameGenerator::create(imageFrames); };
+		} },
+		data->config_.frame);
+
+	for (auto &stream : data->streams_)
+		data->streamConfigs_[&stream].frameGenerator = generator();
 }
 
 void PipelineHandlerVirtual::bufferCompleted(FrameBuffer *buffer)
diff --git a/src/libcamera/pipeline/virtual/virtual.h b/src/libcamera/pipeline/virtual/virtual.h
index e4a3fd085430..aaa04a0e86e5 100644
--- a/src/libcamera/pipeline/virtual/virtual.h
+++ b/src/libcamera/pipeline/virtual/virtual.h
@@ -7,6 +7,7 @@ 
 
 #pragma once
 
+#include <map>
 #include <string>
 #include <variant>
 #include <vector>
@@ -41,7 +42,6 @@  public:
 		std::vector<int64_t> frameRates;
 	};
 	struct StreamConfig {
-		Stream stream;
 		std::unique_ptr<FrameGenerator> frameGenerator;
 		unsigned int seq = 0;
 	};
@@ -67,7 +67,8 @@  public:
 
 	Configuration config_;
 
-	std::vector<StreamConfig> streamConfigs_;
+	std::vector<Stream> streams_;
+	std::map<const Stream *, StreamConfig> streamConfigs_;
 	Signal<FrameBuffer *> bufferCompleted;
 
 	int64_t targetFrameDuration_;