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_stream.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_stream.h
20 * @brief Decode JPEGs with IJG scanlines into BGRA previews or disk-backed rasters.
21 * @details Streaming one scanline at a time avoids retaining both the
22 * compressed source and a full decoded frame in memory. The working raster is
23 * an internal lossless intermediate. Its bounded raster path rejects
24 * progressive JPEGs; preview decoding retains the codec's progressive support.
25 */
26#ifndef PANGEA_JPEG_STREAM_H
27#define PANGEA_JPEG_STREAM_H
28
29#include "map_storage.h"
30#include "jpeg_marker_guard.h"
31#include <algorithm>
32#include <cstdio>
33#include <csetjmp>
34#include <jpeglib.h>
35#include <jerror.h>
36#include <memory>
37#include <functional>
38#include <vector>
39#include <utility>
40
41namespace pangea_survey {
42/** @brief Apply the shared JPEG marker bounds to the current decoder state.
43 * @param state Decoder reporting the marker. */
44inline void validateJpegScanMessage(j_common_ptr state) {
46}
47/**
48 * @brief Convert one baseline JPEG into a row-major BGRA working raster.
49 * @details Instances own decoder state and a reusable scanline buffer and must
50 * not be shared across concurrent decodes.
51 */
53 struct Error {
54 jpeg_error_mgr manager{};
55 std::jmp_buf recovery;
56 char message[JMSG_LENGTH_MAX]{};
57 void (*emit)(j_common_ptr, int) = nullptr;
59 jpeg_decompress_struct decoder_{};
60 FILE* input_ = nullptr;
61 bool created_ = false;
62 std::vector<unsigned char> row_;
63 std::unique_ptr<std::ofstream> output_;
64 /** @brief Preserve the codec diagnostic and jump to the decode recovery point.
65 * @param state Decoder carrying this instance's error manager.
66 * @details The outer operation owns cleanup and C++ exception translation. */
67 static void failure(j_common_ptr state) {
68 auto* error = reinterpret_cast<Error*>(state->err);
69 state->err->format_message(state, error->message);
70 std::longjmp(error->recovery, 1);
71 }
72 /** @brief Check markers before forwarding the codec diagnostic.
73 * @param state Decoder carrying the saved diagnostic handler.
74 * @param level libjpeg diagnostic level. */
75 static void message(j_common_ptr state, int level) {
77 reinterpret_cast<Error*>(state->err)->emit(state, level);
78 }
79 /** @brief Release per-decode state while retaining reusable pixel storage.
80 * @details Clear the creation flag and stream pointers so repeated cleanup
81 * after an error is safe. */
82 void reset() noexcept {
83 if (created_) jpeg_destroy_decompress(&decoder_);
84 created_ = false;
85 decoder_ = {};
86 if (input_) fclose(input_);
87 input_ = nullptr;
88 output_.reset();
89 }
90 struct Operation {
92 /** @brief Release the streams and codec on every operation exit. */
93 ~Operation() { owner.reset(); }
94 };
95public:
96 /** @brief Decoded preview and its scale relative to the source camera image. */
97 struct Image {
98 int width = 0;
99 int height = 0;
100 double scale = 1;
101 std::vector<unsigned char> pixels;
102 };
103private:
105public:
106 /** @brief Construct an idle decoder; files are opened per operation. */
107 JpegStream() = default;
108 /** @brief Release any remaining codec and stream resources. */
110 /** @brief Noncopyable: the decoder and streams have a single owner. */
111 JpegStream(const JpegStream&) = delete;
112 /** @brief Nonassignable: active streams and recovery state cannot be copied. */
113 JpegStream& operator=(const JpegStream&) = delete;
114 /** @brief Read a JPEG preview without retaining the compressed file in memory.
115 * @param source JPEG path with dimensions matching its capture metadata.
116 * @param width Expected full-resolution width.
117 * @param height Expected full-resolution height.
118 * @param maxSide Preferred longest decoded side, or zero for full resolution.
119 * @return Owned BGRA pixels and the decoder's intrinsic scaling ratio.
120 * @throws std::runtime_error For damaged JPEGs, invalid dimensions or I/O errors. */
121 Image read(const std::filesystem::path& source, int width, int height, int maxSide) {
122 reset();
123 const Operation operation{*this};
124 const auto bytes = std::filesystem::file_size(source);
125 if (!bytes || bytes > 128 * 1024 * 1024 || width <= 0 || height <= 0 ||
126 width > 16384 || height > 16384 || maxSide < 0)
127 throw std::runtime_error("Invalid source JPEG size or dimensions");
128 input_ = fopen(source.c_str(), "rb");
129 if (!input_) throw std::runtime_error("Cannot open source JPEG");
130 decoder_.err = jpeg_std_error(&error_.manager);
131 error_.manager.error_exit = failure;
132 error_.emit = error_.manager.emit_message;
133 error_.manager.emit_message = message;
134 if (setjmp(error_.recovery)) throw std::runtime_error(std::string("JPEG decode: ") + error_.message);
135 created_ = true; jpeg_create_decompress(&decoder_);
136 jpeg_stdio_src(&decoder_, input_);
137 jpeg_read_header(&decoder_, TRUE);
138 if (decoder_.image_width != static_cast<unsigned>(width) ||
139 decoder_.image_height != static_cast<unsigned>(height))
140 throw std::runtime_error("Source JPEG dimensions disagree with capture CSV");
141 decoder_.scale_denom = 8;
142 for (unsigned numerator = 8; numerator > 0; --numerator) {
143 decoder_.scale_num = numerator;
144 jpeg_calc_output_dimensions(&decoder_);
145 if (!maxSide || std::max(decoder_.output_width, decoder_.output_height) <= static_cast<unsigned>(maxSide) || numerator == 1)
146 break;
147 }
148 decoder_.out_color_space = JCS_RGB;
149 jpeg_start_decompress(&decoder_);
150 image_.width = static_cast<int>(decoder_.output_width);
151 image_.height = static_cast<int>(decoder_.output_height);
152 image_.scale = double(decoder_.scale_num) / decoder_.scale_denom;
153 image_.pixels.resize(static_cast<std::size_t>(image_.width) * image_.height * 4);
154 row_.resize(static_cast<std::size_t>(image_.width) * 3);
155 while (decoder_.output_scanline < decoder_.output_height) {
156 const auto row = decoder_.output_scanline;
157 JSAMPROW pixels = row_.data();
158 if (jpeg_read_scanlines(&decoder_, &pixels, 1) != 1)
159 throw std::runtime_error("Incomplete JPEG scanline");
160 auto* destination = image_.pixels.data() + static_cast<std::size_t>(row) * image_.width * 4;
161 for (int column = 0; column < image_.width; ++column) {
162 destination[column * 4] = row_[column * 3 + 2];
163 destination[column * 4 + 1] = row_[column * 3 + 1];
164 destination[column * 4 + 2] = row_[column * 3];
165 destination[column * 4 + 3] = 255;
166 }
167 }
168 jpeg_finish_decompress(&decoder_);
169 if (decoder_.err->num_warnings) throw std::runtime_error("Damaged source JPEG");
170 return std::move(image_);
171 }
172 /**
173 * @brief Stream a source JPEG into a new, atomically published raster file.
174 * @param[in] source Input baseline JPEG path.
175 * @param[in] target Destination raster path; existing files are not replaced.
176 * @param[in] width Expected source width in pixels.
177 * @param[in] height Expected source height in pixels.
178 * @param[in] stopped Cooperative cancellation predicate.
179 * @throws std::runtime_error For invalid dimensions, decode/write errors,
180 * damaged JPEG data, or cancellation.
181 */
182 void decode(const std::filesystem::path& source, const std::filesystem::path& target,
183 int width, int height, const std::function<bool()>& stopped) {
184 reset();
185 const Operation operation{*this};
186 if (width <= 0 || height <= 0 || width > 8192 || height > 8192)
187 throw std::runtime_error("Invalid streamed JPEG dimensions");
188 if (std::filesystem::exists(target)) throw std::runtime_error("Working raster already exists");
189 input_ = fopen(source.c_str(), "rb");
190 if (!input_) throw std::runtime_error("Cannot open JPEG for streamed decoding");
191 const auto temporary = target.string() + ".partial";
192 output_ = std::make_unique<std::ofstream>(temporary, std::ios::binary | std::ios::trunc);
193 if (!*output_) throw std::runtime_error("Cannot create working raster");
194 row_.resize(static_cast<std::size_t>(width) * 4);
195 decoder_.err = jpeg_std_error(&error_.manager);
196 error_.manager.error_exit = failure;
197 error_.emit = error_.manager.emit_message;
198 error_.manager.emit_message = message;
199 if (setjmp(error_.recovery)) throw std::runtime_error(std::string("JPEG decode: ") + error_.message);
200 created_ = true; jpeg_create_decompress(&decoder_);
201 jpeg_stdio_src(&decoder_, input_);
202 jpeg_read_header(&decoder_, TRUE);
203 if (decoder_.image_width != static_cast<unsigned>(width) ||
204 decoder_.image_height != static_cast<unsigned>(height) || decoder_.progressive_mode)
205 throw std::runtime_error("Streamed JPEG requires matching dimensions and baseline encoding");
206 decoder_.out_color_space = JCS_RGB;
207 jpeg_start_decompress(&decoder_);
208 while (decoder_.output_scanline < decoder_.output_height) {
209 if (stopped && stopped()) throw std::runtime_error("Streamed source preparation canceled");
210 JSAMPROW pixels = row_.data();
211 if (jpeg_read_scanlines(&decoder_, &pixels, 1) != 1)
212 throw std::runtime_error("Incomplete JPEG scanline");
213 for (std::size_t pixel = static_cast<std::size_t>(width); pixel > 0; --pixel) {
214 const std::size_t source = (pixel - 1) * 3;
215 const std::size_t destination = (pixel - 1) * 4;
216 const unsigned char red = row_[source];
217 const unsigned char green = row_[source + 1];
218 const unsigned char blue = row_[source + 2];
219 row_[destination] = blue;
220 row_[destination + 1] = green;
221 row_[destination + 2] = red;
222 row_[destination + 3] = 255;
223 }
224 output_->write(reinterpret_cast<const char*>(row_.data()), static_cast<std::streamsize>(row_.size()));
225 if (!*output_) throw std::runtime_error("Cannot write working raster");
226 }
227 jpeg_finish_decompress(&decoder_); output_->close();
228 if (!*output_ || decoder_.err->num_warnings) throw std::runtime_error("Damaged JPEG or working raster write");
229 publishWorkingFile(temporary, target, false);
230 }
231};
232}
233#endif
uint8_t bytes[CHDK_CONTROL_REPLY_SIZE]
Definition chdk_pipe.c:144
static void message(j_common_ptr state, int level)
Check markers before forwarding the codec diagnostic.
Definition jpeg_stream.h:75
~JpegStream()
Release any remaining codec and stream resources.
std::vector< unsigned char > row_
Definition jpeg_stream.h:62
struct pangea_survey::JpegStream::Error error_
static void failure(j_common_ptr state)
Preserve the codec diagnostic and jump to the decode recovery point.
Definition jpeg_stream.h:67
Image read(const std::filesystem::path &source, int width, int height, int maxSide)
Read a JPEG preview without retaining the compressed file in memory.
JpegStream(const JpegStream &)=delete
Noncopyable: the decoder and streams have a single owner.
JpegStream()=default
Construct an idle decoder; files are opened per operation.
jpeg_decompress_struct decoder_
Definition jpeg_stream.h:59
void decode(const std::filesystem::path &source, const std::filesystem::path &target, int width, int height, const std::function< bool()> &stopped)
Stream a source JPEG into a new, atomically published raster file.
JpegStream & operator=(const JpegStream &)=delete
Nonassignable: active streams and recovery state cannot be copied.
std::unique_ptr< std::ofstream > output_
Definition jpeg_stream.h:63
void reset() noexcept
Release per-decode state while retaining reusable pixel storage.
Definition jpeg_stream.h:82
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.
uint8_t row[LWIR_MAX_WIDTH *3U]
Definition lwir_image.c:63
struct jpeg_error_mgr error
Definition lwir_image.c:60
Integrity checks and bounded disk-backed intermediates for surveys.
void validateJpegScanMessage(j_common_ptr state)
Apply the shared JPEG marker bounds to the current decoder state.
Definition jpeg_stream.h:44
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.
char message[JMSG_LENGTH_MAX]
Definition jpeg_stream.h:56
void(* emit)(j_common_ptr, int)
Definition jpeg_stream.h:57
Decoded preview and its scale relative to the source camera image.
Definition jpeg_stream.h:97
std::vector< unsigned char > pixels
~Operation()
Release the streams and codec on every operation exit.
Definition jpeg_stream.h:93