Debian Codegraph @

libs/img/src/CImage_JPEG_streams.cpp

raw
1 /* +------------------------------------------------------------------------+
2 | Mobile Robot Programming Toolkit (MRPT) |
3 | https://www.mrpt.org/ |
4 | |
5 | Copyright (c) 2005-2026, Individual contributors, see AUTHORS file |
6 | See: https://www.mrpt.org/Authors - All rights reserved. |
7 | Released under BSD License. See: https://www.mrpt.org/License |
8 +------------------------------------------------------------------------+ */
9
10 #include "img-precomp.h" // Precompiled headers
11 //
12 #include <mrpt/config.h>
13 #include <mrpt/img/CImage.h>
14 #include <mrpt/io/CStream.h>
15
16 #include "CImage_impl.h"
17
18 // Universal include for all versions of OpenCV
19 #include <mrpt/3rdparty/do_opencv_includes.h>
20
21 using namespace mrpt;
22 using namespace mrpt::img;
23
24 // ---------------------------------------------------------------------------------------
25 // START OF JPEG FUNCTIONS PART
26 // ---------------------------------------------------------------------------------------
27 /* Expanded data destination object for stdio output */
28
29 //#undef INT32
30 #undef FAR
31 #define XMD_H
32
33 using mrpt::io::CStream;
34
35 #if MRPT_HAS_JPEG
36 #include <jpeglib.h>
37
38 #include <cstdio>
39 #define mrpt_jpeg_source_mgr jpeg_source_mgr
40
41 typedef struct
42 {
43 struct jpeg_destination_mgr pub; /* public fields */
44
45 CStream* out; /* target stream */
46 JOCTET* buffer; /* start of buffer */
47 } mrpt_destination_mgr;
48
49 using mrpt_dest_ptr = mrpt_destination_mgr*;
50
51 #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
52
53 /*
54 * Initialize destination --- called by jpeg_start_compress
55 * before any data is actually written.
56 */
57
58 METHODDEF(void)
59 init_destination(j_compress_ptr cinfo)
60 {
61 auto dest = reinterpret_cast<mrpt_dest_ptr>(cinfo->dest);
62
63 /* Allocate the output buffer --- it will be released when done with image
64 */
65 dest->buffer = reinterpret_cast<JOCTET*>(((*cinfo->mem->alloc_small)(
66 reinterpret_cast<j_common_ptr>(cinfo), JPOOL_IMAGE, OUTPUT_BUF_SIZE * sizeof(JOCTET))));
67
68 dest->pub.next_output_byte = dest->buffer;
69 dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
70 }
71
72 /*
73 * Empty the output buffer --- called whenever buffer fills up.
74 *
75 * In typical applications, this should write the entire output buffer
76 * (ignoring the current state of next_output_byte & free_in_buffer),
77 * reset the pointer & count to the start of the buffer, and return TRUE
78 * indicating that the buffer has been dumped.
79 *
80 * In applications that need to be able to suspend compression due to output
81 * overrun, a FALSE return indicates that the buffer cannot be emptied now.
82 * In this situation, the compressor will return to its caller (possibly with
83 * an indication that it has not accepted all the supplied scanlines). The
84 * application should resume compression after it has made more room in the
85 * output buffer. Note that there are substantial restrictions on the use of
86 * suspension --- see the documentation.
87 *
88 * When suspending, the compressor will back up to a convenient restart point
89 * (typically the start of the current MCU). next_output_byte & free_in_buffer
90 * indicate where the restart point will be if the current call returns FALSE.
91 * Data beyond this point will be regenerated after resumption, so do not
92 * write it out when emptying the buffer externally.
93 */
94
95 METHODDEF(boolean)
96 empty_output_buffer(j_compress_ptr cinfo)
97 {
98 auto dest = (mrpt_dest_ptr)cinfo->dest;
99
100 dest->out->Write(dest->buffer, OUTPUT_BUF_SIZE);
101
102 dest->pub.next_output_byte = dest->buffer;
103 dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
104
105 return TRUE;
106 }
107
108 /*
109 * Terminate destination --- called by jpeg_finish_compress
110 * after all data has been written. Usually needs to flush buffer.
111 *
112 * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
113 * application must deal with any cleanup that should happen even
114 * for error exit.
115 */
116
117 METHODDEF(void)
118 term_destination(j_compress_ptr cinfo)
119 {
120 auto dest = (mrpt_dest_ptr)cinfo->dest;
121 size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
122
123 /* Write any data remaining in the buffer */
124 if (datacount > 0) dest->out->Write(dest->buffer, (int)datacount);
125 }
126
127 GLOBAL(void)
128 jpeg_stdio_dest(j_compress_ptr cinfo, CStream* out)
129 {
130 mrpt_dest_ptr dest;
131
132 /* The destination object is made permanent so that multiple JPEG images
133 * can be written to the same file without re-executing jpeg_stdio_dest.
134 * This makes it dangerous to use this manager and a different destination
135 * manager serially with the same JPEG object, because their private object
136 * sizes may be different. Caveat programmer.
137 */
138 if (cinfo->dest == nullptr)
139 { /* first time for this JPEG object? */
140 cinfo->dest = (jpeg_destination_mgr*)(*cinfo->mem->alloc_small)(
141 (j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(mrpt_destination_mgr));
142 }
143
144 dest = (mrpt_dest_ptr)cinfo->dest;
145 dest->pub.init_destination = init_destination;
146 dest->pub.empty_output_buffer = empty_output_buffer;
147 dest->pub.term_destination = term_destination;
148 dest->out = out;
149 }
150
151 // -------------------------------------------------------------
152
153 /* Expanded data source object for stdio input */
154
155 typedef struct
156 {
157 mrpt_jpeg_source_mgr pub; /* public fields */
158 CStream* in; /* source stream */
159 JOCTET* buffer; /* start of buffer */
160 boolean start_of_file; /* have we gotten any data yet? */
161 } my_source_mgr;
162
163 using my_src_ptr = my_source_mgr*;
164
165 #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
166
167 /*
168 * Initialize source --- called by jpeg_read_header
169 * before any data is actually read.
170 */
171
172 METHODDEF(void)
173 init_source(j_decompress_ptr cinfo)
174 {
175 auto src = (my_src_ptr)cinfo->src;
176
177 /* We reset the empty-input-file flag for each image,
178 * but we don't clear the input buffer.
179 * This is correct behavior for reading a series of images from one source.
180 */
181 src->start_of_file = TRUE;
182 }
183
184 /*
185 * Fill the input buffer --- called whenever buffer is emptied.
186 *
187 * In typical applications, this should read fresh data into the buffer
188 * (ignoring the current state of next_input_byte & bytes_in_buffer),
189 * reset the pointer & count to the start of the buffer, and return TRUE
190 * indicating that the buffer has been reloaded. It is not necessary to
191 * fill the buffer entirely, only to obtain at least one more byte.
192 *
193 * There is no such thing as an EOF return. If the end of the file has been
194 * reached, the routine has a choice of ERREXIT() or inserting fake data into
195 * the buffer. In most cases, generating a warning message and inserting a
196 * fake EOI marker is the best course of action --- this will allow the
197 * decompressor to output however much of the image is there. However,
198 * the resulting error message is misleading if the real problem is an empty
199 * input file, so we handle that case specially.
200 *
201 * In applications that need to be able to suspend compression due to input
202 * not being available yet, a FALSE return indicates that no more data can be
203 * obtained right now, but more may be forthcoming later. In this situation,
204 * the decompressor will return to its caller (with an indication of the
205 * number of scanlines it has read, if any). The application should resume
206 * decompression after it has loaded more data into the input buffer. Note
207 * that there are substantial restrictions on the use of suspension --- see
208 * the documentation.
209 *
210 * When suspending, the decompressor will back up to a convenient restart point
211 * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
212 * indicate where the restart point will be if the current call returns FALSE.
213 * Data beyond this point must be rescanned after resumption, so move it to
214 * the front of the buffer rather than discarding it.
215 */
216
217 METHODDEF(boolean)
218 fill_input_buffer(j_decompress_ptr cinfo)
219 {
220 auto src = (my_src_ptr)cinfo->src;
221 size_t nbytes;
222
223 nbytes = src->in->Read(src->buffer, INPUT_BUF_SIZE);
224
225 if (nbytes <= 0)
226 {
227 if (src->start_of_file) /* Treat empty input file as fatal error */
228 {
229 THROW_EXCEPTION("Error looking for JPEG start data!");
230 }
231
232 /* Insert a fake EOI marker */
233 src->buffer[0] = (JOCTET)0xFF;
234 src->buffer[1] = (JOCTET)JPEG_EOI;
235 nbytes = 2;
236 }
237
238 src->pub.next_input_byte = src->buffer;
239 src->pub.bytes_in_buffer = nbytes;
240 src->start_of_file = FALSE;
241
242 return TRUE;
243 }
244
245 /*
246 * Skip data --- used to skip over a potentially large amount of
247 * uninteresting data (such as an APPn marker).
248 *
249 * Writers of suspendable-input applications must note that skip_input_data
250 * is not granted the right to give a suspension return. If the skip extends
251 * beyond the data currently in the buffer, the buffer can be marked empty so
252 * that the next read will cause a fill_input_buffer call that can suspend.
253 * Arranging for additional bytes to be discarded before reloading the input
254 * buffer is the application writer's problem.
255 */
256
257 METHODDEF(void)
258 skip_input_data(j_decompress_ptr cinfo, long num_bytes)
259 {
260 auto src = (my_src_ptr)cinfo->src;
261
262 /* Just a dumb implementation for now. Could use fseek() except
263 * it doesn't work on pipes. Not clear that being smart is worth
264 * any trouble anyway --- large skips are infrequent.
265 */
266 if (num_bytes > 0)
267 {
268 while (num_bytes > (long)src->pub.bytes_in_buffer)
269 {
270 num_bytes -= (long)src->pub.bytes_in_buffer;
271 (void)fill_input_buffer(cinfo);
272 /* note we assume that fill_input_buffer will never return FALSE,
273 * so suspension need not be handled.
274 */
275 }
276 src->pub.next_input_byte += (size_t)num_bytes;
277 src->pub.bytes_in_buffer -= (size_t)num_bytes;
278 }
279 }
280
281 /*
282 * An additional method that can be provided by data source modules is the
283 * resync_to_restart method for error recovery in the presence of RST markers.
284 * For the moment, this source module just uses the default resync method
285 * provided by the JPEG library. That method assumes that no backtracking
286 * is possible.
287 */
288
289 /*
290 * Terminate source --- called by jpeg_finish_decompress
291 * after all data has been read. Often a no-op.
292 *
293 * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
294 * application must deal with any cleanup that should happen even
295 * for error exit.
296 */
297
298 METHODDEF(void)
299 term_source([[maybe_unused]] j_decompress_ptr cinfo)
300 { /* no work necessary here */
301 }
302
303 /*
304 * Prepare for input from a stdio stream.
305 * The caller must have already opened the stream, and is responsible
306 * for closing it after finishing decompression.
307 */
308
309 GLOBAL(void)
310 jpeg_stdio_src(j_decompress_ptr cinfo, CStream* in)
311 {
312 my_src_ptr src;
313
314 /* The source object and input buffer are made permanent so that a series
315 * of JPEG images can be read from the same file by calling jpeg_stdio_src
316 * only before the first one. (If we discarded the buffer at the end of
317 * one image, we'd likely lose the start of the next one.)
318 * This makes it unsafe to use this manager and a different source
319 * manager serially with the same JPEG object. Caveat programmer.
320 */
321 if (cinfo->src == nullptr)
322 { /* first time for this JPEG object? */
323 cinfo->src = (mrpt_jpeg_source_mgr*)(*cinfo->mem->alloc_small)(
324 (j_common_ptr)cinfo, JPOOL_PERMANENT, sizeof(my_source_mgr));
325 src = (my_src_ptr)cinfo->src;
326 src->buffer = (JOCTET*)(*cinfo->mem->alloc_small)(
327 (j_common_ptr)cinfo, JPOOL_PERMANENT, INPUT_BUF_SIZE * sizeof(JOCTET));
328 }
329
330 src = (my_src_ptr)cinfo->src;
331 src->pub.init_source = init_source;
332 src->pub.fill_input_buffer = fill_input_buffer;
333 src->pub.skip_input_data = skip_input_data;
334 src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
335 src->pub.term_source = term_source;
336 src->in = in;
337 src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
338 src->pub.next_input_byte = nullptr; /* until buffer loaded */
339 }
340
341 // ---------------------------------------------------------------------------------------
342 // END OF JPEG FUNCTIONS PART
343 // ---------------------------------------------------------------------------------------
344 #endif // MRPT_HAS_JPEG
345
346 void CImage::saveToStreamAsJPEG(CStream& out, const int jpeg_quality) const
347 {
348 #if MRPT_HAS_OPENCV && MRPT_HAS_JPEG
349 MRPT_START
350
351 makeSureImageIsLoaded(); // For delayed loaded images stored externally
352
353 struct jpeg_compress_struct cinfo;
354 struct jpeg_error_mgr jerr;
355
356 const auto& img = m_impl->img;
357
358 const unsigned int nCols = img.cols, nRows = img.rows;
359 const bool is_color = (img.channels() == 3);
360
361 // Some previous verification:
362 ASSERT_(nCols >= 1 && nRows >= 1);
363 ASSERT_(img.channels() == 1 || img.channels() == 3);
364
365 // 1) Initialization of the JPEG compresion object:
366 // --------------------------------------------------
367 cinfo.err = jpeg_std_error(&jerr);
368 jpeg_create_compress(&cinfo);
369
370 // 2) Set the destination of jpeg data:
371 // --------------------------------------------------
372 jpeg_stdio_dest(&cinfo, &out);
373
374 // 3) Set parameters for compression:
375 // --------------------------------------------------
376 cinfo.image_width = nCols;
377 cinfo.image_height = nRows;
378 cinfo.input_components = is_color ? 3 : 1;
379 cinfo.in_color_space = is_color ? JCS_RGB : JCS_GRAYSCALE;
380
381 jpeg_set_defaults(&cinfo);
382 /* Make optional parameter settings here */
383 /* Now you can set any non-default parameters you wish to.
384 * Here we just illustrate the use of quality (quantization table) scaling:
385 */
386 jpeg_set_quality(
387 &cinfo, jpeg_quality /* quality per cent */, TRUE /* limit to baseline-JPEG values */);
388
389 // 4) Start:
390 // --------------------------------------------------
391 jpeg_start_compress(&cinfo, TRUE);
392
393 // 5) Write scan lines:
394 // --------------------------------------------------
395 if (is_color)
396 {
397 JSAMPROW row_pointer[1]; /* pointer to a single row */
398 row_pointer[0] = new uint8_t[img.step[0]];
399
400 for (unsigned int row = 0; row < nRows; row++)
401 {
402 // Flip RGB bytes order!
403 const uint8_t* src = img.ptr<uint8_t>(row);
404 uint8_t* target = row_pointer[0];
405 for (unsigned int col = 0; col < nCols; col++)
406 {
407 target[0] = src[2];
408 target[1] = src[1];
409 target[2] = src[0];
410
411 target += 3;
412 src += 3;
413 }
414
415 if (1 != jpeg_write_scanlines(&cinfo, row_pointer, 1))
416 {
417 THROW_EXCEPTION("jpeg_write_scanlines: didn't work!!");
418 }
419 }
420
421 delete[] row_pointer[0];
422 } // end "color"
423 else
424 { // Is grayscale:
425 JSAMPROW row_pointer[1]; /* pointer to a single row */
426
427 for (unsigned int row = 0; row < nRows; row++)
428 {
429 row_pointer[0] = const_cast<JSAMPROW>(img.ptr<uint8_t>(row));
430
431 // Gray scale:
432 if (1 != jpeg_write_scanlines(&cinfo, row_pointer, 1))
433 {
434 THROW_EXCEPTION("jpeg_write_scanlines: didn't work!!");
435 }
436 }
437 }
438
439 // 6) Compress and finish:
440 // --------------------------------------------------
441 jpeg_finish_compress(&cinfo);
442 jpeg_destroy_compress(&cinfo);
443
444 // DONE!
445 MRPT_END
446 #endif
447 }
448
449 void CImage::loadFromStreamAsJPEG(CStream& in)
450 {
451 #if MRPT_HAS_OPENCV && MRPT_HAS_JPEG
452 MRPT_START
453
454 // This could have been ported to cv::imdecode(). But on a second thought,
455 // it may be not be as easy: imdecode() assumes an input buffer of known
456 // size while here we do not know the size to read from the CStream in
457 // advance.
458
459 struct jpeg_decompress_struct cinfo;
460 struct jpeg_error_mgr jerr;
461
462 /* Step 1: allocate and initialize JPEG decompression object */
463
464 /* We set up the normal JPEG error routines, then override error_exit. */
465 cinfo.err = jpeg_std_error(&jerr);
466
467 /* Now we can initialize the JPEG decompression object. */
468 jpeg_create_decompress(&cinfo);
469
470 /* Step 2: specify data source (eg, a file) */
471 jpeg_stdio_src(&cinfo, &in);
472
473 /* Step 3: read file parameters with jpeg_read_header() */
474 jpeg_read_header(&cinfo, TRUE);
475
476 /* Step 4: set parameters for decompression */
477
478 /* Step 5: Start decompressor */
479 jpeg_start_decompress(&cinfo);
480
481 /* We may need to do some setup of our own at this point before reading
482 * the data. After jpeg_start_decompress() we have the correct scaled
483 * output image dimensions available, as well as the output colormap
484 * if we asked for color quantization.
485 * In this example, we need to make an output work buffer of the right size.
486 */
487 /* JSAMPLEs per row in output buffer */
488 /* physical row width in output buffer */
489 const int row_stride = cinfo.output_width * cinfo.output_components;
490 /* Make a one-row-high sample array that will go away when done with image
491 */
492 /* Output row buffer */
493 JSAMPARRAY buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, row_stride, 1);
494
495 // Resize the CImage now:
496 this->resize(
497 cinfo.output_width, cinfo.output_height, cinfo.out_color_components == 1 ? CH_GRAY : CH_RGB);
498 auto& img = m_impl->img;
499
500 /* Step 6: while (scan lines remain to be read) */
501 /* jpeg_read_scanlines(...); */
502
503 /* Here we use the library's state variable cinfo.output_scanline as the
504 * loop counter, so that we don't have to keep track ourselves.
505 */
506 const unsigned int nCols = cinfo.output_width, nRows = cinfo.output_height;
507
508 for (unsigned int row = 0; row < nRows; row++)
509 {
510 /* jpeg_read_scanlines expects an array of pointers to scanlines.
511 * Here the array is only one element long, but you could ask for
512 * more than one scanline at a time if that's more convenient.
513 */
514 jpeg_read_scanlines(&cinfo, buffer, 1);
515
516 /* Copy into the CImage object */
517 if (isColor())
518 {
519 // Flip RGB bytes order!
520 auto target = img.ptr<uint8_t>(row);
521 const auto* src = buffer[0];
522 for (unsigned int col = 0; col < nCols; col++)
523 {
524 target[0] = src[2];
525 target[1] = src[1];
526 target[2] = src[0];
527
528 target += 3;
529 src += 3;
530 }
531 }
532 else
533 {
534 // Gray scale:
535 std::memcpy(img.ptr<uint8_t>(row), buffer[0], row_stride);
536 }
537 }
538
539 /* Step 7: Finish decompression */
540
541 jpeg_finish_decompress(&cinfo);
542 /* We can ignore the return value since suspension is not possible
543 * with the stdio data source.
544 */
545
546 /* Step 8: Release JPEG decompression object */
547
548 /* This is an important step since it will release a good deal of memory. */
549 jpeg_destroy_decompress(&cinfo);
550
551 // DONE!
552 MRPT_END
553 #endif
554 }