26#ifndef PANGEA_JPEG_ENCODER_H
27#define PANGEA_JPEG_ENCODER_H
58 std::vector<unsigned char>
row_;
66 auto&
error = *
reinterpret_cast<Error*
>(codec->err);
67 codec->err->format_message(codec,
error.message);
68 std::longjmp(
error.recovery, 1);
76 codec->dest->next_output_byte =
encoder.buffer_.data();
77 codec->dest->free_in_buffer = std::min(
encoder.buffer_.size(),
encoder.limit_);
86 const std::size_t used = std::min(
encoder.buffer_.size(),
encoder.limit_);
87 if (used >=
encoder.limit_) ERREXIT(codec, JERR_BUFFER_SIZE);
91 }
catch (
const std::exception&) {
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;
116 if (setjmp(
error_.recovery)) {
118 throw std::runtime_error(std::string(
"Create IJG encoder: ") +
error_.message);
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);
150 limit_ =
static_cast<std::size_t
>(width) * height * 6 + 65536;
152 if (setjmp(
error_.recovery)) {
154 throw std::runtime_error(std::string(
"Compress BGRA image to JPEG: ") +
error_.message);
156 compressor_.image_width =
static_cast<JDIMENSION
>(width);
157 compressor_.image_height =
static_cast<JDIMENSION
>(height);
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;
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];
176 JSAMPROW pixels =
row_.data();
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 ||
197 throw std::runtime_error(
"Invalid encoded JPEG view");
198 std::size_t headerSize = 0;
199 if (
exif || exifSize) {
202 throw std::runtime_error(
"Invalid EXIF payload for JPEG");
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;
215 const std::filesystem::path temporary = path.string() +
".partial";
217 std::ofstream
output(temporary, std::ios::binary);
218 if (!
output)
throw std::runtime_error(
"Cannot create JPEG: " + temporary.u8string());
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)};
224 output.write(
reinterpret_cast<const char*
>(
exif),
static_cast<std::streamsize
>(exifSize));
226 output.write(
reinterpret_cast<const char*
>(
image.data + headerSize),
227 static_cast<std::streamsize
>(
image.size - headerSize));
229 if (!
output)
throw std::runtime_error(
"Failed writing JPEG: " + temporary.u8string());
232 else std::filesystem::rename(temporary, path, ec);
234 throw std::runtime_error(
"Finalize JPEG failed: " + ec.message());
236 std::error_code
error;
237 std::filesystem::remove(temporary,
error);
238 if (
error) std::cerr <<
"WARNING: Cannot remove partial JPEG: " <<
error.message() <<
"\n";
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.
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.
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.
struct exif_document exif
struct jpeg_compress_struct encoder
uint8_t marker[LWIR_THERMAL_HEADER_BYTES+LWIR_THERMAL_CHUNK_CAPACITY]
struct jpeg_error_mgr error
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.
char message[JMSG_LENGTH_MAX]
Borrowed view of a JPEG held in this encoder's reusable buffer.
const unsigned char * data
Borrowed view of a validated APP1 payload.
struct captured_image image