/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright (C) 2022, Utkarsh Tiwari * * qcam - Camera Selection dialog */ #include "cam_select_dialog.h" #include #include #include #include #include #include #include #include #include #include CameraSelectorDialog::CameraSelectorDialog(libcamera::CameraManager *cameraManager, QWidget *parent) : QDialog(parent), cm_(cameraManager) { /* Use a QFormLayout for the dialog. */ QFormLayout *layout = new QFormLayout(this); /* Setup the camera id combo-box. */ cameraIdComboBox_ = new QComboBox; for (const auto &cam : cm_->cameras()) cameraIdComboBox_->addItem(QString::fromStdString(cam->id())); /* Set camera information labels. */ cameraLocation_ = new QLabel; cameraModel_ = new QLabel; updateCameraInfo(cameraIdComboBox_->currentText()); connect(cameraIdComboBox_, &QComboBox::currentTextChanged, this, &CameraSelectorDialog::updateCameraInfo); /* Setup the QDialogButton Box */ QDialogButtonBox *buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept); connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); /* Set the layout. */ layout->addRow("Camera:", cameraIdComboBox_); layout->addRow("Location:", cameraLocation_); layout->addRow("Model:", cameraModel_); layout->addWidget(buttonBox); /* * Decrease the minimum width of dialog to fit on narrow screens, with a * 20 pixels margin. */ QRect screenGeometry = qGuiApp->primaryScreen()->availableGeometry(); if (screenGeometry.width() < minimumWidth()) setMinimumWidth(screenGeometry.width() - 20); } CameraSelectorDialog::~CameraSelectorDialog() = default; std::string CameraSelectorDialog::getCameraId() { return cameraIdComboBox_->currentText().toStdString(); } /* Hotplug / Unplug Support. */ void CameraSelectorDialog::addCamera(QString cameraId) { cameraIdComboBox_->addItem(cameraId); } void CameraSelectorDialog::removeCamera(QString cameraId) { int cameraIndex = cameraIdComboBox_->findText(cameraId); cameraIdComboBox_->removeItem(cameraIndex); } /* Camera Information */ void CameraSelectorDialog::updateCameraInfo(QString cameraId) { const std::shared_ptr &camera = cm_->get(cameraId.toStdString()); if (!camera) return; const libcamera::ControlList &properties = camera->properties(); const auto &location = properties.get(libcamera::properties::Location); if (location) { switch (*location) { case libcamera::properties::CameraLocationFront: cameraLocation_->setText("Internal front camera"); break; case libcamera::properties::CameraLocationBack: cameraLocation_->setText("Internal back camera"); break; case libcamera::properties::CameraLocationExternal: cameraLocation_->setText("External camera"); break; default: cameraLocation_->setText("Unknown"); } } else { cameraLocation_->setText("Unknown"); } const auto &model = properties.get(libcamera::properties::Model) .value_or("Unknown"); cameraModel_->setText(QString::fromStdString(model)); } d9fd17e7bfec41abf09ada08ec8872aa'>rpi/agc.cpp
blob: c02b5ece242f79baadd0cbe522d98d72d5009ec6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
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
/* SPDX-License-Identifier: BSD-2-Clause */
/*
 * Copyright (C) 2019, Raspberry Pi (Trading) Limited
 *
 * agc.cpp - AGC/AEC control algorithm
 */

#include <map>

#include "linux/bcm2835-isp.h"

#include "../awb_status.h"
#include "../device_status.h"
#include "../histogram.hpp"
#include "../logging.hpp"
#include "../lux_status.h"
#include "../metadata.hpp"

#include "agc.hpp"

using namespace RPi;

#define NAME "rpi.agc"

#define PIPELINE_BITS 13 // seems to be a 13-bit pipeline

void AgcMeteringMode::Read(boost::property_tree::ptree const &params)
{
	int num = 0;
	for (auto &p : params.get_child("weights")) {
		if (num == AGC_STATS_SIZE)
			throw std::runtime_error("AgcConfig: too many weights");
		weights[num++] = p.second.get_value<double>();
	}
	if (num != AGC_STATS_SIZE)
		throw std::runtime_error("AgcConfig: insufficient weights");
}

static std::string
read_metering_modes(std::map<std::string, AgcMeteringMode> &metering_modes,
		    boost::property_tree::ptree const &params)
{
	std::string first;
	for (auto &p : params) {
		AgcMeteringMode metering_mode;
		metering_mode.Read(p.second);
		metering_modes[p.first] = std::move(metering_mode);
		if (first.empty())
			first = p.first;
	}
	return first;
}

static int read_double_list(std::vector<double> &list,
			    boost::property_tree::ptree const &params)
{
	for (auto &p : params)
		list.push_back(p.second.get_value<double>());
	return list.size();
}

void AgcExposureMode::Read(boost::property_tree::ptree const &params)
{
	int num_shutters =
		read_double_list(shutter, params.get_child("shutter"));
	int num_ags = read_double_list(gain, params.get_child("gain"));
	if (num_shutters < 2 || num_ags < 2)
		throw std::runtime_error(
			"AgcConfig: must have at least two entries in exposure profile");
	if (num_shutters != num_ags)
		throw std::runtime_error(
			"AgcConfig: expect same number of exposure and gain entries in exposure profile");
}

static std::string
read_exposure_modes(std::map<std::string, AgcExposureMode> &exposure_modes,
		    boost::property_tree::ptree const &params)
{
	std::string first;
	for (auto &p : params) {
		AgcExposureMode exposure_mode;
		exposure_mode.Read(p.second);
		exposure_modes[p.first] = std::move(exposure_mode);
		if (first.empty())
			first = p.first;
	}
	return first;
}

void AgcConstraint::Read(boost::property_tree::ptree const &params)
{
	std::string bound_string = params.get<std::string>("bound", "");
	transform(bound_string.begin(), bound_string.end(),
		  bound_string.begin(), ::toupper);
	if (bound_string != "UPPER" && bound_string != "LOWER")
		throw std::runtime_error(
			"AGC constraint type should be UPPER or LOWER");
	bound = bound_string == "UPPER" ? Bound::UPPER : Bound::LOWER;
	q_lo = params.get<double>("q_lo");
	q_hi = params.get<double>("q_hi");
	Y_target.Read(params.get_child("y_target"));
}

static AgcConstraintMode
read_constraint_mode(boost::property_tree::ptree const &params)
{
	AgcConstraintMode mode;
	for (auto &p : params) {
		AgcConstraint constraint;
		constraint.Read(p.second);
		mode.push_back(std::move(constraint));
	}
	return mode;
}

static std::string read_constraint_modes(
	std::map<std::string, AgcConstraintMode> &constraint_modes,
	boost::property_tree::ptree const &params)
{
	std::string first;
	for (auto &p : params) {
		constraint_modes[p.first] = read_constraint_mode(p.second);
		if (first.empty())
			first = p.first;
	}
	return first;
}

void AgcConfig::Read(boost::property_tree::ptree const &params)
{
	RPI_LOG("AgcConfig");
	default_metering_mode = read_metering_modes(
		metering_modes, params.get_child("metering_modes"));
	default_exposure_mode = read_exposure_modes(
		exposure_modes, params.get_child("exposure_modes"));
	default_constraint_mode = read_constraint_modes(
		constraint_modes, params.get_child("constraint_modes"));
	Y_target.Read(params.get_child("y_target"));
	speed = params.get<double>("speed", 0.2);
	startup_frames = params.get<uint16_t>("startup_frames", 10);
	fast_reduce_threshold =
		params.get<double>("fast_reduce_threshold", 0.4);
	base_ev = params.get<double>("base_ev", 1.0);
}

Agc::Agc(Controller *controller)
	: AgcAlgorithm(controller), metering_mode_(nullptr),
	  exposure_mode_(nullptr), constraint_mode_(nullptr),
	  frame_count_(0), lock_count_(0)
{
	ev_ = status_.ev = 1.0;
	flicker_period_ = status_.flicker_period = 0.0;
	fixed_shutter_ = status_.fixed_shutter = 0;
	fixed_analogue_gain_ = status_.fixed_analogue_gain = 0.0;
	// set to zero initially, so we can tell it's not been calculated
	status_.total_exposure_value = 0.0;
	status_.target_exposure_value = 0.0;
	status_.locked = false;
	output_status_ = status_;
}

char const *Agc::Name() const
{
	return NAME;
}

void Agc::Read(boost::property_tree::ptree const &params)
{
	RPI_LOG("Agc");
	config_.Read(params);
	// Set the config's defaults (which are the first ones it read) as our
	// current modes, until someone changes them.  (they're all known to
	// exist at this point)
	metering_mode_name_ = config_.default_metering_mode;
	metering_mode_ = &config_.metering_modes[metering_mode_name_];
	exposure_mode_name_ = config_.default_exposure_mode;
	exposure_mode_ = &config_.exposure_modes[exposure_mode_name_];
	constraint_mode_name_ = config_.default_constraint_mode;
	constraint_mode_ = &config_.constraint_modes[constraint_mode_name_];
}

void Agc::SetEv(double ev)
{
	std::unique_lock<std::mutex> lock(settings_mutex_);
	ev_ = ev;
}

void Agc::SetFlickerPeriod(double flicker_period)
{
	std::unique_lock<std::mutex> lock(settings_mutex_);
	flicker_period_ = flicker_period;
}

void Agc::SetFixedShutter(double fixed_shutter)
{
	std::unique_lock<std::mutex> lock(settings_mutex_);
	fixed_shutter_ = fixed_shutter;
}

void Agc::SetFixedAnalogueGain(double fixed_analogue_gain)
{
	std::unique_lock<std::mutex> lock(settings_mutex_);
	fixed_analogue_gain_ = fixed_analogue_gain;
}

void Agc::SetMeteringMode(std::string const &metering_mode_name)
{
	std::unique_lock<std::mutex> lock(settings_mutex_);
	metering_mode_name_ = metering_mode_name;
}

void Agc::SetExposureMode(std::string const &exposure_mode_name)
{
	std::unique_lock<std::mutex> lock(settings_mutex_);
	exposure_mode_name_ = exposure_mode_name;
}

void Agc::SetConstraintMode(std::string const &constraint_mode_name)
{
	std::unique_lock<std::mutex> lock(settings_mutex_);
	constraint_mode_name_ = constraint_mode_name;
}

void Agc::SwitchMode(CameraMode const &camera_mode, Metadata *metadata)
{
	// On a mode switch, it's possible the exposure profile could change,
	// so we run through the dividing up of exposure/gain again and
	// write the results into the metadata we've been given.
	if (status_.total_exposure_value) {
		housekeepConfig();
		divvyupExposure();
		writeAndFinish(metadata, false);
	}
}

void Agc::Prepare(Metadata *image_metadata)
{
	AgcStatus status;
	{
		std::unique_lock<std::mutex> lock(output_mutex_);
		status = output_status_;
	}
	int lock_count = lock_count_;
	lock_count_ = 0;
	status.digital_gain = 1.0;
	if (status_.total_exposure_value) {
		// Process has run, so we have meaningful values.
		DeviceStatus device_status;
		if (image_metadata->Get("device.status", device_status) == 0) {
			double actual_exposure = device_status.shutter_speed *
						 device_status.analogue_gain;
			if (actual_exposure) {
				status.digital_gain =
					status_.total_exposure_value /
					actual_exposure;
				RPI_LOG("Want total exposure " << status_.total_exposure_value);
				// Never ask for a gain < 1.0, and also impose
				// some upper limit. Make it customisable?
				status.digital_gain = std::max(
					1.0,
					std::min(status.digital_gain, 4.0));
				RPI_LOG("Actual exposure " << actual_exposure);
				RPI_LOG("Use digital_gain " << status.digital_gain);
				RPI_LOG("Effective exposure " << actual_exposure * status.digital_gain);
				// Decide whether AEC/AGC has converged.
				// Insist AGC is steady for MAX_LOCK_COUNT
				// frames before we say we are "locked".
				// (The hard-coded constants may need to
				// become customisable.)
				if (status.target_exposure_value) {
#define MAX_LOCK_COUNT 3
					double err = 0.10 * status.target_exposure_value + 200;
					if (actual_exposure <
					    status.target_exposure_value + err
					    && actual_exposure >
					    status.target_exposure_value - err)
						lock_count_ =
							std::min(lock_count + 1,
							       MAX_LOCK_COUNT);
					else if (actual_exposure <
						 status.target_exposure_value
						 + 1.5 * err &&
						 actual_exposure >
						 status.target_exposure_value
						 - 1.5 * err)
						lock_count_ = lock_count;
					RPI_LOG("Lock count: " << lock_count_);
				}
			}
		} else
			RPI_LOG(Name() << ": no device metadata");
		status.locked = lock_count_ >= MAX_LOCK_COUNT;
		//printf("%s\n", status.locked ? "+++++++++" : "-");
		image_metadata->Set("agc.status", status);
	}
}

void Agc::Process(StatisticsPtr &stats, Metadata *image_metadata)
{
	frame_count_++;
	// First a little bit of housekeeping, fetching up-to-date settings and
	// configuration, that kind of thing.
	housekeepConfig();
	// Get the current exposure values for the frame that's just arrived.
	fetchCurrentExposure(image_metadata);
	// Compute the total gain we require relative to the current exposure.
	double gain, target_Y;
	computeGain(stats.get(), image_metadata, gain, target_Y);
	// Now compute the target (final) exposure which we think we want.
	computeTargetExposure(gain);
	// Some of the exposure has to be applied as digital gain, so work out
	// what that is. This function also tells us whether it's decided to
	// "desaturate" the image more quickly.
	bool desaturate = applyDigitalGain(image_metadata, gain, target_Y);
	// The results have to be filtered so as not to change too rapidly.
	filterExposure(desaturate);
	// The last thing is to divvy up the exposure value into a shutter time
	// and analogue_gain, according to the current exposure mode.
	divvyupExposure();
	// Finally advertise what we've done.
	writeAndFinish(image_metadata, desaturate);
}

static void copy_string(std::string const &s, char *d, size_t size)
{
	size_t length = s.copy(d, size - 1);
	d[length] = '\0';
}

void Agc::housekeepConfig()
{
	// First fetch all the up-to-date settings, so no one else has to do it.
	std::string new_exposure_mode_name, new_constraint_mode_name,
		new_metering_mode_name;
	{
		std::unique_lock<std::mutex> lock(settings_mutex_);
		new_metering_mode_name = metering_mode_name_;
		new_exposure_mode_name = exposure_mode_name_;
		new_constraint_mode_name = constraint_mode_name_;
		status_.ev = ev_;
		status_.fixed_shutter = fixed_shutter_;
		status_.fixed_analogue_gain = fixed_analogue_gain_;
		status_.flicker_period = flicker_period_;
	}
	RPI_LOG("ev " << status_.ev << " fixed_shutter "
		      << status_.fixed_shutter << " fixed_analogue_gain "
		      << status_.fixed_analogue_gain);
	// Make sure the "mode" pointers point to the up-to-date things, if
	// they've changed.
	if (strcmp(new_metering_mode_name.c_str(), status_.metering_mode)) {
		auto it = config_.metering_modes.find(new_metering_mode_name);
		if (it == config_.metering_modes.end())
			throw std::runtime_error("Agc: no metering mode " +
						 new_metering_mode_name);
		metering_mode_ = &it->second;
		copy_string(new_metering_mode_name, status_.metering_mode,
			    sizeof(status_.metering_mode));
	}
	if (strcmp(new_exposure_mode_name.c_str(), status_.exposure_mode)) {
		auto it = config_.exposure_modes.find(new_exposure_mode_name);
		if (it == config_.exposure_modes.end())
			throw std::runtime_error("Agc: no exposure profile " +
						 new_exposure_mode_name);
		exposure_mode_ = &it->second;
		copy_string(new_exposure_mode_name, status_.exposure_mode,
			    sizeof(status_.exposure_mode));
	}
	if (strcmp(new_constraint_mode_name.c_str(), status_.constraint_mode)) {
		auto it =
			config_.constraint_modes.find(new_constraint_mode_name);
		if (it == config_.constraint_modes.end())
			throw std::runtime_error("Agc: no constraint list " +
						 new_constraint_mode_name);
		constraint_mode_ = &it->second;
		copy_string(new_constraint_mode_name, status_.constraint_mode,
			    sizeof(status_.constraint_mode));
	}
	RPI_LOG("exposure_mode "
		<< new_exposure_mode_name << " constraint_mode "
		<< new_constraint_mode_name << " metering_mode "
		<< new_metering_mode_name);
}

void Agc::fetchCurrentExposure(Metadata *image_metadata)
{
	std::unique_lock<Metadata> lock(*image_metadata);
	DeviceStatus *device_status =
		image_metadata->GetLocked<DeviceStatus>("device.status");
	if (!device_status)
		throw std::runtime_error("Agc: no device metadata");
	current_.shutter = device_status->shutter_speed;
	current_.analogue_gain = device_status->analogue_gain;
	AgcStatus *agc_status =
		image_metadata->GetLocked<AgcStatus>("agc.status");
	current_.total_exposure = agc_status ? agc_status->total_exposure_value : 0;
	current_.total_exposure_no_dg = current_.shutter * current_.analogue_gain;
}

static double compute_initial_Y(bcm2835_isp_stats *stats, Metadata *image_metadata,
				double weights[])
{
	bcm2835_isp_stats_region *regions = stats->agc_stats;
	struct AwbStatus awb;
	awb.gain_r = awb.gain_g = awb.gain_b = 1.0; // in case no metadata
	if (image_metadata->Get("awb.status", awb) != 0)
		RPI_WARN("Agc: no AWB status found");
	double Y_sum = 0, weight_sum = 0;
	for (int i = 0; i < AGC_STATS_SIZE; i++) {
		if (regions[i].counted == 0)
			continue;
		weight_sum += weights[i];
		double Y = regions[i].r_sum * awb.gain_r * .299 +
			   regions[i].g_sum * awb.gain_g * .587 +
			   regions[i].b_sum * awb.gain_b * .114;
		Y /= regions[i].counted;
		Y_sum += Y * weights[i];
	}
	return Y_sum / weight_sum / (1 << PIPELINE_BITS);
}

// We handle extra gain through EV by adjusting our Y targets. However, you
// simply can't monitor histograms once they get very close to (or beyond!)
// saturation, so we clamp the Y targets to this value. It does mean that EV