Debian Codegraph @

src/codec/SkJpegMetadataDecoderImpl.cpp

raw
1 /*
2 * Copyright 2024 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "src/codec/SkJpegMetadataDecoderImpl.h"
9
10 #include "include/core/SkData.h"
11 #include "include/private/base/SkTemplates.h"
12 #include "src/codec/SkCodecPriv.h"
13 #include "src/codec/SkJpegConstants.h"
14
15 #include <cstdint>
16 #include <cstring>
17 #include <memory>
18 #include <utility>
19
20 #ifdef SK_CODEC_DECODES_JPEG_GAINMAPS
21 #include "include/core/SkStream.h"
22 #include "include/private/SkExif.h"
23 #include "include/private/SkGainmapInfo.h"
24 #include "include/private/SkXmp.h"
25 #include "src/base/SkEndian.h"
26 #include "src/codec/SkJpegMultiPicture.h"
27 #include "src/codec/SkJpegSegmentScan.h"
28 #include "src/codec/SkJpegSourceMgr.h"
29 #include "src/codec/SkJpegXmp.h"
30 #else
31 struct SkGainmapInfo;
32 #endif // SK_CODEC_DECODES_JPEG_GAINMAPS
33
34 #ifdef SK_CODEC_DECODES_JPEG_GAINMAPS
35 std::unique_ptr<SkXmp> SkJpegMetadataDecoderImpl::getXmpMetadata() const {
36 std::vector<sk_sp<const SkData>> decoderApp1Params;
37 for (const auto& marker : fMarkerList) {
38 if (marker.fMarker == kXMPMarker) {
39 decoderApp1Params.push_back(marker.fData);
40 }
41 }
42 return SkJpegMakeXmp(decoderApp1Params);
43 }
44
45 // Extract the SkJpegMultiPictureParameters from this image (if they exist). If |sourceMgr| and
46 // |outMpParamsSegment| are non-nullptr, then also return the SkJpegSegment that the parameters came
47 // from (and return nullptr if one cannot be found).
48 static std::unique_ptr<SkJpegMultiPictureParameters> find_mp_params(
49 const SkJpegMarkerList& markerList,
50 SkJpegSourceMgr* sourceMgr,
51 SkJpegSegment* outMpParamsSegment) {
52 std::unique_ptr<SkJpegMultiPictureParameters> mpParams;
53 size_t skippedSegmentCount = 0;
54
55 // Search though the libjpeg segments until we find a segment that parses as MP parameters. Keep
56 // track of how many segments with the MPF marker we skipped over to get there.
57 for (const auto& marker : markerList) {
58 if (marker.fMarker != kMpfMarker) {
59 continue;
60 }
61 mpParams = SkJpegMultiPictureParameters::Make(marker.fData);
62 if (mpParams) {
63 break;
64 }
65 ++skippedSegmentCount;
66 }
67 if (!mpParams) {
68 return nullptr;
69 }
70
71 // If |sourceMgr| is not specified, then do not try to find the SkJpegSegment.
72 if (!sourceMgr) {
73 SkASSERT(!outMpParamsSegment);
74 return mpParams;
75 }
76
77 // Now, find the SkJpegSegmentScanner segment that corresponds to the libjpeg marker.
78 // TODO(ccameron): It may be preferable to make SkJpegSourceMgr save segments with certain
79 // markers to avoid this strangeness.
80 for (const auto& segment : sourceMgr->getAllSegments()) {
81 if (segment.marker != kMpfMarker) {
82 continue;
83 }
84 if (skippedSegmentCount == 0) {
85 *outMpParamsSegment = segment;
86 return mpParams;
87 }
88 skippedSegmentCount--;
89 }
90 return nullptr;
91 }
92
93 // Attempt to extract a gainmap image from a specified offset and size within the decoder's stream.
94 // Returns true only if the extracted gainmap image includes XMP metadata that specifies HDR gainmap
95 // rendering parameters.
96 static std::pair<sk_sp<const SkData>, SkGainmapInfo> extract_gainmap(
97 SkJpegSourceMgr* decoderSource,
98 size_t offset,
99 size_t size,
100 bool baseImageHasIsoVersion,
101 bool baseImageHasAdobeXmp,
102 std::optional<float> baseImageAppleHdrHeadroom) {
103 // Extract the SkData for this image.
104 bool imageDataWasCopied = false;
105 auto imageData = decoderSource->getSubsetData(offset, size, &imageDataWasCopied);
106 if (!imageData) {
107 SkCodecPrintf("Failed to extract MP image.\n");
108 return {};
109 }
110
111 // Parse the potential gainmap image's metadata.
112 SkJpegMetadataDecoderImpl metadataDecoder(imageData);
113
114 // If this image identifies itself as a gainmap, then populate |info|.
115 bool didPopulateInfo = false;
116 SkGainmapInfo info;
117
118 // Check for ISO 21496-1 gain map metadata.
119 if (baseImageHasIsoVersion) {
120 didPopulateInfo = SkGainmapInfo::Parse(
121 metadataDecoder.getISOGainmapMetadata(/*copyData=*/false).get(), info);
122 if (didPopulateInfo) {
123 // SkGainmapInfo::Parse will set fGainmapMathColorSpace to a non-nullptr value if we are
124 // to use the alternate image's color space primaries (which are stored in the ICC
125 // profile of the gain map image) for the gain map application color space.
126 // the gain map image.
127 if (info.fGainmapMathColorSpace) {
128 sk_sp<SkColorSpace> imageColorSpace;
129 auto iccData = metadataDecoder.getICCProfileData(/*copyData=*/false);
130 skcms_ICCProfile iccProfile;
131 if (iccData && skcms_Parse(iccData->data(), iccData->size(), &iccProfile)) {
132 imageColorSpace = SkColorSpace::Make(iccProfile);
133 }
134 // Set fGainmapMathColorSpace to the gain map image's ICC profile's color space. If
135 // it is nullptr (because there was no ICC profile, or because it failed to parse),
136 // then leave fGainmapMathColorSpace to nullptr, indicating to use the base image's
137 // color space primaries for the gain map application color space.
138 // https://crbug.com/402033761
139 info.fGainmapMathColorSpace = std::move(imageColorSpace);
140 }
141 }
142 }
143
144 if (!didPopulateInfo) {
145 // The Adobe and Apple gain map metadata require XMP. Parse it now.
146 auto xmp = metadataDecoder.getXmpMetadata();
147 if (!xmp) {
148 return {};
149 }
150
151 // Check for Adobe gain map metadata only if the base image specified hdrgm:Version="1.0".
152 if (!didPopulateInfo && baseImageHasAdobeXmp) {
153 didPopulateInfo = xmp->getGainmapInfoAdobe(&info);
154 }
155
156 // Next try for Apple gain map metadata. This does not require anything specific from the
157 // base image.
158 if (!didPopulateInfo && baseImageAppleHdrHeadroom.has_value()) {
159 didPopulateInfo = xmp->getGainmapInfoApple(baseImageAppleHdrHeadroom.value(), &info);
160 }
161 }
162
163 // If none of the formats identified itself as a gainmap and populated |info| then fail.
164 if (!didPopulateInfo) {
165 return {};
166 }
167
168 // This image is a gainmap.
169 if (imageDataWasCopied) {
170 return {imageData, info};
171 }
172 return {SkData::MakeWithCopy(imageData->data(), imageData->size()), info};
173 }
174 #endif
175
176 std::pair<sk_sp<const SkData>, SkGainmapInfo> SkJpegMetadataDecoderImpl::findGainmapImage(
177 SkJpegSourceMgr* sourceMgr) const {
178 #ifdef SK_CODEC_DECODES_JPEG_GAINMAPS
179 SkExif::Metadata baseExif;
180 SkExif::Parse(baseExif, getExifMetadata(/*copyData=*/false).get());
181 auto xmp = getXmpMetadata();
182
183 // Determine if a support ISO 21496-1 gain map version is present in the base image.
184 bool isoGainmapPresent =
185 SkGainmapInfo::ParseVersion(getISOGainmapMetadata(/*copyData=*/false).get());
186
187 // Determine if Adobe HDR gain map is indicated in the base image.
188 bool adobeGainmapPresent = xmp && xmp->getGainmapInfoAdobe(nullptr);
189
190 // Attempt to locate the gainmap from the container XMP.
191 size_t containerGainmapOffset = 0;
192 size_t containerGainmapSize = 0;
193 if (xmp && xmp->getContainerGainmapLocation(&containerGainmapOffset, &containerGainmapSize)) {
194 const auto& segments = sourceMgr->getAllSegments();
195 if (!segments.empty()) {
196 const auto& lastSegment = segments.back();
197 if (lastSegment.marker == kJpegMarkerEndOfImage) {
198 containerGainmapOffset += lastSegment.offset + kJpegMarkerCodeSize;
199 }
200 }
201 }
202
203 // Attempt to find MultiPicture parameters.
204 SkJpegSegment mpParamsSegment;
205 auto mpParams = find_mp_params(fMarkerList, sourceMgr, &mpParamsSegment);
206
207 // First, search through the Multi-Picture images.
208 if (mpParams) {
209 for (size_t mpImageIndex = 1; mpImageIndex < mpParams->images.size(); ++mpImageIndex) {
210 size_t mpImageOffset = SkJpegMultiPictureParameters::GetImageAbsoluteOffset(
211 mpParams->images[mpImageIndex].dataOffset, mpParamsSegment.offset);
212 size_t mpImageSize = mpParams->images[mpImageIndex].size;
213
214 if (auto [data, info] = extract_gainmap(sourceMgr,
215 mpImageOffset,
216 mpImageSize,
217 isoGainmapPresent,
218 adobeGainmapPresent,
219 baseExif.fHdrHeadroom);
220 data) {
221 // If the GContainer also suggested an offset and size, assert that we found the
222 // image that the GContainer suggested.
223 if (containerGainmapOffset) {
224 SkASSERT(containerGainmapOffset == mpImageOffset);
225 SkASSERT(containerGainmapSize == mpImageSize);
226 }
227 return {data, info};
228 }
229 }
230 }
231
232 // Next, try the location suggested by the container XMP.
233 if (containerGainmapOffset) {
234 if (auto [data, info] = extract_gainmap(sourceMgr,
235 containerGainmapOffset,
236 containerGainmapSize,
237 /*baseImageHasIsoVersion=*/false,
238 adobeGainmapPresent,
239 /*baseImageAppleHdrHeadroom=*/std::nullopt);
240 data) {
241 return {data, info};
242 }
243 SkCodecPrintf("Failed to extract container-specified gainmap.\n");
244 }
245 #endif
246 return {};
247 }
248
249 /**
250 * Return true if the specified SkJpegMarker has marker |targetMarker| and begins with the specified
251 * signature.
252 */
253 static bool marker_has_signature(const SkJpegMarker& marker,
254 const uint32_t targetMarker,
255 const uint8_t* signature,
256 size_t signatureSize) {
257 if (targetMarker != marker.fMarker) {
258 return false;
259 }
260 if (marker.fData->size() <= signatureSize) {
261 return false;
262 }
263 if (memcmp(marker.fData->bytes(), signature, signatureSize) != 0) {
264 return false;
265 }
266 return true;
267 }
268
269 /*
270 * Return metadata with a specific marker and signature.
271 *
272 * Search for segments that start with the specified targetMarker, followed by the specified
273 * signature, followed by (optional) padding.
274 *
275 * Some types of metadata (e.g, ICC profiles) are too big to fit into a single segment's data (which
276 * is limited to 64k), and come in multiple parts. For this type of data, bytesInIndex is >0. After
277 * the signature comes bytesInIndex bytes (big endian) for the index of the segment's part, followed
278 * by bytesInIndex bytes (big endian) for the total number of parts. If all parts are present,
279 * stitch them together and return the combined result. Return failure if parts are absent, there
280 * are duplicate parts, or parts disagree on the total number of parts.
281 *
282 * Visually, each segment is:
283 * [|signatureSize| bytes containing |signature|]
284 * [|signaturePadding| bytes that are unexamined]
285 * [|bytesInIndex] bytes listing the segment index for multi-segment metadata]
286 * [|bytesInIndex] bytes listing the segment count for multi-segment metadata]
287 * [the returned data]
288 *
289 * If alwaysCopyData is true, then return a copy of the data. If alwaysCopyData is false, then
290 * return a direct reference to the data pointed to by dinfo, if possible.
291 */
292 static sk_sp<const SkData> read_metadata(const SkJpegMarkerList& markerList,
293 const uint32_t targetMarker,
294 const uint8_t* signature,
295 size_t signatureSize,
296 size_t signaturePadding,
297 size_t bytesInIndex,
298 bool alwaysCopyData) {
299 // Compute the total size of the entire header (signature plus padding plus index plus count),
300 // since we'll use it often.
301 const size_t headerSize = signatureSize + signaturePadding + 2 * bytesInIndex;
302
303 // A map from part index to the data in each part.
304 std::vector<sk_sp<const SkData>> parts;
305
306 // Running total of number of data in all parts.
307 size_t partsTotalSize = 0;
308
309 // Running total number of parts found.
310 uint32_t foundPartCount = 0;
311
312 // The expected number of parts (initialized at the first part we encounter).
313 uint32_t expectedPartCount = 0;
314
315 // Iterate through the image's segments.
316 for (const auto& marker : markerList) {
317 // Skip segments that don't have the right marker or signature.
318 if (!marker_has_signature(marker, targetMarker, signature, signatureSize)) {
319 continue;
320 }
321
322 // Skip segments that are too small to include the index and count.
323 const size_t dataLength = marker.fData->size();
324 if (dataLength <= headerSize) {
325 continue;
326 }
327
328 // Read this part's index and count as big-endian (if they are present, otherwise hard-code
329 // them to 1).
330 const uint8_t* data = marker.fData->bytes();
331 uint32_t partIndex = 0;
332 uint32_t partCount = 0;
333 if (bytesInIndex == 0) {
334 partIndex = 1;
335 partCount = 1;
336 } else {
337 for (size_t i = 0; i < bytesInIndex; ++i) {
338 const size_t offset = signatureSize + signaturePadding;
339 partIndex = (partIndex << 8) + data[offset + i];
340 partCount = (partCount << 8) + data[offset + bytesInIndex + i];
341 }
342 }
343
344 // A part count of 0 is invalid.
345 if (!partCount) {
346 SkCodecPrintf("Invalid marker part count zero\n");
347 return nullptr;
348 }
349
350 // The indices must in the range 1, ..., count.
351 if (partIndex <= 0 || partIndex > partCount) {
352 SkCodecPrintf("Invalid marker index %u for count %u\n", partIndex, partCount);
353 return nullptr;
354 }
355
356 // If this is the first marker we've encountered set the expected part count to its count.
357 if (expectedPartCount == 0) {
358 expectedPartCount = partCount;
359 parts.resize(expectedPartCount);
360 }
361
362 // If this does not match the expected part count, then fail.
363 if (partCount != expectedPartCount) {
364 SkCodecPrintf("Conflicting marker counts %u vs %u\n", partCount, expectedPartCount);
365 return nullptr;
366 }
367
368 // Make an SkData directly referencing the decoder's data for this part.
369 auto partData = SkData::MakeWithoutCopy(data + headerSize, dataLength - headerSize);
370
371 // Fail if duplicates are found.
372 if (parts[partIndex - 1]) {
373 SkCodecPrintf("Duplicate parts for index %u of %u\n", partIndex, expectedPartCount);
374 return nullptr;
375 }
376
377 // Save part in the map.
378 partsTotalSize += partData->size();
379 parts[partIndex - 1] = std::move(partData);
380 foundPartCount += 1;
381
382 // Stop as soon as we find all of the parts.
383 if (foundPartCount == expectedPartCount) {
384 break;
385 }
386 }
387
388 // Return nullptr if we don't find the data (this is not an error).
389 if (expectedPartCount == 0) {
390 return nullptr;
391 }
392
393 // Fail if we don't have all of the parts.
394 if (foundPartCount != expectedPartCount) {
395 SkCodecPrintf("Incomplete set of markers (expected %u got %u)\n",
396 expectedPartCount,
397 foundPartCount);
398 return nullptr;
399 }
400
401 // Return a direct reference to the data if there is only one part and we're allowed to.
402 if (!alwaysCopyData && expectedPartCount == 1) {
403 return std::move(parts[0]);
404 }
405
406 // Copy all of the markers and stitch them together.
407 auto result = SkData::MakeUninitialized(partsTotalSize);
408 void* copyDest = result->writable_data();
409 for (const auto& part : parts) {
410 memcpy(copyDest, part->data(), part->size());
411 copyDest = SkTAddOffset<void>(copyDest, part->size());
412 }
413 return result;
414 }
415
416 SkJpegMetadataDecoderImpl::SkJpegMetadataDecoderImpl(SkJpegMarkerList markerList)
417 : fMarkerList(std::move(markerList)) {}
418
419 SkJpegMetadataDecoderImpl::SkJpegMetadataDecoderImpl(sk_sp<const SkData> data) {
420 #ifdef SK_CODEC_DECODES_JPEG_GAINMAPS
421 SkJpegSegmentScanner scan(kJpegMarkerStartOfScan);
422 scan.onBytes(data->data(), data->size());
423 if (scan.hadError() || !scan.isDone()) {
424 SkCodecPrintf("Failed to scan header of MP image.\n");
425 return;
426 }
427 for (const auto& segment : scan.getSegments()) {
428 // Save the APP1 and APP2 parameters (which includes Exif, XMP, ICC, and MPF).
429 if (segment.marker != kJpegMarkerAPP0 + 1 && segment.marker != kJpegMarkerAPP0 + 2) {
430 continue;
431 }
432 auto parameters = SkJpegSegmentScanner::GetParameters(data.get(), segment);
433 if (!parameters) {
434 continue;
435 }
436 fMarkerList.emplace_back(segment.marker, std::move(parameters));
437 }
438 #endif
439 }
440
441 sk_sp<const SkData> SkJpegMetadataDecoderImpl::getExifMetadata(bool copyData) const {
442 return read_metadata(fMarkerList,
443 kExifMarker,
444 kExifSig,
445 sizeof(kExifSig),
446 /*signaturePadding=*/1,
447 /*bytesInIndex=*/0,
448 copyData);
449 }
450
451 sk_sp<const SkData> SkJpegMetadataDecoderImpl::getICCProfileData(bool copyData) const {
452 return read_metadata(fMarkerList,
453 kICCMarker,
454 kICCSig,
455 sizeof(kICCSig),
456 /*signaturePadding=*/0,
457 kICCMarkerIndexSize,
458 copyData);
459 }
460
461 sk_sp<const SkData> SkJpegMetadataDecoderImpl::getISOGainmapMetadata(bool copyData) const {
462 return read_metadata(fMarkerList,
463 kISOGainmapMarker,
464 kISOGainmapSig,
465 sizeof(kISOGainmapSig),
466 /*signaturePadding=*/0,
467 /*bytesInIndex=*/0,
468 copyData);
469 }
470
471 bool SkJpegMetadataDecoderImpl::mightHaveGainmapImage() const {
472 #ifdef SK_CODEC_DECODES_JPEG_GAINMAPS
473 // All supported gainmap formats require MPF. Reject images that do not have MPF.
474 return find_mp_params(fMarkerList, nullptr, nullptr) != nullptr;
475 #else
476 return false;
477 #endif
478 }
479
480 std::pair<sk_sp<const SkData>, SkGainmapInfo> SkJpegMetadataDecoderImpl::findGainmapImage(
481 sk_sp<const SkData> baseImageData) const {
482 #ifdef SK_CODEC_DECODES_JPEG_GAINMAPS
483 auto baseImageStream = SkMemoryStream::Make(baseImageData);
484 auto sourceMgr = SkJpegSourceMgr::Make(baseImageStream.get());
485 return this->findGainmapImage(sourceMgr.get());
486 #else
487 return {};
488 #endif
489 }
490
491 sk_sp<const SkData> SkJpegMetadataDecoderImpl::getJUMBFMetadata(bool copyData) const {
492 return read_metadata(fMarkerList,
493 kJumbfMarker,
494 kJumbfSig,
495 sizeof(kJumbfSig),
496 /*signaturePadding=*/0,
497 /*bytesInindex=*/0,
498 copyData);
499 }
500
501 std::unique_ptr<SkJpegMetadataDecoder> SkJpegMetadataDecoder::Make(std::vector<Segment> segments) {
502 return std::make_unique<SkJpegMetadataDecoderImpl>(std::move(segments));
503 }
504
505 std::unique_ptr<SkJpegMetadataDecoder> SkJpegMetadataDecoder::Make(sk_sp<const SkData> data) {
506 return std::make_unique<SkJpegMetadataDecoderImpl>(std::move(data));
507 }