Debian Codegraph @

src/codec/SkJpegxlCodec.cpp

raw
1 /*
2 * Copyright 2021 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/SkJpegxlCodec.h"
9
10 #include "include/codec/SkCodec.h"
11 #include "include/codec/SkJpegxlDecoder.h"
12 #include "include/core/SkColorType.h"
13 #include "include/core/SkData.h"
14 #include "include/core/SkImageInfo.h"
15 #include "include/core/SkRefCnt.h"
16 #include "include/core/SkStream.h"
17 #include "include/core/SkTypes.h"
18 #include "include/private/SkEncodedInfo.h"
19 #include "include/private/base/SkTFitsIn.h"
20 #include "include/private/base/SkTemplates.h"
21 #include "include/private/base/SkTo.h"
22 #include "modules/skcms/skcms.h"
23 #include "src/codec/SkCodecPriv.h"
24 #include "src/codec/SkFrameHolder.h"
25 #include "src/core/SkStreamPriv.h"
26 #include "src/core/SkSwizzlePriv.h"
27
28 #include "jxl/codestream_header.h" // NO_G3_REWRITE
29 #include "jxl/decode.h" // NO_G3_REWRITE
30 #include "jxl/decode_cxx.h" // NO_G3_REWRITE
31 #include "jxl/types.h" // NO_G3_REWRITE
32
33 #include <cstdint>
34 #include <cstring>
35 #include <limits>
36 #include <utility>
37 #include <vector>
38
39 namespace {
40
41 class Frame : public SkFrame {
42 public:
43 explicit Frame(int i, SkEncodedInfo::Alpha alpha) : INHERITED(i), fReportedAlpha(alpha) {}
44 SkEncodedInfo::Alpha onReportedAlpha() const override { return fReportedAlpha; }
45
46 private:
47 const SkEncodedInfo::Alpha fReportedAlpha;
48
49 using INHERITED = SkFrame;
50 };
51
52 } // namespace
53
54 bool SkJpegxlCodec::IsJpegxl(const void* buffer, size_t bytesRead) {
55 JxlSignature result = JxlSignatureCheck(reinterpret_cast<const uint8_t*>(buffer), bytesRead);
56 return (result == JXL_SIG_CODESTREAM) || (result == JXL_SIG_CONTAINER);
57 }
58
59 class SkJpegxlCodecPriv : public SkFrameHolder {
60 public:
61 SkJpegxlCodecPriv() : fDecoder(JxlDecoderMake(/* memory_manager= */ nullptr)) {}
62 JxlDecoderPtr fDecoder; // unique_ptr with custom destructor
63 JxlBasicInfo fInfo;
64 bool fSeenAllFrames = false;
65 std::vector<Frame> fFrames;
66 int fLastProcessedFrame = SkCodec::kNoFrame;
67 void* fDst;
68 size_t fPixelShift;
69 size_t fRowBytes;
70 SkColorType fDstColorType;
71
72 protected:
73 const SkFrame* onGetFrame(int i) const override {
74 SkASSERT(i >= 0 && static_cast<size_t>(i) < fFrames.size());
75 return static_cast<const SkFrame*>(&fFrames[i]);
76 }
77 };
78
79 SkJpegxlCodec::SkJpegxlCodec(std::unique_ptr<SkJpegxlCodecPriv> codec,
80 SkEncodedInfo&& info,
81 std::unique_ptr<SkStream> stream,
82 sk_sp<const SkData> data)
83 : INHERITED(std::move(info), skcms_PixelFormat_RGBA_16161616LE, std::move(stream))
84 , fCodec(std::move(codec))
85 , fData(std::move(data)) {}
86
87 std::unique_ptr<SkCodec> SkJpegxlCodec::MakeFromStream(std::unique_ptr<SkStream> stream,
88 Result* result) {
89 SkASSERT(result);
90 if (!stream) {
91 *result = SkCodec::kInvalidInput;
92 return nullptr;
93 }
94 *result = kInternalError;
95 // Either wrap or copy stream data.
96 sk_sp<const SkData> data = nullptr;
97 if (stream->getMemoryBase()) {
98 data = SkData::MakeWithoutCopy(stream->getMemoryBase(), stream->getLength());
99 } else {
100 data = SkStreamPriv::CopyStreamToData(stream.get());
101 // Data is copied; stream can be released now.
102 stream.reset(nullptr);
103 }
104
105 auto priv = std::make_unique<SkJpegxlCodecPriv>();
106 JxlDecoder* dec = priv->fDecoder.get();
107
108 // Only query metadata this time.
109 auto status = JxlDecoderSubscribeEvents(dec, JXL_DEC_BASIC_INFO | JXL_DEC_COLOR_ENCODING);
110 if (status != JXL_DEC_SUCCESS) {
111 // Fresh instance must accept request for subscription.
112 SkDEBUGFAIL("libjxl returned unexpected status");
113 return nullptr;
114 }
115
116 status = JxlDecoderSetInput(dec, data->bytes(), data->size());
117 if (status != JXL_DEC_SUCCESS) {
118 // Fresh instance must accept first chunk of input.
119 SkDEBUGFAIL("libjxl returned unexpected status");
120 return nullptr;
121 }
122
123 status = JxlDecoderProcessInput(dec);
124 if (status == JXL_DEC_NEED_MORE_INPUT) {
125 *result = kIncompleteInput;
126 return nullptr;
127 }
128 if (status != JXL_DEC_BASIC_INFO) {
129 *result = kInvalidInput;
130 return nullptr;
131 }
132 JxlBasicInfo& info = priv->fInfo;
133 status = JxlDecoderGetBasicInfo(dec, &info);
134 if (status != JXL_DEC_SUCCESS) {
135 // Current event is "JXL_DEC_BASIC_INFO" -> can't fail.
136 SkDEBUGFAIL("libjxl returned unexpected status");
137 return nullptr;
138 }
139
140 // Check that image dimensions are not too large.
141 if (!SkTFitsIn<int32_t>(info.xsize) || !SkTFitsIn<int32_t>(info.ysize)) {
142 *result = kInvalidInput;
143 return nullptr;
144 }
145 int32_t width = SkTo<int32_t>(info.xsize);
146 int32_t height = SkTo<int32_t>(info.ysize);
147
148 bool hasAlpha = (info.alpha_bits != 0);
149 bool isGray = (info.num_color_channels == 1);
150 SkEncodedInfo::Alpha alpha =
151 hasAlpha ? SkEncodedInfo::kUnpremul_Alpha : SkEncodedInfo::kOpaque_Alpha;
152 SkEncodedInfo::Color color;
153 if (hasAlpha) {
154 color = isGray ? SkEncodedInfo::kGrayAlpha_Color : SkEncodedInfo::kRGBA_Color;
155 } else {
156 color = isGray ? SkEncodedInfo::kGray_Color : SkEncodedInfo::kRGB_Color;
157 }
158
159 status = JxlDecoderProcessInput(dec);
160 if (status != JXL_DEC_COLOR_ENCODING) {
161 *result = kInvalidInput;
162 return nullptr;
163 }
164
165 size_t iccSize = 0;
166 // TODO(eustas): format field is currently ignored by decoder.
167 status = JxlDecoderGetICCProfileSize(
168 dec, /* format = */ nullptr, JXL_COLOR_PROFILE_TARGET_DATA, &iccSize);
169 if (status != JXL_DEC_SUCCESS) {
170 // Likely incompatible colorspace.
171 iccSize = 0;
172 }
173 std::unique_ptr<SkCodecs::ColorProfile> profile;
174 if (iccSize) {
175 auto icc = SkData::MakeUninitialized(iccSize);
176 // TODO(eustas): format field is currently ignored by decoder.
177 status = JxlDecoderGetColorAsICCProfile(dec,
178 /* format = */ nullptr,
179 JXL_COLOR_PROFILE_TARGET_DATA,
180 reinterpret_cast<uint8_t*>(icc->writable_data()),
181 iccSize);
182 if (status != JXL_DEC_SUCCESS) {
183 // Current event is JXL_DEC_COLOR_ENCODING -> can't fail.
184 SkDEBUGFAIL("libjxl returned unexpected status");
185 return nullptr;
186 }
187 profile = SkCodecs::ColorProfile::MakeICCProfile(std::move(icc));
188 }
189
190 int bitsPerChannel = 16;
191
192 *result = kSuccess;
193 SkEncodedInfo encodedInfo =
194 SkEncodedInfo::Make(width, height, color, alpha, bitsPerChannel, std::move(profile));
195
196 return std::unique_ptr<SkCodec>(new SkJpegxlCodec(
197 std::move(priv), std::move(encodedInfo), std::move(stream), std::move(data)));
198 }
199
200 SkCodec::Result SkJpegxlCodec::onGetPixels(const SkImageInfo& dstInfo, void* dst, size_t rowBytes,
201 const Options& options, int* rowsDecodedPtr) {
202 // TODO(eustas): implement
203 if (options.fSubset) {
204 return kUnimplemented;
205 }
206 auto& codec = *fCodec.get();
207 const int index = options.fFrameIndex;
208 SkASSERT(0 == index || static_cast<size_t>(index) < codec.fFrames.size());
209 auto* dec = codec.fDecoder.get();
210 JxlDecoderStatus status;
211
212 if ((codec.fLastProcessedFrame >= index) || (codec.fLastProcessedFrame = SkCodec::kNoFrame)) {
213 codec.fLastProcessedFrame = SkCodec::kNoFrame;
214 JxlDecoderRewind(dec);
215 status = JxlDecoderSubscribeEvents(dec, JXL_DEC_FRAME | JXL_DEC_FULL_IMAGE);
216 if (status != JXL_DEC_SUCCESS) {
217 // Fresh decoder instance (after rewind) must accept subscription request.
218 SkDEBUGFAIL("libjxl returned unexpected status");
219 return kInternalError;
220 }
221 status = JxlDecoderSetInput(dec, fData->bytes(), fData->size());
222 if (status != JXL_DEC_SUCCESS) {
223 // Fresh decoder instance (after rewind) must accept first data chunk.
224 SkDEBUGFAIL("libjxl returned unexpected status");
225 return kInternalError;
226 }
227 SkASSERT(codec.fLastProcessedFrame + 1 == 0);
228 }
229
230 int nextFrame = codec.fLastProcessedFrame + 1;
231 if (nextFrame < index) {
232 JxlDecoderSkipFrames(dec, index - nextFrame);
233 }
234
235 // Decode till the frame start.
236 status = JxlDecoderProcessInput(dec);
237 // TODO(eustas): actually, frame is not completely processed; for streaming / partial decoding
238 // we should also add a flag that "last processed frame" is still incomplete, and
239 // flip that flag when frame decoding is over.
240 codec.fLastProcessedFrame = index;
241 if (status != JXL_DEC_FRAME) {
242 // TODO(eustas): check status: it might be either corrupted or incomplete input.
243 return kInternalError;
244 }
245
246 codec.fDst = dst;
247 codec.fRowBytes = rowBytes;
248
249 // TODO(eustas): consider grayscale.
250 uint32_t numColorChannels = 3;
251 // TODO(eustas): consider no-alpha.
252 uint32_t numAlphaChannels = 1;
253 // NB: SKIA works with little-endian F16s.
254 auto endianness = JXL_LITTLE_ENDIAN;
255
256 // Internally JXL does most processing in floats. By "default" we request
257 // output data type to be U8; it takes less memory, but results in some precision loss.
258 // We request F16 in two cases:
259 // - destination type is F16
260 // - color transformation is required; in this case values are remapped,
261 // and with 8-bit precision it is likely that visual artefact will appear
262 // (like banding, etc.)
263 bool halfFloatOutput = false;
264 if (fCodec->fDstColorType == kRGBA_F16_SkColorType) halfFloatOutput = true;
265 if (colorXform()) halfFloatOutput = true;
266 auto dataType = halfFloatOutput ? JXL_TYPE_FLOAT16 : JXL_TYPE_UINT8;
267
268 JxlPixelFormat format =
269 {numColorChannels + numAlphaChannels, dataType, endianness, /* align = */ 0};
270 status = JxlDecoderSetImageOutCallback(dec, &format, SkJpegxlCodec::imageOutCallback, this);
271 if (status != JXL_DEC_SUCCESS) {
272 // Current event is JXL_DEC_FRAME -> decoder must accept callback.
273 SkDEBUGFAIL("libjxl returned unexpected status");
274 return kInternalError;
275 }
276
277 // Decode till the frame start.
278 status = JxlDecoderProcessInput(dec);
279 if (status != JXL_DEC_FULL_IMAGE) {
280 // TODO(eustas): check status: it might be either corrupted or incomplete input.
281 return kInternalError;
282 }
283 // TODO(eustas): currently it is supposed that complete input is accessible;
284 // when streaming support is added JXL_DEC_NEED_MORE_INPUT would also
285 // become a legal outcome; amount of decoded scanlines should be calculated
286 // based on callback invocations / render-pipeline API.
287 *rowsDecodedPtr = dstInfo.height();
288
289 return kSuccess;
290 }
291
292 bool SkJpegxlCodec::onRewind() {
293 if (!this->rewindStream()) {
294 return false;
295 }
296 JxlDecoderRewind(fCodec->fDecoder.get());
297 return true;
298 }
299
300 bool SkJpegxlCodec::conversionSupported(const SkImageInfo& dstInfo, bool srcIsOpaque,
301 bool needsColorXform) {
302 fCodec->fDstColorType = dstInfo.colorType();
303 switch (dstInfo.colorType()) {
304 case kRGBA_8888_SkColorType:
305 return true; // memcpy
306 case kBGRA_8888_SkColorType:
307 return true; // rgba->bgra
308
309 case kRGBA_F16_SkColorType:
310 SkASSERT(needsColorXform); // TODO(eustas): not necessary for JXL.
311 return true; // memcpy
312
313 // TODO(eustas): implement
314 case kRGB_565_SkColorType:
315 return false;
316 case kGray_8_SkColorType:
317 return false;
318 case kAlpha_8_SkColorType:
319 return false;
320
321 default:
322 return false;
323 }
324 return true;
325 }
326
327 void SkJpegxlCodec::imageOutCallback(void* opaque, size_t x, size_t y,
328 size_t num_pixels, const void* pixels) {
329 SkJpegxlCodec* instance = reinterpret_cast<SkJpegxlCodec*>(opaque);
330 auto& codec = *instance->fCodec.get();
331 size_t offset = y * codec.fRowBytes + (x << codec.fPixelShift);
332 void* dst = SkTAddOffset<void>(codec.fDst, offset);
333 if (instance->colorXform()) {
334 instance->applyColorXform(dst, pixels, num_pixels);
335 return;
336 }
337 switch (codec.fDstColorType) {
338 case kRGBA_8888_SkColorType:
339 memcpy(dst, pixels, 4 * num_pixels);
340 return;
341 case kBGRA_8888_SkColorType:
342 SkOpts::RGBA_to_bgrA((uint32_t*) dst, (const uint32_t*)(pixels), num_pixels);
343 return;
344 case kRGBA_F16_SkColorType:
345 memcpy(dst, pixels, 8 * num_pixels);
346 return;
347 default:
348 SK_ABORT("Selected output format is not supported yet");
349 return;
350 }
351 }
352
353 bool SkJpegxlCodec::scanFrames() {
354 auto decoder = JxlDecoderMake(/* memory_manager = */ nullptr);
355 JxlDecoder* dec = decoder.get();
356 auto* frameHolder = fCodec.get();
357 auto& frames = frameHolder->fFrames;
358 const auto& info = fCodec->fInfo;
359 frames.clear();
360
361 auto alpha = (info.alpha_bits != 0) ? SkEncodedInfo::Alpha::kUnpremul_Alpha
362 : SkEncodedInfo::Alpha::kOpaque_Alpha;
363
364 auto status = JxlDecoderSubscribeEvents(dec, JXL_DEC_FRAME);
365 if (status != JXL_DEC_SUCCESS) {
366 // Fresh instance must accept request for subscription.
367 SkDEBUGFAIL("libjxl returned unexpected status");
368 return true;
369 }
370
371 status = JxlDecoderSetInput(dec, fData->bytes(), fData->size());
372 if (status != JXL_DEC_SUCCESS) {
373 // Fresh instance must accept first input chunk.
374 SkDEBUGFAIL("libjxl returned unexpected status");
375 return true;
376 }
377
378 while (true) {
379 status = JxlDecoderProcessInput(dec);
380 switch (status) {
381 case JXL_DEC_FRAME: {
382 size_t frameId = frames.size();
383 JxlFrameHeader frameHeader;
384 if (JxlDecoderGetFrameHeader(dec, &frameHeader) != JXL_DEC_SUCCESS) {
385 return true;
386 }
387 frames.emplace_back(static_cast<int>(frameId), alpha);
388 auto& frame = frames.back();
389 // TODO(eustas): for better consistency we need to track total duration and report
390 // frame duration as delta to previous frame.
391 int duration = (1000 * frameHeader.duration * info.animation.tps_denominator) /
392 info.animation.tps_numerator;
393 frame.setDuration(duration);
394 frameHolder->setAlphaAndRequiredFrame(&frame);
395 break;
396 }
397 case JXL_DEC_SUCCESS: {
398 return true;
399 }
400 default: {
401 return false;
402 }
403 }
404 }
405 }
406
407 int SkJpegxlCodec::onGetFrameCount() {
408 if (!fCodec->fInfo.have_animation) {
409 return 1;
410 }
411
412 if (!fCodec->fSeenAllFrames) {
413 fCodec->fSeenAllFrames = scanFrames();
414 }
415
416 return fCodec->fFrames.size();
417 }
418
419 bool SkJpegxlCodec::onGetFrameInfo(int index, FrameInfo* frameInfo) const {
420 if (index < 0) {
421 return false;
422 }
423 if (static_cast<size_t>(index) >= fCodec->fFrames.size()) {
424 return false;
425 }
426 fCodec->fFrames[index].fillIn(frameInfo, true);
427 return true;
428 }
429
430 int SkJpegxlCodec::onGetRepetitionCount() {
431 JxlBasicInfo& info = fCodec->fInfo;
432 if (!info.have_animation) {
433 return 0;
434 }
435
436 if (info.animation.num_loops == 0) {
437 return kRepetitionCountInfinite;
438 }
439
440 if (SkTFitsIn<int>(info.animation.num_loops)) {
441 return info.animation.num_loops - 1;
442 }
443
444 // Largest "non-infinite" value.
445 return std::numeric_limits<int>::max();
446 }
447
448 SkCodec::IsAnimated SkJpegxlCodec::onIsAnimated() {
449 JxlBasicInfo& info = fCodec->fInfo;
450 return info.have_animation ? IsAnimated::kYes : IsAnimated::kNo;
451 }
452
453 const SkFrameHolder* SkJpegxlCodec::getFrameHolder() const {
454 return fCodec.get();
455 }
456
457 // TODO(eustas): implement
458 // SkCodec::Result SkJpegxlCodec::onStartScanlineDecode(
459 // const SkImageInfo& /*dstInfo*/, const Options& /*options*/) { return kUnimplemented; }
460
461 // TODO(eustas): implement
462 // SkCodec::Result SkJpegxlCodec::onStartIncrementalDecode(
463 // const SkImageInfo& /*dstInfo*/, void*, size_t, const Options&) { return kUnimplemented; }
464
465 // TODO(eustas): implement
466 // SkCodec::Result SkJpegxlCodec::onIncrementalDecode(int*) { return kUnimplemented; }
467
468 // TODO(eustas): implement
469 // bool SkJpegxlCodec::onSkipScanlines(int /*countLines*/) { return false; }
470
471 // TODO(eustas): implement
472 // int SkJpegxlCodec::onGetScanlines(
473 // void* /*dst*/, int /*countLines*/, size_t /*rowBytes*/) { return 0; }
474
475 // TODO(eustas): implement
476 // SkSampler* SkJpegxlCodec::getSampler(bool /*createIfNecessary*/) { return nullptr; }
477
478 namespace SkJpegxlDecoder {
479 bool IsJpegxl(const void* data, size_t len) {
480 return SkJpegxlCodec::IsJpegxl(data, len);
481 }
482
483 std::unique_ptr<SkCodec> Decode(std::unique_ptr<SkStream> stream,
484 SkCodec::Result* outResult,
485 SkCodecs::DecodeContext) {
486 SkCodec::Result resultStorage;
487 if (!outResult) {
488 outResult = &resultStorage;
489 }
490 return SkJpegxlCodec::MakeFromStream(std::move(stream), outResult);
491 }
492
493 std::unique_ptr<SkCodec> Decode(sk_sp<const SkData> data,
494 SkCodec::Result* outResult,
495 SkCodecs::DecodeContext) {
496 if (!data) {
497 if (outResult) {
498 *outResult = SkCodec::kInvalidInput;
499 }
500 return nullptr;
501 }
502 return Decode(SkMemoryStream::Make(std::move(data)), outResult, nullptr);
503 }
504 } // namespace SkJpegDecoder