blob: 0ae6a639701d50519cb92a5e9304f5dbbb92ac45 [file] [log] [blame]
Dichen Zhang0d12ba82022-10-19 20:44:51 +00001/*
2 * Copyright 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <jpegrecoverymap/jpegdecoder.h>
18
19#include <cutils/log.h>
20
21#include <errno.h>
22#include <setjmp.h>
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +000023#include <string>
24
25using namespace std;
Dichen Zhang0d12ba82022-10-19 20:44:51 +000026
27namespace android::recoverymap {
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +000028
Dichen Zhangd18bc302022-12-16 20:55:24 +000029const uint32_t kAPP0Marker = JPEG_APP0; // JFIF
30const uint32_t kAPP1Marker = JPEG_APP0 + 1; // EXIF, XMP
31const uint32_t kAPP2Marker = JPEG_APP0 + 2; // ICC
32
33const std::string kXmpNameSpace = "http://ns.adobe.com/xap/1.0/";
34const std::string kExifIdCode = "Exif";
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +000035
Dichen Zhang0d12ba82022-10-19 20:44:51 +000036struct jpegr_source_mgr : jpeg_source_mgr {
37 jpegr_source_mgr(const uint8_t* ptr, int len);
38 ~jpegr_source_mgr();
39
40 const uint8_t* mBufferPtr;
41 size_t mBufferLength;
42};
43
44struct jpegrerror_mgr {
45 struct jpeg_error_mgr pub;
46 jmp_buf setjmp_buffer;
47};
48
49static void jpegr_init_source(j_decompress_ptr cinfo) {
50 jpegr_source_mgr* src = static_cast<jpegr_source_mgr*>(cinfo->src);
51 src->next_input_byte = static_cast<const JOCTET*>(src->mBufferPtr);
52 src->bytes_in_buffer = src->mBufferLength;
53}
54
55static boolean jpegr_fill_input_buffer(j_decompress_ptr /* cinfo */) {
56 ALOGE("%s : should not get here", __func__);
57 return FALSE;
58}
59
60static void jpegr_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {
61 jpegr_source_mgr* src = static_cast<jpegr_source_mgr*>(cinfo->src);
62
63 if (num_bytes > static_cast<long>(src->bytes_in_buffer)) {
64 ALOGE("jpegr_skip_input_data - num_bytes > (long)src->bytes_in_buffer");
65 } else {
66 src->next_input_byte += num_bytes;
67 src->bytes_in_buffer -= num_bytes;
68 }
69}
70
71static void jpegr_term_source(j_decompress_ptr /*cinfo*/) {}
72
73jpegr_source_mgr::jpegr_source_mgr(const uint8_t* ptr, int len) :
74 mBufferPtr(ptr), mBufferLength(len) {
75 init_source = jpegr_init_source;
76 fill_input_buffer = jpegr_fill_input_buffer;
77 skip_input_data = jpegr_skip_input_data;
78 resync_to_restart = jpeg_resync_to_restart;
79 term_source = jpegr_term_source;
80}
81
82jpegr_source_mgr::~jpegr_source_mgr() {}
83
84static void jpegrerror_exit(j_common_ptr cinfo) {
85 jpegrerror_mgr* err = reinterpret_cast<jpegrerror_mgr*>(cinfo->err);
86 longjmp(err->setjmp_buffer, 1);
87}
88
89JpegDecoder::JpegDecoder() {
Dichen Zhangd18bc302022-12-16 20:55:24 +000090 mExifPos = 0;
Dichen Zhang0d12ba82022-10-19 20:44:51 +000091}
92
93JpegDecoder::~JpegDecoder() {
94}
95
Fyodor Kyslovea9180f2023-01-06 01:11:43 +000096bool JpegDecoder::decompressImage(const void* image, int length, bool decodeToRGBA) {
Dichen Zhang0d12ba82022-10-19 20:44:51 +000097 if (image == nullptr || length <= 0) {
98 ALOGE("Image size can not be handled: %d", length);
99 return false;
100 }
101
102 mResultBuffer.clear();
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000103 mXMPBuffer.clear();
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000104 if (!decode(image, length, decodeToRGBA)) {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000105 return false;
106 }
107
108 return true;
109}
110
Nick Deakinf6bca5a2022-11-04 10:43:43 -0400111void* JpegDecoder::getDecompressedImagePtr() {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000112 return mResultBuffer.data();
113}
114
115size_t JpegDecoder::getDecompressedImageSize() {
116 return mResultBuffer.size();
117}
118
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000119void* JpegDecoder::getXMPPtr() {
120 return mXMPBuffer.data();
121}
122
123size_t JpegDecoder::getXMPSize() {
124 return mXMPBuffer.size();
125}
126
Dichen Zhangd18bc302022-12-16 20:55:24 +0000127void* JpegDecoder::getEXIFPtr() {
128 return mEXIFBuffer.data();
129}
130
131size_t JpegDecoder::getEXIFSize() {
132 return mEXIFBuffer.size();
133}
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000134
Nick Deakinf6bca5a2022-11-04 10:43:43 -0400135size_t JpegDecoder::getDecompressedImageWidth() {
136 return mWidth;
137}
138
139size_t JpegDecoder::getDecompressedImageHeight() {
140 return mHeight;
141}
142
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000143bool JpegDecoder::decode(const void* image, int length, bool decodeToRGBA) {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000144 jpeg_decompress_struct cinfo;
145 jpegr_source_mgr mgr(static_cast<const uint8_t*>(image), length);
146 jpegrerror_mgr myerr;
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000147
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000148 cinfo.err = jpeg_std_error(&myerr.pub);
149 myerr.pub.error_exit = jpegrerror_exit;
150
151 if (setjmp(myerr.setjmp_buffer)) {
152 jpeg_destroy_decompress(&cinfo);
153 return false;
154 }
155 jpeg_create_decompress(&cinfo);
156
Dichen Zhangd18bc302022-12-16 20:55:24 +0000157 jpeg_save_markers(&cinfo, kAPP0Marker, 0xFFFF);
158 jpeg_save_markers(&cinfo, kAPP1Marker, 0xFFFF);
159 jpeg_save_markers(&cinfo, kAPP2Marker, 0xFFFF);
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000160
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000161 cinfo.src = &mgr;
162 jpeg_read_header(&cinfo, TRUE);
163
Dichen Zhangd18bc302022-12-16 20:55:24 +0000164 // Save XMP data and EXIF data.
165 // Here we only handle the first XMP / EXIF package.
166 // The parameter pos is used for capturing start offset of EXIF, which is hacky, but working...
167 // We assume that all packages are starting with two bytes marker (eg FF E1 for EXIF package),
168 // two bytes of package length which is stored in marker->original_length, and the real data
169 // which is stored in marker->data. The pos is adding up all previous package lengths (
170 // 4 bytes marker and length, marker->original_length) before EXIF appears. Note that here we
171 // we are using marker->original_length instead of marker->data_length because in case the real
172 // package length is larger than the limitation, jpeg-turbo will only copy the data within the
173 // limitation (represented by data_length) and this may vary from original_length / real offset.
174 // A better solution is making jpeg_marker_struct holding the offset, but currently it doesn't.
175 bool exifAppears = false;
176 bool xmpAppears = false;
177 size_t pos = 2; // position after SOI
178 for (jpeg_marker_struct* marker = cinfo.marker_list;
179 marker && !(exifAppears && xmpAppears);
180 marker = marker->next) {
181
182 pos += 4;
183 pos += marker->original_length;
184
185 if (marker->marker != kAPP1Marker) {
186 continue;
187 }
188
189 const unsigned int len = marker->data_length;
190 if (!xmpAppears &&
191 len > kXmpNameSpace.size() &&
192 !strncmp(reinterpret_cast<const char*>(marker->data),
193 kXmpNameSpace.c_str(),
194 kXmpNameSpace.size())) {
195 mXMPBuffer.resize(len+1, 0);
196 memcpy(static_cast<void*>(mXMPBuffer.data()), marker->data, len);
197 xmpAppears = true;
198 } else if (!exifAppears &&
199 len > kExifIdCode.size() &&
200 !strncmp(reinterpret_cast<const char*>(marker->data),
201 kExifIdCode.c_str(),
202 kExifIdCode.size())) {
203 mEXIFBuffer.resize(len, 0);
204 memcpy(static_cast<void*>(mEXIFBuffer.data()), marker->data, len);
205 exifAppears = true;
206 mExifPos = pos - marker->original_length;
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000207 }
208 }
209
Nick Deakinf6bca5a2022-11-04 10:43:43 -0400210 mWidth = cinfo.image_width;
211 mHeight = cinfo.image_height;
212
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000213 if (decodeToRGBA) {
214 if (cinfo.jpeg_color_space == JCS_GRAYSCALE) {
215 // We don't intend to support decoding grayscale to RGBA
216 return false;
217 }
218 // 4 bytes per pixel
219 mResultBuffer.resize(cinfo.image_width * cinfo.image_height * 4);
220 cinfo.out_color_space = JCS_EXT_RGBA;
221 } else {
222 if (cinfo.jpeg_color_space == JCS_YCbCr) {
223 // 1 byte per pixel for Y, 0.5 byte per pixel for U+V
224 mResultBuffer.resize(cinfo.image_width * cinfo.image_height * 3 / 2, 0);
225 } else if (cinfo.jpeg_color_space == JCS_GRAYSCALE) {
226 mResultBuffer.resize(cinfo.image_width * cinfo.image_height, 0);
227 }
228 cinfo.out_color_space = cinfo.jpeg_color_space;
229 cinfo.raw_data_out = TRUE;
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000230 }
231
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000232 cinfo.dct_method = JDCT_IFAST;
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000233
234 jpeg_start_decompress(&cinfo);
235
236 if (!decompress(&cinfo, static_cast<const uint8_t*>(mResultBuffer.data()),
237 cinfo.jpeg_color_space == JCS_GRAYSCALE)) {
238 return false;
239 }
240
241 jpeg_finish_decompress(&cinfo);
242 jpeg_destroy_decompress(&cinfo);
243
244 return true;
245}
246
Dichen Zhangd18bc302022-12-16 20:55:24 +0000247// TODO (Fyodor/Dichen): merge this method with getCompressedImageParameters() since they have
248// similar functionality. Yet Dichen is not familiar with who's calling
249// getCompressedImageParameters(), looks like it's used by some pending CLs.
250bool JpegDecoder::extractEXIF(const void* image, int length) {
251 jpeg_decompress_struct cinfo;
252 jpegr_source_mgr mgr(static_cast<const uint8_t*>(image), length);
253 jpegrerror_mgr myerr;
254
255 cinfo.err = jpeg_std_error(&myerr.pub);
256 myerr.pub.error_exit = jpegrerror_exit;
257
258 if (setjmp(myerr.setjmp_buffer)) {
259 jpeg_destroy_decompress(&cinfo);
260 return false;
261 }
262 jpeg_create_decompress(&cinfo);
263
264 jpeg_save_markers(&cinfo, kAPP0Marker, 0xFFFF);
265 jpeg_save_markers(&cinfo, kAPP1Marker, 0xFFFF);
266 jpeg_save_markers(&cinfo, kAPP2Marker, 0xFFFF);
267
268 cinfo.src = &mgr;
269 jpeg_read_header(&cinfo, TRUE);
270
271 bool exifAppears = false;
272 size_t pos = 2; // position after SOI
273 for (jpeg_marker_struct* marker = cinfo.marker_list;
274 marker && !exifAppears;
275 marker = marker->next) {
276
277 pos += 4;
278 pos += marker->original_length;
279
280 if (marker->marker != kAPP1Marker) {
281 continue;
282 }
283
284 const unsigned int len = marker->data_length;
285 if (!exifAppears &&
286 len > kExifIdCode.size() &&
287 !strncmp(reinterpret_cast<const char*>(marker->data),
288 kExifIdCode.c_str(),
289 kExifIdCode.size())) {
290 mEXIFBuffer.resize(len, 0);
291 memcpy(static_cast<void*>(mEXIFBuffer.data()), marker->data, len);
292 exifAppears = true;
293 mExifPos = pos - marker->original_length;
294 }
295 }
296
297 jpeg_destroy_decompress(&cinfo);
298 return true;
299}
300
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000301bool JpegDecoder::decompress(jpeg_decompress_struct* cinfo, const uint8_t* dest,
302 bool isSingleChannel) {
303 if (isSingleChannel) {
304 return decompressSingleChannel(cinfo, dest);
305 }
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000306 if (cinfo->out_color_space == JCS_EXT_RGBA)
307 return decompressRGBA(cinfo, dest);
308 else
309 return decompressYUV(cinfo, dest);
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000310}
311
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000312bool JpegDecoder::getCompressedImageParameters(const void* image, int length,
313 size_t *pWidth, size_t *pHeight,
Fyodor Kyslova90ee002023-01-10 23:41:41 +0000314 std::vector<uint8_t> *iccData , std::vector<uint8_t> *exifData) {
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000315 jpeg_decompress_struct cinfo;
316 jpegr_source_mgr mgr(static_cast<const uint8_t*>(image), length);
317 jpegrerror_mgr myerr;
318 cinfo.err = jpeg_std_error(&myerr.pub);
319 myerr.pub.error_exit = jpegrerror_exit;
320
321 if (setjmp(myerr.setjmp_buffer)) {
322 jpeg_destroy_decompress(&cinfo);
323 return false;
324 }
325 jpeg_create_decompress(&cinfo);
326
Dichen Zhangd18bc302022-12-16 20:55:24 +0000327 jpeg_save_markers(&cinfo, kAPP1Marker, 0xFFFF);
328 jpeg_save_markers(&cinfo, kAPP2Marker, 0xFFFF);
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000329
330 cinfo.src = &mgr;
331 if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) {
332 jpeg_destroy_decompress(&cinfo);
333 return false;
334 }
335
336 *pWidth = cinfo.image_width;
337 *pHeight = cinfo.image_height;
338
Fyodor Kyslova90ee002023-01-10 23:41:41 +0000339 //TODO: Parse iccProfile
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000340 (void)iccData;
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000341
Fyodor Kyslova90ee002023-01-10 23:41:41 +0000342 if (exifData != nullptr) {
343 bool exifAppears = false;
344 for (jpeg_marker_struct* marker = cinfo.marker_list; marker && !exifAppears;
345 marker = marker->next) {
346 if (marker->marker != kAPP1Marker) {
347 continue;
348 }
349
350 const unsigned int len = marker->data_length;
351 if (len >= kExifIdCode.size() &&
352 !strncmp(reinterpret_cast<const char*>(marker->data), kExifIdCode.c_str(),
353 kExifIdCode.size())) {
354 exifData->resize(len, 0);
355 memcpy(static_cast<void*>(exifData->data()), marker->data, len);
356 exifAppears = true;
357 }
358 }
359 }
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000360
361 jpeg_destroy_decompress(&cinfo);
362 return true;
363}
364
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000365bool JpegDecoder::decompressRGBA(jpeg_decompress_struct* cinfo, const uint8_t* dest) {
366 JSAMPLE* decodeDst = (JSAMPLE*) dest;
367 uint32_t lines = 0;
368 // TODO: use batches for more effectiveness
369 while (lines < cinfo->image_height) {
370 uint32_t ret = jpeg_read_scanlines(cinfo, &decodeDst, 1);
371 if (ret == 0) {
372 break;
373 }
374 decodeDst += cinfo->image_width * 4;
375 lines++;
376 }
377 return lines == cinfo->image_height;
378}
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000379
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000380bool JpegDecoder::decompressYUV(jpeg_decompress_struct* cinfo, const uint8_t* dest) {
381
382 JSAMPROW y[kCompressBatchSize];
383 JSAMPROW cb[kCompressBatchSize / 2];
384 JSAMPROW cr[kCompressBatchSize / 2];
385 JSAMPARRAY planes[3] {y, cb, cr};
386
387 size_t y_plane_size = cinfo->image_width * cinfo->image_height;
388 size_t uv_plane_size = y_plane_size / 4;
389 uint8_t* y_plane = const_cast<uint8_t*>(dest);
390 uint8_t* u_plane = const_cast<uint8_t*>(dest + y_plane_size);
391 uint8_t* v_plane = const_cast<uint8_t*>(dest + y_plane_size + uv_plane_size);
392 std::unique_ptr<uint8_t[]> empty(new uint8_t[cinfo->image_width]);
393 memset(empty.get(), 0, cinfo->image_width);
394
395 while (cinfo->output_scanline < cinfo->image_height) {
396 for (int i = 0; i < kCompressBatchSize; ++i) {
397 size_t scanline = cinfo->output_scanline + i;
398 if (scanline < cinfo->image_height) {
399 y[i] = y_plane + scanline * cinfo->image_width;
400 } else {
401 y[i] = empty.get();
402 }
403 }
404 // cb, cr only have half scanlines
405 for (int i = 0; i < kCompressBatchSize / 2; ++i) {
406 size_t scanline = cinfo->output_scanline / 2 + i;
407 if (scanline < cinfo->image_height / 2) {
408 int offset = scanline * (cinfo->image_width / 2);
409 cb[i] = u_plane + offset;
410 cr[i] = v_plane + offset;
411 } else {
412 cb[i] = cr[i] = empty.get();
413 }
414 }
415
416 int processed = jpeg_read_raw_data(cinfo, planes, kCompressBatchSize);
417 if (processed != kCompressBatchSize) {
418 ALOGE("Number of processed lines does not equal input lines.");
419 return false;
420 }
421 }
422 return true;
423}
424
425bool JpegDecoder::decompressSingleChannel(jpeg_decompress_struct* cinfo, const uint8_t* dest) {
426 JSAMPROW y[kCompressBatchSize];
427 JSAMPARRAY planes[1] {y};
428
429 uint8_t* y_plane = const_cast<uint8_t*>(dest);
430 std::unique_ptr<uint8_t[]> empty(new uint8_t[cinfo->image_width]);
431 memset(empty.get(), 0, cinfo->image_width);
432
433 while (cinfo->output_scanline < cinfo->image_height) {
434 for (int i = 0; i < kCompressBatchSize; ++i) {
435 size_t scanline = cinfo->output_scanline + i;
436 if (scanline < cinfo->image_height) {
437 y[i] = y_plane + scanline * cinfo->image_width;
438 } else {
439 y[i] = empty.get();
440 }
441 }
442
443 int processed = jpeg_read_raw_data(cinfo, planes, kCompressBatchSize);
444 if (processed != kCompressBatchSize / 2) {
445 ALOGE("Number of processed lines does not equal input lines.");
446 return false;
447 }
448 }
449 return true;
450}
451
Nick Deakinf6bca5a2022-11-04 10:43:43 -0400452} // namespace android