[libcamera-devel,RFC/PATCH,2/5] qcam: Allow for a second raw stream to be configured

Message ID 20200430003604.2423018-3-niklas.soderlund@ragnatech.se
State Superseded
Headers show
Series
  • qcam: Add RAW capture support
Related show

Commit Message

Niklas Söderlund April 30, 2020, 12:36 a.m. UTC
Allow a second stream to be configured for raw capture. This change only
adds support for configuring and allocating buffers for the second
stream. Later changes are needed to queue the allocated buffers to the
camera when the user wish to capture a raw frame.

Signed-off-by: Niklas Söderlund <niklas.soderlund@ragnatech.se>
---
 src/qcam/main_window.cpp | 133 +++++++++++++++++++++++++++------------
 src/qcam/main_window.h   |   8 ++-
 2 files changed, 99 insertions(+), 42 deletions(-)

Comments

Laurent Pinchart April 30, 2020, 7:19 p.m. UTC | #1
Hi Niklas,

Thank you for the patch.

On Thu, Apr 30, 2020 at 02:36:01AM +0200, Niklas Söderlund wrote:
> Allow a second stream to be configured for raw capture. This change only
> adds support for configuring and allocating buffers for the second
> stream. Later changes are needed to queue the allocated buffers to the
> camera when the user wish to capture a raw frame.

s/wish/wishes/

> Signed-off-by: Niklas Söderlund <niklas.soderlund@ragnatech.se>
> ---
>  src/qcam/main_window.cpp | 133 +++++++++++++++++++++++++++------------
>  src/qcam/main_window.h   |   8 ++-
>  2 files changed, 99 insertions(+), 42 deletions(-)
> 
> diff --git a/src/qcam/main_window.cpp b/src/qcam/main_window.cpp
> index b683c2e00d317307..e77bc01df8f3edfe 100644
> --- a/src/qcam/main_window.cpp
> +++ b/src/qcam/main_window.cpp
> @@ -278,17 +278,30 @@ void MainWindow::toggleCapture(bool start)
>  int MainWindow::startCapture()
>  {
>  	StreamRoles roles = StreamKeyValueParser::roles(options_[OptStream]);
> +	std::vector<Request *> requests;

Do you need to have this at the beginning of the function ? I suppose
it's needed because of a goto below ?

The function is getting fairly big, please feel free to split it in more
manageable chunks.

>  	int ret;
>  
>  	/* Verify roles are supported. */
> -	if (roles.size() != 1) {
> -		qWarning() << "Only one stream supported";
> -		return -EINVAL;
> -	}
> -
> -	if (roles[0] != StreamRole::Viewfinder) {
> -		qWarning() << "Only viewfinder supported";
> -		return -EINVAL;
> +	switch (roles.size()) {
> +	case 1:
> +		if (roles[0] != StreamRole::Viewfinder) {
> +			qWarning() << "Only viewfinder supported for single stream";
> +			return -EINVAL;
> +		}
> +		break;
> +	case 2:
> +		if (roles[0] != StreamRole::Viewfinder ||
> +		    roles[1] != StreamRole::StillCaptureRaw) {
> +			qWarning() << "Only viewfinder + raw supported for dual streams";
> +			return -EINVAL;
> +		}
> +		break;
> +	default:
> +		if (roles.size() != 1) {
> +			qWarning() << "Unsuported stream configuration";
> +			return -EINVAL;
> +		}
> +		break;
>  	}
>  
>  	/* Configure the camera. */
> @@ -298,17 +311,17 @@ int MainWindow::startCapture()
>  		return -EINVAL;
>  	}
>  
> -	StreamConfiguration &cfg = config_->at(0);
> +	StreamConfiguration &vfConfig = config_->at(0);
>  
>  	/* Use a format supported by the viewfinder if available. */
> -	std::vector<PixelFormat> formats = cfg.formats().pixelformats();
> +	std::vector<PixelFormat> formats = vfConfig.formats().pixelformats();
>  	for (const PixelFormat &format : viewfinder_->nativeFormats()) {
>  		auto match = std::find_if(formats.begin(), formats.end(),
>  					  [&](const PixelFormat &f) {
>  						  return f == format;
>  					  });
>  		if (match != formats.end()) {
> -			cfg.pixelFormat = format;
> +			vfConfig.pixelFormat = format;
>  			break;
>  		}
>  	}
> @@ -326,7 +339,7 @@ int MainWindow::startCapture()
>  
>  	if (validation == CameraConfiguration::Adjusted)
>  		qInfo() << "Stream configuration adjusted to "
> -			<< cfg.toString().c_str();
> +			<< vfConfig.toString().c_str();
>  
>  	ret = camera_->configure(config_.get());
>  	if (ret < 0) {
> @@ -334,10 +347,16 @@ int MainWindow::startCapture()
>  		return ret;
>  	}
>  
> +	/* Store stream allocation. */
> +	vfStream_ = config_->at(0).stream();
> +	if (config_->size() == 2)
> +		rawStream_ = config_->at(1).stream();
> +	else
> +		rawStream_ = nullptr;
> +
>  	/* Configure the viewfinder. */
> -	Stream *stream = cfg.stream();
> -	ret = viewfinder_->setFormat(cfg.pixelFormat,
> -				     QSize(cfg.size.width, cfg.size.height));
> +	ret = viewfinder_->setFormat(vfConfig.pixelFormat,
> +				     QSize(vfConfig.size.width, vfConfig.size.height));
>  	if (ret < 0) {
>  		qInfo() << "Failed to set viewfinder format";
>  		return ret;
> @@ -345,16 +364,33 @@ int MainWindow::startCapture()
>  
>  	adjustSize();
>  
> -	/* Allocate buffers and requests. */
> +	/* Allocate and map buffers. */
>  	allocator_ = new FrameBufferAllocator(camera_);
> -	ret = allocator_->allocate(stream);
> -	if (ret < 0) {
> -		qWarning() << "Failed to allocate capture buffers";
> -		return ret;
> +	for (StreamConfiguration &config : *config_) {
> +		Stream *stream = config.stream();
> +
> +		ret = allocator_->allocate(stream);
> +		if (ret < 0) {
> +			qWarning() << "Failed to allocate capture buffers";
> +			goto error;
> +		}
> +
> +		for (const std::unique_ptr<FrameBuffer> &buffer : allocator_->buffers(stream)) {
> +			/* Map memory buffers and cache the mappings. */
> +			const FrameBuffer::Plane &plane = buffer->planes().front();
> +			void *memory = mmap(NULL, plane.length, PROT_READ, MAP_SHARED,
> +					    plane.fd.fd(), 0);
> +			mappedBuffers_[buffer.get()] = { memory, plane.length };
> +
> +			/* Store buffers on the free list. */
> +			freeBuffers_[stream].enqueue(buffer.get());
> +		}
>  	}
>  
> -	std::vector<Request *> requests;
> -	for (const std::unique_ptr<FrameBuffer> &buffer : allocator_->buffers(stream)) {
> +	/* Create requests and fill it with buffers from the viewfinder. */
> +	while (!freeBuffers_[vfStream_].isEmpty()) {
> +		FrameBuffer *buffer = freeBuffers_[vfStream_].dequeue();
> +
>  		Request *request = camera_->createRequest();
>  		if (!request) {
>  			qWarning() << "Can't create request";
> @@ -362,19 +398,13 @@ int MainWindow::startCapture()
>  			goto error;
>  		}
>  
> -		ret = request->addBuffer(stream, buffer.get());
> +		ret = request->addBuffer(vfStream_, buffer);
>  		if (ret < 0) {
>  			qWarning() << "Can't set buffer for request";
>  			goto error;
>  		}
>  
>  		requests.push_back(request);
> -
> -		/* Map memory buffers and cache the mappings. */
> -		const FrameBuffer::Plane &plane = buffer->planes().front();
> -		void *memory = mmap(NULL, plane.length, PROT_READ, MAP_SHARED,
> -				    plane.fd.fd(), 0);
> -		mappedBuffers_[buffer.get()] = { memory, plane.length };
>  	}
>  
>  	/* Start the title timer and the camera. */
> @@ -419,6 +449,8 @@ error:
>  	}
>  	mappedBuffers_.clear();
>  
> +	freeBuffers_.clear();
> +
>  	delete allocator_;
>  	allocator_ = nullptr;
>  
> @@ -461,7 +493,8 @@ void MainWindow::stopCapture()
>  	 * but not processed yet. Clear the queue of done buffers to avoid
>  	 * racing with the event handler.
>  	 */
> -	doneQueue_.clear();
> +	freeBuffers_.clear();
> +	doneBuffers_.clear();
>  
>  	titleTimer_.stop();
>  	setWindowTitle(title_);
> @@ -500,12 +533,9 @@ void MainWindow::requestComplete(Request *request)
>  	 * are not allowed. Add the buffer to the done queue and post a
>  	 * CaptureEvent for the application thread to handle.
>  	 */
> -	const std::map<Stream *, FrameBuffer *> &buffers = request->buffers();
> -	FrameBuffer *buffer = buffers.begin()->second;
> -
>  	{
>  		QMutexLocker locker(&mutex_);
> -		doneQueue_.enqueue(buffer);
> +		doneBuffers_.push_back(request->buffers());
>  	}
>  
>  	QCoreApplication::postEvent(this, new CaptureEvent);
> @@ -518,16 +548,40 @@ void MainWindow::processCapture()
>  	 * if stopCapture() has been called while a CaptureEvent was posted but
>  	 * not processed yet. Return immediately in that case.
>  	 */
> -	FrameBuffer *buffer;
> -
> +	std::vector<std::map<Stream *, FrameBuffer *>> doneBuffers;

Empty line to show the { } isn't a statement belonging to the previous
line.

>  	{
>  		QMutexLocker locker(&mutex_);
> -		if (doneQueue_.isEmpty())
> +		if (doneBuffers_.empty())
>  			return;
>  
> -		buffer = doneQueue_.dequeue();
> +		doneBuffers = std::move(doneBuffers_);
> +		doneBuffers_.clear();

I don't clear() is needed as you use std::move().

>  	}
>  
> +	/* Process buffers. */
> +	for (std::map<Stream *, FrameBuffer *> &buffers : doneBuffers) {

Is there a reason while you batch processing of all done buffers,
instead of the queue head as done before ? I can't recall if there was a
reason to do so in my original code, or if I just considered it could be
done later :-S

> +		if (buffers.count(vfStream_))
> +			processViewfinder(buffers[vfStream_]);

Do it make sense to push all frames to the viewfinder if the done queue
has more than one element, or should we skip all of them but the last ?
The ViewFinder class will process every frame it gets, but if the code
doesn't go through the Qt event loop in between frames, only the last
one will be pushed to the screen. We would thus convert frames
unnecessarily.

> +
> +		/*
> +		 * Return buffers so they can be reused. No processing involving
> +		 * a buffer can happen after they are returned to the free list.
> +		 */
> +		for (auto &it : buffers) {
> +			Stream *stream = it.first;
> +			FrameBuffer *buffer = it.second;
> +
> +			/* The ViewFinder manages the viewfinder buffers. */
> +			if (stream == vfStream_)
> +				continue;
> +
> +			freeBuffers_[stream].enqueue(buffer);
> +		}

I think this would look nicer if you turned doneBuffers_ from

	std::vector<std::map<Stream *, FrameBuffer *>> doneBuffers_;

to

	std::map<Stream *, std::vector<FrameBuffer *>> doneBuffers_;

but now that I've said this, it may make sense to keep it the way it is,
to retain the relation between elements of doneBuffers_ and requests.

> +	}
> +}
> +
> +void MainWindow::processViewfinder(FrameBuffer *buffer)
> +{
>  	framesCaptured_++;
>  
>  	const FrameMetadata &metadata = buffer->metadata();
> @@ -554,8 +608,7 @@ void MainWindow::queueRequest(FrameBuffer *buffer)
>  		return;
>  	}
>  
> -	Stream *stream = config_->at(0).stream();
> -	request->addBuffer(stream, buffer);
> +	request->addBuffer(vfStream_, buffer);
>  
>  	camera_->queueRequest(request);
>  }
> diff --git a/src/qcam/main_window.h b/src/qcam/main_window.h
> index 5e9d9b8d9c6b2d6d..c2040c0ebcd61bfa 100644
> --- a/src/qcam/main_window.h
> +++ b/src/qcam/main_window.h
> @@ -68,6 +68,7 @@ private:
>  
>  	void requestComplete(Request *request);
>  	void processCapture();
> +	void processViewfinder(FrameBuffer *buffer);
>  
>  	/* UI elements */
>  	QToolBar *toolbar_;
> @@ -93,8 +94,11 @@ private:
>  
>  	/* Capture state, buffers queue and statistics */
>  	bool isCapturing_;
> -	QQueue<FrameBuffer *> doneQueue_;
> -	QMutex mutex_;	/* Protects doneQueue_ */
> +	Stream *vfStream_;
> +	Stream *rawStream_;
> +	std::map<Stream *, QQueue<FrameBuffer *>> freeBuffers_;
> +	std::vector<std::map<Stream *, FrameBuffer *>> doneBuffers_;

Any reason not to keep the QQueue ? If there is, have you considered
QList (which I assume would suffer from the same issue as QQueue
inherits from QList), or std::deque ? I would also prefer keeping the
name doneQueue_ to show it's a queue.

> +	QMutex mutex_; /* Protects freeBuffers_ and doneBuffers_ */
>  
>  	uint64_t lastBufferTime_;
>  	QElapsedTimer frameRateInterval_;

Patch

diff --git a/src/qcam/main_window.cpp b/src/qcam/main_window.cpp
index b683c2e00d317307..e77bc01df8f3edfe 100644
--- a/src/qcam/main_window.cpp
+++ b/src/qcam/main_window.cpp
@@ -278,17 +278,30 @@  void MainWindow::toggleCapture(bool start)
 int MainWindow::startCapture()
 {
 	StreamRoles roles = StreamKeyValueParser::roles(options_[OptStream]);
+	std::vector<Request *> requests;
 	int ret;
 
 	/* Verify roles are supported. */
-	if (roles.size() != 1) {
-		qWarning() << "Only one stream supported";
-		return -EINVAL;
-	}
-
-	if (roles[0] != StreamRole::Viewfinder) {
-		qWarning() << "Only viewfinder supported";
-		return -EINVAL;
+	switch (roles.size()) {
+	case 1:
+		if (roles[0] != StreamRole::Viewfinder) {
+			qWarning() << "Only viewfinder supported for single stream";
+			return -EINVAL;
+		}
+		break;
+	case 2:
+		if (roles[0] != StreamRole::Viewfinder ||
+		    roles[1] != StreamRole::StillCaptureRaw) {
+			qWarning() << "Only viewfinder + raw supported for dual streams";
+			return -EINVAL;
+		}
+		break;
+	default:
+		if (roles.size() != 1) {
+			qWarning() << "Unsuported stream configuration";
+			return -EINVAL;
+		}
+		break;
 	}
 
 	/* Configure the camera. */
@@ -298,17 +311,17 @@  int MainWindow::startCapture()
 		return -EINVAL;
 	}
 
-	StreamConfiguration &cfg = config_->at(0);
+	StreamConfiguration &vfConfig = config_->at(0);
 
 	/* Use a format supported by the viewfinder if available. */
-	std::vector<PixelFormat> formats = cfg.formats().pixelformats();
+	std::vector<PixelFormat> formats = vfConfig.formats().pixelformats();
 	for (const PixelFormat &format : viewfinder_->nativeFormats()) {
 		auto match = std::find_if(formats.begin(), formats.end(),
 					  [&](const PixelFormat &f) {
 						  return f == format;
 					  });
 		if (match != formats.end()) {
-			cfg.pixelFormat = format;
+			vfConfig.pixelFormat = format;
 			break;
 		}
 	}
@@ -326,7 +339,7 @@  int MainWindow::startCapture()
 
 	if (validation == CameraConfiguration::Adjusted)
 		qInfo() << "Stream configuration adjusted to "
-			<< cfg.toString().c_str();
+			<< vfConfig.toString().c_str();
 
 	ret = camera_->configure(config_.get());
 	if (ret < 0) {
@@ -334,10 +347,16 @@  int MainWindow::startCapture()
 		return ret;
 	}
 
+	/* Store stream allocation. */
+	vfStream_ = config_->at(0).stream();
+	if (config_->size() == 2)
+		rawStream_ = config_->at(1).stream();
+	else
+		rawStream_ = nullptr;
+
 	/* Configure the viewfinder. */
-	Stream *stream = cfg.stream();
-	ret = viewfinder_->setFormat(cfg.pixelFormat,
-				     QSize(cfg.size.width, cfg.size.height));
+	ret = viewfinder_->setFormat(vfConfig.pixelFormat,
+				     QSize(vfConfig.size.width, vfConfig.size.height));
 	if (ret < 0) {
 		qInfo() << "Failed to set viewfinder format";
 		return ret;
@@ -345,16 +364,33 @@  int MainWindow::startCapture()
 
 	adjustSize();
 
-	/* Allocate buffers and requests. */
+	/* Allocate and map buffers. */
 	allocator_ = new FrameBufferAllocator(camera_);
-	ret = allocator_->allocate(stream);
-	if (ret < 0) {
-		qWarning() << "Failed to allocate capture buffers";
-		return ret;
+	for (StreamConfiguration &config : *config_) {
+		Stream *stream = config.stream();
+
+		ret = allocator_->allocate(stream);
+		if (ret < 0) {
+			qWarning() << "Failed to allocate capture buffers";
+			goto error;
+		}
+
+		for (const std::unique_ptr<FrameBuffer> &buffer : allocator_->buffers(stream)) {
+			/* Map memory buffers and cache the mappings. */
+			const FrameBuffer::Plane &plane = buffer->planes().front();
+			void *memory = mmap(NULL, plane.length, PROT_READ, MAP_SHARED,
+					    plane.fd.fd(), 0);
+			mappedBuffers_[buffer.get()] = { memory, plane.length };
+
+			/* Store buffers on the free list. */
+			freeBuffers_[stream].enqueue(buffer.get());
+		}
 	}
 
-	std::vector<Request *> requests;
-	for (const std::unique_ptr<FrameBuffer> &buffer : allocator_->buffers(stream)) {
+	/* Create requests and fill it with buffers from the viewfinder. */
+	while (!freeBuffers_[vfStream_].isEmpty()) {
+		FrameBuffer *buffer = freeBuffers_[vfStream_].dequeue();
+
 		Request *request = camera_->createRequest();
 		if (!request) {
 			qWarning() << "Can't create request";
@@ -362,19 +398,13 @@  int MainWindow::startCapture()
 			goto error;
 		}
 
-		ret = request->addBuffer(stream, buffer.get());
+		ret = request->addBuffer(vfStream_, buffer);
 		if (ret < 0) {
 			qWarning() << "Can't set buffer for request";
 			goto error;
 		}
 
 		requests.push_back(request);
-
-		/* Map memory buffers and cache the mappings. */
-		const FrameBuffer::Plane &plane = buffer->planes().front();
-		void *memory = mmap(NULL, plane.length, PROT_READ, MAP_SHARED,
-				    plane.fd.fd(), 0);
-		mappedBuffers_[buffer.get()] = { memory, plane.length };
 	}
 
 	/* Start the title timer and the camera. */
@@ -419,6 +449,8 @@  error:
 	}
 	mappedBuffers_.clear();
 
+	freeBuffers_.clear();
+
 	delete allocator_;
 	allocator_ = nullptr;
 
@@ -461,7 +493,8 @@  void MainWindow::stopCapture()
 	 * but not processed yet. Clear the queue of done buffers to avoid
 	 * racing with the event handler.
 	 */
-	doneQueue_.clear();
+	freeBuffers_.clear();
+	doneBuffers_.clear();
 
 	titleTimer_.stop();
 	setWindowTitle(title_);
@@ -500,12 +533,9 @@  void MainWindow::requestComplete(Request *request)
 	 * are not allowed. Add the buffer to the done queue and post a
 	 * CaptureEvent for the application thread to handle.
 	 */
-	const std::map<Stream *, FrameBuffer *> &buffers = request->buffers();
-	FrameBuffer *buffer = buffers.begin()->second;
-
 	{
 		QMutexLocker locker(&mutex_);
-		doneQueue_.enqueue(buffer);
+		doneBuffers_.push_back(request->buffers());
 	}
 
 	QCoreApplication::postEvent(this, new CaptureEvent);
@@ -518,16 +548,40 @@  void MainWindow::processCapture()
 	 * if stopCapture() has been called while a CaptureEvent was posted but
 	 * not processed yet. Return immediately in that case.
 	 */
-	FrameBuffer *buffer;
-
+	std::vector<std::map<Stream *, FrameBuffer *>> doneBuffers;
 	{
 		QMutexLocker locker(&mutex_);
-		if (doneQueue_.isEmpty())
+		if (doneBuffers_.empty())
 			return;
 
-		buffer = doneQueue_.dequeue();
+		doneBuffers = std::move(doneBuffers_);
+		doneBuffers_.clear();
 	}
 
+	/* Process buffers. */
+	for (std::map<Stream *, FrameBuffer *> &buffers : doneBuffers) {
+		if (buffers.count(vfStream_))
+			processViewfinder(buffers[vfStream_]);
+
+		/*
+		 * Return buffers so they can be reused. No processing involving
+		 * a buffer can happen after they are returned to the free list.
+		 */
+		for (auto &it : buffers) {
+			Stream *stream = it.first;
+			FrameBuffer *buffer = it.second;
+
+			/* The ViewFinder manages the viewfinder buffers. */
+			if (stream == vfStream_)
+				continue;
+
+			freeBuffers_[stream].enqueue(buffer);
+		}
+	}
+}
+
+void MainWindow::processViewfinder(FrameBuffer *buffer)
+{
 	framesCaptured_++;
 
 	const FrameMetadata &metadata = buffer->metadata();
@@ -554,8 +608,7 @@  void MainWindow::queueRequest(FrameBuffer *buffer)
 		return;
 	}
 
-	Stream *stream = config_->at(0).stream();
-	request->addBuffer(stream, buffer);
+	request->addBuffer(vfStream_, buffer);
 
 	camera_->queueRequest(request);
 }
diff --git a/src/qcam/main_window.h b/src/qcam/main_window.h
index 5e9d9b8d9c6b2d6d..c2040c0ebcd61bfa 100644
--- a/src/qcam/main_window.h
+++ b/src/qcam/main_window.h
@@ -68,6 +68,7 @@  private:
 
 	void requestComplete(Request *request);
 	void processCapture();
+	void processViewfinder(FrameBuffer *buffer);
 
 	/* UI elements */
 	QToolBar *toolbar_;
@@ -93,8 +94,11 @@  private:
 
 	/* Capture state, buffers queue and statistics */
 	bool isCapturing_;
-	QQueue<FrameBuffer *> doneQueue_;
-	QMutex mutex_;	/* Protects doneQueue_ */
+	Stream *vfStream_;
+	Stream *rawStream_;
+	std::map<Stream *, QQueue<FrameBuffer *>> freeBuffers_;
+	std::vector<std::map<Stream *, FrameBuffer *>> doneBuffers_;
+	QMutex mutex_; /* Protects freeBuffers_ and doneBuffers_ */
 
 	uint64_t lastBufferTime_;
 	QElapsedTimer frameRateInterval_;