Illustrated C/C++ source sheets, symbol index, API relationship graph, compiler console and debug trace

LIVE AI / FLEXIBLE SENSING / FLIGHT CONTEXT

Sensoraia API

Live AI and sensing, connected to the flight.
See, listen, inspect and return supported results while airborne.

Loading...
Searching...
No Matches
lwir_frame.c
Go to the documentation of this file.
1/*
2 * Copyright 2026 OpenUAS
3 * SPDX-License-Identifier: Apache-2.0
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18/** @file
19 * @brief Frame geometry, structural/live qualification and native temperature measurements.
20 * @details Operates on borrowed Tiny1-C combined frames: YUYV image plane (`Y0 U Y1 V` per
21 * pixel pair) followed by a thermal plane of little-endian uint16 Kelvin*64 codes, where
22 * 0 and 65535 are endpoint/invalid codes. Everything is in native, unrotated coordinates;
23 * display orientation and correction profiles (lwir_render.c) never affect these results.
24 *
25 * Pipeline role: capture calls lwir_frame_capture_valid() to drop camera transition fill
26 * and frames without temperatures; lwir_frame_plausible()/lwir_frame_settled() are optional
27 * heuristics; lwir_measure_temperature() serves point, line and rectangle requests.
28 *
29 * The scalar measurement code is the reference. On little-endian ARM64 NEON handles
30 * eight-pixel rectangle blocks with identical results: exact rounded integer averages,
31 * first-occurrence extrema and the same coverage counts (parity-tested). No heap is used.
32 */
33#include "lwir_frame.h"
34#include "exifite.h"
35#include "lwir_render.h"
36
37#include <errno.h>
38#include <fcntl.h>
39#include <limits.h>
40#include <setjmp.h>
41#include <stdio.h>
42#include <stdlib.h>
43#include <string.h>
44#include <unistd.h>
45
46#if defined(__aarch64__) && defined(__AARCH64EL__) && !defined(LWIR_DISABLE_NEON)
47#include <arm_neon.h>
48#endif
49
50/**
51 * @brief Combined frame size for supported geometry.
52 * @details Two planes of 2 bytes per pixel. Width must be even because YUYV stores pixel pairs.
53 * @return width * height * 4, or 0 for unsupported geometry (also the geometry check used
54 * throughout this module).
55 */
56size_t lwir_frame_bytes(unsigned width, unsigned height)
57{
58 if (width < 2 || width > LWIR_MAX_WIDTH || width % 2 != 0 ||
59 height == 0 || height > LWIR_MAX_HEIGHT) {
60 return 0;
61 }
62 return (size_t)width * height * 4;
63}
64
65/**
66 * @brief Check that a non-empty rectangle lies entirely inside the image.
67 * @return True when every sample is in bounds.
68 * @note Extents are compared as `width <= image_width - x` so `x + width` cannot wrap.
69 */
70bool lwir_roi_valid(unsigned width, unsigned height, const struct lwir_roi *roi)
71{
72 return lwir_frame_bytes(width, height) != 0 && roi != NULL &&
73 roi->width != 0 && roi->height != 0 && roi->x < width && roi->y < height &&
74 roi->width <= width - roi->x && roi->height <= height - roi->y;
75}
76
77/**
78 * @brief Validate a measurement request against native geometry.
79 * @details Rectangles must be in bounds, or entirely zero to mean the full image (a zero
80 * width with any other non-zero field is rejected as ambiguous). Points need an in-bounds
81 * start; lines need in-bounds start and end.
82 * @return True when the request can be measured.
83 */
84bool lwir_measurement_valid(unsigned width, unsigned height, const struct lwir_measurement *measurement)
85{
86 if (!measurement || !lwir_frame_bytes(width, height)) return false;
87 if (measurement->kind == LWIR_RECTANGLE) {
88 if (!measurement->roi.width) return !measurement->roi.x && !measurement->roi.y && !measurement->roi.height;
89 return lwir_roi_valid(width, height, &measurement->roi);
90 }
91 if (measurement->kind != LWIR_POINT && measurement->kind != LWIR_LINE) return false;
92 return measurement->roi.x < width && measurement->roi.y < height &&
93 (measurement->kind == LWIR_POINT || (measurement->end_x < width && measurement->end_y < height));
94}
95
96/**
97 * @brief Read one little-endian thermal code.
98 * @param plane Thermal plane start.
99 * @param width Native width.
100 * @param column Native column (caller-checked).
101 * @param row Native row (caller-checked).
102 * @return Raw Kelvin*64 code, including endpoint codes.
103 */
104static uint16_t thermal_sample(const uint8_t *plane, unsigned width, unsigned column, unsigned row)
105{
106 const size_t offset = ((size_t)row * width + column) * 2;
107 return (uint16_t)plane[offset] | (uint16_t)plane[offset + 1] << 8;
108}
109
110/**
111 * @brief Measured value of one center, optionally 3x3-averaged.
112 * @details Averages the valid (non-endpoint) codes of the 3x3 neighbourhood clipped at
113 * the sensor edges, rounded half up: `(sum + n/2) / n`. The valid center guarantees n >= 1.
114 * @param plane Thermal plane start.
115 * @param width Native width.
116 * @param height Native height.
117 * @param column Center column.
118 * @param row Center row.
119 * @param average Whether averaging is requested.
120 * @param center The center's raw code.
121 * @return center unchanged when not averaging or when it is an endpoint code; otherwise
122 * the rounded mean, which stays within 1..65534.
123 */
124static uint16_t measurement_sample(const uint8_t *plane, unsigned width, unsigned height,
125 unsigned column, unsigned row, bool average, uint16_t center)
126{
127 if (!average || !center || center == UINT16_MAX) return center;
128 const unsigned left = column ? column - 1 : 0, top = row ? row - 1 : 0;
129 const unsigned right = column + 1 < width ? column + 1 : column;
130 const unsigned bottom = row + 1 < height ? row + 1 : row;
131 uint32_t sum = 0; unsigned samples = 0;
132 /* Clip the 3x3 neighbourhood to the sensor; never synthesize invalid centers. */
133 for (unsigned neighbour_y = top; neighbour_y <= bottom; ++neighbour_y) {
134 for (unsigned neighbour_x = left; neighbour_x <= right; ++neighbour_x) {
135 const uint16_t raw = thermal_sample(plane, width, neighbour_x, neighbour_y);
136 if (raw && raw != UINT16_MAX) { sum += raw; ++samples; }
137 }
138 }
139 return (uint16_t)((sum + samples / 2) / samples);
140}
141
142/**
143 * @brief Add one measured sample to running statistics.
144 * @details Strict comparisons keep the first visited extremum, matching the NEON path.
145 * Sums and extrema include endpoint codes; coverage counts exclude them and use the
146 * ORIGINAL center, so averaging cannot move a pixel between coverage bins.
147 * @param result Statistics being accumulated.
148 * @param raw Measured sample (possibly averaged).
149 * @param column Native column, recorded for extrema.
150 * @param row Native row, recorded for extrema.
151 * @param thresholds Optional coverage band.
152 * @param center Original center code used for coverage.
153 * @note Endpoint status of raw and center always agree, because measurement_sample()
154 * returns endpoint centers unchanged and never averages to an endpoint code.
155 */
156static void accumulate_temperature(struct lwir_temperature_stats *result, uint16_t raw, unsigned column,
157 unsigned row, const struct lwir_thresholds *thresholds, uint16_t center)
158{
159 if (!result->pixels || raw < result->min_raw) {
160 result->min_raw = raw; result->min_x = column; result->min_y = row;
161 }
162 if (!result->pixels || raw > result->max_raw) {
163 result->max_raw = raw; result->max_x = column; result->max_y = row;
164 }
165 result->sum_raw += raw;
166 result->sum_squared_raw += (uint64_t)raw * raw;
167 const bool endpoint = !raw || raw == UINT16_MAX;
168 result->endpoint_codes += endpoint;
169 ++result->pixels;
170 /* Integer comparisons reuse this pass; display/profile/denoise never affect coverage. */
171 if (thresholds && thresholds->enabled && !endpoint) {
172 result->below += center < thresholds->low;
173 result->above += center > thresholds->high;
174 result->within += center >= thresholds->low && center <= thresholds->high;
175 }
176}
177
178#if defined(__aarch64__) && defined(__AARCH64EL__) && !defined(LWIR_DISABLE_NEON)
179/**
180 * @brief Load eight consecutive thermal codes of one row.
181 * @details VLD2 splits low/high bytes; widening and `low | high << 8` rebuilds the
182 * little-endian codes.
183 * @param plane Thermal plane start.
184 * @param width Native width.
185 * @param column First column; column + 7 must be in the row.
186 * @param row Native row.
187 * @return Raw codes for columns column..column+7.
188 */
189static uint16x8_t thermal_block(const uint8_t *plane, unsigned width, unsigned column, unsigned row)
190{
191 const uint8x8x2_t bytes = vld2_u8(plane + ((size_t)row * width + column) * 2);
192 return vorrq_u16(vmovl_u8(bytes.val[0]), vshlq_n_u16(vmovl_u8(bytes.val[1]), 8));
193}
194
195/**
196 * @brief Lane mask of valid (non-endpoint) codes.
197 * @param raw Eight raw codes.
198 * @return 0xFFFF where 0 < code < 65535, else 0.
199 */
200static uint16x8_t valid_block(uint16x8_t raw)
201{
202 return vandq_u16(vcgtq_u16(raw, vdupq_n_u16(0)), vcltq_u16(raw, vdupq_n_u16(UINT16_MAX)));
203}
204
205/**
206 * @brief Lane index of the first lane equal to value.
207 * @details The 0xFFFF/0 compare mask is viewed as two 64-bit halves; the count of trailing
208 * zero bits divided by 16 is the lane index within a half, so the lowest (first-in-raster)
209 * matching lane wins, as in the scalar path.
210 * @param samples Eight samples.
211 * @param value A value known to occur in samples (a vminv/vmaxv result).
212 * @return Lane 0..7.
213 * @warning ctz of zero is undefined; callers must guarantee a match exists.
214 */
215static unsigned first_equal(uint16x8_t samples, uint16_t value)
216{
217 const uint16x8_t equal = vceqq_u16(samples, vdupq_n_u16(value));
218 const uint64_t low = vget_lane_u64(vreinterpret_u64_u16(vget_low_u16(equal)), 0);
219 const uint64_t high = vget_lane_u64(vreinterpret_u64_u16(vget_high_u16(equal)), 0);
220 return low ? (unsigned)__builtin_ctzll(low) / 16 : 4U + (unsigned)__builtin_ctzll(high) / 16;
221}
222
223/**
224 * @brief Add eight measured samples to running statistics, matching accumulate_temperature().
225 * @details Horizontal min/max with first_equal() preserve first-occurrence coordinates;
226 * strict comparisons keep earlier blocks on ties. Squares use widening u16 x u16 -> u32
227 * multiplies (65535^2 fits u32) summed into u64. Coverage uses the original centers.
228 * @param result Statistics being accumulated.
229 * @param samples Measured samples (raw or averaged).
230 * @param centers Original center codes.
231 * @param column Native column of lane 0.
232 * @param row Native row.
233 * @param thresholds Optional coverage band.
234 */
235static void accumulate_block(struct lwir_temperature_stats *result, uint16x8_t samples, uint16x8_t centers,
236 unsigned column, unsigned row, const struct lwir_thresholds *thresholds)
237{
238 const uint16_t minimum = vminvq_u16(samples), maximum = vmaxvq_u16(samples);
239 if (!result->pixels || minimum < result->min_raw) {
240 result->min_raw = minimum; result->min_x = column + first_equal(samples, minimum); result->min_y = row;
241 }
242 if (!result->pixels || maximum > result->max_raw) {
243 result->max_raw = maximum; result->max_x = column + first_equal(samples, maximum); result->max_y = row;
244 }
245 result->sum_raw += vaddlvq_u16(samples);
246 result->sum_squared_raw += vaddlvq_u32(vmull_u16(vget_low_u16(samples), vget_low_u16(samples)));
247 result->sum_squared_raw += vaddlvq_u32(vmull_u16(vget_high_u16(samples), vget_high_u16(samples)));
248 const uint16x8_t valid = valid_block(centers);
249 /* 0xFFFF lanes >> 15 become 1, so a horizontal add counts true lanes. */
250 const unsigned valid_count = vaddlvq_u16(vshrq_n_u16(valid, 15));
251 result->pixels += 8; result->endpoint_codes += 8 - valid_count;
252 if (thresholds && thresholds->enabled) {
253 const unsigned below = vaddlvq_u16(vshrq_n_u16(vandq_u16(valid, vcltq_u16(centers, vdupq_n_u16(thresholds->low))), 15));
254 const unsigned above = vaddlvq_u16(vshrq_n_u16(vandq_u16(valid, vcgtq_u16(centers, vdupq_n_u16(thresholds->high))), 15));
255 result->below += below; result->above += above; result->within += valid_count - below - above;
256 }
257}
258
259/**
260 * @brief Exact per-lane `floor(numerator / denominator)` without integer vector division.
261 * @details 1. Estimate q = trunc(float(n) / float(d)); n < 2^24 converts exactly and the
262 * correctly rounded division can only land q one unit away from the true floor.
263 * 2. If q * d > n, subtract 1. 3. If (q + 1) * d <= n, add 1. Compare masks >> 31 give
264 * 0 or 1. Products stay far below 2^32 for these ranges.
265 * @param numerator Rounded sums, at most 589810 (nine 65534 codes plus count/2).
266 * @param denominator Valid-sample counts 1..9.
267 * @return Exact floor quotients.
268 */
269static uint32x4_t exact_block_divide(uint32x4_t numerator, uint32x4_t denominator)
270{
271 /* These integers are <=589810. Float estimates can miss by at most one;
272 * integer product checks restore the EXACT floor quotient, including boundaries. */
273 uint32x4_t quotient = vcvtq_u32_f32(vdivq_f32(vcvtq_f32_u32(numerator), vcvtq_f32_u32(denominator)));
274 quotient = vsubq_u32(quotient, vshrq_n_u32(vcgtq_u32(vmulq_u32(quotient, denominator), numerator), 31));
275 const uint32x4_t next = vaddq_u32(quotient, vdupq_n_u32(1));
276 return vaddq_u32(quotient, vshrq_n_u32(vcleq_u32(vmulq_u32(next, denominator), numerator), 31));
277}
278
279/**
280 * @brief 3x3 valid-sample average for eight consecutive interior centers.
281 * @details Each of the (up to) 3x3 shifted eight-lane loads supplies one neighbour per
282 * lane. Endpoint codes are masked to zero and not counted; rows are clipped at the top and
283 * bottom edges. Adding count/2 before exact_block_divide() reproduces the scalar
284 * round-half-up mean. Lanes whose center is an endpoint code keep the center unchanged
285 * (their count may be zero, hence the max(count, 1) guard).
286 * @param plane Thermal plane start.
287 * @param width Native width.
288 * @param height Native height.
289 * @param column Column of lane 0; requires column >= 1 and column + 8 < width.
290 * @param row Native row.
291 * @param centers Original codes at column..column+7.
292 * @return Averaged samples, identical to measurement_sample() per lane.
293 */
294static uint16x8_t average_block(const uint8_t *plane, unsigned width, unsigned height, unsigned column, unsigned row, uint16x8_t centers)
295{
296 uint32x4_t low_sum = vdupq_n_u32(0), high_sum = low_sum;
297 uint16x8_t count = vdupq_n_u16(0);
298 const unsigned top = row ? row - 1 : 0, bottom = row + 1 < height ? row + 1 : row;
299 /* Caller reserves one real neighbor column on each side; borders use scalar clipping. */
300 for (unsigned vertical = top; vertical <= bottom; ++vertical) {
301 for (unsigned horizontal = column - 1; horizontal <= column + 1; ++horizontal) {
302 const uint16x8_t samples = thermal_block(plane, width, horizontal, vertical), valid = valid_block(samples);
303 const uint16x8_t accepted = vandq_u16(samples, valid);
304 low_sum = vaddw_u16(low_sum, vget_low_u16(accepted)); high_sum = vaddw_u16(high_sum, vget_high_u16(accepted));
305 count = vaddq_u16(count, vshrq_n_u16(valid, 15));
306 }
307 }
308 const uint16x8_t safe_count = vmaxq_u16(count, vdupq_n_u16(1));
309 low_sum = vaddw_u16(low_sum, vget_low_u16(vshrq_n_u16(count, 1)));
310 high_sum = vaddw_u16(high_sum, vget_high_u16(vshrq_n_u16(count, 1)));
311 const uint16x8_t averaged = vcombine_u16(vmovn_u32(exact_block_divide(low_sum, vmovl_u16(vget_low_u16(safe_count)))),
312 vmovn_u32(exact_block_divide(high_sum, vmovl_u16(vget_high_u16(safe_count)))));
313 return vbslq_u16(valid_block(centers), averaged, centers);
314}
315#endif
316
317/**
318 * @brief Measure a point, line or rectangle in native coordinates.
319 * @details Lines use integer Bresenham traversal of every center from start to end
320 * inclusive. Rectangles are visited in raster order; on ARM64 NEON handles eight-center
321 * blocks and scalar code handles the first column (when averaging), the right border and
322 * the tail. Results are built in a local copy and published only on success.
323 * @return False for NULL pointers, invalid request/geometry, size mismatch or an empty
324 * threshold band; errno is not set.
325 */
326bool lwir_measure_temperature(const uint8_t *frame, size_t bytes, unsigned width, unsigned height,
327 const struct lwir_measurement *measurement, const struct lwir_thresholds *thresholds,
328 struct lwir_temperature_stats *statistics)
329{
330 if (!frame || !statistics || !lwir_measurement_valid(width, height, measurement) ||
331 bytes != lwir_frame_bytes(width, height) ||
332 (thresholds && thresholds->enabled && thresholds->low >= thresholds->high)) return false;
333 struct lwir_temperature_stats result = {0};
334 const uint8_t *plane = frame + bytes / 2;
335 if (measurement->kind == LWIR_LINE) {
336 int column = (int)measurement->roi.x, row = (int)measurement->roi.y;
337 const int end_x = (int)measurement->end_x, end_y = (int)measurement->end_y;
338 /* All-octant error form: delta_x = |dx| and delta_y = -|dy| (deliberately negative),
339 * error = delta_x + delta_y tracks the signed distance from the ideal line. */
340 const int delta_x = end_x > column ? end_x - column : column - end_x;
341 const int delta_y = end_y > row ? row - end_y : end_y - row;
342 const int step_x = column < end_x ? 1 : -1, step_y = row < end_y ? 1 : -1;
343 int error = delta_x + delta_y;
344 /* Inclusive Bresenham traversal: max(|dx|,|dy|)+1 centers (<=640), no allocations
345 * or float geometry. */
346 for (;;) {
347 const uint16_t center = thermal_sample(plane, width, (unsigned)column, (unsigned)row);
348 const uint16_t raw = measurement_sample(plane, width, height, (unsigned)column, (unsigned)row, measurement->average_3x3, center);
349 accumulate_temperature(&result, raw, (unsigned)column, (unsigned)row, thresholds, center);
350 if (column == end_x && row == end_y) break;
351 /* Doubling avoids the half-pixel midpoint. Stepping x when 2e >= dy and y when
352 * 2e <= dx; both may fire, giving a diagonal step. */
353 const int twice = error * 2;
354 if (twice >= delta_y) { error += delta_y; column += step_x; }
355 if (twice <= delta_x) { error += delta_x; row += step_y; }
356 }
357 } else {
358 struct lwir_roi region = measurement->roi;
359 if (measurement->kind == LWIR_POINT) { region.width = 1; region.height = 1; }
360 else if (!region.width) { region.width = width; region.height = height; }
361 for (unsigned row = region.y; row < region.y + region.height; ++row) {
362 unsigned column = region.x;
363#if defined(__aarch64__) && defined(__AARCH64EL__) && !defined(LWIR_DISABLE_NEON)
364 /* Eight native centers per block, no staging frame. Scalar borders/tails
365 * preserve clipped neighborhoods and the identical raw-coordinate contract. */
366 /* Column 0 has no left neighbour for the shifted loads, so it goes scalar. */
367 if (measurement->average_3x3 && !column) {
368 const uint16_t center = thermal_sample(plane, width, column, row);
369 accumulate_temperature(&result, measurement_sample(plane, width, height, column, row, true, center), column, row, thresholds, center);
370 ++column;
371 }
372 /* Averaging needs column + 8 (right neighbour of lane 7) inside the row. */
373 for (; region.x + region.width - column >= 8 && (!measurement->average_3x3 || column + 8 < width); column += 8) {
374 const uint16x8_t centers = thermal_block(plane, width, column, row);
375 const uint16x8_t samples = measurement->average_3x3 ? average_block(plane, width, height, column, row, centers) : centers;
376 accumulate_block(&result, samples, centers, column, row, thresholds);
377 }
378#endif
379 for (; column < region.x + region.width; ++column) {
380 const uint16_t center = thermal_sample(plane, width, column, row);
381 const uint16_t raw = measurement_sample(plane, width, height, column, row, measurement->average_3x3, center);
382 accumulate_temperature(&result, raw, column, row, thresholds, center);
383 }
384 }
385 }
386 *statistics = result;
387 return true;
388}
389
390/**
391 * @brief Rectangle statistics without averaging or thresholds.
392 * @return False for an invalid roi or any lwir_measure_temperature() failure.
393 */
394bool lwir_temperature_statistics(const uint8_t *frame, size_t bytes, unsigned width, unsigned height,
395 const struct lwir_roi *roi, struct lwir_temperature_stats *statistics)
396{
397 struct lwir_measurement measurement = {0};
398 if (roi) {
399 if (!lwir_roi_valid(width, height, roi)) return false;
400 measurement.roi = *roi;
401 }
402 return lwir_measure_temperature(frame, bytes, width, height, &measurement, NULL, statistics);
403}
404
405/**
406 * @brief Absolute difference of two bytes without signed overflow concerns.
407 * @param first First byte.
408 * @param second Second byte.
409 * @return |first - second|, 0..255.
410 */
411static unsigned byte_difference(uint8_t first, uint8_t second)
412{
413 return first > second ? (unsigned)first - second : (unsigned)second - first;
414}
415
416/**
417 * @brief Structural check: non-NULL, supported geometry, exact combined size.
418 * @return True for a structurally valid combined frame; says nothing about content.
419 */
420bool lwir_frame_valid(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
421{
422 const size_t expected = lwir_frame_bytes(width, height);
423 return frame != NULL && expected != 0 && bytes == expected;
424}
425
426/**
427 * @brief Detect the camera's whole-frame neutral fill.
428 * @details Scans both planes as byte pairs; any pair other than (0x00, 0x80) ends the scan
429 * early, so real frames are usually rejected after a few bytes.
430 * @return True only for a valid frame consisting entirely of fill.
431 */
432bool lwir_frame_is_neutral_fill(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
433{
434 if (!lwir_frame_valid(frame, bytes, width, height)) return false;
435 for (size_t offset = 0; offset < bytes; offset += 2)
436 if (frame[offset] != 0 || frame[offset + 1] != 128) return false;
437 return true;
438}
439
440/**
441 * @brief Live-capture qualification.
442 * @details Rejects structurally invalid frames, neutral fill and frames whose thermal plane
443 * holds only endpoint codes; stops at the first valid code. Uniform real scenes pass.
444 * @return True when the frame carries at least one usable temperature.
445 */
446bool lwir_frame_capture_valid(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
447{
448 if (!lwir_frame_valid(frame, bytes, width, height) || lwir_frame_is_neutral_fill(frame, bytes, width, height)) return false;
449 for (size_t offset = bytes / 2; offset < bytes; offset += 2) {
450 const uint16_t raw = (uint16_t)frame[offset] | (uint16_t)frame[offset + 1] << 8;
451 if (raw && raw != UINT16_MAX) return true;
452 }
453 return false;
454}
455
456/**
457 * @brief Conservative scene-plausibility heuristic.
458 * @details
459 * 1. Chroma: every odd image byte is U or V; more than 1% outside 128 +/- 8 fails.
460 * 2. Roughness: sum of |Y(x) - Y(x+1)| must average at most 45 per adjacent pair.
461 * 3. Temperature: every eighth thermal sample; more than 10% outside raw 14000..40000
462 * (about -54..352 degC, endpoint codes included) fails.
463 * @return True when all checks pass. Unusual but genuine scenes may fail.
464 */
465bool lwir_frame_plausible(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
466{
467 if (!lwir_frame_valid(frame, bytes, width, height)) return false;
468 const size_t pixels = (size_t)width * height;
469 size_t invalid_chroma = 0;
470 uint64_t roughness = 0;
471 for (size_t row = 0; row < height; ++row) {
472 for (size_t column = 0; column < width; ++column) {
473 const size_t offset = (row * width + column) * 2;
474 /* offset + 1 alternates U and V; offset + 2 is the next pixel's Y. */
475 invalid_chroma += frame[offset + 1] < 120 || frame[offset + 1] > 136;
476 if (column + 1 < width) roughness += byte_difference(frame[offset], frame[offset + 2]);
477 }
478 }
479 if (invalid_chroma * 100 > pixels || roughness > (uint64_t)height * (width - 1) * 45) return false;
480 size_t invalid_temperatures = 0;
481 size_t samples = 0;
482 /* Every eighth pixel bounds cost; the 10% tolerance admits some out-of-band samples. */
483 for (size_t pixel = 0; pixel < pixels; pixel += 8) {
484 const size_t offset = pixels * 2 + pixel * 2;
485 const uint16_t temperature = (uint16_t)frame[offset] | (uint16_t)frame[offset + 1] << 8;
486 invalid_temperatures += temperature < 14000 || temperature > 40000;
487 ++samples;
488 }
489 return invalid_temperatures * 10 <= samples;
490}
491
492/**
493 * @brief Image-stability heuristic between consecutive frames.
494 * @details Sums absolute luma differences (even image bytes only) and accepts a mean of
495 * at most 12 per pixel. Chroma and thermal data are ignored.
496 * @return True when settled; false for NULL inputs or unsupported geometry.
497 */
498bool lwir_frame_settled(const uint8_t *frame, const uint8_t *previous_image,
499 unsigned width, unsigned height)
500{
501 if (frame == NULL || previous_image == NULL || lwir_frame_bytes(width, height) == 0) return false;
502 uint64_t change = 0;
503 const size_t pixels = (size_t)width * height;
504 for (size_t pixel = 0; pixel < pixels; ++pixel) {
505 change += byte_difference(frame[pixel * 2], previous_image[pixel * 2]);
506 }
507 return change <= pixels * 12;
508}
509
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
struct latest_measurement measurement
static struct ear_sample samples[EAR_MAX_SAMPLES]
Bounded C11 EXIF metadata and JPEG streaming interfaces.
bool lwir_frame_is_neutral_fill(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
Detect the camera's whole-frame neutral fill.
Definition lwir_frame.c:432
static uint16_t measurement_sample(const uint8_t *plane, unsigned width, unsigned height, unsigned column, unsigned row, bool average, uint16_t center)
Measured value of one center, optionally 3x3-averaged.
Definition lwir_frame.c:124
bool lwir_measurement_valid(unsigned width, unsigned height, const struct lwir_measurement *measurement)
Validate a measurement request against native geometry.
Definition lwir_frame.c:84
bool lwir_measure_temperature(const uint8_t *frame, size_t bytes, unsigned width, unsigned height, const struct lwir_measurement *measurement, const struct lwir_thresholds *thresholds, struct lwir_temperature_stats *statistics)
Measure a point, line or rectangle in native coordinates.
Definition lwir_frame.c:326
bool lwir_frame_valid(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
Structural check: non-NULL, supported geometry, exact combined size.
Definition lwir_frame.c:420
static uint16_t thermal_sample(const uint8_t *plane, unsigned width, unsigned column, unsigned row)
Read one little-endian thermal code.
Definition lwir_frame.c:104
static void accumulate_temperature(struct lwir_temperature_stats *result, uint16_t raw, unsigned column, unsigned row, const struct lwir_thresholds *thresholds, uint16_t center)
Add one measured sample to running statistics.
Definition lwir_frame.c:156
bool lwir_frame_capture_valid(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
Live-capture qualification.
Definition lwir_frame.c:446
bool lwir_frame_plausible(const uint8_t *frame, size_t bytes, unsigned width, unsigned height)
Conservative scene-plausibility heuristic.
Definition lwir_frame.c:465
bool lwir_roi_valid(unsigned width, unsigned height, const struct lwir_roi *roi)
Check that a non-empty rectangle lies entirely inside the image.
Definition lwir_frame.c:70
bool lwir_temperature_statistics(const uint8_t *frame, size_t bytes, unsigned width, unsigned height, const struct lwir_roi *roi, struct lwir_temperature_stats *statistics)
Rectangle statistics without averaging or thresholds.
Definition lwir_frame.c:394
size_t lwir_frame_bytes(unsigned width, unsigned height)
Combined frame size for supported geometry.
Definition lwir_frame.c:56
static unsigned byte_difference(uint8_t first, uint8_t second)
Absolute difference of two bytes without signed overflow concerns.
Definition lwir_frame.c:411
bool lwir_frame_settled(const uint8_t *frame, const uint8_t *previous_image, unsigned width, unsigned height)
Image-stability heuristic between consecutive frames.
Definition lwir_frame.c:498
Native frame arithmetic and camera measurements; no codec or flight dependencies.
#define LWIR_MAX_WIDTH
Largest supported native width in pixels.
Definition lwir_frame.h:47
@ LWIR_POINT
Definition lwir_frame.h:71
@ LWIR_LINE
Definition lwir_frame.h:72
@ LWIR_RECTANGLE
Definition lwir_frame.h:70
#define LWIR_MAX_HEIGHT
Largest supported native height in pixels.
Definition lwir_frame.h:49
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
struct jpeg_error_mgr error
Definition lwir_image.c:60
uint8_t frame[LWIR_MAX_FRAME_BYTES]
Definition lwir_mock.c:58
static uint16_t temperature(const uint8_t *frame, size_t pixels, size_t pixel)
Read one little-endian thermal code.
Definition lwir_render.c:63
Display rendering of Tiny1-C frames into JPEG-ready Y/Cb/Cr scanlines.
static size_t count
Definition pose_log.c:79
static uint64_t accepted
Definition pose_log.c:81
One native-coordinate measurement request.
Definition lwir_frame.h:76
struct lwir_roi roi
Definition lwir_frame.h:79
Native rectangle; a zero width/height pair selects the full image.
Definition lwir_frame.h:61
unsigned y
Definition lwir_frame.h:63
unsigned width
Definition lwir_frame.h:64
unsigned height
Definition lwir_frame.h:65
unsigned x
Definition lwir_frame.h:62
Raw-unit measurement results; derive mean/variance from the sums and pixels.
Definition lwir_frame.h:98
Optional coverage band counted alongside measurement statistics.
Definition lwir_frame.h:89
uint16_t high
Definition lwir_frame.h:92
bool valid
Definition usher.c:537
struct usher_control_result result
Definition usher.c:377