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
image_mock_transform.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/**
19 * @file image_mock_transform.c
20 * @brief Deterministic attitude-based JPEG transform used by local USHER simulation. */
22
23#include <errno.h>
24#include <fcntl.h>
25#include <limits.h>
26#include <math.h>
27#include <pthread.h>
28#include <setjmp.h>
29#include <stdbool.h>
30#include <stdint.h>
31#include <stdio.h>
32#include <stdlib.h>
33#include <string.h>
34#include <sys/stat.h>
35#include <unistd.h>
36
37#include <jpeglib.h>
38#include "jpeg_marker_guard.h"
39
40#define ANGLE_BFP_SCALE 4096.0
41#define SPEED_BFP_SCALE 524288.0
42#define POSITION_BFP_SCALE 256.0
43#define RAD_TO_DEG 57.29577951308232
44#define JPEG_COMPONENTS 3U
45#define JPEG_QUALITY 95
46#define FOCAL_LENGTH_FACTOR 0.9
47#define PROJECTION_EPSILON 1e-9
48#define PROJECTION_MIN_DEPTH 1e-4
49#define PROJECTION_FOV_SAMPLES 192
50#define PROJECTION_REFINE_STEPS 48
51#define PROJECTION_MIN_RAY_SCALE 1e-4
52#define COVER_SAFETY_FACTOR 0.999
53#define IMAGE_MOCK_MAX_DIMENSION 8192U
54#define IMAGE_MOCK_MAX_PIXELS (2028U * 1520U)
55#define IMAGE_MOCK_RGB_CAPACITY ((size_t)IMAGE_MOCK_MAX_PIXELS * JPEG_COMPONENTS)
56#define MAP_TILE_SIZE 256U
57#define MAP_MOSAIC_DIMENSION (3U * MAP_TILE_SIZE)
58#define MAP_MOSAIC_CAPACITY ((size_t)MAP_MOSAIC_DIMENSION * MAP_MOSAIC_DIMENSION * JPEG_COMPONENTS)
59
60#ifndef near_horizon_case_black
61 #define near_horizon_case_black 0
62#endif
63
64#ifndef near_horizon_roll_deg
65 #define near_horizon_roll_deg 75.0
66#endif
67
68#ifndef near_horizon_pitch_deg
69 #define near_horizon_pitch_deg 75.0
70#endif
71
72#ifndef near_horizon_combined_tilt_deg
73 #define near_horizon_combined_tilt_deg 70.0
74#endif
75
76#if near_horizon_case_black != 0 && near_horizon_case_black != 1
77 #error "near_horizon_case_black must be 0 or 1"
78#endif
79
81 double ray_scale;
83 double offset_x;
84 double offset_y;
85};
86
88 struct jpeg_error_mgr manager;
89 jmp_buf recovery;
90 void (*emit)(j_common_ptr, int);
91};
92
94 unsigned char *pixels;
95 size_t width;
96 size_t height;
97};
98
103 struct jpeg_decompress_struct decoder;
104 struct jpeg_compress_struct encoder;
107};
108
110static pthread_mutex_t workspace_mutex = PTHREAD_MUTEX_INITIALIZER;
111
112static void transform_jpeg_error_exit(j_common_ptr jpeg_info);
113static bool is_near_horizon(double roll_rad, double pitch_rad);
114static bool dimensions_fit(size_t width, size_t height);
115static int read_jpeg_dimensions(FILE *input, struct decoded_image *image);
116static int decode_jpeg(FILE *input, struct decoded_image *image);
117static int encode_jpeg(FILE *output, const struct decoded_image *image);
118static int transform_pixels(const struct decoded_image *source, struct decoded_image *destination,
119 double roll_rad, double pitch_rad, double yaw_rad,
120 bool synthesize_terrain);
121static void build_rotation(double roll_rad, double pitch_rad, double yaw_rad,
122 double rotation[3][3]);
123static bool project_point(double rotation[3][3], double focal_length,
124 double center_x, double center_y, double ray_scale,
125 double destination_x, double destination_y,
126 double *source_x, double *source_y);
127static bool projection_corners_valid(const struct decoded_image *source,
128 double rotation[3][3], double focal_length,
129 double center_x, double center_y, double ray_scale);
131 double rotation[3][3], double focal_length,
132 double center_x, double center_y, double ray_scale,
133 struct projection_fit *fit);
134static int compute_projection_fit(const struct decoded_image *source,
135 double rotation[3][3], double focal_length,
136 double center_x, double center_y,
137 struct projection_fit *fit);
138static void bilinear_sample_rgb(const struct decoded_image *image, double source_x,
139 double source_y, unsigned char output[JPEG_COMPONENTS]);
140static double mirror_coordinate(double coordinate, size_t extent);
141static int create_black_frame(const char *filename);
142static int replace_image_atomically(const char *filename, const struct decoded_image *image);
143static int image_mock_map_locked(const char *filename, const char *cache_directory,
144 const union dc_shot_union *shot, size_t width, size_t height,
145 double horizontal_fov_deg, double vertical_fov_deg);
146static int image_mock_transform_locked(const char *filename, const union dc_shot_union *shot);
147
148/**
149 * @brief Intersect a camera ray with a local flat ground plane.
150 * @param rotation Body-to-north/east/down rotation.
151 * @param forward Forward component of the body ray, with unit down component.
152 * @param right Rightward component of that ray.
153 * @param altitude_pixels Height above the plane at the local map scale.
154 * @param center_x World pixel column below the aircraft.
155 * @param center_y World pixel row below the aircraft.
156 * @param[out] map_x Projected world pixel column on success.
157 * @param[out] map_y Projected world pixel row on success.
158 * @return True for a finite intersection in front of the camera.
159 * @details Divide by the ray's downward component to intersect the plane.
160 * Negate north when converting to image rows, which increase southward.
161 */
162static bool map_project(double rotation[3][3], double forward, double right,
163 double altitude_pixels, double center_x, double center_y,
164 double *map_x, double *map_y)
165{
166 double north = rotation[0][0] * forward + rotation[0][1] * right + rotation[0][2];
167 double east = rotation[1][0] * forward + rotation[1][1] * right + rotation[1][2];
168 double down = rotation[2][0] * forward + rotation[2][1] * right + rotation[2][2];
169 if (down <= PROJECTION_MIN_DEPTH) return false;
170 *map_x = center_x + altitude_pixels * east / down;
171 *map_y = center_y - altitude_pixels * north / down;
172 return isfinite(*map_x) && isfinite(*map_y);
173}
174
175/** @brief Render a map-backed simulated exposure.
176 * @param filename Destination JPEG path.
177 * @param cache_directory Local map tile cache root.
178 * @param shot Trigger containing position, attitude and AGL.
179 * @param width Output columns.
180 * @param height Output rows.
181 * @param horizontal_fov_deg Horizontal field of view in degrees.
182 * @param vertical_fov_deg Vertical field of view in degrees.
183 * @return Zero on publication, or -1 on lock, geometry, cache, or I/O failure.
184 * @details Serialize rendering with fixture transforms because both reuse
185 * the same codec and pixel workspace. */
186int image_mock_map(const char *filename, const char *cache_directory,
187 const union dc_shot_union *shot, size_t width, size_t height,
188 double horizontal_fov_deg, double vertical_fov_deg)
189{
190 int lock_result = pthread_mutex_lock(&workspace_mutex);
191 if (lock_result != 0) {
192 errno = lock_result;
193 return -1;
194 }
195 int result = image_mock_map_locked(filename, cache_directory, shot, width, height,
196 horizontal_fov_deg, vertical_fov_deg);
197 pthread_mutex_unlock(&workspace_mutex);
198 return result;
199}
200
201/**
202 * @brief Render a simulated camera view from cached map tiles.
203 * @param filename Destination JPEG path.
204 * @param cache_directory Root of the local map tile cache.
205 * @param shot Trigger containing the position, attitude, and height above ground.
206 * @param width Output width in pixels.
207 * @param height Output height in pixels.
208 * @param horizontal_fov_deg Horizontal field of view in degrees.
209 * @param vertical_fov_deg Vertical field of view in degrees.
210 * @return Zero on publication, or -1 on invalid geometry, missing data, or I/O failure.
211 * @details With the workspace mutex held, project the image footprint onto
212 * the zoom-18 map, load its required tiles, and inverse-sample the footprint.
213 * Reject views outside the bounded tile workspace rather than filling gaps.
214 */
215static int image_mock_map_locked(const char *filename, const char *cache_directory,
216 const union dc_shot_union *shot, size_t width, size_t height,
217 double horizontal_fov_deg, double vertical_fov_deg)
218{
219 const int tile_size = MAP_TILE_SIZE;
220 const int tile_count = 1 << 18;
221 const double earth_radius = 6378137.0;
222 const double pi = 3.14159265358979323846;
223 if (filename == NULL || cache_directory == NULL || cache_directory[0] == '\0'
224 || shot == NULL || !dimensions_fit(width, height)
225 || !isfinite(horizontal_fov_deg) || !isfinite(vertical_fov_deg)
226 || horizontal_fov_deg <= 0.0 || horizontal_fov_deg >= 179.0
227 || vertical_fov_deg <= 0.0 || vertical_fov_deg >= 179.0
228 || shot->data.groundalt <= 0 || fabs(shot->data.lat / 1e7) > 85.05112878
229 || fabs(shot->data.lon / 1e7) > 180.0) {
230 fprintf(stderr, "MOCK_MAP:\tinvalid pose, positive AGL, image size, or FOV required\n");
231 errno = EINVAL;
232 return -1;
233 }
234 double latitude = shot->data.lat / 1e7 / RAD_TO_DEG;
235 double world_pixels = (double)tile_size * tile_count;
236 double center_x = (shot->data.lon / 1e7 + 180.0) / 360.0 * world_pixels;
237 double center_y = (1.0 - asinh(tan(latitude)) / pi) * 0.5 * world_pixels;
238 /* Use the scale at the capture latitude: Mercator world pixels do not span
239 * the same ground distance at the equator and near the poles. */
240 double meters_per_pixel = 2.0 * pi * earth_radius * cos(latitude) / world_pixels;
241 double altitude_pixels = shot->data.groundalt / POSITION_BFP_SCALE / meters_per_pixel;
242 double half_horizontal = tan(horizontal_fov_deg / RAD_TO_DEG * 0.5);
243 double half_vertical = tan(vertical_fov_deg / RAD_TO_DEG * 0.5);
244 double rotation[3][3];
245 build_rotation(shot->data.phi / ANGLE_BFP_SCALE, shot->data.theta / ANGLE_BFP_SCALE,
246 shot->data.psi / ANGLE_BFP_SCALE, rotation);
247 double minimum_x = INFINITY, minimum_y = INFINITY;
248 double maximum_x = -INFINITY, maximum_y = -INFINITY;
249 for (int row = -1; row <= 1; row += 2) {
250 for (int column = -1; column <= 1; column += 2) {
251 double map_x, map_y;
252 if (!map_project(rotation, -row * half_vertical, column * half_horizontal,
253 altitude_pixels, center_x, center_y, &map_x, &map_y)) {
254 fprintf(stderr, "MOCK_MAP:\tcamera footprint reaches the horizon\n");
255 errno = ERANGE;
256 return -1;
257 }
258 minimum_x = fmin(minimum_x, map_x);
259 minimum_y = fmin(minimum_y, map_y);
260 maximum_x = fmax(maximum_x, map_x);
261 maximum_y = fmax(maximum_y, map_y);
262 }
263 }
264 int center_tile_x = (int)floor(center_x / tile_size);
265 int center_tile_y = (int)floor(center_y / tile_size);
266 if (minimum_x < (center_tile_x - 1.0) * tile_size
267 || minimum_y < (center_tile_y - 1.0) * tile_size
268 || ceil(maximum_x) >= (center_tile_x + 2.0) * tile_size
269 || ceil(maximum_y) >= (center_tile_y + 2.0) * tile_size
270 || minimum_y < 0.0 || ceil(maximum_y) >= world_pixels) {
271 fprintf(stderr, "MOCK_MAP:\tfootprint exceeds the zoom-18 XYZ tile 3x3 neighborhood\n");
272 errno = ERANGE;
273 return -1;
274 }
275 int first_x = (int)floor(minimum_x / tile_size);
276 int first_y = (int)floor(minimum_y / tile_size);
277 int last_x = (int)floor(ceil(maximum_x) / tile_size);
278 int last_y = (int)floor(ceil(maximum_y) / tile_size);
279 struct decoded_image mosaic = {
280 workspace.mosaic, (size_t)(last_x - first_x + 1) * tile_size,
281 (size_t)(last_y - first_y + 1) * tile_size
282 };
283 for (int tile_y = first_y; tile_y <= last_y; ++tile_y) {
284 for (int tile_x = first_x; tile_x <= last_x; ++tile_x) {
285 char path[PATH_MAX];
286 int wrapped_x = (tile_x % tile_count + tile_count) % tile_count;
287 int length = snprintf(path, sizeof(path), "%s/GOOGLE/18/%d/%d.jpeg",
288 cache_directory, wrapped_x, tile_y);
289 if (length < 0 || (size_t)length >= sizeof(path)) {
290 errno = ENAMETOOLONG;
291 return -1;
292 }
293 FILE *input = fopen(path, "rb");
294 struct decoded_image tile = {0};
295 int result = input == NULL ? -1 : read_jpeg_dimensions(input, &tile);
296 if (result == 0 && (tile.width != (size_t)tile_size || tile.height != (size_t)tile_size)) {
297 result = -1;
298 }
299 if (result == 0) {
300 rewind(input);
301 result = decode_jpeg(input, &tile);
302 }
303 if (input != NULL && fclose(input) != 0) result = -1;
304 if (result != 0) {
305 fprintf(stderr, "MOCK_MAP:\tmissing or invalid 256x256 JPEG tile: %s\n", path);
306 return -1;
307 }
308 size_t offset_x = (size_t)(tile_x - first_x) * tile_size;
309 size_t offset_y = (size_t)(tile_y - first_y) * tile_size;
310 for (size_t row = 0; row < tile.height && row + offset_y < mosaic.height; ++row) {
311 for (size_t column = 0; column < tile.width && column + offset_x < mosaic.width; ++column) {
312 for (size_t component = 0; component < JPEG_COMPONENTS; ++component) {
313 mosaic.pixels[((row + offset_y) * mosaic.width + column + offset_x) * JPEG_COMPONENTS + component]
314 = tile.pixels[(row * tile.width + column) * JPEG_COMPONENTS + component];
315 }
316 }
317 }
318 }
319 }
320 struct decoded_image image = {workspace.destination, width, height};
321 for (size_t row = 0; row < height; ++row) {
322 double forward = (1.0 - 2.0 * row / (height - 1)) * half_vertical;
323 for (size_t column = 0; column < width; ++column) {
324 double right = (2.0 * column / (width - 1) - 1.0) * half_horizontal;
325 double map_x, map_y;
326 if (!map_project(rotation, forward, right, altitude_pixels, center_x, center_y, &map_x, &map_y)) {
327 return -1;
328 }
329 map_x -= (double)first_x * tile_size;
330 map_y -= (double)first_y * tile_size;
331 if (map_x < 0.0 || map_y < 0.0 || map_x > mosaic.width - 1 || map_y > mosaic.height - 1) {
332 return -1;
333 }
334 bilinear_sample_rgb(&mosaic, map_x, map_y, &image.pixels[(row * width + column) * JPEG_COMPONENTS]);
335 }
336 }
337 int result = replace_image_atomically(filename, &image);
338 if (result == 0) {
339 printf("MOCK_MAP:\tXYZ z18 tiles %d..%d/%d..%d | %.7f,%.7f AGL %.2fm FOV %.2fx%.2f | %s\n",
340 first_x, last_x, first_y, last_y, shot->data.lat / 1e7, shot->data.lon / 1e7,
341 shot->data.groundalt / POSITION_BFP_SCALE, horizontal_fov_deg, vertical_fov_deg, filename);
342 }
343 return result;
344}
345
346int image_mock_transform(const char *filename, const union dc_shot_union *shot)
347{
348 int lock_result = pthread_mutex_lock(&workspace_mutex);
349 if (lock_result != 0) {
350 errno = lock_result;
351 return -1;
352 }
353 int result = image_mock_transform_locked(filename, shot);
354 pthread_mutex_unlock(&workspace_mutex);
355 return result;
356}
357
358/**
359 * @brief Apply simulated attitude to the existing fixture JPEG.
360 * @param filename Fixture JPEG to replace if a transform is applied.
361 * @param shot Trigger containing fixed-point aircraft attitude.
362 * @return Applied or skipped status, or -1 on failure.
363 * @details With the workspace mutex held, select the configured horizon policy
364 * before full decode. Skip an effectively identity transform to avoid an
365 * unnecessary lossy JPEG re-encode.
366 */
367static int image_mock_transform_locked(const char *filename, const union dc_shot_union *shot)
368{
369 if (filename == NULL || shot == NULL) {
370 errno = EINVAL;
371 return -1;
372 }
373 if (!isfinite(near_horizon_roll_deg) || near_horizon_roll_deg < 0.0
374 || near_horizon_roll_deg > 180.0
376 || near_horizon_pitch_deg > 180.0
380 fprintf(stderr, "MOCK_TRANSFORM:\tnear-horizon thresholds must be between 0 and 180 degrees\n");
381 errno = EINVAL;
382 return -1;
383 }
384
385 double altitude_m = shot->data.alt / 1000.0;
386 double ground_altitude_m = shot->data.groundalt / POSITION_BFP_SCALE;
387 double roll_rad = shot->data.phi / ANGLE_BFP_SCALE;
388 double pitch_rad = shot->data.theta / ANGLE_BFP_SCALE;
389 double yaw_rad = shot->data.psi / ANGLE_BFP_SCALE;
390 double speed_m_s = shot->data.vground / SPEED_BFP_SCALE;
391 double course_deg = shot->data.course / ANGLE_BFP_SCALE * RAD_TO_DEG;
392 double blur_factor = speed_m_s / 100.0;
393 bool near_horizon = is_near_horizon(roll_rad, pitch_rad);
394
395 printf("MOCK_TRANSFORM:\talt %.3f m AGL %.3f m | roll %.3f pitch %.3f yaw %.3f deg | "
396 "speed %.3f m/s course %.3f deg | blur factor %.6f (not applied)\n",
397 altitude_m, ground_altitude_m,
398 roll_rad * RAD_TO_DEG, pitch_rad * RAD_TO_DEG, yaw_rad * RAD_TO_DEG,
399 speed_m_s, course_deg, blur_factor);
400
401 if (near_horizon && near_horizon_case_black) {
402 printf("MOCK_TRANSFORM:\tnear-horizon attitude: generating black frame\n");
403 return create_black_frame(filename);
404 }
405
406 if (!near_horizon && fabs(roll_rad) < PROJECTION_EPSILON
407 && fabs(pitch_rad) < PROJECTION_EPSILON && fabs(yaw_rad) < PROJECTION_EPSILON) {
409 }
410
411 FILE *input = fopen(filename, "rb");
412 if (input == NULL) {
413 fprintf(stderr, "MOCK_TRANSFORM:\tfailed to open %s: %s\n", filename, strerror(errno));
414 return -1;
415 }
416
417 struct decoded_image source = {workspace.source, 0, 0};
418 if (decode_jpeg(input, &source) != 0) {
419 fprintf(stderr, "MOCK_TRANSFORM:\tfailed to decode JPEG %s\n", filename);
420 fclose(input);
421 return -1;
422 }
423 if (fclose(input) != 0) {
424 return -1;
425 }
426
427 struct decoded_image transformed = {workspace.destination, source.width, source.height};
428 int result = transform_pixels(&source, &transformed, roll_rad, pitch_rad, yaw_rad,
429 near_horizon);
430 if (result < 0) {
431 return -1;
432 }
434 return result;
435 }
436
437 result = replace_image_atomically(filename, &transformed);
438 return result;
439}
440
441/**
442 * @brief Redirect a fatal libjpeg error to the active codec operation.
443 * @param jpeg_info Codec state with this module's installed error manager.
444 * @details The codec caller owns cleanup at its recovery point; the callback
445 * does not return and must not run without an active recovery frame.
446 */
447static void transform_jpeg_error_exit(j_common_ptr jpeg_info)
448{
449 struct transform_jpeg_error *error = (struct transform_jpeg_error *)jpeg_info->err;
450 longjmp(error->recovery, 1);
451}
452
453/**
454 * @brief Check marker bounds before forwarding a libjpeg diagnostic.
455 * @param state Codec state with this module's installed error manager.
456 * @param level libjpeg diagnostic level.
457 * @details Preserve the installed diagnostic behavior for accepted input.
458 * A marker rejected by the guard takes the codec's fatal recovery path.
459 */
460static void transform_jpeg_message(j_common_ptr state, int level)
461{
462 struct transform_jpeg_error *error = (struct transform_jpeg_error *)state->err;
464 error->emit(state, level);
465}
466
467/**
468 * @brief Apply both axis-specific and combined near-horizon limits.
469 * @param roll_rad Aircraft roll in radians.
470 * @param pitch_rad Aircraft pitch in radians.
471 * @return True if any configured tilt threshold is reached.
472 * @details The down-axis cosine combines roll and pitch, catching attitudes
473 * where neither axis alone reaches its limit. Clamp it before inverse cosine.
474 */
475static bool is_near_horizon(double roll_rad, double pitch_rad)
476{
477 double absolute_roll_deg = fabs(roll_rad * RAD_TO_DEG);
478 double absolute_pitch_deg = fabs(pitch_rad * RAD_TO_DEG);
479 double optical_axis_cosine = cos(roll_rad) * cos(pitch_rad);
480 optical_axis_cosine = fmax(-1.0, fmin(1.0, optical_axis_cosine));
481 double combined_tilt_deg = acos(optical_axis_cosine) * RAD_TO_DEG;
482 return absolute_roll_deg >= near_horizon_roll_deg
483 || absolute_pitch_deg >= near_horizon_pitch_deg
484 || combined_tilt_deg >= near_horizon_combined_tilt_deg;
485}
486
487/**
488 * @brief Check that an image can fit the bounded RGB workspace.
489 * @param width Pixel columns.
490 * @param height Pixel rows.
491 * @return True for dimensions of at least two pixels within axis and area limits.
492 * @details Test area by division so a malformed header cannot overflow the check.
493 */
494static bool dimensions_fit(size_t width, size_t height)
495{
496 return width >= 2 && height >= 2
498 && width <= IMAGE_MOCK_MAX_PIXELS / height;
499}
500
501/**
502 * @brief Read bounded image dimensions without decoding pixels.
503 * @param input Open JPEG stream positioned at the start of the image.
504 * @param[out] image Descriptor whose width and height are set on success.
505 * @return Zero on success, or -1 for a codec or dimension error.
506 * @details The black-frame fallback needs the original size only. Reuse the
507 * locked decoder workspace and leave stream ownership with the caller.
508 */
509static int read_jpeg_dimensions(FILE *input, struct decoded_image *image)
510{
511 struct jpeg_decompress_struct *decoder = &workspace.decoder;
512 struct transform_jpeg_error *error = &workspace.decode_error;
513 memset(decoder, 0, sizeof(*decoder));
514 decoder->err = jpeg_std_error(&error->manager);
515 error->emit = error->manager.emit_message;
516 error->manager.emit_message = transform_jpeg_message;
517 error->manager.error_exit = transform_jpeg_error_exit;
518 if (setjmp(error->recovery) != 0) {
519 jpeg_destroy_decompress(decoder);
520 return -1;
521 }
522
523 jpeg_create_decompress(decoder);
524 jpeg_stdio_src(decoder, input);
525 if (jpeg_read_header(decoder, TRUE) != JPEG_HEADER_OK
526 || !dimensions_fit(decoder->image_width, decoder->image_height)) {
527 jpeg_destroy_decompress(decoder);
528 errno = EINVAL;
529 return -1;
530 }
531 image->width = decoder->image_width;
532 image->height = decoder->image_height;
533 jpeg_destroy_decompress(decoder);
534 return 0;
535}
536
537/**
538 * @brief Decode bounded RGB scanlines from an open JPEG stream.
539 * @param input JPEG stream positioned at the start of the image.
540 * @param[in,out] image Destination descriptor; a null pixel buffer selects the
541 * shared source buffer. A supplied buffer must fit the image.
542 * @return Zero for a complete decode, or -1 on failure; discard partial output.
543 * @details Validate both header and output dimensions before indexing the RGB
544 * buffer. The caller holds the workspace mutex and owns the input stream.
545 */
546static int decode_jpeg(FILE *input, struct decoded_image *image)
547{
548 struct jpeg_decompress_struct *decoder = &workspace.decoder;
549 struct transform_jpeg_error *error = &workspace.decode_error;
550 memset(decoder, 0, sizeof(*decoder));
551 decoder->err = jpeg_std_error(&error->manager);
552 error->emit = error->manager.emit_message;
553 error->manager.emit_message = transform_jpeg_message;
554 error->manager.error_exit = transform_jpeg_error_exit;
555 if (setjmp(error->recovery) != 0) {
556 jpeg_destroy_decompress(decoder);
557 return -1;
558 }
559
560 jpeg_create_decompress(decoder);
561 jpeg_stdio_src(decoder, input);
562 if (jpeg_read_header(decoder, TRUE) != JPEG_HEADER_OK
563 || !dimensions_fit(decoder->image_width, decoder->image_height)) {
564 jpeg_destroy_decompress(decoder);
565 errno = EOVERFLOW;
566 return -1;
567 }
568 decoder->out_color_space = JCS_RGB;
569 jpeg_start_decompress(decoder);
570
571 image->width = decoder->output_width;
572 image->height = decoder->output_height;
573 if (decoder->output_components != JPEG_COMPONENTS || image->width < 2 || image->height < 2
574 || !dimensions_fit(image->width, image->height)) {
575 jpeg_destroy_decompress(decoder);
576 errno = EOVERFLOW;
577 return -1;
578 }
579
580 size_t row_size = image->width * JPEG_COMPONENTS;
581 if (image->pixels == NULL) {
582 image->pixels = workspace.source;
583 }
584
585 while (decoder->output_scanline < decoder->output_height) {
586 JSAMPROW row[1] = {&image->pixels[(size_t)decoder->output_scanline * row_size]};
587 if (jpeg_read_scanlines(decoder, row, 1) != 1) {
588 jpeg_destroy_decompress(decoder);
589 return -1;
590 }
591 }
592
593 jpeg_finish_decompress(decoder);
594 jpeg_destroy_decompress(decoder);
595 return 0;
596}
597
598/**
599 * @brief Encode a bounded interleaved RGB image at the simulation quality setting.
600 * @param output Open output stream, closed by the caller.
601 * @param image Populated RGB image descriptor.
602 * @return Zero on completion, or -1 for an invalid image or codec failure.
603 * @details Reuse the locked encoder workspace. Publication is the caller's
604 * responsibility: a failed encode may leave partial output on the stream.
605 */
606static int encode_jpeg(FILE *output, const struct decoded_image *image)
607{
608 if (!dimensions_fit(image->width, image->height) || image->pixels == NULL) {
609 errno = EOVERFLOW;
610 return -1;
611 }
612 struct jpeg_compress_struct *encoder = &workspace.encoder;
613 struct transform_jpeg_error *error = &workspace.encode_error;
614 memset(encoder, 0, sizeof(*encoder));
615 encoder->err = jpeg_std_error(&error->manager);
616 error->manager.error_exit = transform_jpeg_error_exit;
617 if (setjmp(error->recovery) != 0) {
618 jpeg_destroy_compress(encoder);
619 return -1;
620 }
621
622 jpeg_create_compress(encoder);
623 jpeg_stdio_dest(encoder, output);
624 encoder->image_width = (JDIMENSION)image->width;
625 encoder->image_height = (JDIMENSION)image->height;
626 encoder->input_components = JPEG_COMPONENTS;
627 encoder->in_color_space = JCS_RGB;
628 jpeg_set_defaults(encoder);
629 jpeg_set_quality(encoder, JPEG_QUALITY, TRUE);
630 jpeg_start_compress(encoder, TRUE);
631
632 size_t row_size = image->width * JPEG_COMPONENTS;
633 while (encoder->next_scanline < encoder->image_height) {
634 JSAMPROW row[1] = {(JSAMPROW) &image->pixels[(size_t)encoder->next_scanline * row_size]};
635 if (jpeg_write_scanlines(encoder, row, 1) != 1) {
636 jpeg_destroy_compress(encoder);
637 return -1;
638 }
639 }
640
641 jpeg_finish_compress(encoder);
642 jpeg_destroy_compress(encoder);
643 return 0;
644}
645
646/**
647 * @brief Resample a fixture into a camera view at the supplied attitude.
648 * @param source Decoded fixture RGB raster.
649 * @param[out] destination Separate output raster with caller-provided storage.
650 * @param roll_rad Aircraft roll in radians.
651 * @param pitch_rad Aircraft pitch in radians.
652 * @param yaw_rad Aircraft yaw in radians.
653 * @param synthesize_terrain Initially allow mirrored terrain beyond the fixture.
654 * @return @c IMAGE_MOCK_TRANSFORM_APPLIED on success, or -1 on failure.
655 * @details Fit a borderless crop when possible. For the near-horizon fallback,
656 * reflect out-of-bounds samples instead of claiming the fixture covers the view.
657 * In both cases inverse-map the destination and sample the fixture bilinearly.
658 */
659static int transform_pixels(const struct decoded_image *source, struct decoded_image *destination,
660 double roll_rad, double pitch_rad, double yaw_rad,
661 bool synthesize_terrain)
662{
663 double center_x = ((double)source->width - 1.0) / 2.0;
664 double center_y = ((double)source->height - 1.0) / 2.0;
665 double largest_dimension = source->width > source->height ? source->width : source->height;
666 double focal_length = largest_dimension * FOCAL_LENGTH_FACTOR;
667 double rotation[3][3];
668 build_rotation(roll_rad, pitch_rad, yaw_rad, rotation);
669 if (rotation[2][2] <= PROJECTION_MIN_DEPTH) {
670 synthesize_terrain = true;
671 }
672 struct projection_fit fit;
673 if (synthesize_terrain) {
674 fit.ray_scale = 1.0;
675 fit.image_scale = 1.0;
676 fit.offset_x = 0.0;
677 fit.offset_y = 0.0;
678 printf("MOCK_TRANSFORM:\tnear-horizon attitude: synthesizing extended terrain\n");
679 } else if (compute_projection_fit(source, rotation, focal_length, center_x, center_y, &fit) != 0) {
680 fprintf(stderr, "MOCK_TRANSFORM:\tattitude is outside the usable single-image camera model\n");
681 return -1;
682 }
683
684 if (!dimensions_fit(source->width, source->height)
685 || destination->pixels == NULL) {
686 errno = EOVERFLOW;
687 return -1;
688 }
689 if (!synthesize_terrain) {
690 double cover_zoom = 1.0 / (fit.ray_scale * fit.image_scale);
691 double pan_x = fit.offset_x + (fit.image_scale - 1.0) * center_x;
692 double pan_y = fit.offset_y + (fit.image_scale - 1.0) * center_y;
693 printf("MOCK_TRANSFORM:\tborderless cover crop: %.3fx zoom, pan %.1f px x %.1f px\n",
694 cover_zoom, pan_x, pan_y);
695 }
696
697 /* The unnormalized ray is affine across a scanline; advance it by a
698 * constant step rather than multiplying by the rotation for every pixel. */
699 double ray_x_start = -fit.ray_scale * center_x / focal_length;
700 double ray_x_increment = fit.ray_scale / focal_length;
701 double source_ray_x_increment = rotation[0][0] * ray_x_increment;
702 double source_ray_y_increment = rotation[0][1] * ray_x_increment;
703 double source_ray_z_increment = rotation[0][2] * ray_x_increment;
704
705 for (size_t destination_y = 0; destination_y < destination->height; destination_y++) {
706 double ray_y = fit.ray_scale * ((double)destination_y - center_y) / focal_length;
707 double source_ray_x = rotation[0][0] * ray_x_start + rotation[1][0] * ray_y + rotation[2][0];
708 double source_ray_y = rotation[0][1] * ray_x_start + rotation[1][1] * ray_y + rotation[2][1];
709 double source_ray_z = rotation[0][2] * ray_x_start + rotation[1][2] * ray_y + rotation[2][2];
710
711 for (size_t destination_x = 0; destination_x < destination->width; destination_x++) {
712 double projection_depth = source_ray_z;
713 if (projection_depth <= PROJECTION_MIN_DEPTH) {
714 if (!synthesize_terrain) {
715 return -1;
716 }
717 projection_depth = projection_depth < 0.0
718 ? fmin(projection_depth, -PROJECTION_MIN_DEPTH)
720 }
721 double inverse_depth = focal_length / projection_depth;
722 double source_x = source_ray_x * inverse_depth + center_x;
723 double source_y = source_ray_y * inverse_depth + center_y;
724
725 source_x = fit.image_scale * source_x + fit.offset_x;
726 source_y = fit.image_scale * source_y + fit.offset_y;
727 if (synthesize_terrain) {
728 source_x = mirror_coordinate(source_x, source->width);
729 source_y = mirror_coordinate(source_y, source->height);
730 } else {
731 source_x = fmax(0.0, fmin((double)(source->width - 1), source_x));
732 source_y = fmax(0.0, fmin((double)(source->height - 1), source_y));
733 }
734
735 size_t destination_offset = (destination_y * destination->width + destination_x) * JPEG_COMPONENTS;
736 bilinear_sample_rgb(source, source_x, source_y,
737 &destination->pixels[destination_offset]);
738 source_ray_x += source_ray_x_increment;
739 source_ray_y += source_ray_y_increment;
740 source_ray_z += source_ray_z_increment;
741 }
742 }
744}
745
746/**
747 * @brief Reflect a sample coordinate into the source image.
748 * @param coordinate Finite source position, possibly outside the image.
749 * @param extent Axis length, at least two pixels.
750 * @return A reflected coordinate in [0, extent - 1].
751 * @details Use a triangle wave across repeated reflections so the fallback
752 * has no hard seam caused by wrapping from one edge to the opposite edge.
753 */
754static double mirror_coordinate(double coordinate, size_t extent)
755{
756 double maximum = (double)(extent - 1);
757 double period = 2.0 * maximum;
758 double mirrored = fmod(coordinate, period);
759 if (mirrored < 0.0) {
760 mirrored += period;
761 }
762 return mirrored <= maximum ? mirrored : period - mirrored;
763}
764
765/**
766 * @brief Replace the fixture with a black JPEG of the same dimensions.
767 * @param filename Fixture JPEG path.
768 * @return Zero on replacement, or -1 on header, codec, or I/O failure.
769 * @details Read only the original header: near-horizon black frames do not
770 * need any source pixels.
771 */
772static int create_black_frame(const char *filename)
773{
774 FILE *input = fopen(filename, "rb");
775 if (input == NULL) {
776 return -1;
777 }
778 struct decoded_image black = {NULL, 0, 0};
779 int result = read_jpeg_dimensions(input, &black);
780 if (fclose(input) != 0) {
781 result = -1;
782 }
783 if (result != 0 || black.width > SIZE_MAX / JPEG_COMPONENTS
784 || !dimensions_fit(black.width, black.height)) {
785 return -1;
786 }
787 black.pixels = workspace.destination;
788 memset(black.pixels, 0, black.width * black.height * JPEG_COMPONENTS);
789 result = replace_image_atomically(filename, &black);
790 return result;
791}
792
793/**
794 * @brief Construct the body-to-north/east/down attitude rotation.
795 * @param roll_rad Roll about the forward axis, in radians.
796 * @param pitch_rad Pitch about the right axis, in radians.
797 * @param yaw_rad Heading rotation about the down axis, in radians.
798 * @param[out] rotation Row-major 3 by 3 rotation.
799 * @details Compose yaw, pitch, and roll in that order. The map renderer
800 * uses the forward mapping; the fixture warp uses its transpose.
801 */
802static void build_rotation(double roll_rad, double pitch_rad, double yaw_rad,
803 double rotation[3][3])
804{
805 double cosine_roll = cos(roll_rad);
806 double sine_roll = sin(roll_rad);
807 double cosine_pitch = cos(pitch_rad);
808 double sine_pitch = sin(pitch_rad);
809 double cosine_yaw = cos(yaw_rad);
810 double sine_yaw = sin(yaw_rad);
811
812 rotation[0][0] = cosine_yaw * cosine_pitch;
813 rotation[0][1] = cosine_yaw * sine_pitch * sine_roll - sine_yaw * cosine_roll;
814 rotation[0][2] = cosine_yaw * sine_pitch * cosine_roll + sine_yaw * sine_roll;
815 rotation[1][0] = sine_yaw * cosine_pitch;
816 rotation[1][1] = sine_yaw * sine_pitch * sine_roll + cosine_yaw * cosine_roll;
817 rotation[1][2] = sine_yaw * sine_pitch * cosine_roll - cosine_yaw * sine_roll;
818 rotation[2][0] = -sine_pitch;
819 rotation[2][1] = cosine_pitch * sine_roll;
820 rotation[2][2] = cosine_pitch * cosine_roll;
821}
822
823/**
824 * @brief Map a destination pixel back into the fixture JPEG.
825 * @param rotation Attitude rotation, applied here by its transpose.
826 * @param focal_length Pinhole focal length in pixels.
827 * @param center_x Principal point column.
828 * @param center_y Principal point row.
829 * @param ray_scale Field-of-view contraction applied before rotation.
830 * @param destination_x Output pixel column.
831 * @param destination_y Output pixel row.
832 * @param[out] source_x Projected source column on success.
833 * @param[out] source_y Projected source row on success.
834 * @return True for a finite projection with sufficient positive depth.
835 * @details Use inverse mapping to avoid holes between forward-projected
836 * pixels. The caller still needs to check source raster bounds.
837 */
838static bool project_point(double rotation[3][3], double focal_length,
839 double center_x, double center_y, double ray_scale,
840 double destination_x, double destination_y,
841 double *source_x, double *source_y)
842{
843 double ray_x = ray_scale * (destination_x - center_x) / focal_length;
844 double ray_y = ray_scale * (destination_y - center_y) / focal_length;
845 double source_ray_x = rotation[0][0] * ray_x + rotation[1][0] * ray_y + rotation[2][0];
846 double source_ray_y = rotation[0][1] * ray_x + rotation[1][1] * ray_y + rotation[2][1];
847 double source_ray_z = rotation[0][2] * ray_x + rotation[1][2] * ray_y + rotation[2][2];
848 if (source_ray_z <= PROJECTION_MIN_DEPTH) {
849 return false;
850 }
851
852 *source_x = focal_length * source_ray_x / source_ray_z + center_x;
853 *source_y = focal_length * source_ray_y / source_ray_z + center_y;
854 return isfinite(*source_x) && isfinite(*source_y);
855}
856
857/**
858 * @brief Check for a horizon crossing in the candidate projection.
859 * @param source Image descriptor defining the candidate raster dimensions.
860 * @param rotation Attitude rotation.
861 * @param focal_length Focal length in pixels.
862 * @param center_x Principal point column.
863 * @param center_y Principal point row.
864 * @param ray_scale Candidate field-of-view contraction.
865 * @return True if each corner has a finite, positive-depth projection.
866 * @details Depth is affine in destination coordinates, so corner checks
867 * bound the depth over the whole rectangle. They do not check image coverage.
868 */
869static bool projection_corners_valid(const struct decoded_image *source,
870 double rotation[3][3], double focal_length,
871 double center_x, double center_y, double ray_scale)
872{
873 const double corners[4][2] = {
874 {0.0, 0.0},
875 {(double)(source->width - 1), 0.0},
876 {(double)(source->width - 1), (double)(source->height - 1)},
877 {0.0, (double)(source->height - 1)}
878 };
879 for (size_t index = 0; index < 4; index++) {
880 double source_x;
881 double source_y;
882 if (!project_point(rotation, focal_length, center_x, center_y, ray_scale,
883 corners[index][0], corners[index][1], &source_x, &source_y)) {
884 return false;
885 }
886 }
887 return true;
888}
889
890/**
891 * @brief Find a fitted projection with low effective zoom.
892 * @param source Source raster descriptor.
893 * @param rotation Attitude rotation.
894 * @param focal_length Focal length in pixels.
895 * @param center_x Principal point column.
896 * @param center_y Principal point row.
897 * @param[out] fit Best candidate found by the bounded search.
898 * @return Zero if a candidate was found, or -1 if none was usable.
899 * @details Sample ray scales on a logarithmic grid, then refine around
900 * the best candidate. This bounds search work without claiming a global optimum.
901 */
902static int compute_projection_fit(const struct decoded_image *source,
903 double rotation[3][3], double focal_length,
904 double center_x, double center_y,
905 struct projection_fit *fit)
906{
907 if (rotation[2][2] <= PROJECTION_MIN_DEPTH) {
908 errno = ERANGE;
909 return -1;
910 }
911
912 double minimum_log_scale = log(PROJECTION_MIN_RAY_SCALE);
913 double best_log_scale = minimum_log_scale;
914 double best_zoom = INFINITY;
915 bool fit_found = false;
916 for (int sample = 0; sample <= PROJECTION_FOV_SAMPLES; sample++) {
917 double fraction = (double)sample / PROJECTION_FOV_SAMPLES;
918 double log_scale = minimum_log_scale * (1.0 - fraction);
919 double ray_scale = exp(log_scale);
920 struct projection_fit candidate;
921 if (compute_projection_fit_at_scale(source, rotation, focal_length,
922 center_x, center_y, ray_scale, &candidate) != 0) {
923 continue;
924 }
925 double zoom = 1.0 / (candidate.ray_scale * candidate.image_scale);
926 if (zoom < best_zoom) {
927 best_zoom = zoom;
928 best_log_scale = log_scale;
929 *fit = candidate;
930 fit_found = true;
931 }
932 }
933 if (!fit_found) {
934 errno = ERANGE;
935 return -1;
936 }
937
938 double coarse_step = -minimum_log_scale / PROJECTION_FOV_SAMPLES;
939 double lower_log_scale = fmax(minimum_log_scale, best_log_scale - coarse_step);
940 double upper_log_scale = fmin(0.0, best_log_scale + coarse_step);
941 for (int step = 0; step < PROJECTION_REFINE_STEPS; step++) {
942 double first_log_scale = (2.0 * lower_log_scale + upper_log_scale) / 3.0;
943 double second_log_scale = (lower_log_scale + 2.0 * upper_log_scale) / 3.0;
944 struct projection_fit first_fit;
945 struct projection_fit second_fit;
946 bool first_valid = compute_projection_fit_at_scale(source, rotation, focal_length,
947 center_x, center_y, exp(first_log_scale),
948 &first_fit) == 0;
949 bool second_valid = compute_projection_fit_at_scale(source, rotation, focal_length,
950 center_x, center_y, exp(second_log_scale),
951 &second_fit) == 0;
952 double first_zoom = first_valid ? 1.0 / (first_fit.ray_scale * first_fit.image_scale) : INFINITY;
953 double second_zoom = second_valid ? 1.0 / (second_fit.ray_scale * second_fit.image_scale) : INFINITY;
954 if (first_zoom < best_zoom) {
955 best_zoom = first_zoom;
956 *fit = first_fit;
957 }
958 if (second_zoom < best_zoom) {
959 best_zoom = second_zoom;
960 *fit = second_fit;
961 }
962 if (first_zoom <= second_zoom) {
963 upper_log_scale = second_log_scale;
964 } else {
965 lower_log_scale = first_log_scale;
966 }
967 }
968 return 0;
969}
970
971/**
972 * @brief Fit one projected destination rectangle into the source raster.
973 * @param source Source raster descriptor.
974 * @param rotation Attitude rotation.
975 * @param focal_length Focal length in pixels.
976 * @param center_x Principal point column.
977 * @param center_y Principal point row.
978 * @param ray_scale Candidate field-of-view contraction.
979 * @param[out] fit Sampling scale and offsets; use only on success.
980 * @return Zero for a usable fit, or -1 for a singular or degenerate projection.
981 * @details Measure the projected corner bounds and fit both axes with a
982 * common scale to avoid stretching. Preserve a full-scale fit that is
983 * already covered; otherwise center the bounds with a numerical margin.
984 */
985static int compute_projection_fit_at_scale(const struct decoded_image *source,
986 double rotation[3][3], double focal_length,
987 double center_x, double center_y, double ray_scale,
988 struct projection_fit *fit)
989{
990 if (!projection_corners_valid(source, rotation, focal_length, center_x, center_y,
991 ray_scale)) {
992 return -1;
993 }
994 fit->ray_scale = ray_scale;
995
996 const double corners[4][2] = {
997 {0.0, 0.0},
998 {(double)(source->width - 1), 0.0},
999 {(double)(source->width - 1), (double)(source->height - 1)},
1000 {0.0, (double)(source->height - 1)}
1001 };
1002 double minimum_x = INFINITY;
1003 double minimum_y = INFINITY;
1004 double maximum_x = -INFINITY;
1005 double maximum_y = -INFINITY;
1006 for (size_t index = 0; index < 4; index++) {
1007 double source_x;
1008 double source_y;
1009 if (!project_point(rotation, focal_length, center_x, center_y, fit->ray_scale,
1010 corners[index][0], corners[index][1], &source_x, &source_y)) {
1011 errno = ERANGE;
1012 return -1;
1013 }
1014 minimum_x = fmin(minimum_x, source_x);
1015 minimum_y = fmin(minimum_y, source_y);
1016 maximum_x = fmax(maximum_x, source_x);
1017 maximum_y = fmax(maximum_y, source_y);
1018 }
1019
1020 double span_x = maximum_x - minimum_x;
1021 double span_y = maximum_y - minimum_y;
1022 if (span_x <= PROJECTION_EPSILON || span_y <= PROJECTION_EPSILON) {
1023 errno = ERANGE;
1024 return -1;
1025 }
1026
1027 double horizontal_fit = (double)(source->width - 1) / span_x;
1028 double vertical_fit = (double)(source->height - 1) / span_y;
1029 bool already_covered = minimum_x >= 0.0 && minimum_y >= 0.0
1030 && maximum_x <= (double)(source->width - 1)
1031 && maximum_y <= (double)(source->height - 1);
1032 if (already_covered && fit->ray_scale == 1.0) {
1033 fit->image_scale = 1.0;
1034 fit->offset_x = 0.0;
1035 fit->offset_y = 0.0;
1036 return 0;
1037 }
1038
1039 fit->image_scale = fmin(1.0, fmin(horizontal_fit, vertical_fit)) * COVER_SAFETY_FACTOR;
1040 fit->offset_x = center_x - fit->image_scale * (minimum_x + maximum_x) / 2.0;
1041 fit->offset_y = center_y - fit->image_scale * (minimum_y + maximum_y) / 2.0;
1042 return 0;
1043}
1044
1045/**
1046 * @brief Sample the RGB raster at an in-bounds fractional position.
1047 * @param image Source RGB raster.
1048 * @param source_x Fractional pixel column in the valid raster range.
1049 * @param source_y Fractional pixel row in the valid raster range.
1050 * @param[out] output Three-byte RGB sample.
1051 * @details Interpolate channel values along each axis and collapse the
1052 * neighbor to the edge pixel on the last row or column.
1053 */
1054static void bilinear_sample_rgb(const struct decoded_image *image, double source_x,
1055 double source_y, unsigned char output[JPEG_COMPONENTS])
1056{
1057 size_t left = (size_t)floor(source_x);
1058 size_t top = (size_t)floor(source_y);
1059 size_t right = left + 1 < image->width ? left + 1 : left;
1060 size_t bottom = top + 1 < image->height ? top + 1 : top;
1061 double horizontal = source_x - (double)left;
1062 double vertical = source_y - (double)top;
1063
1064 size_t top_left = (top * image->width + left) * JPEG_COMPONENTS;
1065 size_t top_right = (top * image->width + right) * JPEG_COMPONENTS;
1066 size_t bottom_left = (bottom * image->width + left) * JPEG_COMPONENTS;
1067 size_t bottom_right = (bottom * image->width + right) * JPEG_COMPONENTS;
1068 for (size_t component = 0; component < JPEG_COMPONENTS; component++) {
1069 double top_value = image->pixels[top_left + component] * (1.0 - horizontal)
1070 + image->pixels[top_right + component] * horizontal;
1071 double bottom_value = image->pixels[bottom_left + component] * (1.0 - horizontal)
1072 + image->pixels[bottom_right + component] * horizontal;
1073 double value = top_value * (1.0 - vertical) + bottom_value * vertical;
1074 output[component] = (unsigned char)(value + 0.5);
1075 }
1076}
1077
1078/**
1079 * @brief Publish a complete simulated JPEG in place of its fixture.
1080 * @param filename Final JPEG path.
1081 * @param image RGB raster to encode.
1082 * @return Zero on replacement, or -1 on an encode or filesystem error.
1083 * @details Encode under a temporary sibling name so readers of the final
1084 * path do not see a partially written JPEG.
1085 */
1086static int replace_image_atomically(const char *filename, const struct decoded_image *image)
1087{
1088 struct stat original_status = {.st_mode = 0644};
1089 if (stat(filename, &original_status) != 0 && errno != ENOENT) {
1090 return -1;
1091 }
1092
1093 size_t filename_length = strlen(filename);
1094 const char suffix[] = ".transform.XXXXXX";
1095 char temporary_name[PATH_MAX];
1096 if (filename_length >= sizeof(temporary_name)
1097 || sizeof(suffix) > sizeof(temporary_name) - filename_length) {
1098 errno = ENAMETOOLONG;
1099 return -1;
1100 }
1101 int name_length = snprintf(temporary_name, sizeof(temporary_name), "%s%s", filename, suffix);
1102 if (name_length < 0 || (size_t)name_length >= sizeof(temporary_name)) {
1103 errno = ENAMETOOLONG;
1104 return -1;
1105 }
1106
1107 int temporary_fd = mkstemp(temporary_name);
1108 if (temporary_fd < 0) {
1109 return -1;
1110 }
1111 FILE *output = fdopen(temporary_fd, "wb");
1112 if (output == NULL) {
1113 close(temporary_fd);
1114 unlink(temporary_name);
1115 return -1;
1116 }
1117
1119 if (result == 0 && fflush(output) != 0) {
1120 result = -1;
1121 }
1122 if (result == 0 && fsync(temporary_fd) != 0) {
1123 result = -1;
1124 }
1125 if (result == 0 && fchmod(temporary_fd, original_status.st_mode & 0777) != 0) {
1126 result = -1;
1127 }
1128 if (fclose(output) != 0) {
1129 result = -1;
1130 }
1131 if (result == 0 && rename(temporary_name, filename) != 0) {
1132 result = -1;
1133 }
1134 if (result != 0) {
1135 unlink(temporary_name);
1136 fprintf(stderr, "MOCK_TRANSFORM:\tfailed to replace %s: %s\n", filename, strerror(errno));
1137 }
1138 return result;
1139}
static double latitude
void(* close)(struct usbfs_handle *)
Definition chdkbridge.c:57
#define ANGLE_BFP_SCALE
#define POSITION_BFP_SCALE
#define RAD_TO_DEG
Definition ear_fusion.c:35
#define JPEG_QUALITY
#define SPEED_BFP_SCALE
Definition image_exif.c:49
#define IMAGE_MOCK_MAX_DIMENSION
#define near_horizon_pitch_deg
static struct image_mock_workspace workspace
#define PROJECTION_MIN_RAY_SCALE
static void build_rotation(double roll_rad, double pitch_rad, double yaw_rad, double rotation[3][3])
Construct the body-to-north/east/down attitude rotation.
#define PROJECTION_REFINE_STEPS
static int read_jpeg_dimensions(FILE *input, struct decoded_image *image)
Read bounded image dimensions without decoding pixels.
static void transform_jpeg_message(j_common_ptr state, int level)
Check marker bounds before forwarding a libjpeg diagnostic.
static int replace_image_atomically(const char *filename, const struct decoded_image *image)
Publish a complete simulated JPEG in place of its fixture.
#define PROJECTION_EPSILON
static bool is_near_horizon(double roll_rad, double pitch_rad)
Apply both axis-specific and combined near-horizon limits.
#define FOCAL_LENGTH_FACTOR
static int image_mock_map_locked(const char *filename, const char *cache_directory, const union dc_shot_union *shot, size_t width, size_t height, double horizontal_fov_deg, double vertical_fov_deg)
Render a simulated camera view from cached map tiles.
int image_mock_map(const char *filename, const char *cache_directory, const union dc_shot_union *shot, size_t width, size_t height, double horizontal_fov_deg, double vertical_fov_deg)
Render a map-backed simulated exposure.
#define COVER_SAFETY_FACTOR
static int compute_projection_fit(const struct decoded_image *source, double rotation[3][3], double focal_length, double center_x, double center_y, struct projection_fit *fit)
Find a fitted projection with low effective zoom.
#define near_horizon_roll_deg
#define MAP_MOSAIC_CAPACITY
int image_mock_transform(const char *filename, const union dc_shot_union *shot)
Rewrite a local test JPEG to simulate the shot attitude.
static int image_mock_transform_locked(const char *filename, const union dc_shot_union *shot)
Apply simulated attitude to the existing fixture JPEG.
#define near_horizon_combined_tilt_deg
#define PROJECTION_FOV_SAMPLES
static bool projection_corners_valid(const struct decoded_image *source, double rotation[3][3], double focal_length, double center_x, double center_y, double ray_scale)
Check for a horizon crossing in the candidate projection.
#define MAP_TILE_SIZE
static bool dimensions_fit(size_t width, size_t height)
Check that an image can fit the bounded RGB workspace.
static bool project_point(double rotation[3][3], double focal_length, double center_x, double center_y, double ray_scale, double destination_x, double destination_y, double *source_x, double *source_y)
Map a destination pixel back into the fixture JPEG.
#define IMAGE_MOCK_RGB_CAPACITY
static int transform_pixels(const struct decoded_image *source, struct decoded_image *destination, double roll_rad, double pitch_rad, double yaw_rad, bool synthesize_terrain)
Resample a fixture into a camera view at the supplied attitude.
#define IMAGE_MOCK_MAX_PIXELS
#define PROJECTION_MIN_DEPTH
#define JPEG_COMPONENTS
#define near_horizon_case_black
static void bilinear_sample_rgb(const struct decoded_image *image, double source_x, double source_y, unsigned char output[JPEG_COMPONENTS])
Sample the RGB raster at an in-bounds fractional position.
static void transform_jpeg_error_exit(j_common_ptr jpeg_info)
Redirect a fatal libjpeg error to the active codec operation.
static bool map_project(double rotation[3][3], double forward, double right, double altitude_pixels, double center_x, double center_y, double *map_x, double *map_y)
Intersect a camera ray with a local flat ground plane.
static double mirror_coordinate(double coordinate, size_t extent)
Reflect a sample coordinate into the source image.
static pthread_mutex_t workspace_mutex
static int encode_jpeg(FILE *output, const struct decoded_image *image)
Encode a bounded interleaved RGB image at the simulation quality setting.
static int decode_jpeg(FILE *input, struct decoded_image *image)
Decode bounded RGB scanlines from an open JPEG stream.
static int compute_projection_fit_at_scale(const struct decoded_image *source, double rotation[3][3], double focal_length, double center_x, double center_y, double ray_scale, struct projection_fit *fit)
Fit one projected destination rectangle into the source raster.
static int create_black_frame(const char *filename)
Replace the fixture with a black JPEG of the same dimensions.
Local-simulation JPEG attitude transform API.
#define IMAGE_MOCK_TRANSFORM_SKIPPED
Successful result: transform was intentionally skipped for a near-horizon attitude.
#define IMAGE_MOCK_TRANSFORM_APPLIED
Successful result: the JPEG was rewritten with the simulated attitude transform.
Reject invalid Huffman selectors before the bundled codec indexes its tables.
static void usher_jpeg_validate_marker(j_common_ptr state)
Validate marker parameters from an error manager's emit_message callback.
struct jpeg_compress_struct encoder
Definition lwir_image.c:59
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
struct jpeg_error_mgr error
Definition lwir_image.c:60
struct jpeg_decompress_struct decoder
Definition lwir_mock.c:55
#define PATH_MAX
Definition path_utils.h:39
static FILE * output
Definition pose_log.c:77
unsigned char * pixels
struct jpeg_compress_struct encoder
struct transform_jpeg_error encode_error
unsigned char destination[IMAGE_MOCK_RGB_CAPACITY]
struct transform_jpeg_error decode_error
struct jpeg_decompress_struct decoder
unsigned char source[IMAGE_MOCK_RGB_CAPACITY]
unsigned char mosaic[MAP_MOSAIC_CAPACITY]
void(* emit)(j_common_ptr, int)
struct jpeg_error_mgr manager
struct usher_control_result result
Definition usher.c:377
struct captured_image image
Definition usher.c:371
union dc_shot_union shot
Definition usher.c:534