summaryrefslogtreecommitdiff
path: root/src/ipa/raspberrypi/controller/rpi/alsc.cpp
blob: be3d1ae476cdcc7523d60e737e5a319d16de1e0a (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
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
/* SPDX-License-Identifier: BSD-2-Clause */
/*
 * Copyright (C) 2019, Raspberry Pi (Trading) Limited
 *
 * alsc.cpp - ALSC (auto lens shading correction) control algorithm
 */
#include <math.h>

#include <libcamera/base/log.h>

#include "../awb_status.h"
#include "alsc.hpp"

// Raspberry Pi ALSC (Auto Lens Shading Correction) algorithm.

using namespace RPiController;
using namespace libcamera;

LOG_DEFINE_CATEGORY(RPiAlsc)

#define NAME "rpi.alsc"

static const int X = ALSC_CELLS_X;
static const int Y = ALSC_CELLS_Y;
static const int XY = X * Y;
static const double INSUFFICIENT_DATA = -1.0;

Alsc::Alsc(Controller *controller)
	: Algorithm(controller)
{
	async_abort_ = async_start_ = async_started_ = async_finished_ = false;
	async_thread_ = std::thread(std::bind(&Alsc::asyncFunc, this));
}

Alsc::~Alsc()
{
	{
		std::lock_guard<std::mutex> lock(mutex_);
		async_abort_ = true;
	}
	async_signal_.notify_one();
	async_thread_.join();
}

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

static void generate_lut(double *lut, boost::property_tree::ptree const &params)
{
	double cstrength = params.get<double>("corner_strength", 2.0);
	if (cstrength <= 1.0)
		throw std::runtime_error("Alsc: corner_strength must be > 1.0");
	double asymmetry = params.get<double>("asymmetry", 1.0);
	if (asymmetry < 0)
		throw std::runtime_error("Alsc: asymmetry must be >= 0");
	double f1 = cstrength - 1, f2 = 1 + sqrt(cstrength);
	double R2 = X * Y / 4 * (1 + asymmetry * asymmetry);
	int num = 0;
	for (int y = 0; y < Y; y++) {
		for (int x = 0; x < X; x++) {
			double dy = y - Y / 2 + 0.5,
			       dx = (x - X / 2 + 0.5) * asymmetry;
			double r2 = (dx * dx + dy * dy) / R2;
			lut[num++] =
				(f1 * r2 + f2) * (f1 * r2 + f2) /
				(f2 * f2); // this reproduces the cos^4 rule
		}
	}
}

static void read_lut(double *lut, boost::property_tree::ptree const &params)
{
	int num = 0;
	const int max_num = XY;
	for (auto &p : params) {
		if (num == max_num)
			throw std::runtime_error(
				"Alsc: too many entries in LSC table");
		lut[num++] = p.second.get_value<double>();
	}
	if (num < max_num)
		throw std::runtime_error("Alsc: too few entries in LSC table");
}

static void read_calibrations(std::vector<AlscCalibration> &calibrations,
			      boost::property_tree::ptree const &params,
			      std::string const &name)
{
	if (params.get_child_optional(name)) {
		double last_ct = 0;
		for (auto &p : params.get_child(name)) {
			double ct = p.second.get<double>("ct");
			if (ct <= last_ct)
				throw std::runtime_error(
					"Alsc: entries in " + name +
					" must be in increasing ct order");
			AlscCalibration calibration;
			calibration.ct = last_ct = ct;
			boost::property_tree::ptree const &table =
				p.second.get_child("table");
			int num = 0;
			for (auto it = table.begin(); it != table.end(); it++) {
				if (num == XY)
					throw std::runtime_error(
						"Alsc: too many values for ct " +
						std::to_string(ct) + " in " +
						name);
				calibration.table[num++] =
					it->second.get_value<double>();
			}
			if (num != XY)
				throw std::runtime_error(
					"Alsc: too few values for ct " +
					std::to_string(ct) + " in " + name);
			calibrations.push_back(calibration);
			LOG(RPiAlsc, Debug)
				<< "Read " << name << " calibration for ct " << ct;
		}
	}
}

void Alsc::Read(boost::property_tree::ptree const &params)
{
	config_.frame_period = params.get<uint16_t>("frame_period", 12);
	config_.startup_frames = params.get<uint16_t>("startup_frames", 10);
	config_.speed = params.get<double>("speed", 0.05);
	double sigma = params.get<double>("sigma", 0.01);
	config_.sigma_Cr = params.get<double>("sigma_Cr", sigma);
	config_.sigma_Cb = params.get<double>("sigma_Cb", sigma);
	config_.min_count = params.get<double>("min_count", 10.0);
	config_.min_G = params.get<uint16_t>("min_G", 50);
	config_.omega = params.get<double>("omega", 1.3);
	config_.n_iter = params.get<uint32_t>("n_iter", X + Y);
	config_.luminance_strength =
		params.get<double>("luminance_strength", 1.0);
	for (int i = 0; i < XY; i++)
		config_.luminance_lut[i] = 1.0;
	if (params.get_child_optional("corner_strength"))
		generate_lut(config_.luminance_lut, params);
	else if (params.get_child_optional("luminance_lut"))
		read_lut(config_.luminance_lut,
			 params.get_child("luminance_lut"));
	else
		LOG(RPiAlsc, Warning)
			<< "no luminance table - assume unity everywhere";
	read_calibrations(config_.calibrations_Cr, params, "calibrations_Cr");
	read_calibrations(config_.calibrations_Cb, params, "calibrations_Cb");
	config_.default_ct = params.get<double>("default_ct", 4500.0);
	config_.threshold = params.get<double>("threshold", 1e-3);
}

static double get_ct(Metadata *metadata, double default_ct);
static void get_cal_table(double ct,
			  std::vector<AlscCalibration> const &calibrations,
			  double cal_table[XY]);
static void resample_cal_table(double const cal_table_in[XY],
			       CameraMode const &camera_mode,
			       double cal_table_out[XY]);
static void compensate_lambdas_for_cal(double const cal_table[XY],
				       double const old_lambdas[XY],
				       double new_lambdas[XY]);
static void add_luminance_to_tables(double results[3][Y][X],
				    double const lambda_r[XY], double lambda_g,
				    double const lambda_b[XY],
				    double const luminance_lut[XY],
				    double luminance_strength);

void Alsc::Initialise()
{
	frame_count2_ = frame_count_ = frame_phase_ = 0;
	first_time_ = true;
	ct_ = config_.default_ct;
	// The lambdas are initialised in the SwitchMode.
}

void Alsc::waitForAysncThread()
{
	if (async_started_) {
		async_started_ = false;
		std::unique_lock<std::mutex> lock(mutex_);
		sync_signal_.wait(lock, [&] {
			return async_finished_;
		});
		async_finished_ = false;
	}
}

static bool compare_modes(CameraMode const &cm0, CameraMode const &cm1)
{
	// Return true if the modes crop from the sensor significantly differently,
	// or if the user transform has changed.
	if (cm0.transform != cm1.transform)
		return true;
	int left_diff = abs(cm0.crop_x - cm1.crop_x);
	int top_diff = abs(cm0.crop_y - cm1.crop_y);
	int right_diff = fabs(cm0.crop_x + cm0.scale_x * cm0.width -
			      cm1.crop_x - cm1.scale_x * cm1.width);
	int bottom_diff = fabs(cm0.crop_y + cm0.scale_y * cm0.height -
			       cm1.crop_y - cm1.scale_y * cm1.height);
	// These thresholds are a rather arbitrary amount chosen to trigger
	// when carrying on with the previously calculated tables might be
	// worse than regenerating them (but without the adaptive algorithm).
	int threshold_x = cm0.sensor_width >> 4;
	int threshold_y = cm0.sensor_height >> 4;
	return left_diff > threshold_x || right_diff > threshold_x ||
	       top_diff > threshold_y || bottom_diff > threshold_y;
}

void Alsc::SwitchMode(CameraMode const &camera_mode,
		      [[maybe_unused]] Metadata *metadata)
{
	// We're going to start over with the tables if there's any "significant"
	// change.
	bool reset_tables = first_time_ || compare_modes(camera_mode_, camera_mode);

	// Believe the colour temperature from the AWB, if there is one.
	ct_ = get_ct(metadata, ct_);

	// Ensure the other thread isn't running while we do this.
	waitForAysncThread();

	camera_mode_ = camera_mode;

	// We must resample the luminance table like we do the others, but it's
	// fixed so we can simply do it up front here.
	resample_cal_table(config_.luminance_lut, camera_mode_, luminance_table_);

	if (reset_tables) {
		// Upon every "table reset", arrange for something sensible to be
		// generated. Construct the tables for the previous recorded colour
		// temperature. In order to start over from scratch we initialise
		// the lambdas, but the rest of this code then echoes the code in
		// doAlsc, without the adaptive algorithm.
		for (int i = 0; i < XY; i++)
			lambda_r_[i] = lambda_b_[i] = 1.0;
		double cal_table_r[XY], cal_table_b[XY], cal_table_tmp[XY];
		get_cal_table(ct_, config_.calibrations_Cr, cal_table_tmp);
		resample_cal_table(cal_table_tmp, camera_mode_, cal_table_r);
		get_cal_table(ct_, config_.calibrations_Cb, cal_table_tmp);
		resample_cal_table(cal_table_tmp, camera_mode_, cal_table_b);
		compensate_lambdas_for_cal(cal_table_r, lambda_r_,
					   async_lambda_r_);
		compensate_lambdas_for_cal(cal_table_b, lambda_b_,
					   async_lambda_b_);
		add_luminance_to_tables(sync_results_, async_lambda_r_, 1.0,
					async_lambda_b_, luminance_table_,
					config_.luminance_strength);
		memcpy(prev_sync_results_, sync_results_,
		       sizeof(prev_sync_results_));
		frame_phase_ = config_.frame_period; // run the algo again asap
		first_time_ = false;
	}
}

void Alsc::fetchAsyncResults()
{
	LOG(RPiAlsc, Debug) << "Fetch ALSC results";
	async_finished_ = false;
	async_started_ = false;
	memcpy(sync_results_, async_results_, sizeof(sync_results_));
}

double get_ct(Metadata *metadata, double default_ct)
{
	AwbStatus awb_status;
	awb_status.temperature_K = default_ct; // in case nothing found
	if (metadata->Get("awb.status", awb_status) != 0)
		LOG(RPiAlsc, Debug) << "no AWB results found, using "
				    << awb_status.temperature_K;
	else
		LOG(RPiAlsc, Debug) << "AWB results found, using "
				    << awb_status.temperature_K;
	return awb_status.temperature_K;
}

static void copy_stats(bcm2835_isp_stats_region regions[XY], StatisticsPtr &stats,
		       AlscStatus const &status)
{
	bcm2835_isp_stats_region *input_regions = stats->awb_stats;
	double *r_table = (double *)status.r;
	double *g_table = (double *)status.g;
	double *b_table = (double *)status.b;
	for (int i = 0; i < XY; i++) {
		regions[i].r_sum = input_regions[i].r_sum / r_table[i];
		regions[i].g_sum = input_regions[i].g_sum / g_table[i];
		regions[i].b_sum = input_regions[i].b_sum / b_table[i];
		regions[i].counted = input_regions[i].counted;
		// (don't care about the uncounted value)
	}
}

void Alsc::restartAsync(StatisticsPtr &stats, Metadata *image_metadata)
{
	LOG(RPiAlsc, Debug) << "Starting ALSC calculation";
	// Get the current colour temperature. It's all we need from the
	// metadata. Default to the last CT value (which could be the default).
	ct_ = get_ct(image_metadata, ct_);
	// We have to copy the statistics here, dividing out our best guess of
	// the LSC table that the pipeline applied to them.
	AlscStatus alsc_status;
	if (image_metadata->Get("alsc.status", alsc_status) != 0) {
		LOG(RPiAlsc, Warning)
			<< "No ALSC status found for applied gains!";
		for (int y = 0; y < Y; y++)
			for (int x = 0; x < X; x++) {
				alsc_status.r[y][x] = 1.0;
				alsc_status.g[y][x] = 1.0;
				alsc_status.b[y][x] = 1.0;
			}
	}
	copy_stats(statistics_, stats, alsc_status);
	frame_phase_ = 0;
	async_started_ = true;
	{
		std::lock_guard<std::mutex> lock(mutex_);
		async_start_ = true;
	}
	async_signal_.notify_one();
}

void Alsc::Prepare(Metadata *image_metadata)
{
	// Count frames since we started, and since we last poked the async
	// thread.
	if (frame_count_ < (int)config_.startup_frames)
		frame_count_++;
	double speed = frame_count_ < (int)config_.startup_frames
			       ? 1.0
			       : config_.speed;
	LOG(RPiAlsc, Debug)
		<< "frame_count " << frame_count_ << " speed " << speed;
	{
		std::unique_lock<std::mutex> lock(mutex_);
		if (async_started_ && async_finished_)
			fetchAsyncResults();
	}
	// Apply IIR filter to results and program into the pipeline.
	double *ptr = (double *)sync_results_,
	       *pptr = (double *)prev_sync_results_;
	for (unsigned int i = 0;
	     i < sizeof(sync_results_) / sizeof(double); i++)
		pptr[i] = speed * ptr[i] + (1.0 - speed) * pptr[i];
	// Put output values into status metadata.
	AlscStatus status;
	memcpy(status.r, prev_sync_results_[0], sizeof(status.r));
	memcpy(status.g, prev_sync_results_[1], sizeof(status.g));
	memcpy(status.b, prev_sync_results_[2], sizeof(status.b));
	image_metadata->Set("alsc.status", status);
}

void Alsc::Process(StatisticsPtr &stats, Metadata *image_metadata)
{
	// Count frames since we started, and since we last poked the async
	// thread.
	if (frame_phase_ < (int)config_.frame_period)
		frame_phase_++;
	if (frame_count2_ < (int)config_.startup_frames)
		frame_count2_++;
	LOG(RPiAlsc, Debug) << "frame_phase " << frame_phase_;
	if (frame_phase_ >= (int)config_.frame_period ||
	    frame_count2_ < (int)config_.startup_frames) {
		if (async_started_ == false)
			restartAsync(stats, image_metadata);
	}
}

void Alsc::asyncFunc()
{
	while (true) {
		{
			std::unique_lock<std::mutex> lock(mutex_);
			async_signal_.wait(lock, [&] {
				return async_start_ || async_abort_;
			});
			async_start_ = false;
			if (async_abort_)
				break;
		}
		doAlsc();
		{
			std::lock_guard<std::mutex> lock(mutex_);
			async_finished_ = true;
		}
		sync_signal_.notify_one();
	}
}

void get_cal_table(double ct, std::vector<AlscCalibration> const &calibrations,
		   double cal_table[XY])
{
	if (calibrations.empty()) {
		for (int i = 0; i < XY; i++)
			cal_table[i] = 1.0;
		LOG(RPiAlsc, Debug) << "no calibrations found";
	} else if (ct <= calibrations.front().ct) {
		memcpy(cal_table, calibrations.front().table,
		       XY * sizeof(double));
		LOG(RPiAlsc, Debug) << "using calibration for "
				    << calibrations.front().ct;
	} else if (ct >= calibrations.back().ct) {
		memcpy(cal_table, calibrations.back().table,
		       XY * sizeof(double));
		LOG(RPiAlsc, Debug) << "using calibration for "
				    << calibrations.back().ct;
	} else {
		int idx = 0;
		while (ct > calibrations[idx + 1].ct)
			idx++;
		double ct0 = calibrations[idx].ct,
		       ct1 = calibrations[idx + 1].ct;
		LOG(RPiAlsc, Debug)
			<< "ct is " << ct << ", interpolating between "
			<< ct0 << " and " << ct1;
		for (int i = 0; i < XY; i++)
			cal_table[i] =
				(calibrations[idx].table[i] * (ct1 - ct) +
				 calibrations[idx + 1].table[i] * (ct - ct0)) /
				(ct1 - ct0);
	}
}

void resample_cal_table(double const cal_table_in[XY],
			CameraMode const &camera_mode, double cal_table_out[XY])
{
	// Precalculate and cache the x sampling locations and phases to save
	// recomputing them on every row.
	int x_lo[X], x_hi[X];
	double xf[X];
	double scale_x = camera_mode.sensor_width /
			 (camera_mode.width * camera_mode.scale_x);
	double x_off = camera_mode.crop_x / (double)camera_mode.sensor_width;
	double x = .5 / scale_x + x_off * X - .5;
	double x_inc = 1 / scale_x;
	for (int i = 0; i < X; i++, x += x_inc) {
		x_lo[i] = floor(x);
		xf[i] = x - x_lo[i];
		x_hi[i] = std::min(x_lo[i] + 1, X - 1);
		x_lo[i] = std::max(x_lo[i], 0);
		if (!!(camera_mode.transform & libcamera::Transform::HFlip)) {
			x_lo[i] = X - 1 - x_lo[i];
			x_hi[i] = X - 1 - x_hi[i];
		}
	}
	// Now march over the output table generating the new values.
	double scale_y = camera_mode.sensor_height /
			 (camera_mode.height * camera_mode.scale_y);
	double y_off = camera_mode.crop_y / (double)camera_mode.sensor_height;
	double y = .5 / scale_y + y_off * Y - .5;
	double y_inc = 1 / scale_y;
	for (int j = 0; j < Y; j++, y += y_inc) {
		int y_lo = floor(y);
		double yf = y - y_lo;
		int y_hi = std::min(y_lo + 1, Y - 1);
		y_lo = std::max(y_lo, 0);
		if (!!(camera_mode.transform & libcamera::Transform::VFlip)) {
			y_lo = Y - 1 - y_lo;
			y_hi = Y - 1 - y_hi;
		}
		double const *row_above = cal_table_in + X * y_lo;
		double const *row_below = cal_table_in + X * y_hi;
		for (int i = 0; i < X; i++) {
			double above = row_above[x_lo[i]] * (1 - xf[i]) +
				       row_above[x_hi[i]] * xf[i];
			double below = row_below[x_lo[i]] * (1 - xf[i]) +
				       row_below[x_hi[i]] * xf[i];
			*(cal_table_out++) = above * (1 - yf) + below * yf;
		}
	}
}

// Calculate chrominance statistics (R/G and B/G) for each region.
static_assert(XY == AWB_REGIONS, "ALSC/AWB statistics region mismatch");
static void calculate_Cr_Cb(bcm2835_isp_stats_region *awb_region, double Cr[XY],
			    double Cb[XY], uint32_t min_count, uint16_t min_G)
{
	for (int i = 0; i < XY; i++) {
		bcm2835_isp_stats_region &zone = awb_region[i];
		if (zone.counted <= min_count ||
		    zone.g_sum / zone.counted <= min_G) {
			Cr[i] = Cb[i] = INSUFFICIENT_DATA;
			continue;
		}
		Cr[i] = zone.r_sum / (double)zone.g_sum;
		Cb[i] = zone.b_sum / (double)zone.g_sum;
	}
}

static void apply_cal_table(double const cal_table[XY], double C[XY])
{
	for (int i = 0; i < XY; i++)
		if (C[i] != INSUFFICIENT_DATA)
			C[i] *= cal_table[i];
}

void compensate_lambdas_for_cal(double const cal_table[XY],
				double const old_lambdas[XY],
				double new_lambdas[XY])
{
	double min_new_lambda = std::numeric_limits<double>::max();
	for (int i = 0; i < XY; i++) {
		new_lambdas[i] = old_lambdas[i] * cal_table[i];
		min_new_lambda = std::min(min_new_lambda, new_lambdas[i]);
	}
	for (int i = 0; i < XY; i++)
		new_lambdas[i] /= min_new_lambda;
}

[[maybe_unused]] static void print_cal_table(double const C[XY])
{
	printf("table: [\n");
	for (int j = 0; j < Y; j++) {
		for (int i = 0; i < X; i++) {
			printf("%5.3f", 1.0 / C[j * X + i]);
			if (i != X - 1 || j != Y - 1)
				printf(",");
		}
		printf("\n");
	}
	printf("]\n");
}

// Compute weight out of 1.0 which reflects how similar we wish to make the
// colours of these two regions.
static double compute_weight(double C_i, double C_j, double sigma)
{
	if (C_i == INSUFFICIENT_DATA || C_j == INSUFFICIENT_DATA)
		return 0;
	double diff = (C_i - C_j) / sigma;
	return exp(-diff * diff / 2);
}

// Compute all weights.
static void compute_W(double const C[XY], double sigma, double W[XY][4])
{
	for (int i = 0; i < XY; i++) {
		// Start with neighbour above and go clockwise.
		W[i][0] = i >= X ? compute_weight(C[i], C[i - X], sigma) : 0;
		W[i][1] = i % X < X - 1 ? compute_weight(C[i], C[i + 1], sigma)
					: 0;
		W[i][2] =
			i < XY - X ? compute_weight(C[i], C[i + X], sigma) : 0;
		W[i][3] = i % X ? compute_weight(C[i], C[i - 1], sigma) : 0;
	}
}

// Compute M, the large but sparse matrix such that M * lambdas = 0.
static void construct_M(double const C[XY], double const W[XY][4],
			double M[XY][4])
{
	double epsilon = 0.001;
	for (int i = 0; i < XY; i++) {
		// Note how, if C[i] == INSUFFICIENT_DATA, the weights will all
		// be zero so the equation is still set up correctly.
		int m = !!(i >= X) + !!(i % X < X - 1) + !!(i < XY - X) +
			!!(i % X); // total number of neighbours
		// we'll divide the diagonal out straight away
		double diagonal =
			(epsilon + W[i][0] + W[i][1] + W[i][2] + W[i][3]) *
			C[i];
		M[i][0] = i >= X ? (W[i][0] * C[i - X] + epsilon / m * C[i]) /
					   diagonal
				 : 0;
		M[i][1] = i % X < X - 1
				  ? (W[i][1] * C[i + 1] + epsilon / m * C[i]) /
					    diagonal
				  : 0;
		M[i][2] = i < XY - X
				  ? (W[i][2] * C[i + X] + epsilon / m * C[i]) /
					    diagonal
				  : 0;
		M[i][3] = i % X ? (W[i][3] * C[i - 1] + epsilon / m * C[i]) /
					  diagonal
				: 0;
	}
}

// In the compute_lambda_ functions, note that the matrix coefficients for the
// left/right neighbours are zero down the left/right edges, so we don't need
// need to test the i value to exclude them.
static double compute_lambda_bottom(int i, double const M[XY][4],
				    double lambda[XY])
{
	return M[i][1] * lambda[i + 1] + M[i][2] * lambda[i + X] +
	       M[i][3] * lambda[i - 1];
}
static double compute_lambda_bottom_start(int i, double const M[XY][4],
					  double lambda[XY])
{
	return M[i][1] * lambda[i + 1] + M[i][2] * lambda[i + X];
}
static double compute_lambda_interior(int i, double const M[XY][4],
				      double lambda[XY])
{
	return M[i][0] * lambda[i - X] + M[i][1] * lambda[i + 1] +
	       M[i][2] * lambda[i + X] + M[i][3] * lambda[i - 1];
}
static double compute_lambda_top(int i, double const M[XY][4],
				 double lambda[XY])
{
	return M[i][0] * lambda[i - X] + M[i][1] * lambda[i + 1] +
	       M[i][3] * lambda[i - 1];
}
static double compute_lambda_top_end(int i, double const M[XY][4],
				     double lambda[XY])
{
	return M[i][0] * lambda[i - X] + M[i][3] * lambda[i - 1];
}

// Gauss-Seidel iteration with over-relaxation.
static double gauss_seidel2_SOR(double const M[XY][4], double omega,
				double lambda[XY])
{
	double old_lambda[XY];
	int i;
	for (i = 0; i < XY; i++)
		old_lambda[i] = lambda[i];
	lambda[0] = compute_lambda_bottom_start(0, M, lambda);
	for (i = 1; i < X; i++)
		lambda[i] = compute_lambda_bottom(i, M, lambda);
	for (; i < XY - X; i++)
		lambda[i] = compute_lambda_interior(i, M, lambda);
	for (; i < XY - 1; i++)
		lambda[i] = compute_lambda_top(i, M, lambda);
	lambda[i] = compute_lambda_top_end(i, M, lambda);
	// Also solve the system from bottom to top, to help spread the updates
	// better.
	lambda[i] = compute_lambda_top_end(i, M, lambda);
	for (i = XY - 2; i >= XY - X; i--)
		lambda[i] = compute_lambda_top(i, M, lambda);
	for (; i >= X; i--)
		lambda[i] = compute_lambda_interior(i, M, lambda);
	for (; i >= 1; i--)
		lambda[i] = compute_lambda_bottom(i, M, lambda);
	lambda[0] = compute_lambda_bottom_start(0, M, lambda);
	double max_diff = 0;
	for (i = 0; i < XY; i++) {
		lambda[i] = old_lambda[i] + (lambda[i] - old_lambda[i]) * omega;
		if (fabs(lambda[i] - old_lambda[i]) > fabs(max_diff))
			max_diff = lambda[i] - old_lambda[i];
	}
	return max_diff;
}

// Normalise the values so that the smallest value is 1.
static void normalise(double *ptr, size_t n)
{
	double minval = ptr[0];
	for (size_t i = 1; i < n; i++)
		minval = std::min(minval, ptr[i]);
	for (size_t i = 0; i < n; i++)
		ptr[i] /= minval;
}

static void run_matrix_iterations(double const C[XY], double lambda[XY],
				  double const W[XY][4], double omega,
				  int n_iter, double threshold)
{
	double M[XY][4];
	construct_M(C, W, M);
	double last_max_diff = std::numeric_limits<double>::max();
	for (int i = 0; i < n_iter; i++) {
		double max_diff = fabs(gauss_seidel2_SOR(M, omega, lambda));
		if (max_diff < threshold) {
			LOG(RPiAlsc, Debug)
				<< "Stop after " << i + 1 << " iterations";
			break;
		}
		// this happens very occasionally (so make a note), though
		// doesn't seem to matter
		if (max_diff > last_max_diff)
			LOG(RPiAlsc, Debug)
				<< "Iteration " << i << ": max_diff gone up "
				<< last_max_diff << " to " << max_diff;
		last_max_diff = max_diff;
	}
	// We're going to normalise the lambdas so the smallest is 1. Not sure
	// this is really necessary as they get renormalised later, but I
	// suppose it does stop these quantities from wandering off...
	normalise(lambda, XY);
}

static void add_luminance_rb(double result[XY], double const lambda[XY],
			     double const luminance_lut[XY],
			     double luminance_strength)
{
	for (int i = 0; i < XY; i++)
		result[i] = lambda[i] *
			    ((luminance_lut[i] - 1) * luminance_strength + 1);
}

static void add_luminance_g(double result[XY], double lambda,
			    double const luminance_lut[XY],
			    double luminance_strength)
{
	for (int i = 0; i < XY; i++)
		result[i] = lambda *
			    ((luminance_lut[i] - 1) * luminance_strength + 1);
}

void add_luminance_to_tables(double results[3][Y][X], double const lambda_r[XY],
			     double lambda_g, double const lambda_b[XY],
			     double const luminance_lut[XY],
			     double luminance_strength)
{
	add_luminance_rb((double *)results[0], lambda_r, luminance_lut,
			 luminance_strength);
	add_luminance_g((double *)results[1], lambda_g, luminance_lut,
			luminance_strength);
	add_luminance_rb((double *)results[2], lambda_b, luminance_lut,
			 luminance_strength);
	normalise((double *)results, 3 * XY);
}

void Alsc::doAlsc()
{
	double Cr[XY], Cb[XY], Wr[XY][4], Wb[XY][4], cal_table_r[XY],
		cal_table_b[XY], cal_table_tmp[XY];
	// Calculate our R/B ("Cr"/"Cb") colour statistics, and assess which are
	// usable.
	calculate_Cr_Cb(statistics_, Cr, Cb, config_.min_count, config_.min_G);
	// Fetch the new calibrations (if any) for this CT. Resample them in
	// case the camera mode is not full-frame.
	get_cal_table(ct_, config_.calibrations_Cr, cal_table_tmp);
	resample_cal_table(cal_table_tmp, camera_mode_, cal_table_r);
	get_cal_table(ct_, config_.calibrations_Cb, cal_table_tmp);
	resample_cal_table(cal_table_tmp, camera_mode_, cal_table_b);
	// You could print out the cal tables for this image here, if you're
	// tuning the algorithm...
	// Apply any calibration to the statistics, so the adaptive algorithm
	// makes only the extra adjustments.
	apply_cal_table(cal_table_r, Cr);
	apply_cal_table(cal_table_b, Cb);
	// Compute weights between zones.
	compute_W(Cr, config_.sigma_Cr, Wr);
	compute_W(Cb, config_.sigma_Cb, Wb);
	// Run Gauss-Seidel iterations over the resulting matrix, for R and B.
	run_matrix_iterations(Cr, lambda_r_, Wr, config_.omega, config_.n_iter,
			      config_.threshold);
	run_matrix_iterations(Cb, lambda_b_, Wb, config_.omega, config_.n_iter,
			      config_.threshold);
	// Fold the calibrated gains into our final lambda values. (Note that on
	// the next run, we re-start with the lambda values that don't have the
	// calibration gains included.)
	compensate_lambdas_for_cal(cal_table_r, lambda_r_, async_lambda_r_);
	compensate_lambdas_for_cal(cal_table_b, lambda_b_, async_lambda_b_);
	// Fold in the luminance table at the appropriate strength.
	add_luminance_to_tables(async_results_, async_lambda_r_, 1.0,
				async_lambda_b_, luminance_table_,
				config_.luminance_strength);
}

// Register algorithm with the system.
static Algorithm *Create(Controller *controller)
{
	return (Algorithm *)new Alsc(controller);
}
static RegisterAlgorithm reg(NAME, &Create);
"hl kwb">struct ipu3_uapi_bnr_static_config_wb_gains_config { __u16 gr; __u16 r; __u16 b; __u16 gb; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_wb_gains_thr_config - Threshold config * * @gr: white balance threshold gain for Gr channel. * @r: white balance threshold gain for R channel. * @b: white balance threshold gain for B channel. * @gb: white balance threshold gain for Gb channel. * * Defines the threshold that specifies how different a defect pixel can be from * its neighbors.(used by dynamic defect pixel correction sub block) * Precision u4.4 range [0, 8]. */ struct ipu3_uapi_bnr_static_config_wb_gains_thr_config { __u8 gr; __u8 r; __u8 b; __u8 gb; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_thr_coeffs_config - Noise model * coefficients that controls noise threshold * * @cf: Free coefficient for threshold calculation, range [0, 8191], default 0. * @reserved0: reserved * @cg: Gain coefficient for threshold calculation, [0, 31], default 8. * @ci: Intensity coefficient for threshold calculation. range [0, 0x1f] * default 6. * format: u3.2 (3 most significant bits represent whole number, * 2 least significant bits represent the fractional part * with each count representing 0.25) * e.g. 6 in binary format is 00110, that translates to 1.5 * @reserved1: reserved * @r_nf: Normalization shift value for r^2 calculation, range [12, 20] * where r is a radius of pixel [row, col] from centor of sensor. * default 14. * * Threshold used to distinguish between noise and details. */ struct ipu3_uapi_bnr_static_config_thr_coeffs_config { __u32 cf:13; __u32 reserved0:3; __u32 cg:5; __u32 ci:5; __u32 reserved1:1; __u32 r_nf:5; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_thr_ctrl_shd_config - Shading config * * @gr: Coefficient defines lens shading gain approximation for gr channel * @r: Coefficient defines lens shading gain approximation for r channel * @b: Coefficient defines lens shading gain approximation for b channel * @gb: Coefficient defines lens shading gain approximation for gb channel * * Parameters for noise model (NM) adaptation of BNR due to shading correction. * All above have precision of u3.3, default to 0. */ struct ipu3_uapi_bnr_static_config_thr_ctrl_shd_config { __u8 gr; __u8 r; __u8 b; __u8 gb; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_opt_center_config - Optical center config * * @x_reset: Reset value of X (col start - X center). Precision s12.0. * @reserved0: reserved * @y_reset: Reset value of Y (row start - Y center). Precision s12.0. * @reserved2: reserved * * Distance from corner to optical center for NM adaptation due to shading * correction (should be calculated based on shading tables) */ struct ipu3_uapi_bnr_static_config_opt_center_config { __s32 x_reset:13; __u32 reserved0:3; __s32 y_reset:13; __u32 reserved2:3; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_lut_config - BNR square root lookup table * * @values: pre-calculated values of square root function. * * LUT implementation of square root operation. */ struct ipu3_uapi_bnr_static_config_lut_config { __u8 values[IPU3_UAPI_BNR_LUT_SIZE]; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_bp_ctrl_config - Detect bad pixels (bp) * * @bp_thr_gain: Defines the threshold that specifies how different a * defect pixel can be from its neighbors. Threshold is * dependent on de-noise threshold calculated by algorithm. * Range [4, 31], default 4. * @reserved0: reserved * @defect_mode: Mode of addressed defect pixels, * 0 - single defect pixel is expected, * 1 - 2 adjacent defect pixels are expected, default 1. * @bp_gain: Defines how 2nd derivation that passes through a defect pixel * is different from 2nd derivations that pass through * neighbor pixels. u4.2, range [0, 256], default 8. * @reserved1: reserved * @w0_coeff: Blending coefficient of defect pixel correction. * Precision u4, range [0, 8], default 8. * @reserved2: reserved * @w1_coeff: Enable influence of incorrect defect pixel correction to be * avoided. Precision u4, range [1, 8], default 8. * @reserved3: reserved */ struct ipu3_uapi_bnr_static_config_bp_ctrl_config { __u32 bp_thr_gain:5; __u32 reserved0:2; __u32 defect_mode:1; __u32 bp_gain:6; __u32 reserved1:18; __u32 w0_coeff:4; __u32 reserved2:4; __u32 w1_coeff:4; __u32 reserved3:20; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_dn_detect_ctrl_config - Denoising config * * @alpha: Weight of central element of smoothing filter. * @beta: Weight of peripheral elements of smoothing filter, default 4. * @gamma: Weight of diagonal elements of smoothing filter, default 4. * * beta and gamma parameter define the strength of the noise removal filter. * All above has precision u0.4, range [0, 0xf] * format: u0.4 (no / zero bits represent whole number, * 4 bits represent the fractional part * with each count representing 0.0625) * e.g. 0xf translates to 0.0625x15 = 0.9375 * * @reserved0: reserved * @max_inf: Maximum increase of peripheral or diagonal element influence * relative to the pre-defined value range: [0x5, 0xa] * @reserved1: reserved * @gd_enable: Green disparity enable control, 0 - disable, 1 - enable. * @bpc_enable: Bad pixel correction enable control, 0 - disable, 1 - enable. * @bnr_enable: Bayer noise removal enable control, 0 - disable, 1 - enable. * @ff_enable: Fixed function enable, 0 - disable, 1 - enable. * @reserved2: reserved */ struct ipu3_uapi_bnr_static_config_dn_detect_ctrl_config { __u32 alpha:4; __u32 beta:4; __u32 gamma:4; __u32 reserved0:4; __u32 max_inf:4; __u32 reserved1:7; __u32 gd_enable:1; __u32 bpc_enable:1; __u32 bnr_enable:1; __u32 ff_enable:1; __u32 reserved2:1; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_opt_center_sqr_config - BNR optical square * * @x_sqr_reset: Reset value of X^2. * @y_sqr_reset: Reset value of Y^2. * * Please note: * * #. X and Y ref to * &ipu3_uapi_bnr_static_config_opt_center_config * #. Both structs are used in threshold formula to calculate r^2, where r * is a radius of pixel [row, col] from centor of sensor. */ struct ipu3_uapi_bnr_static_config_opt_center_sqr_config { __u32 x_sqr_reset; __u32 y_sqr_reset; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config - BNR static config * * @wb_gains: white balance gains &ipu3_uapi_bnr_static_config_wb_gains_config * @wb_gains_thr: white balance gains threshold as defined by * &ipu3_uapi_bnr_static_config_wb_gains_thr_config * @thr_coeffs: coefficients of threshold * &ipu3_uapi_bnr_static_config_thr_coeffs_config * @thr_ctrl_shd: control of shading threshold * &ipu3_uapi_bnr_static_config_thr_ctrl_shd_config * @opt_center: optical center &ipu3_uapi_bnr_static_config_opt_center_config * * Above parameters and opt_center_sqr are used for white balance and shading. * * @lut: lookup table &ipu3_uapi_bnr_static_config_lut_config * @bp_ctrl: detect and remove bad pixels as defined in struct * &ipu3_uapi_bnr_static_config_bp_ctrl_config * @dn_detect_ctrl: detect and remove noise. * &ipu3_uapi_bnr_static_config_dn_detect_ctrl_config * @column_size: The number of pixels in column. * @opt_center_sqr: Reset value of r^2 to optical center, see * &ipu3_uapi_bnr_static_config_opt_center_sqr_config. */ struct ipu3_uapi_bnr_static_config { struct ipu3_uapi_bnr_static_config_wb_gains_config wb_gains; struct ipu3_uapi_bnr_static_config_wb_gains_thr_config wb_gains_thr; struct ipu3_uapi_bnr_static_config_thr_coeffs_config thr_coeffs; struct ipu3_uapi_bnr_static_config_thr_ctrl_shd_config thr_ctrl_shd; struct ipu3_uapi_bnr_static_config_opt_center_config opt_center; struct ipu3_uapi_bnr_static_config_lut_config lut; struct ipu3_uapi_bnr_static_config_bp_ctrl_config bp_ctrl; struct ipu3_uapi_bnr_static_config_dn_detect_ctrl_config dn_detect_ctrl; __u32 column_size; struct ipu3_uapi_bnr_static_config_opt_center_sqr_config opt_center_sqr; } __attribute__((packed)); /** * struct ipu3_uapi_bnr_static_config_green_disparity - Correct green disparity * * @gd_red: Shading gain coeff for gr disparity level in bright red region. * Precision u0.6, default 4(0.0625). * @reserved0: reserved * @gd_green: Shading gain coeff for gr disparity level in bright green * region. Precision u0.6, default 4(0.0625). * @reserved1: reserved * @gd_blue: Shading gain coeff for gr disparity level in bright blue region. * Precision u0.6, default 4(0.0625). * @reserved2: reserved * @gd_black: Maximal green disparity level in dark region (stronger disparity * assumed to be image detail). Precision u14, default 80. * @reserved3: reserved * @gd_shading: Change maximal green disparity level according to square * distance from image center. * @reserved4: reserved * @gd_support: Lower bound for the number of second green color pixels in * current pixel neighborhood with less than threshold difference * from it. * * The shading gain coeff of red, green, blue and black are used to calculate * threshold given a pixel's color value and its coordinates in the image. * * @reserved5: reserved * @gd_clip: Turn green disparity clip on/off, [0, 1], default 1. * @gd_central_weight: Central pixel weight in 9 pixels weighted sum. */ struct ipu3_uapi_bnr_static_config_green_disparity { __u32 gd_red:6; __u32 reserved0:2; __u32 gd_green:6; __u32 reserved1:2; __u32 gd_blue:6; __u32 reserved2:10; __u32 gd_black:14; __u32 reserved3:2; __u32 gd_shading:7; __u32 reserved4:1; __u32 gd_support:2; __u32 reserved5:1; __u32 gd_clip:1; __u32 gd_central_weight:4; } __attribute__((packed)); /** * struct ipu3_uapi_dm_config - De-mosaic parameters * * @dm_en: de-mosaic enable. * @ch_ar_en: Checker artifacts removal enable flag. Default 0. * @fcc_en: False color correction (FCC) enable flag. Default 0. * @reserved0: reserved * @frame_width: do not care * @gamma_sc: Sharpening coefficient (coefficient of 2-d derivation of * complementary color in Hamilton-Adams interpolation). * u5, range [0, 31], default 8. * @reserved1: reserved * @lc_ctrl: Parameter that controls weights of Chroma Homogeneity metric * in calculation of final homogeneity metric. * u5, range [0, 31], default 7. * @reserved2: reserved * @cr_param1: First parameter that defines Checker artifact removal * feature gain. Precision u5, range [0, 31], default 8. * @reserved3: reserved * @cr_param2: Second parameter that defines Checker artifact removal * feature gain. Precision u5, range [0, 31], default 8. * @reserved4: reserved * @coring_param: Defines power of false color correction operation. * low for preserving edge colors, high for preserving gray * edge artifacts. * Precision u1.4, range [0, 1.9375], default 4 (0.25). * @reserved5: reserved * * The demosaic fixed function block is responsible to covert Bayer(mosaiced) * images into color images based on demosaicing algorithm. */ struct ipu3_uapi_dm_config { __u32 dm_en:1; __u32 ch_ar_en:1; __u32 fcc_en:1; __u32 reserved0:13; __u32 frame_width:16; __u32 gamma_sc:5; __u32 reserved1:3; __u32 lc_ctrl:5; __u32 reserved2:3; __u32 cr_param1:5; __u32 reserved3:3; __u32 cr_param2:5; __u32 reserved4:3; __u32 coring_param:5; __u32 reserved5:27; } __attribute__((packed)); /** * struct ipu3_uapi_ccm_mat_config - Color correction matrix * * @coeff_m11: CCM 3x3 coefficient, range [-65536, 65535] * @coeff_m12: CCM 3x3 coefficient, range [-8192, 8191] * @coeff_m13: CCM 3x3 coefficient, range [-32768, 32767] * @coeff_o_r: Bias 3x1 coefficient, range [-8191, 8181] * @coeff_m21: CCM 3x3 coefficient, range [-32767, 32767] * @coeff_m22: CCM 3x3 coefficient, range [-8192, 8191] * @coeff_m23: CCM 3x3 coefficient, range [-32768, 32767] * @coeff_o_g: Bias 3x1 coefficient, range [-8191, 8181] * @coeff_m31: CCM 3x3 coefficient, range [-32768, 32767] * @coeff_m32: CCM 3x3 coefficient, range [-8192, 8191] * @coeff_m33: CCM 3x3 coefficient, range [-32768, 32767] * @coeff_o_b: Bias 3x1 coefficient, range [-8191, 8181] * * Transform sensor specific color space to standard sRGB by applying 3x3 matrix * and adding a bias vector O. The transformation is basically a rotation and * translation in the 3-dimensional color spaces. Here are the defaults: * * 9775, -2671, 1087, 0 * -1071, 8303, 815, 0 * -23, -7887, 16103, 0 */ struct ipu3_uapi_ccm_mat_config { __s16 coeff_m11; __s16 coeff_m12; __s16 coeff_m13; __s16 coeff_o_r; __s16 coeff_m21; __s16 coeff_m22; __s16 coeff_m23; __s16 coeff_o_g; __s16 coeff_m31; __s16 coeff_m32; __s16 coeff_m33; __s16 coeff_o_b; } __attribute__((packed)); /** * struct ipu3_uapi_gamma_corr_ctrl - Gamma correction * * @enable: gamma correction enable. * @reserved: reserved */ struct ipu3_uapi_gamma_corr_ctrl { __u32 enable:1; __u32 reserved:31; } __attribute__((packed)); /** * struct ipu3_uapi_gamma_corr_lut - Per-pixel tone mapping implemented as LUT. * * @lut: 256 tabulated values of the gamma function. LUT[1].. LUT[256] * format u13.0, range [0, 8191]. * * The tone mapping operation is done by a Piece wise linear graph * that is implemented as a lookup table(LUT). The pixel component input * intensity is the X-axis of the graph which is the table entry. */ struct ipu3_uapi_gamma_corr_lut { __u16 lut[IPU3_UAPI_GAMMA_CORR_LUT_ENTRIES]; } __attribute__((packed)); /** * struct ipu3_uapi_gamma_config - Gamma config * * @gc_ctrl: control of gamma correction &ipu3_uapi_gamma_corr_ctrl * @gc_lut: lookup table of gamma correction &ipu3_uapi_gamma_corr_lut */ struct ipu3_uapi_gamma_config { struct ipu3_uapi_gamma_corr_ctrl gc_ctrl __attribute__((aligned(32))); struct ipu3_uapi_gamma_corr_lut gc_lut __attribute__((aligned(32))); } __attribute__((packed)); /** * struct ipu3_uapi_csc_mat_config - Color space conversion matrix config * * @coeff_c11: Conversion matrix value, format s0.14, range [-16384, 16383]. * @coeff_c12: Conversion matrix value, format s0.14, range [-8192, 8191]. * @coeff_c13: Conversion matrix value, format s0.14, range [-16384, 16383]. * @coeff_b1: Bias 3x1 coefficient, s13.0 range [-8192, 8191]. * @coeff_c21: Conversion matrix value, format s0.14, range [-16384, 16383]. * @coeff_c22: Conversion matrix value, format s0.14, range [-8192, 8191]. * @coeff_c23: Conversion matrix value, format s0.14, range [-16384, 16383]. * @coeff_b2: Bias 3x1 coefficient, s13.0 range [-8192, 8191]. * @coeff_c31: Conversion matrix value, format s0.14, range [-16384, 16383]. * @coeff_c32: Conversion matrix value, format s0.14, range [-8192, 8191]. * @coeff_c33: Conversion matrix value, format s0.14, range [-16384, 16383]. * @coeff_b3: Bias 3x1 coefficient, s13.0 range [-8192, 8191]. * * To transform each pixel from RGB to YUV (Y - brightness/luminance, * UV -chroma) by applying the pixel's values by a 3x3 matrix and adding an * optional bias 3x1 vector. Here are the default values for the matrix: * * 4898, 9617, 1867, 0, * -2410, -4732, 7143, 0, * 10076, -8437, -1638, 0, * * (i.e. for real number 0.299, 0.299 * 2^14 becomes 4898.) */ struct ipu3_uapi_csc_mat_config { __s16 coeff_c11; __s16 coeff_c12; __s16 coeff_c13; __s16 coeff_b1; __s16 coeff_c21; __s16 coeff_c22; __s16 coeff_c23; __s16 coeff_b2; __s16 coeff_c31; __s16 coeff_c32; __s16 coeff_c33; __s16 coeff_b3; } __attribute__((packed)); /** * struct ipu3_uapi_cds_params - Chroma down-scaling * * @ds_c00: range [0, 3] * @ds_c01: range [0, 3] * @ds_c02: range [0, 3] * @ds_c03: range [0, 3] * @ds_c10: range [0, 3] * @ds_c11: range [0, 3] * @ds_c12: range [0, 3] * @ds_c13: range [0, 3] * * In case user does not provide, above 4x2 filter will use following defaults: * 1, 3, 3, 1, * 1, 3, 3, 1, * * @ds_nf: Normalization factor for Chroma output downscaling filter, * range 0,4, default 2. * @reserved0: reserved * @csc_en: Color space conversion enable * @uv_bin_output: 0: output YUV 4.2.0, 1: output YUV 4.2.2(default). * @reserved1: reserved */ struct ipu3_uapi_cds_params { __u32 ds_c00:2; __u32 ds_c01:2; __u32 ds_c02:2; __u32 ds_c03:2; __u32 ds_c10:2; __u32 ds_c11:2; __u32 ds_c12:2; __u32 ds_c13:2; __u32 ds_nf:5; __u32 reserved0:3; __u32 csc_en:1; __u32 uv_bin_output:1; __u32 reserved1:6; } __attribute__((packed)); /** * struct ipu3_uapi_shd_grid_config - Bayer shading(darkening) correction * * @width: Grid horizontal dimensions, u8, [8, 128], default 73 * @height: Grid vertical dimensions, u8, [8, 128], default 56 * @block_width_log2: Log2 of the width of the grid cell in pixel count * u4, [0, 15], default value 5. * @reserved0: reserved * @block_height_log2: Log2 of the height of the grid cell in pixel count * u4, [0, 15], default value 6. * @reserved1: reserved * @grid_height_per_slice: SHD_MAX_CELLS_PER_SET/width. * (with SHD_MAX_CELLS_PER_SET = 146). * @x_start: X value of top left corner of sensor relative to ROI * s13, [-4096, 0], default 0, only negative values. * @y_start: Y value of top left corner of sensor relative to ROI * s13, [-4096, 0], default 0, only negative values. */ struct ipu3_uapi_shd_grid_config { /* reg 0 */ __u8 width; __u8 height; __u8 block_width_log2:3; __u8 reserved0:1; __u8 block_height_log2:3; __u8 reserved1:1; __u8 grid_height_per_slice; /* reg 1 */ __s16 x_start; __s16 y_start; } __attribute__((packed)); /** * struct ipu3_uapi_shd_general_config - Shading general config * * @init_set_vrt_offst_ul: set vertical offset, * y_start >> block_height_log2 % grid_height_per_slice. * @shd_enable: shading enable. * @gain_factor: Gain factor. Shift calculated anti shading value. Precision u2. * 0x0 - gain factor [1, 5], means no shift interpolated value. * 0x1 - gain factor [1, 9], means shift interpolated by 1. * 0x2 - gain factor [1, 17], means shift interpolated by 2. * @reserved: reserved * * Correction is performed by multiplying a gain factor for each of the 4 Bayer * channels as a function of the pixel location in the sensor. */ struct ipu3_uapi_shd_general_config { __u32 init_set_vrt_offst_ul:8; __u32 shd_enable:1; __u32 gain_factor:2; __u32 reserved:21; } __attribute__((packed)); /** * struct ipu3_uapi_shd_black_level_config - Black level correction * * @bl_r: Bios values for green red. s11 range [-2048, 2047]. * @bl_gr: Bios values for green blue. s11 range [-2048, 2047]. * @bl_gb: Bios values for red. s11 range [-2048, 2047]. * @bl_b: Bios values for blue. s11 range [-2048, 2047]. */ struct ipu3_uapi_shd_black_level_config { __s16 bl_r; __s16 bl_gr; __s16 bl_gb; __s16 bl_b; } __attribute__((packed)); /** * struct ipu3_uapi_shd_config_static - Shading config static * * @grid: shading grid config &ipu3_uapi_shd_grid_config * @general: shading general config &ipu3_uapi_shd_general_config * @black_level: black level config for shading correction as defined by * &ipu3_uapi_shd_black_level_config */ struct ipu3_uapi_shd_config_static { struct ipu3_uapi_shd_grid_config grid; struct ipu3_uapi_shd_general_config general; struct ipu3_uapi_shd_black_level_config black_level; } __attribute__((packed)); /** * struct ipu3_uapi_shd_lut - Shading gain factor lookup table. * * @sets: array * @sets.r_and_gr: Red and GreenR Lookup table. * @sets.r_and_gr.r: Red shading factor. * @sets.r_and_gr.gr: GreenR shading factor. * @sets.reserved1: reserved * @sets.gb_and_b: GreenB and Blue Lookup table. * @sets.gb_and_b.gb: GreenB shading factor. * @sets.gb_and_b.b: Blue shading factor. * @sets.reserved2: reserved * * Map to shading correction LUT register set. */ struct ipu3_uapi_shd_lut { struct { struct { __u16 r; __u16 gr; } r_and_gr[IPU3_UAPI_SHD_MAX_CELLS_PER_SET]; __u8 reserved1[24]; struct { __u16 gb; __u16 b; } gb_and_b[IPU3_UAPI_SHD_MAX_CELLS_PER_SET]; __u8 reserved2[24]; } sets[IPU3_UAPI_SHD_MAX_CFG_SETS]; } __attribute__((packed)); /** * struct ipu3_uapi_shd_config - Shading config * * @shd: shading static config, see &ipu3_uapi_shd_config_static * @shd_lut: shading lookup table &ipu3_uapi_shd_lut */ struct ipu3_uapi_shd_config { struct ipu3_uapi_shd_config_static shd __attribute__((aligned(32))); struct ipu3_uapi_shd_lut shd_lut __attribute__((aligned(32))); } __attribute__((packed)); /* Image Enhancement Filter directed */ /** * struct ipu3_uapi_iefd_cux2 - IEFd Config Unit 2 parameters * * @x0: X0 point of Config Unit, u9.0, default 0. * @x1: X1 point of Config Unit, u9.0, default 0. * @a01: Slope A of Config Unit, s4.4, default 0. * @b01: Slope B, always 0. * * Calculate weight for blending directed and non-directed denoise elements * * Note: * Each instance of Config Unit needs X coordinate of n points and * slope A factor between points calculated by driver based on calibration * parameters. * * All CU inputs are unsigned, they will be converted to signed when written * to register, i.e. a01 will be written to 9 bit register in s4.4 format. * The data precision s4.4 means 4 bits for integer parts and 4 bits for the * fractional part, the first bit indicates positive or negative value. * For userspace software (commonly the imaging library), the computation for * the CU slope values should be based on the slope resolution 1/16 (binary * 0.0001 - the minimal interval value), the slope value range is [-256, +255]. * This applies to &ipu3_uapi_iefd_cux6_ed, &ipu3_uapi_iefd_cux2_1, * &ipu3_uapi_iefd_cux2_1, &ipu3_uapi_iefd_cux4 and &ipu3_uapi_iefd_cux6_rad. */ struct ipu3_uapi_iefd_cux2 { __u32 x0:9; __u32 x1:9; __u32 a01:9; __u32 b01:5; } __attribute__((packed)); /** * struct ipu3_uapi_iefd_cux6_ed - Calculate power of non-directed sharpening * element, Config Unit 6 for edge detail (ED). * * @x0: X coordinate of point 0, u9.0, default 0. * @x1: X coordinate of point 1, u9.0, default 0. * @x2: X coordinate of point 2, u9.0, default 0. * @reserved0: reserved * @x3: X coordinate of point 3, u9.0, default 0. * @x4: X coordinate of point 4, u9.0, default 0. * @x5: X coordinate of point 5, u9.0, default 0. * @reserved1: reserved * @a01: slope A points 01, s4.4, default 0. * @a12: slope A points 12, s4.4, default 0. * @a23: slope A points 23, s4.4, default 0. * @reserved2: reserved * @a34: slope A points 34, s4.4, default 0. * @a45: slope A points 45, s4.4, default 0. * @reserved3: reserved * @b01: slope B points 01, s4.4, default 0. * @b12: slope B points 12, s4.4, default 0. * @b23: slope B points 23, s4.4, default 0. * @reserved4: reserved * @b34: slope B points 34, s4.4, default 0. * @b45: slope B points 45, s4.4, default 0. * @reserved5: reserved. */ struct ipu3_uapi_iefd_cux6_ed { __u32 x0:9; __u32 x1:9; __u32 x2:9; __u32 reserved0:5; __u32 x3:9; __u32 x4:9; __u32 x5:9; __u32 reserved1:5; __u32 a01:9; __u32 a12:9; __u32 a23:9; __u32 reserved2:5; __u32 a34:9; __u32 a45:9; __u32 reserved3:14; __u32 b01:9; __u32 b12:9; __u32 b23:9; __u32 reserved4:5; __u32 b34:9; __u32 b45:9; __u32 reserved5:14; } __attribute__((packed)); /** * struct ipu3_uapi_iefd_cux2_1 - Calculate power of non-directed denoise * element apply. * @x0: X0 point of Config Unit, u9.0, default 0. * @x1: X1 point of Config Unit, u9.0, default 0. * @a01: Slope A of Config Unit, s4.4, default 0. * @reserved1: reserved * @b01: offset B0 of Config Unit, u7.0, default 0. * @reserved2: reserved */ struct ipu3_uapi_iefd_cux2_1 { __u32 x0:9; __u32 x1:9; __u32 a01:9; __u32 reserved1:5; __u32 b01:8; __u32 reserved2:24; } __attribute__((packed)); /** * struct ipu3_uapi_iefd_cux4 - Calculate power of non-directed sharpening * element. * * @x0: X0 point of Config Unit, u9.0, default 0. * @x1: X1 point of Config Unit, u9.0, default 0. * @x2: X2 point of Config Unit, u9.0, default 0. * @reserved0: reserved * @x3: X3 point of Config Unit, u9.0, default 0. * @a01: Slope A0 of Config Unit, s4.4, default 0. * @a12: Slope A1 of Config Unit, s4.4, default 0. * @reserved1: reserved * @a23: Slope A2 of Config Unit, s4.4, default 0. * @b01: Offset B0 of Config Unit, s7.0, default 0. * @b12: Offset B1 of Config Unit, s7.0, default 0. * @reserved2: reserved * @b23: Offset B2 of Config Unit, s7.0, default 0. * @reserved3: reserved */ struct ipu3_uapi_iefd_cux4 { __u32 x0:9; __u32 x1:9; __u32 x2:9; __u32 reserved0:5; __u32 x3:9; __u32 a01:9; __u32 a12:9; __u32 reserved1:5; __u32 a23:9; __u32 b01:8; __u32 b12:8; __u32 reserved2:7; __u32 b23:8; __u32 reserved3:24; } __attribute__((packed)); /** * struct ipu3_uapi_iefd_cux6_rad - Radial Config Unit (CU) * * @x0: x0 points of Config Unit radial, u8.0 * @x1: x1 points of Config Unit radial, u8.0 * @x2: x2 points of Config Unit radial, u8.0 * @x3: x3 points of Config Unit radial, u8.0 * @x4: x4 points of Config Unit radial, u8.0 * @x5: x5 points of Config Unit radial, u8.0 * @reserved1: reserved * @a01: Slope A of Config Unit radial, s7.8 * @a12: Slope A of Config Unit radial, s7.8 * @a23: Slope A of Config Unit radial, s7.8 * @a34: Slope A of Config Unit radial, s7.8 * @a45: Slope A of Config Unit radial, s7.8 * @reserved2: reserved * @b01: Slope B of Config Unit radial, s9.0 * @b12: Slope B of Config Unit radial, s9.0 * @b23: Slope B of Config Unit radial, s9.0 * @reserved4: reserved * @b34: Slope B of Config Unit radial, s9.0 * @b45: Slope B of Config Unit radial, s9.0 * @reserved5: reserved */ struct ipu3_uapi_iefd_cux6_rad { __u32 x0:8; __u32 x1:8; __u32 x2:8; __u32 x3:8; __u32 x4:8; __u32 x5:8; __u32 reserved1:16; __u32 a01:16; __u32 a12:16; __u32 a23:16; __u32 a34:16; __u32 a45:16; __u32 reserved2:16; __u32 b01:10; __u32 b12:10; __u32 b23:10; __u32 reserved4:2; __u32 b34:10; __u32 b45:10; __u32 reserved5:12; } __attribute__((packed)); /** * struct ipu3_uapi_yuvp1_iefd_cfg_units - IEFd Config Units parameters * * @cu_1: calculate weight for blending directed and * non-directed denoise elements. See &ipu3_uapi_iefd_cux2 * @cu_ed: calculate power of non-directed sharpening element, see * &ipu3_uapi_iefd_cux6_ed * @cu_3: calculate weight for blending directed and * non-directed denoise elements. A &ipu3_uapi_iefd_cux2 * @cu_5: calculate power of non-directed denoise element apply, use * &ipu3_uapi_iefd_cux2_1 * @cu_6: calculate power of non-directed sharpening element. See * &ipu3_uapi_iefd_cux4 * @cu_7: calculate weight for blending directed and * non-directed denoise elements. Use &ipu3_uapi_iefd_cux2 * @cu_unsharp: Config Unit of unsharp &ipu3_uapi_iefd_cux4 * @cu_radial: Config Unit of radial &ipu3_uapi_iefd_cux6_rad * @cu_vssnlm: Config Unit of vssnlm &ipu3_uapi_iefd_cux2 */ struct ipu3_uapi_yuvp1_iefd_cfg_units { struct ipu3_uapi_iefd_cux2 cu_1; struct ipu3_uapi_iefd_cux6_ed cu_ed; struct ipu3_uapi_iefd_cux2 cu_3; struct ipu3_uapi_iefd_cux2_1 cu_5; struct ipu3_uapi_iefd_cux4 cu_6; struct ipu3_uapi_iefd_cux2 cu_7; struct ipu3_uapi_iefd_cux4 cu_unsharp; struct ipu3_uapi_iefd_cux6_rad cu_radial; struct ipu3_uapi_iefd_cux2 cu_vssnlm; } __attribute__((packed)); /** * struct ipu3_uapi_yuvp1_iefd_config_s - IEFd config * * @horver_diag_coeff: Gradient compensation. Compared with vertical / * horizontal (0 / 90 degree), coefficient of diagonal (45 / * 135 degree) direction should be corrected by approx. * 1/sqrt(2). * @reserved0: reserved * @clamp_stitch: Slope to stitch between clamped and unclamped edge values * @reserved1: reserved * @direct_metric_update: Update coeff for direction metric * @reserved2: reserved * @ed_horver_diag_coeff: Radial Coefficient that compensates for * different distance for vertical/horizontal and * diagonal gradient calculation (approx. 1/sqrt(2)) * @reserved3: reserved */ struct ipu3_uapi_yuvp1_iefd_config_s { __u32 horver_diag_coeff:7; __u32 reserved0:1; __u32 clamp_stitch:6; __u32 reserved1:2; __u32 direct_metric_update:5; __u32 reserved2:3; __u32 ed_horver_diag_coeff:7; __u32 reserved3:1; } __attribute__((packed)); /** * struct ipu3_uapi_yuvp1_iefd_control - IEFd control * * @iefd_en: Enable IEFd * @denoise_en: Enable denoise * @direct_smooth_en: Enable directional smooth * @rad_en: Enable radial update * @vssnlm_en: Enable VSSNLM output filter * @reserved: reserved */ struct ipu3_uapi_yuvp1_iefd_control { __u32 iefd_en:1; __u32 denoise_en:1; __u32 direct_smooth_en:1; __u32 rad_en:1; __u32 vssnlm_en:1; __u32 reserved:27; } __attribute__((packed)); /** * struct ipu3_uapi_sharp_cfg - Sharpening config * * @nega_lmt_txt: Sharpening limit for negative overshoots for texture. * @reserved0: reserved * @posi_lmt_txt: Sharpening limit for positive overshoots for texture. * @reserved1: reserved * @nega_lmt_dir: Sharpening limit for negative overshoots for direction (edge). * @reserved2: reserved * @posi_lmt_dir: Sharpening limit for positive overshoots for direction (edge). * @reserved3: reserved * * Fixed point type u13.0, range [0, 8191]. */ struct ipu3_uapi_sharp_cfg { __u32 nega_lmt_txt:13; __u32 reserved0:19; __u32 posi_lmt_txt:13; __u32 reserved1:19; __u32 nega_lmt_dir:13; __u32 reserved2:19; __u32 posi_lmt_dir:13; __u32 reserved3:19; } __attribute__((packed)); /** * struct ipu3_uapi_far_w - Sharpening config for far sub-group * * @dir_shrp: Weight of wide direct sharpening, u1.6, range [0, 64], default 64. * @reserved0: reserved * @dir_dns: Weight of wide direct denoising, u1.6, range [0, 64], default 0. * @reserved1: reserved * @ndir_dns_powr: Power of non-direct denoising, * Precision u1.6, range [0, 64], default 64. * @reserved2: reserved */ struct ipu3_uapi_far_w { __u32 dir_shrp:7; __u32 reserved0:1; __u32 dir_dns:7; __u32 reserved1:1; __u32 ndir_dns_powr:7; __u32 reserved2:9; } __attribute__((packed)); /** * struct ipu3_uapi_unsharp_cfg - Unsharp config * * @unsharp_weight: Unsharp mask blending weight. * u1.6, range [0, 64], default 16. * 0 - disabled, 64 - use only unsharp. * @reserved0: reserved * @unsharp_amount: Unsharp mask amount, u4.5, range [0, 511], default 0. * @reserved1: reserved */ struct ipu3_uapi_unsharp_cfg { __u32 unsharp_weight:7; __u32 reserved0:1; __u32 unsharp_amount:9; __u32 reserved1:15; } __attribute__((packed)); /** * struct ipu3_uapi_yuvp1_iefd_shrp_cfg - IEFd sharpness config * * @cfg: sharpness config &ipu3_uapi_sharp_cfg * @far_w: wide range config, value as specified by &ipu3_uapi_far_w: * The 5x5 environment is separated into 2 sub-groups, the 3x3 nearest * neighbors (8 pixels called Near), and the second order neighborhood * around them (16 pixels called Far). * @unshrp_cfg: unsharpness config. &ipu3_uapi_unsharp_cfg */ struct ipu3_uapi_yuvp1_iefd_shrp_cfg { struct ipu3_uapi_sharp_cfg cfg; struct ipu3_uapi_far_w far_w; struct ipu3_uapi_unsharp_cfg unshrp_cfg; } __attribute__((packed)); /** * struct ipu3_uapi_unsharp_coef0 - Unsharp mask coefficients * * @c00: Coeff11, s0.8, range [-255, 255], default 1. * @c01: Coeff12, s0.8, range [-255, 255], default 5. * @c02: Coeff13, s0.8, range [-255, 255], default 9. * @reserved: reserved * * Configurable registers for common sharpening support. */ struct ipu3_uapi_unsharp_coef0 { __u32 c00:9; __u32 c01:9; __u32 c02:9; __u32 reserved:5; } __attribute__((packed)); /** * struct ipu3_uapi_unsharp_coef1 - Unsharp mask coefficients * * @c11: Coeff22, s0.8, range [-255, 255], default 29. * @c12: Coeff23, s0.8, range [-255, 255], default 55. * @c22: Coeff33, s0.8, range [-255, 255], default 96. * @reserved: reserved */ struct ipu3_uapi_unsharp_coef1 { __u32 c11:9; __u32 c12:9; __u32 c22:9; __u32 reserved:5; } __attribute__((packed)); /** * struct ipu3_uapi_yuvp1_iefd_unshrp_cfg - Unsharp mask config * * @unsharp_coef0: unsharp coefficient 0 config. See &ipu3_uapi_unsharp_coef0 * @unsharp_coef1: unsharp coefficient 1 config. See &ipu3_uapi_unsharp_coef1 */ struct ipu3_uapi_yuvp1_iefd_unshrp_cfg { struct ipu3_uapi_unsharp_coef0 unsharp_coef0; struct ipu3_uapi_unsharp_coef1 unsharp_coef1; } __attribute__((packed)); /** * struct ipu3_uapi_radial_reset_xy - Radial coordinate reset * * @x: Radial reset of x coordinate. Precision s12, [-4095, 4095], default 0. * @reserved0: reserved * @y: Radial center y coordinate. Precision s12, [-4095, 4095], default 0. * @reserved1: reserved */ struct ipu3_uapi_radial_reset_xy { __s32 x:13; __u32 reserved0:3; __s32 y:13; __u32 reserved1:3; } __attribute__((packed)); /** * struct ipu3_uapi_radial_reset_x2 - Radial X^2 reset * * @x2: Radial reset of x^2 coordinate. Precision u24, default 0. * @reserved: reserved */ struct ipu3_uapi_radial_reset_x2 { __u32 x2:24; __u32 reserved:8; } __attribute__((packed)); /** * struct ipu3_uapi_radial_reset_y2 - Radial Y^2 reset * * @y2: Radial reset of y^2 coordinate. Precision u24, default 0. * @reserved: reserved */ struct ipu3_uapi_radial_reset_y2 { __u32 y2:24; __u32 reserved:8; } __attribute__((packed)); /** * struct ipu3_uapi_radial_cfg - Radial config * * @rad_nf: Radial. R^2 normalization factor is scale down by 2^ - (15 + scale) * @reserved0: reserved * @rad_inv_r2: Radial R^-2 normelized to (0.5..1). * Precision u7, range [0, 127]. * @reserved1: reserved */ struct ipu3_uapi_radial_cfg { __u32 rad_nf:4; __u32 reserved0:4; __u32 rad_inv_r2:7; __u32 reserved1:17; } __attribute__((packed)); /** * struct ipu3_uapi_rad_far_w - Radial FAR sub-group * * @rad_dir_far_sharp_w: Weight of wide direct sharpening, u1.6, range [0, 64], * default 64. * @rad_dir_far_dns_w: Weight of wide direct denoising, u1.6, range [0, 64], * default 0. * @rad_ndir_far_dns_power: power of non-direct sharpening, u1.6, range [0, 64], * default 0. * @reserved: reserved */ struct ipu3_uapi_rad_far_w { __u32 rad_dir_far_sharp_w:8; __u32 rad_dir_far_dns_w:8; __u32 rad_ndir_far_dns_power:8; __u32 reserved:8; } __attribute__((packed)); /** * struct ipu3_uapi_cu_cfg0 - Radius Config Unit cfg0 register * * @cu6_pow: Power of CU6. Power of non-direct sharpening, u3.4. * @reserved0: reserved * @cu_unsharp_pow: Power of unsharp mask, u2.4. * @reserved1: reserved * @rad_cu6_pow: Radial/corner CU6. Directed sharpening power, u3.4. * @reserved2: reserved * @rad_cu_unsharp_pow: Radial power of unsharp mask, u2.4. * @reserved3: reserved */ struct ipu3_uapi_cu_cfg0 { __u32 cu6_pow:7; __u32 reserved0:1; __u32 cu_unsharp_pow:7; __u32 reserved1:1;