-
Notifications
You must be signed in to change notification settings - Fork 173
Expand file tree
/
Copy pathipa_base.cpp
More file actions
1877 lines (1605 loc) · 61.4 KB
/
ipa_base.cpp
File metadata and controls
1877 lines (1605 loc) · 61.4 KB
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
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SPDX-License-Identifier: BSD-2-Clause */
/*
* Copyright (C) 2019-2023, Raspberry Pi Ltd
*
* Raspberry Pi IPA base class
*/
#include "ipa_base.h"
#include <array>
#include <cmath>
#include <libcamera/base/log.h>
#include <libcamera/base/span.h>
#include <libcamera/control_ids.h>
#include <libcamera/property_ids.h>
#include "controller/af_algorithm.h"
#include "controller/af_status.h"
#include "controller/agc_algorithm.h"
#include "controller/awb_algorithm.h"
#include "controller/awb_status.h"
#include "controller/black_level_status.h"
#include "controller/ccm_algorithm.h"
#include "controller/ccm_status.h"
#include "controller/contrast_algorithm.h"
#include "controller/denoise_algorithm.h"
#include "controller/hdr_algorithm.h"
#include "controller/lux_status.h"
#include "controller/sharpen_algorithm.h"
#include "controller/statistics.h"
#include "controller/sync_algorithm.h"
#include "controller/sync_status.h"
namespace libcamera {
using namespace std::literals::chrono_literals;
using utils::Duration;
namespace {
/* Number of frame length times to hold in the queue. */
constexpr unsigned int FrameLengthsQueueSize = 10;
/* Configure the sensor with these values initially. */
constexpr double defaultAnalogueGain = 1.0;
constexpr Duration defaultExposureTime = 20.0ms;
constexpr Duration defaultMinFrameDuration = 1.0s / 30.0;
constexpr Duration defaultMaxFrameDuration = 250.0s;
/*
* Determine the minimum allowable inter-frame duration to run the controller
* algorithms. If the pipeline handler provider frames at a rate higher than this,
* we rate-limit the controller Prepare() and Process() calls to lower than or
* equal to this rate.
*/
constexpr Duration controllerMinFrameDuration = 1.0s / 30.0;
/* List of controls handled by the Raspberry Pi IPA */
const ControlInfoMap::Map ipaControls{
/* \todo Move this to the Camera class */
{ &controls::AeEnable, ControlInfo(false, true, true) },
{ &controls::ExposureTimeMode,
ControlInfo({ { ControlValue(controls::ExposureTimeModeAuto),
ControlValue(controls::ExposureTimeModeManual) } },
ControlValue(controls::ExposureTimeModeAuto)) },
{ &controls::ExposureTime,
ControlInfo(1, 66666, static_cast<int32_t>(defaultExposureTime.get<std::micro>())) },
{ &controls::AnalogueGainMode,
ControlInfo({ { ControlValue(controls::AnalogueGainModeAuto),
ControlValue(controls::AnalogueGainModeManual) } },
ControlValue(controls::AnalogueGainModeAuto)) },
{ &controls::AnalogueGain, ControlInfo(1.0f, 16.0f, 1.0f) },
{ &controls::AeMeteringMode, ControlInfo(controls::AeMeteringModeValues) },
{ &controls::AeConstraintMode, ControlInfo(controls::AeConstraintModeValues) },
{ &controls::AeExposureMode, ControlInfo(controls::AeExposureModeValues) },
{ &controls::ExposureValue, ControlInfo(-8.0f, 8.0f, 0.0f) },
{ &controls::AeFlickerMode,
ControlInfo({ { ControlValue(controls::FlickerOff),
ControlValue(controls::FlickerManual) } },
ControlValue(controls::FlickerOff)) },
{ &controls::AeFlickerPeriod, ControlInfo(100, 1000000) },
{ &controls::Brightness, ControlInfo(-1.0f, 1.0f, 0.0f) },
{ &controls::Contrast, ControlInfo(0.0f, 32.0f, 1.0f) },
{ &controls::HdrMode, ControlInfo(controls::HdrModeValues) },
{ &controls::Sharpness, ControlInfo(0.0f, 16.0f, 1.0f) },
{ &controls::ScalerCrop, ControlInfo(Rectangle{}, Rectangle(65535, 65535, 65535, 65535), Rectangle{}) },
{ &controls::FrameDurationLimits,
ControlInfo(static_cast<int64_t>(defaultMinFrameDuration.get<std::micro>()),
static_cast<int64_t>(defaultMaxFrameDuration.get<std::micro>()),
Span<const int64_t, 2>{ { static_cast<int64_t>(defaultMinFrameDuration.get<std::micro>()),
static_cast<int64_t>(defaultMinFrameDuration.get<std::micro>()) } }) },
{ &controls::draft::NoiseReductionMode, ControlInfo(controls::draft::NoiseReductionModeValues) },
{ &controls::rpi::StatsOutputEnable, ControlInfo(false, true, false) },
{ &controls::rpi::CnnEnableInputTensor, ControlInfo(false, true, false) },
{ &controls::rpi::SyncMode,
ControlInfo({ { ControlValue(controls::rpi::SyncModeOff),
ControlValue(controls::rpi::SyncModeClient) } },
ControlValue(controls::rpi::SyncModeOff)) },
{ &controls::rpi::SyncFrames, ControlInfo(100, 100000, 1000) },
};
/* IPA controls handled conditionally, if the sensor is not mono */
const ControlInfoMap::Map ipaColourControls{
{ &controls::AwbEnable, ControlInfo(false, true) },
{ &controls::AwbMode, ControlInfo(controls::AwbModeValues) },
{ &controls::ColourGains, ControlInfo(0.0f, 32.0f) },
{ &controls::ColourCorrectionMatrix, ControlInfo(0.0f, 8.0f) },
{ &controls::ColourTemperature, ControlInfo(100, 100000) },
{ &controls::Saturation, ControlInfo(0.0f, 32.0f, 1.0f) },
};
/* IPA controls handled conditionally, if the lens has a focus control */
const ControlInfoMap::Map ipaAfControls{
{ &controls::AfMode, ControlInfo(controls::AfModeValues) },
{ &controls::AfRange, ControlInfo(controls::AfRangeValues) },
{ &controls::AfSpeed, ControlInfo(controls::AfSpeedValues) },
{ &controls::AfMetering, ControlInfo(controls::AfMeteringValues) },
{ &controls::AfWindows, ControlInfo(Rectangle{}, Rectangle(65535, 65535, 65535, 65535),
Span<const Rectangle, 1>{ { Rectangle{} } }) },
{ &controls::AfTrigger, ControlInfo(controls::AfTriggerValues) },
{ &controls::AfPause, ControlInfo(controls::AfPauseValues) },
{ &controls::LensPosition, ControlInfo(0.0f, 32.0f, 1.0f) }
};
/* Platform specific controls */
const std::map<const std::string, ControlInfoMap::Map> platformControls {
{ "pisp", {
{ &controls::rpi::ScalerCrops, ControlInfo(Rectangle{}, Rectangle(65535, 65535, 65535, 65535), Rectangle{}) }
} },
};
} /* namespace */
LOG_DEFINE_CATEGORY(IPARPI)
namespace ipa::RPi {
IpaBase::IpaBase()
: controller_(), frameLengths_(FrameLengthsQueueSize, 0s), statsMetadataOutput_(false),
stitchSwapBuffers_(false), frameCount_(0), mistrustCount_(0), lastRunTimestamp_(0),
firstStart_(true), flickerState_({ 0, 0s }), cnnEnableInputTensor_(false), awbEnabled_(true)
{
}
IpaBase::~IpaBase()
{
}
int32_t IpaBase::init(const IPASettings &settings, const InitParams ¶ms, InitResult *result)
{
/*
* Load the "helper" for this sensor. This tells us all the device specific stuff
* that the kernel driver doesn't. We only do this the first time; we don't need
* to re-parse the metadata after a simple mode-switch for no reason.
*/
helper_ = std::unique_ptr<RPiController::CamHelper>(RPiController::CamHelper::create(settings.sensorModel));
if (!helper_) {
LOG(IPARPI, Error) << "Could not create camera helper for "
<< settings.sensorModel;
return -EINVAL;
}
/* Pass out the sensor metadata to the pipeline handler */
int sensorMetadata = helper_->sensorEmbeddedDataPresent();
result->sensorConfig.sensorMetadata = sensorMetadata;
/* Load the tuning file for this sensor. */
int ret = controller_.read(settings.configurationFile.c_str());
if (ret) {
LOG(IPARPI, Error)
<< "Failed to load tuning data file "
<< settings.configurationFile;
return ret;
}
lensPresent_ = params.lensPresent;
controller_.initialise();
helper_->setHwConfig(controller_.getHardwareConfig());
/* Return the controls handled by the IPA */
ControlInfoMap::Map ctrlMap = ipaControls;
if (lensPresent_)
ctrlMap.merge(ControlInfoMap::Map(ipaAfControls));
auto platformCtrlsIt = platformControls.find(controller_.getTarget());
if (platformCtrlsIt != platformControls.end())
ctrlMap.merge(ControlInfoMap::Map(platformCtrlsIt->second));
monoSensor_ = params.sensorInfo.cfaPattern == properties::draft::ColorFilterArrangementEnum::MONO;
if (!monoSensor_)
ctrlMap.merge(ControlInfoMap::Map(ipaColourControls));
result->controlInfo = ControlInfoMap(std::move(ctrlMap), controls::controls);
return platformInit(params, result);
}
int32_t IpaBase::configure(const IPACameraSensorInfo &sensorInfo, const ConfigParams ¶ms,
ConfigResult *result)
{
sensorCtrls_ = params.sensorControls;
if (!validateSensorControls()) {
LOG(IPARPI, Error) << "Sensor control validation failed.";
return -1;
}
if (lensPresent_) {
lensCtrls_ = params.lensControls;
if (!validateLensControls()) {
LOG(IPARPI, Warning) << "Lens validation failed, "
<< "no lens control will be available.";
lensPresent_ = false;
}
}
/* Setup a metadata ControlList to output metadata. */
libcameraMetadata_ = ControlList(controls::controls);
/* Re-assemble camera mode using the sensor info. */
setMode(sensorInfo);
mode_.transform = static_cast<libcamera::Transform>(params.transform);
/* Pass the camera mode to the CamHelper to setup algorithms. */
helper_->setCameraMode(mode_);
/*
* Initialise this ControlList correctly, even if empty, in case the IPA is
* running is isolation mode (passing the ControlList through the IPC layer).
*/
ControlList ctrls(sensorCtrls_);
/* The pipeline handler passes out the mode's sensitivity. */
result->modeSensitivity = mode_.sensitivity;
if (firstStart_) {
/* Supply initial values for frame durations. */
applyFrameDurations(defaultMinFrameDuration, defaultMaxFrameDuration);
/* Supply initial values for gain and exposure. */
AgcStatus agcStatus;
agcStatus.exposureTime = defaultExposureTime;
agcStatus.analogueGain = defaultAnalogueGain;
applyAGC(&agcStatus, ctrls);
}
result->sensorControls = std::move(ctrls);
/*
* Apply the correct limits to the exposure, gain and frame duration controls
* based on the current sensor mode.
*/
ControlInfoMap::Map ctrlMap = ipaControls;
ctrlMap[&controls::FrameDurationLimits] =
ControlInfo(static_cast<int64_t>(mode_.minFrameDuration.get<std::micro>()),
static_cast<int64_t>(mode_.maxFrameDuration.get<std::micro>()),
Span<const int64_t, 2>{ { static_cast<int64_t>(defaultMinFrameDuration.get<std::micro>()),
static_cast<int64_t>(defaultMinFrameDuration.get<std::micro>()) } });
ctrlMap[&controls::AnalogueGain] =
ControlInfo(static_cast<float>(mode_.minAnalogueGain),
static_cast<float>(mode_.maxAnalogueGain),
static_cast<float>(defaultAnalogueGain));
ctrlMap[&controls::ExposureTime] =
ControlInfo(static_cast<int32_t>(mode_.minExposureTime.get<std::micro>()),
static_cast<int32_t>(mode_.maxExposureTime.get<std::micro>()),
static_cast<int32_t>(defaultExposureTime.get<std::micro>()));
/* Declare colour processing related controls for non-mono sensors. */
if (!monoSensor_)
ctrlMap.merge(ControlInfoMap::Map(ipaColourControls));
/* Declare Autofocus controls, only if we have a controllable lens */
if (lensPresent_) {
ctrlMap.merge(ControlInfoMap::Map(ipaAfControls));
RPiController::AfAlgorithm *af =
dynamic_cast<RPiController::AfAlgorithm *>(controller_.getAlgorithm("af"));
if (af) {
double min, max, dflt;
af->getLensLimits(min, max);
dflt = af->getDefaultLensPosition();
ctrlMap[&controls::LensPosition] =
ControlInfo(static_cast<float>(min),
static_cast<float>(max),
static_cast<float>(dflt));
}
}
result->controlInfo = ControlInfoMap(std::move(ctrlMap), controls::controls);
return platformConfigure(params, result);
}
void IpaBase::start(const ControlList &controls, StartResult *result)
{
RPiController::Metadata metadata;
if (!controls.empty()) {
/* We have been given some controls to action before start. */
applyControls(controls);
}
controller_.switchMode(mode_, &metadata);
/* Reset the frame lengths queue state. */
lastTimeout_ = 0s;
frameLengths_.clear();
frameLengths_.resize(FrameLengthsQueueSize, 0s);
/*
* SwitchMode may supply updated exposure/gain values to use.
* agcStatus_ will store these values for us to use until delayed_status values
* start to appear.
*/
agcStatus_.exposureTime = 0.0s;
agcStatus_.analogueGain = 0.0;
metadata.get("agc.status", agcStatus_);
if (agcStatus_.exposureTime && agcStatus_.analogueGain) {
ControlList ctrls(sensorCtrls_);
applyAGC(&agcStatus_, ctrls);
result->controls = std::move(ctrls);
setCameraTimeoutValue();
}
/* Make a note of this as it tells us the HDR status of the first few frames. */
hdrStatus_ = agcStatus_.hdr;
/*
* AF: If no lens position was specified, drive lens to a default position.
* This had to be deferred (not initialised by a constructor) until here
* to ensure that exactly ONE starting position is sent to the lens driver.
* It should be the static API default, not dependent on AF range or mode.
*/
if (firstStart_ && lensPresent_) {
RPiController::AfAlgorithm *af = dynamic_cast<RPiController::AfAlgorithm *>(
controller_.getAlgorithm("af"));
if (af && !af->getLensPosition()) {
int32_t hwpos;
double pos = af->getDefaultLensPosition();
if (af->setLensPosition(pos, &hwpos, true)) {
ControlList lensCtrls(lensCtrls_);
lensCtrls.set(V4L2_CID_FOCUS_ABSOLUTE, hwpos);
setLensControls.emit(lensCtrls);
}
}
}
/*
* Initialise frame counts, and decide how many frames must be hidden or
* "mistrusted", which depends on whether this is a startup from cold,
* or merely a mode switch in a running system.
*/
unsigned int agcConvergenceFrames = 0, awbConvergenceFrames = 0;
frameCount_ = 0;
if (firstStart_) {
invalidCount_ = helper_->hideFramesStartup();
mistrustCount_ = helper_->mistrustFramesStartup();
/*
* Query the AGC/AWB for how many frames they may take to
* converge sufficiently. Where these numbers are non-zero
* we must allow for the frames with bad statistics
* (mistrustCount_) that they won't see. But if zero (i.e.
* no convergence necessary), no frames need to be dropped.
*/
RPiController::AgcAlgorithm *agc = dynamic_cast<RPiController::AgcAlgorithm *>(
controller_.getAlgorithm("agc"));
if (agc) {
agcConvergenceFrames = agc->getConvergenceFrames();
if (agcConvergenceFrames)
agcConvergenceFrames += mistrustCount_;
}
RPiController::AwbAlgorithm *awb = dynamic_cast<RPiController::AwbAlgorithm *>(
controller_.getAlgorithm("awb"));
if (awb) {
awbConvergenceFrames = awb->getConvergenceFrames();
if (awbConvergenceFrames)
awbConvergenceFrames += mistrustCount_;
}
} else {
invalidCount_ = helper_->hideFramesModeSwitch();
mistrustCount_ = helper_->mistrustFramesModeSwitch();
}
result->startupFrameCount = std::max({ agcConvergenceFrames, awbConvergenceFrames });
result->invalidFrameCount = invalidCount_;
invalidCount_ = std::max({ invalidCount_, agcConvergenceFrames, awbConvergenceFrames });
LOG(IPARPI, Debug) << "Startup frames: " << result->startupFrameCount
<< " Invalid frames: " << result->invalidFrameCount;
firstStart_ = false;
lastRunTimestamp_ = 0;
platformStart(controls, result);
}
void IpaBase::mapBuffers(const std::vector<IPABuffer> &buffers)
{
for (const IPABuffer &buffer : buffers) {
const FrameBuffer fb(buffer.planes);
buffers_.emplace(buffer.id,
MappedFrameBuffer(&fb, MappedFrameBuffer::MapFlag::ReadWrite));
}
}
void IpaBase::unmapBuffers(const std::vector<unsigned int> &ids)
{
for (unsigned int id : ids) {
auto it = buffers_.find(id);
if (it == buffers_.end())
continue;
buffers_.erase(id);
}
}
void IpaBase::prepareIsp(const PrepareParams ¶ms)
{
applyControls(params.requestControls);
/*
* At start-up, or after a mode-switch, we may want to
* avoid running the control algos for a few frames in case
* they are "unreliable".
*/
int64_t frameTimestamp = params.sensorControls.get(controls::SensorTimestamp).value_or(0);
unsigned int ipaContext = params.ipaContext % rpiMetadata_.size();
RPiController::Metadata &rpiMetadata = rpiMetadata_[ipaContext];
Span<uint8_t> embeddedBuffer;
rpiMetadata.clear();
fillDeviceStatus(params.sensorControls, ipaContext);
fillSyncParams(params, ipaContext);
if (!params.requestControls.empty())
rpiMetadata.set("ipa.request_controls", true);
if (params.buffers.embedded) {
/*
* Pipeline handler has supplied us with an embedded data buffer,
* we must pass it to the CamHelper for parsing.
*/
auto it = buffers_.find(params.buffers.embedded);
ASSERT(it != buffers_.end());
embeddedBuffer = it->second.planes()[0];
}
/*
* AGC wants to know the algorithm status from the time it actioned the
* sensor exposure/gain changes. So fetch it from the metadata list
* indexed by the IPA cookie returned, and put it in the current frame
* metadata.
*
* Note if the HDR mode has changed, as things like tonemaps may need updating.
*/
AgcStatus agcStatus;
bool hdrChange = false;
RPiController::Metadata &delayedMetadata = rpiMetadata_[params.delayContext % rpiMetadata_.size()];
if (!delayedMetadata.get<AgcStatus>("agc.status", agcStatus)) {
rpiMetadata.set("agc.delayed_status", agcStatus);
hdrChange = agcStatus.hdr.mode != hdrStatus_.mode;
hdrStatus_ = agcStatus.hdr;
}
/*
* This may overwrite the DeviceStatus using values from the sensor
* metadata, and may also do additional custom processing.
*/
helper_->prepare(embeddedBuffer, rpiMetadata);
bool delayedRequestControls = false;
delayedMetadata.get<bool>("ipa.request_controls", delayedRequestControls);
/* Allow a 10% margin on the comparison below. */
Duration delta = (frameTimestamp - lastRunTimestamp_) * 1.0ns;
if (!delayedRequestControls && params.requestControls.empty() &&
lastRunTimestamp_ && frameCount_ > invalidCount_ &&
delta < controllerMinFrameDuration * 0.9 && !hdrChange) {
/*
* Ensure we merge the previous frame's metadata with the current
* frame. This will not overwrite exposure/gain values for the
* current frame, or any other bits of metadata that were added
* in helper_->Prepare().
*/
RPiController::Metadata &lastMetadata =
rpiMetadata_[(ipaContext ? ipaContext : rpiMetadata_.size()) - 1];
rpiMetadata.mergeCopy(lastMetadata);
processPending_ = false;
} else {
processPending_ = true;
lastRunTimestamp_ = frameTimestamp;
}
/*
* If the statistics are inline (i.e. already available with the Bayer
* frame), call processStats() now before prepare().
*/
if (controller_.getHardwareConfig().statsInline)
processStats({ params.buffers, params.ipaContext });
/* Do we need/want to call prepare? */
if (processPending_) {
controller_.prepare(&rpiMetadata);
/* Actually prepare the ISP parameters for the frame. */
platformPrepareIsp(params, rpiMetadata);
platformPrepareAgc(rpiMetadata);
} else
platformPrepareAgc(rpiMetadata);
frameCount_++;
/* If the statistics are inline the metadata can be returned early. */
if (controller_.getHardwareConfig().statsInline)
reportMetadata(ipaContext);
/* Ready to push the input buffer into the ISP. */
prepareIspComplete.emit(params.buffers, stitchSwapBuffers_);
}
void IpaBase::processStats(const ProcessParams ¶ms)
{
unsigned int ipaContext = params.ipaContext % rpiMetadata_.size();
RPiController::Metadata &rpiMetadata = rpiMetadata_[ipaContext];
Duration offset(0s);
if (processPending_ && frameCount_ >= mistrustCount_) {
auto it = buffers_.find(params.buffers.stats);
if (it == buffers_.end()) {
LOG(IPARPI, Error) << "Could not find stats buffer!";
return;
}
RPiController::StatisticsPtr statistics = platformProcessStats(it->second.planes()[0]);
/* reportMetadata() will pick this up and set the FocusFoM metadata */
rpiMetadata.set("focus.status", statistics->focusRegions);
helper_->process(statistics, rpiMetadata);
controller_.process(statistics, &rpiMetadata);
/* Send any sync algorithm outputs back to the pipeline handler */
struct SyncStatus syncStatus;
if (rpiMetadata.get("sync.status", syncStatus) == 0) {
if (minFrameDuration_ != maxFrameDuration_)
LOG(IPARPI, Error) << "Sync algorithm enabled with variable framerate. "
<< minFrameDuration_ << " " << maxFrameDuration_;
offset = syncStatus.frameDurationOffset;
libcameraMetadata_.set(controls::rpi::SyncReady, syncStatus.ready);
if (syncStatus.timerKnown)
libcameraMetadata_.set(controls::rpi::SyncTimer, syncStatus.timerValue);
}
}
struct AgcStatus agcStatus;
if (rpiMetadata.get("agc.status", agcStatus) == 0) {
ControlList ctrls(sensorCtrls_);
applyAGC(&agcStatus, ctrls, offset);
rpiMetadata.set("agc.status", agcStatus);
setDelayedControls.emit(ctrls, params.ipaContext);
setCameraTimeoutValue();
}
/*
* If the statistics are not inline the metadata must be returned now,
* before the processStatsComplete signal.
*/
if (!controller_.getHardwareConfig().statsInline)
reportMetadata(ipaContext);
processStatsComplete.emit(params.buffers);
}
void IpaBase::setMode(const IPACameraSensorInfo &sensorInfo)
{
mode_.bitdepth = sensorInfo.bitsPerPixel;
mode_.width = sensorInfo.outputSize.width;
mode_.height = sensorInfo.outputSize.height;
mode_.sensorWidth = sensorInfo.activeAreaSize.width;
mode_.sensorHeight = sensorInfo.activeAreaSize.height;
mode_.cropX = sensorInfo.analogCrop.x;
mode_.cropY = sensorInfo.analogCrop.y;
mode_.pixelRate = sensorInfo.pixelRate;
/*
* Calculate scaling parameters. The scale_[xy] factors are determined
* by the ratio between the crop rectangle size and the output size.
*/
mode_.scaleX = sensorInfo.analogCrop.width / sensorInfo.outputSize.width;
mode_.scaleY = sensorInfo.analogCrop.height / sensorInfo.outputSize.height;
/*
* We're not told by the pipeline handler how scaling is split between
* binning and digital scaling. For now, as a heuristic, assume that
* downscaling up to 2 is achieved through binning, and that any
* additional scaling is achieved through digital scaling.
*
* \todo Get the pipeline handle to provide the full data
*/
mode_.binX = std::min(2, static_cast<int>(mode_.scaleX));
mode_.binY = std::min(2, static_cast<int>(mode_.scaleY));
/* The noise factor is the square root of the total binning factor. */
mode_.noiseFactor = std::sqrt(mode_.binX * mode_.binY);
/*
* Calculate the line length as the ratio between the line length in
* pixels and the pixel rate.
*/
mode_.minLineLength = sensorInfo.minLineLength * (1.0s / sensorInfo.pixelRate);
mode_.maxLineLength = sensorInfo.maxLineLength * (1.0s / sensorInfo.pixelRate);
/*
* Ensure that the maximum pixel processing rate does not exceed the ISP
* hardware capabilities. If it does, try adjusting the minimum line
* length to compensate if possible.
*/
Duration minPixelTime = controller_.getHardwareConfig().minPixelProcessingTime;
Duration pixelTime = mode_.minLineLength / mode_.width;
if (minPixelTime && pixelTime < minPixelTime) {
Duration adjustedLineLength = minPixelTime * mode_.width;
if (adjustedLineLength <= mode_.maxLineLength) {
LOG(IPARPI, Info)
<< "Adjusting mode minimum line length from " << mode_.minLineLength
<< " to " << adjustedLineLength << " because of ISP constraints.";
mode_.minLineLength = adjustedLineLength;
} else {
LOG(IPARPI, Error)
<< "Sensor minimum line length of " << Duration(pixelTime * mode_.width)
<< " (" << 1us / pixelTime << " MPix/s)"
<< " is below the minimum allowable ISP limit of "
<< adjustedLineLength
<< " (" << 1us / minPixelTime << " MPix/s) ";
LOG(IPARPI, Error)
<< "THIS WILL CAUSE IMAGE CORRUPTION!!! "
<< "Please update the camera sensor driver to allow more horizontal blanking control.";
}
}
/*
* Set the frame length limits for the mode to ensure exposure and
* framerate calculations are clipped appropriately.
*/
mode_.minFrameLength = sensorInfo.minFrameLength;
mode_.maxFrameLength = sensorInfo.maxFrameLength;
/* Store these for convenience. */
mode_.minFrameDuration = mode_.minFrameLength * mode_.minLineLength;
mode_.maxFrameDuration = mode_.maxFrameLength * mode_.maxLineLength;
/*
* Some sensors may have different sensitivities in different modes;
* the CamHelper will know the correct value.
*/
mode_.sensitivity = helper_->getModeSensitivity(mode_);
const ControlInfo &gainCtrl = sensorCtrls_.at(V4L2_CID_ANALOGUE_GAIN);
const ControlInfo &exposureTimeCtrl = sensorCtrls_.at(V4L2_CID_EXPOSURE);
mode_.minAnalogueGain = helper_->gain(gainCtrl.min().get<int32_t>());
mode_.maxAnalogueGain = helper_->gain(gainCtrl.max().get<int32_t>());
/*
* We need to give the helper the min/max frame durations so it can calculate
* the correct exposure limits below.
*/
helper_->setCameraMode(mode_);
/*
* Exposure time is calculated based on the limits of the frame
* durations.
*/
mode_.minExposureTime = helper_->exposure(exposureTimeCtrl.min().get<int32_t>(),
mode_.minLineLength);
mode_.maxExposureTime = Duration::max();
helper_->getBlanking(mode_.maxExposureTime, mode_.minFrameDuration,
mode_.maxFrameDuration);
}
void IpaBase::setCameraTimeoutValue()
{
/*
* Take the maximum value of the exposure queue as the camera timeout
* value to pass back to the pipeline handler. Only signal if it has changed
* from the last set value.
*/
auto max = std::max_element(frameLengths_.begin(), frameLengths_.end());
if (*max != lastTimeout_) {
setCameraTimeout.emit(max->get<std::milli>());
lastTimeout_ = *max;
}
}
bool IpaBase::validateSensorControls()
{
static const uint32_t ctrls[] = {
V4L2_CID_ANALOGUE_GAIN,
V4L2_CID_EXPOSURE,
V4L2_CID_VBLANK,
V4L2_CID_HBLANK,
};
for (auto c : ctrls) {
if (sensorCtrls_.find(c) == sensorCtrls_.end()) {
LOG(IPARPI, Error) << "Unable to find sensor control "
<< utils::hex(c);
return false;
}
}
return true;
}
bool IpaBase::validateLensControls()
{
if (lensCtrls_.find(V4L2_CID_FOCUS_ABSOLUTE) == lensCtrls_.end()) {
LOG(IPARPI, Error) << "Unable to find Lens control V4L2_CID_FOCUS_ABSOLUTE";
return false;
}
return true;
}
/*
* Converting between enums (used in the libcamera API) and the names that
* we use to identify different modes. Unfortunately, the conversion tables
* must be kept up-to-date by hand.
*/
static const std::map<int32_t, std::string> MeteringModeTable = {
{ controls::MeteringCentreWeighted, "centre-weighted" },
{ controls::MeteringSpot, "spot" },
{ controls::MeteringMatrix, "matrix" },
{ controls::MeteringCustom, "custom" },
};
static const std::map<int32_t, std::string> ConstraintModeTable = {
{ controls::ConstraintNormal, "normal" },
{ controls::ConstraintHighlight, "highlight" },
{ controls::ConstraintShadows, "shadows" },
{ controls::ConstraintCustom, "custom" },
};
static const std::map<int32_t, std::string> ExposureModeTable = {
{ controls::ExposureNormal, "normal" },
{ controls::ExposureShort, "short" },
{ controls::ExposureLong, "long" },
{ controls::ExposureCustom, "custom" },
};
static const std::map<int32_t, std::string> AwbModeTable = {
{ controls::AwbAuto, "auto" },
{ controls::AwbIncandescent, "incandescent" },
{ controls::AwbTungsten, "tungsten" },
{ controls::AwbFluorescent, "fluorescent" },
{ controls::AwbIndoor, "indoor" },
{ controls::AwbDaylight, "daylight" },
{ controls::AwbCloudy, "cloudy" },
{ controls::AwbCustom, "custom" },
};
static const std::map<int32_t, RPiController::AfAlgorithm::AfMode> AfModeTable = {
{ controls::AfModeManual, RPiController::AfAlgorithm::AfModeManual },
{ controls::AfModeAuto, RPiController::AfAlgorithm::AfModeAuto },
{ controls::AfModeContinuous, RPiController::AfAlgorithm::AfModeContinuous },
};
static const std::map<int32_t, RPiController::AfAlgorithm::AfRange> AfRangeTable = {
{ controls::AfRangeNormal, RPiController::AfAlgorithm::AfRangeNormal },
{ controls::AfRangeMacro, RPiController::AfAlgorithm::AfRangeMacro },
{ controls::AfRangeFull, RPiController::AfAlgorithm::AfRangeFull },
};
static const std::map<int32_t, RPiController::AfAlgorithm::AfPause> AfPauseTable = {
{ controls::AfPauseImmediate, RPiController::AfAlgorithm::AfPauseImmediate },
{ controls::AfPauseDeferred, RPiController::AfAlgorithm::AfPauseDeferred },
{ controls::AfPauseResume, RPiController::AfAlgorithm::AfPauseResume },
};
static const std::map<int32_t, std::string> HdrModeTable = {
{ controls::HdrModeOff, "Off" },
{ controls::HdrModeMultiExposureUnmerged, "MultiExposureUnmerged" },
{ controls::HdrModeMultiExposure, "MultiExposure" },
{ controls::HdrModeSingleExposure, "SingleExposure" },
{ controls::HdrModeNight, "Night" },
};
void IpaBase::applyControls(const ControlList &controls)
{
using RPiController::AgcAlgorithm;
using RPiController::AfAlgorithm;
using RPiController::ContrastAlgorithm;
using RPiController::DenoiseAlgorithm;
using RPiController::HdrAlgorithm;
using RPiController::SyncAlgorithm;
/* Clear the return metadata buffer. */
libcameraMetadata_.clear();
/* Because some AF controls are mode-specific, handle AF mode change first. */
if (controls.contains(controls::AF_MODE)) {
AfAlgorithm *af = dynamic_cast<AfAlgorithm *>(controller_.getAlgorithm("af"));
if (!af) {
LOG(IPARPI, Warning)
<< "Could not set AF_MODE - no AF algorithm";
}
int32_t idx = controls.get(controls::AF_MODE).get<int32_t>();
auto mode = AfModeTable.find(idx);
if (mode == AfModeTable.end()) {
LOG(IPARPI, Error) << "AF mode " << idx
<< " not recognised";
} else if (af)
af->setMode(mode->second);
}
/*
* Because some AE controls are mode-specific, handle the AE-related
* mode changes first.
*/
const auto analogueGainMode = controls.get(controls::AnalogueGainMode);
const auto exposureTimeMode = controls.get(controls::ExposureTimeMode);
if (analogueGainMode || exposureTimeMode) {
RPiController::AgcAlgorithm *agc = dynamic_cast<RPiController::AgcAlgorithm *>(
controller_.getAlgorithm("agc"));
if (agc) {
if (analogueGainMode) {
if (*analogueGainMode == controls::AnalogueGainModeManual)
agc->disableAutoGain();
else
agc->enableAutoGain();
libcameraMetadata_.set(controls::AnalogueGainMode,
*analogueGainMode);
}
if (exposureTimeMode) {
if (*exposureTimeMode == controls::ExposureTimeModeManual)
agc->disableAutoExposure();
else
agc->enableAutoExposure();
libcameraMetadata_.set(controls::ExposureTimeMode,
*exposureTimeMode);
}
} else {
LOG(IPARPI, Warning)
<< "Could not set AnalogueGainMode or ExposureTimeMode - no AGC algorithm";
}
}
/*
* We must also handle any AWB on/off changes first, so that the CCM algorithm
* knows its state correctly.
*/
const auto awbEnable = controls.get(controls::AwbEnable);
if (awbEnable)
do {
/* Silently ignore this control for a mono sensor. */
if (monoSensor_)
break;
RPiController::AwbAlgorithm *awb = dynamic_cast<RPiController::AwbAlgorithm *>(
controller_.getAlgorithm("awb"));
if (!awb) {
LOG(IPARPI, Warning)
<< "Could not set AWB_ENABLE - no AWB algorithm";
break;
}
awbEnabled_ = *awbEnable;
if (!awbEnabled_)
awb->disableAuto();
else {
awb->enableAuto();
/* The CCM algorithm must go back to auto as well. */
RPiController::CcmAlgorithm *ccm = dynamic_cast<RPiController::CcmAlgorithm *>(
controller_.getAlgorithm("ccm"));
if (ccm)
ccm->enableAuto();
}
libcameraMetadata_.set(controls::AwbEnable, awbEnabled_);
} while (false);
const auto colourGains = controls.get(controls::ColourGains);
if (colourGains)
do {
/* Silently ignore this control for a mono sensor. */
if (monoSensor_)
break;
auto gains = *colourGains;
RPiController::AwbAlgorithm *awb = dynamic_cast<RPiController::AwbAlgorithm *>(
controller_.getAlgorithm("awb"));
if (!awb) {
LOG(IPARPI, Warning)
<< "Could not set COLOUR_GAINS - no AWB algorithm";
break;
}
awb->setManualGains(gains[0], gains[1]);
if (gains[0] != 0.0f && gains[1] != 0.0f) {
/* A gain of 0.0f will switch back to auto mode. */
libcameraMetadata_.set(controls::ColourGains,
{ gains[0], gains[1] });
awbEnabled_ = false; /* doing this puts AWB into manual mode */
} else {
awbEnabled_ = true; /* doing this puts AWB into auto mode */
/* The CCM algorithm must go back to auto as well. */
RPiController::CcmAlgorithm *ccm = dynamic_cast<RPiController::CcmAlgorithm *>(
controller_.getAlgorithm("ccm"));
if (ccm)
ccm->enableAuto();
}
/* This metadata will get reported back automatically. */
break;
} while (false);
const auto colourTemperature = controls.get(controls::ColourTemperature);
if (colourTemperature)
do {
/* Silently ignore this control for a mono sensor. */
if (monoSensor_)
break;
auto temperatureK = *colourTemperature;
RPiController::AwbAlgorithm *awb = dynamic_cast<RPiController::AwbAlgorithm *>(
controller_.getAlgorithm("awb"));
if (!awb) {
LOG(IPARPI, Warning)
<< "Could not set COLOUR_TEMPERATURE - no AWB algorithm";
break;
}
awb->setColourTemperature(temperatureK);
awbEnabled_ = false; /* doing this puts AWB into manual mode */
/* This metadata will get reported back automatically. */
break;
} while (false);
/* Iterate over controls */
for (auto const &ctrl : controls) {
LOG(IPARPI, Debug) << "Request ctrl: "
<< controls::controls.at(ctrl.first)->name()
<< " = " << ctrl.second.toString();
switch (ctrl.first) {
case controls::EXPOSURE_TIME_MODE:
break; /* We already handled this one above */
case controls::EXPOSURE_TIME: {
RPiController::AgcAlgorithm *agc = dynamic_cast<RPiController::AgcAlgorithm *>(
controller_.getAlgorithm("agc"));
if (!agc) {
LOG(IPARPI, Warning)
<< "Could not set EXPOSURE_TIME - no AGC algorithm";
break;
}
/*
* Ignore manual exposure time when the auto exposure
* algorithm is running.
*/
if (agc->autoExposureEnabled())
break;
/* The control provides units of microseconds. */
agc->setFixedExposureTime(0, ctrl.second.get<int32_t>() * 1.0us);
break;
}
case controls::ANALOGUE_GAIN_MODE:
break; /* We already handled this one above */
case controls::ANALOGUE_GAIN: {
RPiController::AgcAlgorithm *agc = dynamic_cast<RPiController::AgcAlgorithm *>(
controller_.getAlgorithm("agc"));
if (!agc) {
LOG(IPARPI, Warning)
<< "Could not set ANALOGUE_GAIN - no AGC algorithm";
break;
}
/*