summaryrefslogtreecommitdiff
path: root/test/controls/control_value.cpp
diff options
context:
space:
mode:
authorLaurent Pinchart <laurent.pinchart@ideasonboard.com>2022-10-03 22:55:11 +0300
committerLaurent Pinchart <laurent.pinchart@ideasonboard.com>2022-10-07 18:02:06 +0300
commitb4a3e6ade7864620e453ad81595407aac1979dee (patch)
tree5662e02e3a1442708a29642f74082568bce8efac /test/controls/control_value.cpp
parentc4d39f0c31d968d874b8519af7458cbb34e3abe0 (diff)
ipa: camera_sensor_helper: Make registerType() and createInstance() private
The CameraSensorHelperFactory registerType() and createInstance() functions are called by the CameraSensorHelperFactory class only. Make them private. Signed-off-by: Laurent Pinchart <laurent.pinchart@ideasonboard.com> Reviewed-by: Xavier Roumegue <xavier.roumegue@oss.nxp.com> Reviewed-by: Jacopo Mondi <jacopo@jmondi.org>
Diffstat (limited to 'test/controls/control_value.cpp')
0 files changed, 0 insertions, 0 deletions
'>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 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
 * Copyright (C) 2019, Google Inc.
 *
 * camera_sensor.cpp - A camera sensor
 */

#include "libcamera/internal/camera_sensor.h"
#include "libcamera/internal/media_device.h"

#include <algorithm>
#include <float.h>
#include <iomanip>
#include <limits.h>
#include <math.h>
#include <regex>
#include <string.h>

#include <libcamera/property_ids.h>

#include "libcamera/internal/bayer_format.h"
#include "libcamera/internal/formats.h"
#include "libcamera/internal/sysfs.h"
#include "libcamera/internal/utils.h"

/**
 * \file camera_sensor.h
 * \brief A camera sensor
 */

namespace libcamera {

LOG_DEFINE_CATEGORY(CameraSensor)

/**
 * \struct CameraSensorInfo
 * \brief Report the image sensor characteristics
 *
 * The structure reports image sensor characteristics used by IPA modules to
 * tune their algorithms based on the image sensor model currently in use and
 * its configuration.
 *
 * The reported information describes the sensor's intrinsics characteristics,
 * such as its pixel array size and the sensor model name, as well as
 * information relative to the currently configured mode, such as the produced
 * image size and the bit depth of the requested image format.
 *
 * Instances of this structure are meant to be assembled by the CameraSensor
 * class by inspecting the sensor static properties as well as information
 * relative to the current configuration.
 */

/**
 * \var CameraSensorInfo::model
 * \brief The image sensor model name
 *
 * The sensor model name is a free-formed string that uniquely identifies the
 * sensor model.
 */

/**
 * \var CameraSensorInfo::bitsPerPixel
 * \brief The number of bits per pixel of the image format produced by the
 * image sensor
 */

/**
 * \var CameraSensorInfo::activeAreaSize
 * \brief The size of the pixel array active area of the sensor
 */

/**
 * \var CameraSensorInfo::analogCrop
 * \brief The portion of the pixel array active area which is read-out and
 * processed
 *
 * The analog crop rectangle top-left corner is defined as the displacement
 * from the top-left corner of the pixel array active area. The rectangle
 * horizontal and vertical sizes define the portion of the pixel array which
 * is read-out and provided to the sensor's internal processing pipeline, before
 * any pixel sub-sampling method, such as pixel binning, skipping and averaging
 * take place.
 */

/**
 * \var CameraSensorInfo::outputSize
 * \brief The size of the images produced by the camera sensor
 *
 * The output image size defines the horizontal and vertical sizes of the images
 * produced by the image sensor. The output image size is defined as the end
 * result of the sensor's internal image processing pipeline stages, applied on
 * the pixel array portion defined by the analog crop rectangle. Each image
 * processing stage that performs pixel sub-sampling techniques, such as pixel
 * binning or skipping, or perform any additional digital scaling concur in the
 * definition of the output image size.
 */

/**
 * \var CameraSensorInfo::pixelRate
 * \brief The number of pixels produced in a second
 *
 * To obtain the read-out time in seconds of a full line:
 *
 * \verbatim
	lineDuration(s) = lineLength(pixels) / pixelRate(pixels per second)
   \endverbatim
 */

/**
 * \var CameraSensorInfo::lineLength
 * \brief Total line length in pixels
 *
 * The total line length in pixel clock periods, including blanking.
 */

/**
 * \var CameraSensorInfo::minFrameLength
 * \brief The minimum allowable frame length in units of lines
 *
 * The sensor frame length comprises of active output lines and blanking lines
 * in a frame. The minimum frame length value dictates the minimum allowable
 * frame duration of the sensor mode.
 *
 * To obtain the minimum frame duration:
 *
 * \verbatim
	frameDuration(s) = minFrameLength(lines) * lineLength(pixels) / pixelRate(pixels per second)
   \endverbatim
 */

/**
 * \var CameraSensorInfo::maxFrameLength
 * \brief The maximum allowable frame length in units of lines
 *
 * The sensor frame length comprises of active output lines and blanking lines
 * in a frame. The maximum frame length value dictates the maximum allowable
 * frame duration of the sensor mode.
 *
 * To obtain the maximum frame duration:
 *
 * \verbatim
	frameDuration(s) = maxFrameLength(lines) * lineLength(pixels) / pixelRate(pixels per second)
   \endverbatim
 */

/**
 * \class CameraSensor
 * \brief A camera sensor based on V4L2 subdevices
 *
 * The CameraSensor class eases handling of sensors for pipeline handlers by
 * hiding the details of the V4L2 subdevice kernel API and caching sensor
 * information.
 *
 * The implementation is currently limited to sensors that expose a single V4L2
 * subdevice with a single pad. It will be extended to support more complex
 * devices as the needs arise.
 */

/**
 * \brief Construct a CameraSensor
 * \param[in] entity The media entity backing the camera sensor
 *
 * Once constructed the instance must be initialized with init().
 */
CameraSensor::CameraSensor(const MediaEntity *entity)
	: entity_(entity), pad_(UINT_MAX), properties_(properties::properties)
{
}

/**
 * \brief Destroy a CameraSensor
 */
CameraSensor::~CameraSensor()
{
}

/**
 * \brief Initialize the camera sensor instance
 *
 * This method performs the initialisation steps of the CameraSensor that may
 * fail. It shall be called once and only once after constructing the instance.
 *
 * \return 0 on success or a negative error code otherwise
 */
int CameraSensor::init()
{
	for (const MediaPad *pad : entity_->pads()) {
		if (pad->flags() & MEDIA_PAD_FL_SOURCE) {
			pad_ = pad->index();
			break;
		}
	}

	if (pad_ == UINT_MAX) {
		LOG(CameraSensor, Error)
			<< "Sensors with more than one pad are not supported";
		return -EINVAL;
	}

	if (entity_->function() != MEDIA_ENT_F_CAM_SENSOR) {
		LOG(CameraSensor, Error)
			<< "Invalid sensor function "
			<< utils::hex(entity_->function());
		return -EINVAL;
	}

	/* Create and open the subdev. */
	subdev_ = std::make_unique<V4L2Subdevice>(entity_);
	int ret = subdev_->open();
	if (ret < 0)
		return ret;

	/* Enumerate, sort and cache media bus codes and sizes. */
	formats_ = subdev_->formats(pad_);
	if (formats_.empty()) {
		LOG(CameraSensor, Error) << "No image format found";
		return -EINVAL;
	}

	mbusCodes_ = utils::map_keys(formats_);
	std::sort(mbusCodes_.begin(), mbusCodes_.end());

	for (const auto &format : formats_) {
		const std::vector<SizeRange> &ranges = format.second;
		std::transform(ranges.begin(), ranges.end(), std::back_inserter(sizes_),
			       [](const SizeRange &range) { return range.max; });
	}

	std::sort(sizes_.begin(), sizes_.end());

	/* Remove duplicates. */
	auto last = std::unique(sizes_.begin(), sizes_.end());
	sizes_.erase(last, sizes_.end());

	/*
	 * The sizes_ vector is sorted in ascending order, the resolution is
	 * thus the last element of the vector.
	 */
	resolution_ = sizes_.back();

	/*
	 * VIMC is a bit special, as it does not yet support all the mandatory
	 * requirements regular sensors have to respect.
	 *
	 * Do not validate the driver if it's VIMC and initialize the sensor
	 * properties with static information.
	 *
	 * \todo Remove the special case once the VIMC driver has been
	 * updated in all test platforms.
	 */
	if (entity_->device()->driver() == "vimc") {
		initVimcDefaultProperties();
		return initProperties();
	}

	ret = validateSensorDriver();
	if (ret)
		return ret;

	ret = initProperties();
	if (ret)
		return ret;

	return 0;
}

int CameraSensor::validateSensorDriver()
{
	/*
	 * Make sure the sensor driver supports the mandatory controls
	 * required by the CameraSensor class.
	 */
	const std::vector<uint32_t> mandatoryControls{
		V4L2_CID_EXPOSURE,
		V4L2_CID_HBLANK,
		V4L2_CID_PIXEL_RATE,
		V4L2_CID_VBLANK,
	};

	ControlList ctrls = subdev_->getControls(mandatoryControls);
	if (ctrls.empty()) {
		LOG(CameraSensor, Error)
			<< "Mandatory V4L2 controls not available";
		LOG(CameraSensor, Error)
			<< "The sensor kernel driver needs to be fixed";
		LOG(CameraSensor, Error)
			<< "See Documentation/sensor_driver_requirements.rst in the libcamera sources for more information";
		return -EINVAL;
	}

	/*
	 * Optional controls are used to register optional sensor properties. If
	 * not present, some values will be defaulted.
	 */
	const std::vector<uint32_t> optionalControls{
		V4L2_CID_CAMERA_ORIENTATION,
		V4L2_CID_CAMERA_SENSOR_ROTATION,
	};

	ctrls = subdev_->getControls(optionalControls);
	if (ctrls.empty())
		LOG(CameraSensor, Debug) << "Optional V4L2 controls not supported";

	/*
	 * Make sure the required selection targets are supported.
	 *
	 * Failures in reading any of the targets are not deemed to be fatal,
	 * but some properties and features, like constructing a
	 * CameraSensorInfo for the IPA module, won't be supported.
	 *
	 * \todo Make support for selection targets mandatory as soon as all
	 * test platforms have been updated.
	 */
	int err = 0;
	Rectangle rect;
	int ret = subdev_->getSelection(pad_, V4L2_SEL_TGT_CROP_BOUNDS, &rect);
	if (ret) {
		rect = Rectangle(resolution());
		LOG(CameraSensor, Warning)
			<< "The PixelArraySize property has been defaulted to "
			<< rect.toString();
		err = -EINVAL;
	}
	pixelArraySize_.width = rect.width;
	pixelArraySize_.height = rect.height;

	ret = subdev_->getSelection(pad_, V4L2_SEL_TGT_CROP_DEFAULT, &activeArea_);
	if (ret) {
		activeArea_ = Rectangle(pixelArraySize_);
		LOG(CameraSensor, Warning)
			<< "The PixelArrayActiveAreas property has been defaulted to "
			<< activeArea_.toString();
		err = -EINVAL;
	}

	ret = subdev_->getSelection(pad_, V4L2_SEL_TGT_CROP, &rect);
	if (ret) {
		LOG(CameraSensor, Warning)
			<< "Failed to retrieve the sensor crop rectangle";
		err = -EINVAL;
	}

	if (err) {
		LOG(CameraSensor, Warning)
			<< "The sensor kernel driver needs to be fixed";
		LOG(CameraSensor, Warning)
			<< "See Documentation/sensor_driver_requirements.rst in the libcamera sources for more information";
	}

	return 0;
}

/*
 * \brief Initialize properties that cannot be intialized by the
 * regular initProperties() function for VIMC
 */
void CameraSensor::initVimcDefaultProperties()
{
	pixelArraySize_ = resolution();
	activeArea_ = Rectangle(pixelArraySize_);
}

int CameraSensor::initProperties()
{
	/*
	 * Extract the camera sensor model name from the media entity name.
	 *
	 * There is no standardized naming scheme for sensor entities in the
	 * Linux kernel at the moment.
	 *
	 * - The most common rule, used by I2C sensors, associates the model
	 *   name with the I2C bus number and address (e.g. 'imx219 0-0010').
	 *
	 * - When the sensor exposes multiple subdevs, the model name is
	 *   usually followed by a function name, as in the smiapp driver (e.g.
	 *   'jt8ew9 pixel_array 0-0010').
	 *
	 * - The vimc driver names its sensors 'Sensor A' and 'Sensor B'.
	 *
	 * Other schemes probably exist. As a best effort heuristic, use the
	 * part of the entity name before the first space if the name contains
	 * an I2C address, and use the full entity name otherwise.
	 */
	std::string entityName = entity_->name();
	std::regex i2cRegex{ " [0-9]+-[0-9a-f]{4}" };
	std::smatch match;

	if (std::regex_search(entityName, match, i2cRegex))
		model_ = entityName.substr(0, entityName.find(' '));
	else
		model_ = entityName;

	properties_.set(properties::Model, utils::toAscii(model_));

	/* Generate a unique ID for the sensor. */
	int ret = generateId();
	if (ret)
		return ret;

	/* Retrieve and store the camera sensor properties. */
	const ControlInfoMap &controls = subdev_->controls();
	int32_t propertyValue;

	const auto &orientation = controls.find(V4L2_CID_CAMERA_ORIENTATION);
	if (orientation != controls.end()) {
		int32_t v4l2Orientation = orientation->second.def().get<int32_t>();

		switch (v4l2Orientation) {
		default:
			LOG(CameraSensor, Warning)
				<< "Unsupported camera location "
				<< v4l2Orientation << ", setting to External";
			/* Fall-through */
		case V4L2_CAMERA_ORIENTATION_EXTERNAL:
			propertyValue = properties::CameraLocationExternal;
			break;
		case V4L2_CAMERA_ORIENTATION_FRONT:
			propertyValue = properties::CameraLocationFront;
			break;
		case V4L2_CAMERA_ORIENTATION_BACK:
			propertyValue = properties::CameraLocationBack;
			break;
		}
	} else {
		propertyValue = properties::CameraLocationExternal;
	}
	properties_.set(properties::Location, propertyValue);

	const auto &rotationControl = controls.find(V4L2_CID_CAMERA_SENSOR_ROTATION);
	if (rotationControl != controls.end()) {
		propertyValue = rotationControl->second.def().get<int32_t>();
		properties_.set(properties::Rotation, propertyValue);
	}

	properties_.set(properties::PixelArraySize, pixelArraySize_);
	properties_.set(properties::PixelArrayActiveAreas, { activeArea_ });

	/* Color filter array pattern, register only for RAW sensors. */
	for (const auto &format : formats_) {
		unsigned int mbusCode = format.first;
		BayerFormat bayerFormat = BayerFormat::fromMbusCode(mbusCode);
		if (!bayerFormat.isValid())
			continue;

		int32_t cfa;
		switch (bayerFormat.order) {
		case BayerFormat::BGGR:
			cfa = properties::draft::BGGR;
			break;
		case BayerFormat::GBRG:
			cfa = properties::draft::GBRG;
			break;
		case BayerFormat::GRBG: