summaryrefslogtreecommitdiff
path: root/src/ipa/raspberrypi/controller/pwl.cpp
blob: 7e11d8f3c3db639991dfa189a45a8a71c41f3251 (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
/* SPDX-License-Identifier: BSD-2-Clause */
/*
 * Copyright (C) 2019, Raspberry Pi (Trading) Limited
 *
 * pwl.cpp - piecewise linear functions
 */

#include <cassert>
#include <stdexcept>

#include "pwl.hpp"

using namespace RPi;

void Pwl::Read(boost::property_tree::ptree const &params)
{
	for (auto it = params.begin(); it != params.end(); it++) {
		double x = it->second.get_value<double>();
		assert(it == params.begin() || x > points_.back().x);
		it++;
		double y = it->second.get_value<double>();
		points_.push_back(Point(x, y));
	}
	assert(points_.size() >= 2);
}

void Pwl::Append(double x, double y, const double eps)
{
	if (points_.empty() || points_.back().x + eps < x)
		points_.push_back(Point(x, y));
}

void Pwl::Prepend(double x, double y, const double eps)
{
	if (points_.empty() || points_.front().x - eps > x)
		points_.insert(points_.begin(), Point(x, y));
}

Pwl::Interval Pwl::Domain() const
{
	return Interval(points_[0].x, points_[points_.size() - 1].x);
}

Pwl::Interval Pwl::Range() const
{
	double lo = points_[0].y, hi = lo;
	for (auto &p : points_)
		lo = std::min(lo, p.y), hi = std::max(hi, p.y);
	return Interval(lo, hi);
}

bool Pwl::Empty() const
{
	return points_.empty();
}

double Pwl::Eval(double x, int *span_ptr, bool update_span) const
{
	int span = findSpan(x, span_ptr && *span_ptr != -1
				       ? *span_ptr
				       : points_.size() / 2 - 1);
	if (span_ptr && update_span)
		*span_ptr = span;
	return points_[span].y +
	       (x - points_[span].x) * (points_[span + 1].y - points_[span].y) /
		       (points_[span + 1].x - points_[span].x);
}

int Pwl::findSpan(double x, int span) const
{
	// Pwls are generally small, so linear search may well be faster than
	// binary, though could review this if large PWls start turning up.
	int last_span = points_.size() - 2;
	// some algorithms may call us with span pointing directly at the last
	// control point
	span = std::max(0, std::min(last_span, span));
	while (span < last_span && x >= points_[span + 1].x)
		span++;
	while (span && x < points_[span].x)
		span--;
	return span;
}

Pwl::PerpType Pwl::Invert(Point const &xy, Point &perp, int &span,
			  const double eps) const
{
	assert(span >= -1);
	bool prev_off_end = false;
	for (span = span + 1; span < (int)points_.size() - 1; span++) {
		Point span_vec = points_[span + 1] - points_[span];
		double t = ((xy - points_[span]) % span_vec) / span_vec.Len2();
		if (t < -eps) // off the start of this span
		{
			if (span == 0) {
				perp = points_[span];
				return PerpType::Start;
			} else if (prev_off_end) {
				perp = points_[span];
				return PerpType::Vertex;
			}
		} else if (t > 1 + eps) // off the end of this span
		{
			if (span == (int)points_.size() - 2) {
				perp = points_[span + 1];
				return PerpType::End;
			}
			prev_off_end = true;
		} else // a true perpendicular
		{
			perp = points_[span] + span_vec * t;
			return PerpType::Perpendicular;
		}
	}
	return PerpType::None;
}

Pwl Pwl::Compose(Pwl const &other, const double eps) const
{
	double this_x = points_[0].x, this_y = points_[0].y;
	int this_span = 0, other_span = other.findSpan(this_y, 0);
	Pwl result({ { this_x, other.Eval(this_y, &other_span, false) } });
	while (this_span != (int)points_.size() - 1) {
		double dx = points_[this_span + 1].x - points_[this_span].x,
		       dy = points_[this_span + 1].y - points_[this_span].y;
		if (abs(dy) > eps &&
		    other_span + 1 < (int)other.points_.size() &&
		    points_[this_span + 1].y >=
			    other.points_[other_span + 1].x + eps) {
			// next control point in result will be where this
			// function's y reaches the next span in other
			this_x = points_[this_span].x +
				 (other.points_[other_span + 1].x -
				  points_[this_span].y) * dx / dy;
			this_y = other.points_[++other_span].x;
		} else if (abs(dy) > eps && other_span > 0 &&
			   points_[this_span + 1].y <=
				   other.points_[other_span - 1].x - eps) {
			// next control point in result will be where this
			// function's y reaches the previous span in other
			this_x = points_[this_span].x +
				 (other.points_[other_span + 1].x -
				  points_[this_span].y) * dx / dy;
			this_y = other.points_[--other_span].x;
		} else {
			// we stay in the same span in other
			this_span++;
			this_x = points_[this_span].x,
			this_y = points_[this_span].y;
		}
		result.Append(this_x, other.Eval(this_y, &other_span, false),
			      eps);
	}
	return result;
}

void Pwl::Map(std::function<void(double x, double y)> f) const
{
	for (auto &pt : points_)
		f(pt.x, pt.y);
}

void Pwl::Map2(Pwl const &pwl0, Pwl const &pwl1,
	       std::function<void(double x, double y0, double y1)> f)
{
	int span0 = 0, span1 = 0;
	double x = std::min(pwl0.points_[0].x, pwl1.points_[0].x);
	f(x, pwl0.Eval(x, &span0, false), pwl1.Eval(x, &span1, false));
	while (span0 < (int)pwl0.points_.size() - 1 ||
	       span1 < (int)pwl1.points_.size() - 1) {
		if (span0 == (int)pwl0.points_.size() - 1)
			x = pwl1.points_[++span1].x;
		else if (span1 == (int)pwl1.points_.size() - 1)
			x = pwl0.points_[++span0].x;
		else if (pwl0.points_[span0 + 1].x > pwl1.points_[span1 + 1].x)
			x = pwl1.points_[++span1].x;
		else
			x = pwl0.points_[++span0].x;
		f(x, pwl0.Eval(x, &span0, false), pwl1.Eval(x, &span1, false));
	}
}

Pwl Pwl::Combine(Pwl const &pwl0, Pwl const &pwl1,
		 std::function<double(double x, double y0, double y1)> f,
		 const double eps)
{
	Pwl result;
	Map2(pwl0, pwl1, [&](double x, double y0, double y1) {
		result.Append(x, f(x, y0, y1), eps);
	});
	return result;
}

void Pwl::MatchDomain(Interval const &domain, bool clip, const double eps)
{
	int span = 0;
	Prepend(domain.start, Eval(clip ? points_[0].x : domain.start, &span),
		eps);
	span = points_.size() - 2;
	Append(domain.end, Eval(clip ? points_.back().x : domain.end, &span),
	       eps);
}

Pwl &Pwl::operator*=(double d)
{
	for (auto &pt : points_)
		pt.y *= d;
	return *this;
}

void Pwl::Debug(FILE *fp) const
{
	fprintf(fp, "Pwl {\n");
	for (auto &p : points_)
		fprintf(fp, "\t(%g, %g)\n", p.x, p.y);
	fprintf(fp, "}\n");
}
/span> context.configuration.agc.measureWindow.v_offs = configInfo.outputSize.height / 8; context.configuration.agc.measureWindow.h_size = 3 * configInfo.outputSize.width / 4; context.configuration.agc.measureWindow.v_size = 3 * configInfo.outputSize.height / 4; setLimits(context.configuration.sensor.minExposureTime, context.configuration.sensor.maxExposureTime, context.configuration.sensor.minAnalogueGain, context.configuration.sensor.maxAnalogueGain); resetFrameCount(); return 0; } /** * \copydoc libcamera::ipa::Algorithm::queueRequest */ void Agc::queueRequest(IPAContext &context, [[maybe_unused]] const uint32_t frame, IPAFrameContext &frameContext, const ControlList &controls) { auto &agc = context.activeState.agc; if (!context.configuration.raw) { const auto &aeEnable = controls.get(controls::ExposureTimeMode); if (aeEnable && (*aeEnable == controls::ExposureTimeModeAuto) != agc.autoExposureEnabled) { agc.autoExposureEnabled = (*aeEnable == controls::ExposureTimeModeAuto); LOG(RkISP1Agc, Debug) << (agc.autoExposureEnabled ? "Enabling" : "Disabling") << " AGC (exposure)"; /* * If we go from auto -> manual with no manual control * set, use the last computed value, which we don't * know until prepare() so save this information. * * \todo Check the previous frame at prepare() time * instead of saving a flag here */ if (!agc.autoExposureEnabled && !controls.get(controls::ExposureTime)) frameContext.agc.autoExposureModeChange = true; } const auto &agEnable = controls.get(controls::AnalogueGainMode); if (agEnable && (*agEnable == controls::AnalogueGainModeAuto) != agc.autoGainEnabled) { agc.autoGainEnabled = (*agEnable == controls::AnalogueGainModeAuto); LOG(RkISP1Agc, Debug) << (agc.autoGainEnabled ? "Enabling" : "Disabling") << " AGC (gain)"; /* * If we go from auto -> manual with no manual control * set, use the last computed value, which we don't * know until prepare() so save this information. */ if (!agc.autoGainEnabled && !controls.get(controls::AnalogueGain)) frameContext.agc.autoGainModeChange = true; } } const auto &exposure = controls.get(controls::ExposureTime); if (exposure && !agc.autoExposureEnabled) { agc.manual.exposure = *exposure * 1.0us / context.configuration.sensor.lineDuration; LOG(RkISP1Agc, Debug) << "Set exposure to " << agc.manual.exposure; } const auto &gain = controls.get(controls::AnalogueGain); if (gain && !agc.autoGainEnabled) { agc.manual.gain = *gain; LOG(RkISP1Agc, Debug) << "Set gain to " << agc.manual.gain; } frameContext.agc.autoExposureEnabled = agc.autoExposureEnabled; frameContext.agc.autoGainEnabled = agc.autoGainEnabled; if (!frameContext.agc.autoExposureEnabled) frameContext.agc.exposure = agc.manual.exposure; if (!frameContext.agc.autoGainEnabled) frameContext.agc.gain = agc.manual.gain; const auto &meteringMode = controls.get(controls::AeMeteringMode); if (meteringMode) { frameContext.agc.updateMetering = agc.meteringMode != *meteringMode; agc.meteringMode = static_cast<controls::AeMeteringModeEnum>(*meteringMode); } frameContext.agc.meteringMode = agc.meteringMode; const auto &exposureMode = controls.get(controls::AeExposureMode); if (exposureMode) agc.exposureMode = static_cast<controls::AeExposureModeEnum>(*exposureMode); frameContext.agc.exposureMode = agc.exposureMode; const auto &constraintMode = controls.get(controls::AeConstraintMode); if (constraintMode) agc.constraintMode = static_cast<controls::AeConstraintModeEnum>(*constraintMode); frameContext.agc.constraintMode = agc.constraintMode; const auto &frameDurationLimits = controls.get(controls::FrameDurationLimits); if (frameDurationLimits) { utils::Duration maxFrameDuration = std::chrono::milliseconds((*frameDurationLimits).back()); agc.maxFrameDuration = maxFrameDuration; } frameContext.agc.maxFrameDuration = agc.maxFrameDuration; } /** * \copydoc libcamera::ipa::Algorithm::prepare */ void Agc::prepare(IPAContext &context, const uint32_t frame, IPAFrameContext &frameContext, RkISP1Params *params) { uint32_t activeAutoExposure = context.activeState.agc.automatic.exposure; double activeAutoGain = context.activeState.agc.automatic.gain; /* Populate exposure and gain in auto mode */ if (frameContext.agc.autoExposureEnabled) frameContext.agc.exposure = activeAutoExposure; if (frameContext.agc.autoGainEnabled) frameContext.agc.gain = activeAutoGain; /* * Populate manual exposure and gain from the active auto values when * transitioning from auto to manual */ if (!frameContext.agc.autoExposureEnabled && frameContext.agc.autoExposureModeChange) { context.activeState.agc.manual.exposure = activeAutoExposure; frameContext.agc.exposure = activeAutoExposure; } if (!frameContext.agc.autoGainEnabled && frameContext.agc.autoGainModeChange) { context.activeState.agc.manual.gain = activeAutoGain; frameContext.agc.gain = activeAutoGain; } if (frame > 0 && !frameContext.agc.updateMetering) return; /* * Configure the AEC measurements. Set the window, measure * continuously, and estimate Y as (R + G + B) x (85/256). */ auto aecConfig = params->block<BlockType::Aec>(); aecConfig.setEnabled(true); aecConfig->meas_window = context.configuration.agc.measureWindow; aecConfig->autostop = RKISP1_CIF_ISP_EXP_CTRL_AUTOSTOP_0; aecConfig->mode = RKISP1_CIF_ISP_EXP_MEASURING_MODE_1; /* * Configure the histogram measurement. Set the window, produce a * luminance histogram, and set the weights and predivider. */ auto hstConfig = params->block<BlockType::Hst>(); hstConfig.setEnabled(true); hstConfig->meas_window = context.configuration.agc.measureWindow; hstConfig->mode = RKISP1_CIF_ISP_HISTOGRAM_MODE_Y_HISTOGRAM; Span<uint8_t> weights{ hstConfig->hist_weight, context.hw->numHistogramWeights }; std::vector<uint8_t> &modeWeights = meteringModes_.at(frameContext.agc.meteringMode); std::copy(modeWeights.begin(), modeWeights.end(), weights.begin()); struct rkisp1_cif_isp_window window = hstConfig->meas_window; Size windowSize = { window.h_size, window.v_size }; hstConfig->histogram_predivider = computeHistogramPredivider(windowSize, static_cast<rkisp1_cif_isp_histogram_mode>(hstConfig->mode)); } void Agc::fillMetadata(IPAContext &context, IPAFrameContext &frameContext, ControlList &metadata) { utils::Duration exposureTime = context.configuration.sensor.lineDuration * frameContext.sensor.exposure; metadata.set(controls::AnalogueGain, frameContext.sensor.gain); metadata.set(controls::ExposureTime, exposureTime.get<std::micro>()); metadata.set(controls::ExposureTimeMode, frameContext.agc.autoExposureEnabled ? controls::ExposureTimeModeAuto : controls::ExposureTimeModeManual); metadata.set(controls::AnalogueGainMode, frameContext.agc.autoGainEnabled ? controls::AnalogueGainModeAuto : controls::AnalogueGainModeManual); /* \todo Use VBlank value calculated from each frame exposure. */ uint32_t vTotal = context.configuration.sensor.size.height + context.configuration.sensor.defVBlank; utils::Duration frameDuration = context.configuration.sensor.lineDuration * vTotal; metadata.set(controls::FrameDuration, frameDuration.get<std::micro>()); metadata.set(controls::AeMeteringMode, frameContext.agc.meteringMode); metadata.set(controls::AeExposureMode, frameContext.agc.exposureMode); metadata.set(controls::AeConstraintMode, frameContext.agc.constraintMode); } /** * \brief Estimate the relative luminance of the frame with a given gain * \param[in] gain The gain to apply to the frame * * This function estimates the average relative luminance of the frame that * would be output by the sensor if an additional \a gain was applied. * * The estimation is based on the AE statistics for the current frame. Y * averages for all cells are first multiplied by the gain, and then saturated * to approximate the sensor behaviour at high brightness values. The * approximation is quite rough, as it doesn't take into account non-linearities * when approaching saturation. In this case, saturating after the conversion to * YUV doesn't take into account the fact that the R, G and B components * contribute differently to the relative luminance. * * The values are normalized to the [0.0, 1.0] range, where 1.0 corresponds to a * theoretical perfect reflector of 100% reference white. * * More detailed information can be found in: * https://en.wikipedia.org/wiki/Relative_luminance * * \return The relative luminance */ double Agc::estimateLuminance(double gain) const { double ySum = 0.0; /* Sum the averages, saturated to 255. */ for (uint8_t expMean : expMeans_) ySum += std::min(expMean * gain, 255.0); /* \todo Weight with the AWB gains */ return ySum / expMeans_.size() / 255; } /** * \brief Process RkISP1 statistics, and run AGC operations * \param[in] context The shared IPA context * \param[in] frame The frame context sequence number * \param[in] frameContext The current frame context * \param[in] stats The RKISP1 statistics and ISP results * \param[out] metadata Metadata for the frame, to be filled by the algorithm * * Identify the current image brightness, and use that to estimate the optimal * new exposure and gain for the scene. */ void Agc::process(IPAContext &context, [[maybe_unused]] const uint32_t frame, IPAFrameContext &frameContext, const rkisp1_stat_buffer *stats, ControlList &metadata) { if (!stats) { fillMetadata(context, frameContext, metadata); return; } if (!(stats->meas_type & RKISP1_CIF_ISP_STAT_AUTOEXP)) { fillMetadata(context, frameContext, metadata); LOG(RkISP1Agc, Error) << "AUTOEXP data is missing in statistics"; return; } /* * \todo Verify that the exposure and gain applied by the sensor for * this frame match what has been requested. This isn't a hard * requirement for stability of the AGC (the guarantee we need in * automatic mode is a perfect match between the frame and the values * we receive), but is important in manual mode. */ const rkisp1_cif_isp_stat *params = &stats->params; /* The lower 4 bits are fractional and meant to be discarded. */ Histogram hist({ params->hist.hist_bins, context.hw->numHistogramBins }, [](uint32_t x) { return x >> 4; }); expMeans_ = { params->ae.exp_mean, context.hw->numAeCells }; /* * Set the AGC limits using the fixed exposure time and/or gain in * manual mode, or the sensor limits in auto mode. */ utils::Duration minExposureTime; utils::Duration maxExposureTime; double minAnalogueGain; double maxAnalogueGain; if (frameContext.agc.autoExposureEnabled) { minExposureTime = context.configuration.sensor.minExposureTime; maxExposureTime = std::clamp(frameContext.agc.maxFrameDuration, context.configuration.sensor.minExposureTime, context.configuration.sensor.maxExposureTime); } else { minExposureTime = context.configuration.sensor.lineDuration * frameContext.agc.exposure; maxExposureTime = minExposureTime; } if (frameContext.agc.autoGainEnabled) { minAnalogueGain = context.configuration.sensor.minAnalogueGain; maxAnalogueGain = context.configuration.sensor.maxAnalogueGain; } else { minAnalogueGain = frameContext.agc.gain; maxAnalogueGain = frameContext.agc.gain; } setLimits(minExposureTime, maxExposureTime, minAnalogueGain, maxAnalogueGain); /* * The Agc algorithm needs to know the effective exposure value that was * applied to the sensor when the statistics were collected. */ utils::Duration exposureTime = context.configuration.sensor.lineDuration * frameContext.sensor.exposure; double analogueGain = frameContext.sensor.gain; utils::Duration effectiveExposureValue = exposureTime * analogueGain; utils::Duration newExposureTime; double aGain, dGain; std::tie(newExposureTime, aGain, dGain) = calculateNewEv(frameContext.agc.constraintMode, frameContext.agc.exposureMode, hist, effectiveExposureValue); LOG(RkISP1Agc, Debug) << "Divided up exposure time, analogue gain and digital gain are " << newExposureTime << ", " << aGain << " and " << dGain; IPAActiveState &activeState = context.activeState; /* Update the estimated exposure and gain. */ activeState.agc.automatic.exposure = newExposureTime / context.configuration.sensor.lineDuration; activeState.agc.automatic.gain = aGain; fillMetadata(context, frameContext, metadata); expMeans_ = {}; } REGISTER_IPA_ALGORITHM(Agc, "Agc") } /* namespace ipa::rkisp1::algorithms */ } /* namespace libcamera */