blob: d36bbf8165daca47464ec24b6f86ae65abdf89e9 [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
Dichen Zhang02dd0592023-02-10 20:16:57 +000017#include <jpegrecoverymap/jpegdecoderhelper.h>
Dichen Zhang0d12ba82022-10-19 20:44:51 +000018
Dichen Zhangb27d06d2022-12-14 19:57:50 +000019#include <utils/Log.h>
Dichen Zhang0d12ba82022-10-19 20:44:51 +000020
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
Dichen Zhangb2ed8302023-02-10 23:05:04 +000027namespace android::jpegrecoverymap {
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 Kyslove00916d2023-01-16 22:12:02 +000035constexpr uint32_t kICCMarkerHeaderSize = 14;
36constexpr uint8_t kICCSig[] = {
37 'I', 'C', 'C', '_', 'P', 'R', 'O', 'F', 'I', 'L', 'E', '\0',
38};
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +000039
Dichen Zhang0d12ba82022-10-19 20:44:51 +000040struct jpegr_source_mgr : jpeg_source_mgr {
41 jpegr_source_mgr(const uint8_t* ptr, int len);
42 ~jpegr_source_mgr();
43
44 const uint8_t* mBufferPtr;
45 size_t mBufferLength;
46};
47
48struct jpegrerror_mgr {
49 struct jpeg_error_mgr pub;
50 jmp_buf setjmp_buffer;
51};
52
53static void jpegr_init_source(j_decompress_ptr cinfo) {
54 jpegr_source_mgr* src = static_cast<jpegr_source_mgr*>(cinfo->src);
55 src->next_input_byte = static_cast<const JOCTET*>(src->mBufferPtr);
56 src->bytes_in_buffer = src->mBufferLength;
57}
58
59static boolean jpegr_fill_input_buffer(j_decompress_ptr /* cinfo */) {
60 ALOGE("%s : should not get here", __func__);
61 return FALSE;
62}
63
64static void jpegr_skip_input_data(j_decompress_ptr cinfo, long num_bytes) {
65 jpegr_source_mgr* src = static_cast<jpegr_source_mgr*>(cinfo->src);
66
67 if (num_bytes > static_cast<long>(src->bytes_in_buffer)) {
68 ALOGE("jpegr_skip_input_data - num_bytes > (long)src->bytes_in_buffer");
69 } else {
70 src->next_input_byte += num_bytes;
71 src->bytes_in_buffer -= num_bytes;
72 }
73}
74
75static void jpegr_term_source(j_decompress_ptr /*cinfo*/) {}
76
77jpegr_source_mgr::jpegr_source_mgr(const uint8_t* ptr, int len) :
78 mBufferPtr(ptr), mBufferLength(len) {
79 init_source = jpegr_init_source;
80 fill_input_buffer = jpegr_fill_input_buffer;
81 skip_input_data = jpegr_skip_input_data;
82 resync_to_restart = jpeg_resync_to_restart;
83 term_source = jpegr_term_source;
84}
85
86jpegr_source_mgr::~jpegr_source_mgr() {}
87
88static void jpegrerror_exit(j_common_ptr cinfo) {
89 jpegrerror_mgr* err = reinterpret_cast<jpegrerror_mgr*>(cinfo->err);
90 longjmp(err->setjmp_buffer, 1);
91}
92
Dichen Zhang02dd0592023-02-10 20:16:57 +000093JpegDecoderHelper::JpegDecoderHelper() {
Dichen Zhangd18bc302022-12-16 20:55:24 +000094 mExifPos = 0;
Dichen Zhang0d12ba82022-10-19 20:44:51 +000095}
96
Dichen Zhang02dd0592023-02-10 20:16:57 +000097JpegDecoderHelper::~JpegDecoderHelper() {
Dichen Zhang0d12ba82022-10-19 20:44:51 +000098}
99
Dichen Zhang02dd0592023-02-10 20:16:57 +0000100bool JpegDecoderHelper::decompressImage(const void* image, int length, bool decodeToRGBA) {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000101 if (image == nullptr || length <= 0) {
102 ALOGE("Image size can not be handled: %d", length);
103 return false;
104 }
105
106 mResultBuffer.clear();
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000107 mXMPBuffer.clear();
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000108 if (!decode(image, length, decodeToRGBA)) {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000109 return false;
110 }
111
112 return true;
113}
114
Dichen Zhang02dd0592023-02-10 20:16:57 +0000115void* JpegDecoderHelper::getDecompressedImagePtr() {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000116 return mResultBuffer.data();
117}
118
Dichen Zhang02dd0592023-02-10 20:16:57 +0000119size_t JpegDecoderHelper::getDecompressedImageSize() {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000120 return mResultBuffer.size();
121}
122
Dichen Zhang02dd0592023-02-10 20:16:57 +0000123void* JpegDecoderHelper::getXMPPtr() {
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000124 return mXMPBuffer.data();
125}
126
Dichen Zhang02dd0592023-02-10 20:16:57 +0000127size_t JpegDecoderHelper::getXMPSize() {
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000128 return mXMPBuffer.size();
129}
130
Dichen Zhang02dd0592023-02-10 20:16:57 +0000131void* JpegDecoderHelper::getEXIFPtr() {
Dichen Zhangd18bc302022-12-16 20:55:24 +0000132 return mEXIFBuffer.data();
133}
134
Dichen Zhang02dd0592023-02-10 20:16:57 +0000135size_t JpegDecoderHelper::getEXIFSize() {
Dichen Zhangd18bc302022-12-16 20:55:24 +0000136 return mEXIFBuffer.size();
137}
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000138
Dichen Zhang02dd0592023-02-10 20:16:57 +0000139size_t JpegDecoderHelper::getDecompressedImageWidth() {
Nick Deakinf6bca5a2022-11-04 10:43:43 -0400140 return mWidth;
141}
142
Dichen Zhang02dd0592023-02-10 20:16:57 +0000143size_t JpegDecoderHelper::getDecompressedImageHeight() {
Nick Deakinf6bca5a2022-11-04 10:43:43 -0400144 return mHeight;
145}
146
Dichen Zhang02dd0592023-02-10 20:16:57 +0000147bool JpegDecoderHelper::decode(const void* image, int length, bool decodeToRGBA) {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000148 jpeg_decompress_struct cinfo;
149 jpegr_source_mgr mgr(static_cast<const uint8_t*>(image), length);
150 jpegrerror_mgr myerr;
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000151
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000152 cinfo.err = jpeg_std_error(&myerr.pub);
153 myerr.pub.error_exit = jpegrerror_exit;
154
155 if (setjmp(myerr.setjmp_buffer)) {
156 jpeg_destroy_decompress(&cinfo);
157 return false;
158 }
159 jpeg_create_decompress(&cinfo);
160
Dichen Zhangd18bc302022-12-16 20:55:24 +0000161 jpeg_save_markers(&cinfo, kAPP0Marker, 0xFFFF);
162 jpeg_save_markers(&cinfo, kAPP1Marker, 0xFFFF);
163 jpeg_save_markers(&cinfo, kAPP2Marker, 0xFFFF);
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000164
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000165 cinfo.src = &mgr;
166 jpeg_read_header(&cinfo, TRUE);
167
Dichen Zhangd18bc302022-12-16 20:55:24 +0000168 // Save XMP data and EXIF data.
169 // Here we only handle the first XMP / EXIF package.
170 // The parameter pos is used for capturing start offset of EXIF, which is hacky, but working...
171 // We assume that all packages are starting with two bytes marker (eg FF E1 for EXIF package),
172 // two bytes of package length which is stored in marker->original_length, and the real data
173 // which is stored in marker->data. The pos is adding up all previous package lengths (
174 // 4 bytes marker and length, marker->original_length) before EXIF appears. Note that here we
175 // we are using marker->original_length instead of marker->data_length because in case the real
176 // package length is larger than the limitation, jpeg-turbo will only copy the data within the
177 // limitation (represented by data_length) and this may vary from original_length / real offset.
178 // A better solution is making jpeg_marker_struct holding the offset, but currently it doesn't.
179 bool exifAppears = false;
180 bool xmpAppears = false;
181 size_t pos = 2; // position after SOI
182 for (jpeg_marker_struct* marker = cinfo.marker_list;
183 marker && !(exifAppears && xmpAppears);
184 marker = marker->next) {
185
186 pos += 4;
187 pos += marker->original_length;
188
189 if (marker->marker != kAPP1Marker) {
190 continue;
191 }
192
193 const unsigned int len = marker->data_length;
194 if (!xmpAppears &&
195 len > kXmpNameSpace.size() &&
196 !strncmp(reinterpret_cast<const char*>(marker->data),
197 kXmpNameSpace.c_str(),
198 kXmpNameSpace.size())) {
199 mXMPBuffer.resize(len+1, 0);
200 memcpy(static_cast<void*>(mXMPBuffer.data()), marker->data, len);
201 xmpAppears = true;
202 } else if (!exifAppears &&
203 len > kExifIdCode.size() &&
204 !strncmp(reinterpret_cast<const char*>(marker->data),
205 kExifIdCode.c_str(),
206 kExifIdCode.size())) {
207 mEXIFBuffer.resize(len, 0);
208 memcpy(static_cast<void*>(mEXIFBuffer.data()), marker->data, len);
209 exifAppears = true;
210 mExifPos = pos - marker->original_length;
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000211 }
212 }
213
Nick Deakinf6bca5a2022-11-04 10:43:43 -0400214 mWidth = cinfo.image_width;
215 mHeight = cinfo.image_height;
216
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000217 if (decodeToRGBA) {
218 if (cinfo.jpeg_color_space == JCS_GRAYSCALE) {
219 // We don't intend to support decoding grayscale to RGBA
220 return false;
221 }
222 // 4 bytes per pixel
223 mResultBuffer.resize(cinfo.image_width * cinfo.image_height * 4);
224 cinfo.out_color_space = JCS_EXT_RGBA;
225 } else {
226 if (cinfo.jpeg_color_space == JCS_YCbCr) {
227 // 1 byte per pixel for Y, 0.5 byte per pixel for U+V
228 mResultBuffer.resize(cinfo.image_width * cinfo.image_height * 3 / 2, 0);
229 } else if (cinfo.jpeg_color_space == JCS_GRAYSCALE) {
230 mResultBuffer.resize(cinfo.image_width * cinfo.image_height, 0);
231 }
232 cinfo.out_color_space = cinfo.jpeg_color_space;
233 cinfo.raw_data_out = TRUE;
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000234 }
235
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000236 cinfo.dct_method = JDCT_IFAST;
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000237
238 jpeg_start_decompress(&cinfo);
239
240 if (!decompress(&cinfo, static_cast<const uint8_t*>(mResultBuffer.data()),
241 cinfo.jpeg_color_space == JCS_GRAYSCALE)) {
242 return false;
243 }
244
245 jpeg_finish_decompress(&cinfo);
246 jpeg_destroy_decompress(&cinfo);
247
248 return true;
249}
250
Dichen Zhang02dd0592023-02-10 20:16:57 +0000251bool JpegDecoderHelper::decompress(jpeg_decompress_struct* cinfo, const uint8_t* dest,
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000252 bool isSingleChannel) {
253 if (isSingleChannel) {
254 return decompressSingleChannel(cinfo, dest);
255 }
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000256 if (cinfo->out_color_space == JCS_EXT_RGBA)
257 return decompressRGBA(cinfo, dest);
258 else
259 return decompressYUV(cinfo, dest);
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000260}
261
Dichen Zhang02dd0592023-02-10 20:16:57 +0000262bool JpegDecoderHelper::getCompressedImageParameters(const void* image, int length,
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000263 size_t *pWidth, size_t *pHeight,
Fyodor Kyslova90ee002023-01-10 23:41:41 +0000264 std::vector<uint8_t> *iccData , std::vector<uint8_t> *exifData) {
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000265 jpeg_decompress_struct cinfo;
266 jpegr_source_mgr mgr(static_cast<const uint8_t*>(image), length);
267 jpegrerror_mgr myerr;
268 cinfo.err = jpeg_std_error(&myerr.pub);
269 myerr.pub.error_exit = jpegrerror_exit;
270
271 if (setjmp(myerr.setjmp_buffer)) {
272 jpeg_destroy_decompress(&cinfo);
273 return false;
274 }
275 jpeg_create_decompress(&cinfo);
276
Dichen Zhangd18bc302022-12-16 20:55:24 +0000277 jpeg_save_markers(&cinfo, kAPP1Marker, 0xFFFF);
278 jpeg_save_markers(&cinfo, kAPP2Marker, 0xFFFF);
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000279
280 cinfo.src = &mgr;
281 if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) {
282 jpeg_destroy_decompress(&cinfo);
283 return false;
284 }
285
286 *pWidth = cinfo.image_width;
287 *pHeight = cinfo.image_height;
288
Fyodor Kyslove00916d2023-01-16 22:12:02 +0000289 if (iccData != nullptr) {
290 for (jpeg_marker_struct* marker = cinfo.marker_list; marker;
291 marker = marker->next) {
292 if (marker->marker != kAPP2Marker) {
293 continue;
294 }
295 if (marker->data_length <= kICCMarkerHeaderSize ||
296 memcmp(marker->data, kICCSig, sizeof(kICCSig)) != 0) {
297 continue;
298 }
299
300 const unsigned int len = marker->data_length - kICCMarkerHeaderSize;
301 const uint8_t *src = marker->data + kICCMarkerHeaderSize;
302 iccData->insert(iccData->end(), src, src+len);
303 }
304 }
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000305
Fyodor Kyslova90ee002023-01-10 23:41:41 +0000306 if (exifData != nullptr) {
307 bool exifAppears = false;
308 for (jpeg_marker_struct* marker = cinfo.marker_list; marker && !exifAppears;
309 marker = marker->next) {
310 if (marker->marker != kAPP1Marker) {
311 continue;
312 }
313
314 const unsigned int len = marker->data_length;
315 if (len >= kExifIdCode.size() &&
316 !strncmp(reinterpret_cast<const char*>(marker->data), kExifIdCode.c_str(),
317 kExifIdCode.size())) {
318 exifData->resize(len, 0);
319 memcpy(static_cast<void*>(exifData->data()), marker->data, len);
320 exifAppears = true;
321 }
322 }
323 }
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000324
325 jpeg_destroy_decompress(&cinfo);
326 return true;
327}
328
Dichen Zhang02dd0592023-02-10 20:16:57 +0000329bool JpegDecoderHelper::decompressRGBA(jpeg_decompress_struct* cinfo, const uint8_t* dest) {
Fyodor Kyslovea9180f2023-01-06 01:11:43 +0000330 JSAMPLE* decodeDst = (JSAMPLE*) dest;
331 uint32_t lines = 0;
332 // TODO: use batches for more effectiveness
333 while (lines < cinfo->image_height) {
334 uint32_t ret = jpeg_read_scanlines(cinfo, &decodeDst, 1);
335 if (ret == 0) {
336 break;
337 }
338 decodeDst += cinfo->image_width * 4;
339 lines++;
340 }
341 return lines == cinfo->image_height;
342}
Fyodor Kyslov1dcc4422022-11-16 01:40:53 +0000343
Dichen Zhang02dd0592023-02-10 20:16:57 +0000344bool JpegDecoderHelper::decompressYUV(jpeg_decompress_struct* cinfo, const uint8_t* dest) {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000345
346 JSAMPROW y[kCompressBatchSize];
347 JSAMPROW cb[kCompressBatchSize / 2];
348 JSAMPROW cr[kCompressBatchSize / 2];
349 JSAMPARRAY planes[3] {y, cb, cr};
350
351 size_t y_plane_size = cinfo->image_width * cinfo->image_height;
352 size_t uv_plane_size = y_plane_size / 4;
353 uint8_t* y_plane = const_cast<uint8_t*>(dest);
354 uint8_t* u_plane = const_cast<uint8_t*>(dest + y_plane_size);
355 uint8_t* v_plane = const_cast<uint8_t*>(dest + y_plane_size + uv_plane_size);
356 std::unique_ptr<uint8_t[]> empty(new uint8_t[cinfo->image_width]);
357 memset(empty.get(), 0, cinfo->image_width);
358
359 while (cinfo->output_scanline < cinfo->image_height) {
360 for (int i = 0; i < kCompressBatchSize; ++i) {
361 size_t scanline = cinfo->output_scanline + i;
362 if (scanline < cinfo->image_height) {
363 y[i] = y_plane + scanline * cinfo->image_width;
364 } else {
365 y[i] = empty.get();
366 }
367 }
368 // cb, cr only have half scanlines
369 for (int i = 0; i < kCompressBatchSize / 2; ++i) {
370 size_t scanline = cinfo->output_scanline / 2 + i;
371 if (scanline < cinfo->image_height / 2) {
372 int offset = scanline * (cinfo->image_width / 2);
373 cb[i] = u_plane + offset;
374 cr[i] = v_plane + offset;
375 } else {
376 cb[i] = cr[i] = empty.get();
377 }
378 }
379
380 int processed = jpeg_read_raw_data(cinfo, planes, kCompressBatchSize);
381 if (processed != kCompressBatchSize) {
382 ALOGE("Number of processed lines does not equal input lines.");
383 return false;
384 }
385 }
386 return true;
387}
388
Dichen Zhang02dd0592023-02-10 20:16:57 +0000389bool JpegDecoderHelper::decompressSingleChannel(jpeg_decompress_struct* cinfo, const uint8_t* dest) {
Dichen Zhang0d12ba82022-10-19 20:44:51 +0000390 JSAMPROW y[kCompressBatchSize];
391 JSAMPARRAY planes[1] {y};
392
393 uint8_t* y_plane = const_cast<uint8_t*>(dest);
394 std::unique_ptr<uint8_t[]> empty(new uint8_t[cinfo->image_width]);
395 memset(empty.get(), 0, cinfo->image_width);
396
397 while (cinfo->output_scanline < cinfo->image_height) {
398 for (int i = 0; i < kCompressBatchSize; ++i) {
399 size_t scanline = cinfo->output_scanline + i;
400 if (scanline < cinfo->image_height) {
401 y[i] = y_plane + scanline * cinfo->image_width;
402 } else {
403 y[i] = empty.get();
404 }
405 }
406
407 int processed = jpeg_read_raw_data(cinfo, planes, kCompressBatchSize);
408 if (processed != kCompressBatchSize / 2) {
409 ALOGE("Number of processed lines does not equal input lines.");
410 return false;
411 }
412 }
413 return true;
414}
415
Dichen Zhangb2ed8302023-02-10 23:05:04 +0000416} // namespace jpegrecoverymap