#!/usr/bin/env python3 # SPDX-License-Identifier: BSD-3-Clause # Copyright (C) 2022, Tomi Valkeinen # A simple capture example extending the simple-capture.py example: # - Capture frames using events from multiple cameras # - Listening events from stdin to exit the application # - Memory mapping the frames and calculating CRC import binascii import libcamera as libcam import libcamera.utils import selectors import sys # A container class for our state per camera class CameraCaptureContext: idx: int cam: libcam.Camera reqs: list[libcam.Request] mfbs: dict[libcam.FrameBuffer, libcamera.utils.MappedFrameBuffer] def __init__(self, cam, idx): self.idx = idx self.cam = cam # Acquire the camera for our use cam.acquire() # Configure the camera cam_config = cam.generate_configuration([libcam.StreamRole.Viewfinder]) stream_config = cam_config.at(0) cam.configure(cam_config) stream = stream_config.stream # Allocate the buffers for capture allocator = libcam.FrameBufferAllocator(cam) ret = allocator.allocate(stream) assert ret > 0 num_bufs = len(allocator.buffers(stream)) print(f'cam{idx} ({cam.id}): capturing {num_bufs} buffers with {stream_config}') # Create the requests and assign a buffer for each request self.reqs = [] self.mfbs = {} for i in range(num_bufs): # Use the buffer index as the "cookie" req = cam.create_request(idx) buffer = allocator.buffers(stream)[i] req.add_buffer(stream, buffer) self.reqs.append(req) # Save a mmapped buffer so we can calculate the CRC later self.mfbs[buffer] = libcamera.utils.MappedFrameBuffer(buffer).mmap() def uninit_camera(self): # Stop the camera self.cam.stop() # Release the camera self.cam.release() # A container class for our state class CaptureContext: cm: libcam.CameraManager camera_contexts: list[CameraCaptureContext] = [] def handle_camera_event(self): # cm.get_ready_requests() returns the ready requests, which in our case # should almost always return a single Request, but in some cases there # could be multiple or none. reqs = self.cm.get_ready_requests() # Process the captured frames for req in reqs: self.handle_request(req) return True def handle_request(self, req: libcam.Request): cam_ctx = self.camera_contexts[req.cookie] buffers = req.buffers assert len(buffers) == 1 # A ready Request could contain multiple buffers if multiple streams # were being used. Here we know we only have a single stream, # and we use next(iter()) to get the first and only buffer. stream, fb = next(iter(buffers.items())) # Use the MappedFrameBuffer to access the pixel data with CPU. We calculate # the crc for each plane. mfb = cam_ctx.mfbs[fb] crcs = [binascii.crc32(p) for p in mfb.planes] meta = fb.metadata print('cam{:<6} seq {:<6} bytes {:10} CRCs {}' .format(cam_ctx.idx, meta.sequence, '/'.join([str(p.bytes_used) for p in meta.planes]), crcs)) # We want to re-queue the buffer we just handled. Instead of creating # a new Request, we re-use the old one. We need to call req.reuse() # to re-initialize the Request before queuing. req.reuse() cam_ctx.cam.queue_request(req) def handle_key_event(self): sys.stdin.readline() print('Exiting...') return False def capture(self): # Queue the requests to the camera for cam_ctx in self.camera_contexts: for req in cam_ctx.reqs: cam_ctx.cam.queue_request(req) # Use Selector to wait for events from the camera and from the keyboard sel = selectors.DefaultSelector() sel.register(sys.stdin, selectors.EVENT_READ, self.handle_key_event) sel.register(self.cm.event_fd, selectors.EVENT_READ, lambda: self.handle_camera_event()) running = True while running: events = sel.select() for key, mask in events: # If the handler return False, we should exit if not key.data(): running = False def main(): cm = libcam.CameraManager.singleton() ctx = CaptureContext() ctx.cm = cm for idx, cam in enumerate(cm.cameras): cam_ctx = CameraCaptureContext(cam, idx) ctx.camera_contexts.append(cam_ctx) # Start the cameras for cam_ctx in ctx.camera_contexts: cam_ctx.cam.start() ctx.capture() for cam_ctx in ctx.camera_contexts: cam_ctx.uninit_camera() return 0 if __name__ == '__main__': sys.exit(main()) '#n55'>55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * camera_session.cpp - Camera capture session
 */

#include <iomanip>
#include <iostream>
#include <limits.h>
#include <sstream>

#include <libcamera/control_ids.h>
#include <libcamera/property_ids.h>

#include "camera_session.h"
#include "capture_script.h"
#include "event_loop.h"
#include "file_sink.h"
#ifdef HAVE_KMS
#include "kms_sink.h"
#endif
#include "main.h"
#ifdef HAVE_SDL
#include "sdl_sink.h"
#endif
#include "stream_options.h"

using namespace libcamera;

CameraSession::CameraSession(CameraManager *cm,
			     const std::string &cameraId,
			     unsigned int cameraIndex,
			     const OptionsParser::Options &options)
	: options_(options), cameraIndex_(cameraIndex), last_(0),
	  queueCount_(0), captureCount_(0), captureLimit_(0),
	  printMetadata_(false)
{
	char *endptr;
	unsigned long index = strtoul(cameraId.c_str(), &endptr, 10);
	if (*endptr == '\0' && index > 0 && index <= cm->cameras().size())
		camera_ = cm->cameras()[index - 1];
	else
		camera_ = cm->get(cameraId);

	if (!camera_) {
		std::cerr << "Camera " << cameraId << " not found" << std::endl;
		return;
	}

	if (camera_->acquire()) {
		std::cerr << "Failed to acquire camera " << cameraId
			  << std::endl;
		return;
	}

	StreamRoles roles = StreamKeyValueParser::roles(options_[OptStream]);

	std::unique_ptr<CameraConfiguration> config =
		camera_->generateConfiguration(roles);
	if (!config || config->size() != roles.size()) {
		std::cerr << "Failed to get default stream configuration"
			  << std::endl;
		return;
	}

	/* Apply configuration if explicitly requested. */
	if (StreamKeyValueParser::updateConfiguration(config.get(),
						      options_[OptStream])) {
		std::cerr << "Failed to update configuration" << std::endl;
		return;
	}

	bool strictFormats = options_.isSet(OptStrictFormats);

#ifdef HAVE_KMS
	if (options_.isSet(OptDisplay)) {
		if (options_.isSet(OptFile)) {
			std::cerr << "--display and --file options are mutually exclusive"
				  << std::endl;
			return;
		}

		if (roles.size() != 1) {
			std::cerr << "Display doesn't support multiple streams"
				  << std::endl;
			return;
		}

		if (roles[0] != StreamRole::Viewfinder) {
			std::cerr << "Display requires a viewfinder stream"
				  << std::endl;
			return;
		}
	}
#endif

	if (options_.isSet(OptCaptureScript)) {
		std::string scriptName = options_[OptCaptureScript].toString();
		script_ = std::make_unique<CaptureScript>(camera_, scriptName);
		if (!script_->valid()) {
			std::cerr << "Invalid capture script '" << scriptName
				  << "'" << std::endl;
			return;
		}
	}

	switch (config->validate()) {