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
jpeg_encoder.h
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 jpeg_encoder.h
20 * @brief Encode BGRA map pixels and publish JPEGs with optional EXIF.
21 * @details The encoder owns and reuses its IJG workspace to avoid a new
22 * large output allocation for every tile. EXIF is inserted into the compressed
23 * stream, preserving encoded image bytes rather than decoding and encoding the
24 * pixels a second time.
25 */
26#ifndef PANGEA_JPEG_ENCODER_H
27#define PANGEA_JPEG_ENCODER_H
28
29#include "exifite.h"
30#include "map_storage.h"
31#include <algorithm>
32#include <csetjmp>
33#include <cstdio>
34#include <jpeglib.h>
35#include <jerror.h>
36#include <filesystem>
37#include <fstream>
38#include <iostream>
39#include <limits>
40#include <stdexcept>
41#include <string>
42#include <vector>
43
44/**
45 * @brief Reusable IJG compressor and JPEG publisher.
46 * @details Instances are stateful and are not safe for concurrent calls; create
47 * one per worker when tiles are encoded in parallel.
48 */
50 struct Error {
51 jpeg_error_mgr manager{};
52 std::jmp_buf recovery;
53 char message[JMSG_LENGTH_MAX]{};
55 jpeg_compress_struct compressor_{};
56 jpeg_destination_mgr destination_{};
57 std::vector<unsigned char> buffer_;
58 std::vector<unsigned char> row_;
59 std::size_t size_ = 0;
60 std::size_t limit_ = 0;
61
62 /** @brief Save the codec diagnostic and transfer control to recovery.
63 * @param codec Compressor carrying the installed error manager.
64 * @details Convert to a C++ exception at the recovery site, not in this callback. */
65 static void failure(j_common_ptr codec) {
66 auto& error = *reinterpret_cast<Error*>(codec->err);
67 codec->err->format_message(codec, error.message);
68 std::longjmp(error.recovery, 1);
69 }
70 /** @brief Point the codec at reusable compressed-output storage.
71 * @param codec Compressor whose client data identifies the encoder.
72 * @details Cap the writable span at the current operation limit even
73 * when a previous call allocated a larger buffer. */
74 static void startOutput(j_compress_ptr codec) {
75 auto& encoder = *static_cast<JpegEncoder*>(codec->client_data);
76 codec->dest->next_output_byte = encoder.buffer_.data();
77 codec->dest->free_in_buffer = std::min(encoder.buffer_.size(), encoder.limit_);
78 }
79 /** @brief Grow compressed storage without exceeding the operation limit.
80 * @param codec Compressor that filled its destination span.
81 * @return TRUE once more room is available; failures take codec recovery.
82 * @details Resume writing at the consumed offset after resize, because
83 * vector growth can invalidate the codec's previous output pointer. */
84 static boolean growOutput(j_compress_ptr codec) {
85 auto& encoder = *static_cast<JpegEncoder*>(codec->client_data);
86 const std::size_t used = std::min(encoder.buffer_.size(), encoder.limit_);
87 if (used >= encoder.limit_) ERREXIT(codec, JERR_BUFFER_SIZE);
88 bool resized = true;
89 try {
90 encoder.buffer_.resize(std::min(encoder.limit_, encoder.buffer_.size() * 2));
91 } catch (const std::exception&) {
92 resized = false;
93 }
94 if (!resized) ERREXIT1(codec, JERR_OUT_OF_MEMORY, 0);
95 codec->dest->next_output_byte = encoder.buffer_.data() + used;
96 codec->dest->free_in_buffer = encoder.buffer_.size() - used;
97 return TRUE;
98 }
99 /** @brief Record the compressed byte count, excluding unused buffer space.
100 * @param codec Compressor supplying the remaining destination bytes. */
101 static void finishOutput(j_compress_ptr codec) {
102 auto& encoder = *static_cast<JpegEncoder*>(codec->client_data);
103 encoder.size_ = std::min(encoder.buffer_.size(), encoder.limit_) - codec->dest->free_in_buffer;
104 }
105public:
106 /** @brief Borrowed view of a JPEG held in this encoder's reusable buffer. */
107 struct Image {
108 const unsigned char* data;
109 std::size_t size;
110 };
111
112 /** @brief Create a compressor; throws if the codec cannot be initialized. */
114 compressor_.err = jpeg_std_error(&error_.manager);
115 error_.manager.error_exit = failure;
116 if (setjmp(error_.recovery)) {
117 jpeg_destroy_compress(&compressor_);
118 throw std::runtime_error(std::string("Create IJG encoder: ") + error_.message);
119 }
120 jpeg_create_compress(&compressor_);
121 compressor_.client_data = this;
122 destination_.init_destination = startOutput;
123 destination_.empty_output_buffer = growOutput;
124 destination_.term_destination = finishOutput;
126 }
127 /** @brief Release the compressor and invalidate any borrowed JPEG view. */
128 ~JpegEncoder() { jpeg_destroy_compress(&compressor_); }
129 /** @brief Noncopyable: the compressor stores a pointer to its encoder owner. */
130 JpegEncoder(const JpegEncoder&) = delete;
131 /** @brief Nonassignable: codec and destination state must remain paired. */
133
134 /**
135 * @brief Encode one BGRA image using the configured JPEG quality.
136 * @param[in] bgra Top-left pixel of the source image.
137 * @param[in] width Image width in pixels.
138 * @param[in] height Image height in pixels.
139 * @param[in] stride Source row stride in bytes.
140 * @param[in] quality JPEG quality from 1 through 100.
141 * @return JPEG bytes borrowed from this encoder; the next encode may replace them.
142 * @throws std::runtime_error If dimensions, quality, or codec processing is invalid.
143 */
144 Image encode(const unsigned char* bgra, int width, int height, int stride, int quality) {
145 if (!bgra || width <= 0 || height <= 0 || width > 16384 || height > 16384 ||
146 stride < width * 4 || quality < 1 || quality > 100)
147 throw std::runtime_error("Invalid BGRA dimensions, stride or JPEG quality");
148 row_.resize(static_cast<std::size_t>(width) * 3);
149 if (buffer_.empty()) buffer_.resize(4096);
150 limit_ = static_cast<std::size_t>(width) * height * 6 + 65536;
151 size_ = 0;
152 if (setjmp(error_.recovery)) {
153 jpeg_abort_compress(&compressor_);
154 throw std::runtime_error(std::string("Compress BGRA image to JPEG: ") + error_.message);
155 }
156 compressor_.image_width = static_cast<JDIMENSION>(width);
157 compressor_.image_height = static_cast<JDIMENSION>(height);
158 compressor_.input_components = 3;
159 compressor_.in_color_space = JCS_RGB;
160 jpeg_set_defaults(&compressor_);
161 if (quality > 90) {
162 for (int component = 0; component < compressor_.num_components; ++component) {
163 compressor_.comp_info[component].h_samp_factor = 1;
164 compressor_.comp_info[component].v_samp_factor = 1;
165 }
166 }
167 jpeg_set_quality(&compressor_, quality, TRUE);
168 jpeg_start_compress(&compressor_, TRUE);
169 while (compressor_.next_scanline < compressor_.image_height) {
170 const auto* source = bgra + static_cast<std::size_t>(compressor_.next_scanline) * stride;
171 for (int column = 0; column < width; ++column) {
172 row_[column * 3] = source[column * 4 + 2];
173 row_[column * 3 + 1] = source[column * 4 + 1];
174 row_[column * 3 + 2] = source[column * 4];
175 }
176 JSAMPROW pixels = row_.data();
177 jpeg_write_scanlines(&compressor_, &pixels, 1);
178 }
179 jpeg_finish_compress(&compressor_);
180 return {buffer_.data(), size_};
181 }
182
183 /**
184 * @brief Publish encoded JPEG bytes, optionally adding one EXIF APP1 segment.
185 * @param[in] image Encoded JPEG view returned by @ref encode.
186 * @param[in] path New destination path; the caller controls overwrite policy.
187 * @param[in] exif Serialized EXIF payload, or null when no metadata is added.
188 * @param[in] exifSize EXIF payload size in bytes.
189 * @param[in] durable Whether to use the fsync-backed working-file publisher.
190 * @throws std::runtime_error If JPEG framing, EXIF, or file publication fails.
191 */
192 static void save(const Image& image, const std::filesystem::path& path,
193 const unsigned char* exif = nullptr, std::size_t exifSize = 0, bool durable = false) {
194 if (!image.data || image.size < 4 || image.size > static_cast<std::size_t>(std::numeric_limits<std::streamsize>::max()) ||
195 image.data[0] != 0xff || image.data[1] != 0xd8 ||
196 image.data[image.size - 2] != 0xff || image.data[image.size - 1] != 0xd9)
197 throw std::runtime_error("Invalid encoded JPEG view");
198 std::size_t headerSize = 0;
199 if (exif || exifSize) {
200 exif_view view{};
201 if (exif_parse(&view, exif, exifSize) != 0)
202 throw std::runtime_error("Invalid EXIF payload for JPEG");
203 headerSize = 2;
204 // Preserve leading JFIF/APP0 markers before the new EXIF APP1.
205 while (image.size - headerSize >= 2 && image.data[headerSize] == 0xff &&
206 image.data[headerSize + 1] == 0xe0) {
207 if (image.size - headerSize < 4)
208 throw std::runtime_error("Truncated JPEG APP0 header");
209 const std::size_t length = image.data[headerSize + 2] * 256 + image.data[headerSize + 3];
210 if (length < 2 || length > image.size - headerSize - 2)
211 throw std::runtime_error("Invalid JPEG APP0 length");
212 headerSize += length + 2;
213 }
214 }
215 const std::filesystem::path temporary = path.string() + ".partial";
216 try {
217 std::ofstream output(temporary, std::ios::binary);
218 if (!output) throw std::runtime_error("Cannot create JPEG: " + temporary.u8string());
219 if (exif) {
220 output.write(reinterpret_cast<const char*>(image.data), static_cast<std::streamsize>(headerSize));
221 const unsigned char marker[] = {0xff, 0xe1, static_cast<unsigned char>((exifSize + 2) >> 8),
222 static_cast<unsigned char>(exifSize + 2)};
223 output.write(reinterpret_cast<const char*>(marker), sizeof(marker));
224 output.write(reinterpret_cast<const char*>(exif), static_cast<std::streamsize>(exifSize));
225 }
226 output.write(reinterpret_cast<const char*>(image.data + headerSize),
227 static_cast<std::streamsize>(image.size - headerSize));
228 output.close();
229 if (!output) throw std::runtime_error("Failed writing JPEG: " + temporary.u8string());
230 std::error_code ec;
231 if (durable) pangea_survey::publishWorkingFile(temporary, path);
232 else std::filesystem::rename(temporary, path, ec);
233 if (ec)
234 throw std::runtime_error("Finalize JPEG failed: " + ec.message());
235 } catch (...) {
236 std::error_code error;
237 std::filesystem::remove(temporary, error);
238 if (error) std::cerr << "WARNING: Cannot remove partial JPEG: " << error.message() << "\n";
239 throw;
240 }
241 }
242};
243#endif
static boolean growOutput(j_compress_ptr codec)
Grow compressed storage without exceeding the operation limit.
Image encode(const unsigned char *bgra, int width, int height, int stride, int quality)
Encode one BGRA image using the configured JPEG quality.
std::vector< unsigned char > buffer_
JpegEncoder(const JpegEncoder &)=delete
Noncopyable: the compressor stores a pointer to its encoder owner.
~JpegEncoder()
Release the compressor and invalidate any borrowed JPEG view.
std::size_t size_
struct JpegEncoder::Error error_
std::vector< unsigned char > row_
jpeg_compress_struct compressor_
jpeg_destination_mgr destination_
static void startOutput(j_compress_ptr codec)
Point the codec at reusable compressed-output storage.
static void failure(j_common_ptr codec)
Save the codec diagnostic and transfer control to recovery.
static void finishOutput(j_compress_ptr codec)
Record the compressed byte count, excluding unused buffer space.
JpegEncoder & operator=(const JpegEncoder &)=delete
Nonassignable: codec and destination state must remain paired.
JpegEncoder()
Create a compressor; throws if the codec cannot be initialized.
static void save(const Image &image, const std::filesystem::path &path, const unsigned char *exif=nullptr, std::size_t exifSize=0, bool durable=false)
Publish encoded JPEG bytes, optionally adding one EXIF APP1 segment.
std::size_t limit_
Bounded C11 EXIF metadata and JPEG streaming interfaces.
int exif_parse(struct exif_view *view, const unsigned char *payload, size_t size)
Validate an EXIF APP1 payload and create a borrowed view.
Definition exifite.c:257
struct exif_document exif
Definition lwir_image.c:64
struct jpeg_compress_struct encoder
Definition lwir_image.c:59
uint8_t marker[LWIR_THERMAL_HEADER_BYTES+LWIR_THERMAL_CHUNK_CAPACITY]
Definition lwir_image.c:62
struct jpeg_error_mgr error
Definition lwir_image.c:60
Integrity checks and bounded disk-backed intermediates for surveys.
void publishWorkingFile(const std::filesystem::path &temporary, const std::filesystem::path &target, bool replace=true)
Fsync a completed working file, rename it, then sync its directory.
static FILE * output
Definition pose_log.c:77
jpeg_error_mgr manager
char message[JMSG_LENGTH_MAX]
std::jmp_buf recovery
Borrowed view of a JPEG held in this encoder's reusable buffer.
const unsigned char * data
Borrowed view of a validated APP1 payload.
Definition exifite.h:131
struct captured_image image
Definition usher.c:371