Krita Source Code Documentation
Loading...
Searching...
No Matches
JPEGXLImport Class Reference

#include <JPEGXLImport.h>

+ Inheritance diagram for JPEGXLImport:

Public Member Functions

KisImportExportErrorCode convert (KisDocument *document, QIODevice *io, KisPropertiesConfigurationSP configuration=nullptr) override
 
 JPEGXLImport (QObject *parent, const QVariantList &)
 
bool supportsIO () const override
 Override and return false for the filters that use a library that cannot handle file handles, only file names.
 
 ~JPEGXLImport () override=default
 
- Public Member Functions inherited from KisImportExportFilter
virtual KisConfigWidget * createConfigurationWidget (QWidget *parent, const QByteArray &from="", const QByteArray &to="") const
 createConfigurationWidget creates a widget that can be used to define the settings for a given import/export filter
 
virtual KisPropertiesConfigurationSP defaultConfiguration (const QByteArray &from="", const QByteArray &to="") const
 defaultConfiguration defines the default settings for the given import export filter
 
virtual QMap< QString, KisExportCheckBase * > exportChecks ()
 generate and return the list of capabilities of this export filter. The list
 
virtual bool exportSupportsGuides () const
 exportSupportsGuides Because guides are in the document and not the image, checking for guides cannot be made an exportCheck.
 
KisPropertiesConfigurationSP lastSavedConfiguration (const QByteArray &from="", const QByteArray &to="") const
 lastSavedConfiguration return the last saved configuration for this filter
 
 Private ()
 
void setBatchMode (bool batchmode)
 
void setFilename (const QString &filename)
 
void setImportUserFeedBackInterface (KisImportUserFeedbackInterface *interface)
 
void setMimeType (const QString &mime)
 
void setRealFilename (const QString &filename)
 
void setUpdater (QPointer< KoUpdater > updater)
 
QPointer< KoUpdater > updater ()
 
virtual QString verify (const QString &fileName) const
 Verify whether the given file is correct and readable.
 
 ~KisImportExportFilter () override
 
 ~Private ()
 

Additional Inherited Members

- Public Attributes inherited from KisImportExportFilter
bool batchmode
 
QMap< QString, KisExportCheckBase * > capabilities
 
QString filename
 
KisImportUserFeedbackInterface * importUserFeedBackInterface {nullptr}
 
QByteArray mime
 
QString realFilename
 
QPointer< KoUpdater > updater
 
- Static Public Attributes inherited from KisImportExportFilter
static const QString CICPPrimariesTag = "CICPCompatiblePrimaries"
 
static const QString CICPTransferCharacteristicsTag = "CICPCompatibleTransferFunction"
 
static const QString ColorDepthIDTag = "ColorDepthID"
 
static const QString ColorModelIDTag = "ColorModelID"
 
static const QString HDRTag = "HDRSupported"
 
static const QString ImageContainsTransparencyTag = "ImageContainsTransparency"
 
static const QString sRGBTag = "sRGB"
 
- Protected Member Functions inherited from KisImportExportFilter
void addCapability (KisExportCheckBase *capability)
 
void addSupportedColorModels (QList< QPair< KoID, KoID > > supportedColorModels, const QString &name, KisExportCheckBase::Level level=KisExportCheckBase::PARTIALLY)
 
bool batchMode () const
 
QString filename () const
 
KisImportUserFeedbackInterface * importUserFeedBackInterface () const
 
virtual void initializeCapabilities ()
 
 KisImportExportFilter (QObject *parent=0)
 
QByteArray mimeType () const
 
QString realFilename () const
 
void setProgress (int value)
 
QString verifyZiPBasedFiles (const QString &fileName, const QStringList &filesToCheck) const
 

Detailed Description

Definition at line 12 of file JPEGXLImport.h.

Constructor & Destructor Documentation

◆ JPEGXLImport()

JPEGXLImport::JPEGXLImport ( QObject * parent,
const QVariantList &  )

Definition at line 240 of file JPEGXLImport.cpp.

241 : KisImportExportFilter(parent)
242{
243}
KisImportExportFilter(QObject *parent=0)

◆ ~JPEGXLImport()

JPEGXLImport::~JPEGXLImport ( )
overridedefault

Member Function Documentation

◆ convert()

KisImportExportErrorCode JPEGXLImport::convert ( KisDocument * document,
QIODevice * io,
KisPropertiesConfigurationSP configuration = nullptr )
overridevirtual

The filter chain calls this method to perform the actual conversion. The passed mimetypes should be a pair of those you specified in your .desktop file. You have to implement this method to make the filter work.

Returns
The error status, see the #ConversionStatus enum. KisImportExportFilter::OK means that everything is alright.

Implements KisImportExportFilter.

Definition at line 246 of file JPEGXLImport.cpp.

247{
248 if (!io->isReadable()) {
249 errFile << "Cannot read image contents";
251 }
252
254 const auto data = io->readAll();
255
256 const auto validation =
257 JxlSignatureCheck(reinterpret_cast<const uint8_t *>(data.constData()), static_cast<size_t>(data.size()));
258
259 switch (validation) {
260 case JXL_SIG_NOT_ENOUGH_BYTES:
261 errFile << "Failed magic byte validation, not enough data";
263 case JXL_SIG_INVALID:
264 errFile << "Failed magic byte validation, incorrect format";
266 default:
267 break;
268 }
269
270 // Multi-threaded parallel runner.
271 auto runner = JxlResizableParallelRunnerMake(nullptr);
272 auto dec = JxlDecoderMake(nullptr);
273
275
276 // List of blend mode that we can currently support
277 static constexpr std::array<JxlBlendMode, 3> supportedBlendMode = {JXL_BLEND_REPLACE, JXL_BLEND_BLEND, JXL_BLEND_MULADD};
278
279 // Metadata and frame header decoding
280 bool isAnimated = false;
281 bool isMultilayer = false;
282 bool isMultipage = false;
283 bool forceCoalesce = false;
284 {
285 if (JXL_DEC_SUCCESS
286 != JxlDecoderSubscribeEvents(dec.get(), JXL_DEC_BASIC_INFO | JXL_DEC_FRAME)) {
287 errFile << "JxlDecoderSubscribeEvents failed";
289 }
290
291 if (JXL_DEC_SUCCESS != JxlDecoderSetParallelRunner(dec.get(), JxlResizableParallelRunner, runner.get())) {
292 errFile << "JxlDecoderSetParallelRunner failed";
294 }
295
296 if (JXL_DEC_SUCCESS
297 != JxlDecoderSetInput(dec.get(),
298 reinterpret_cast<const uint8_t *>(data.constData()),
299 static_cast<size_t>(data.size()))) {
300 errFile << "JxlDecoderSetInput failed";
302 };
303 JxlDecoderCloseInput(dec.get());
304
305 if (JXL_DEC_SUCCESS != JxlDecoderSetDecompressBoxes(dec.get(), JXL_TRUE)) {
306 errFile << "JxlDecoderSetDecompressBoxes failed";
308 };
309
310 if (JXL_DEC_SUCCESS != JxlDecoderSetCoalescing(dec.get(), JXL_FALSE)) {
311 errFile << "JxlDecoderSetCoalescing failed";
313 };
314
315 for (;;) {
316 JxlDecoderStatus status = JxlDecoderProcessInput(dec.get());
317
318 if (status == JXL_DEC_ERROR) {
319 errFile << "Decoder error";
321 } else if (status == JXL_DEC_NEED_MORE_INPUT) {
322 errFile << "Error, already provided all input";
324 } else if (status == JXL_DEC_BASIC_INFO) {
325 if (JXL_DEC_SUCCESS != JxlDecoderGetBasicInfo(dec.get(), &d.m_info)) {
326 errFile << "JxlDecoderGetBasicInfo failed";
328 }
329 // Coalesce frame on animation import
330 if (d.m_info.have_animation) {
331 isMultilayer = false;
332 isAnimated = true;
333 isMultipage = true;
334 forceCoalesce = true;
335 }
336
337 dbgFile << "Extra Channel[s] info:";
338 for (uint32_t i = 0; i < d.m_info.num_extra_channels; i++) {
339 if (JXL_DEC_SUCCESS != JxlDecoderGetExtraChannelInfo(dec.get(), i, &d.m_extra)) {
340 errFile << "JxlDecoderGetExtraChannelInfo failed";
341 break;
342 }
343 // Channel name references taken from libjxl repo:
344 // https://github.com/libjxl/libjxl/blob/v0.8.0/lib/extras/enc/pnm.cc#L262
345 // With added "JXL-" prefix to indicate that it comes from JXL image.
346 const QString channelTypeString = [&]() {
347 switch (d.m_extra.type) {
348 case JXL_CHANNEL_ALPHA:
349 return QString("JXL-Alpha");
350 case JXL_CHANNEL_DEPTH:
351 return QString("JXL-Depth");
352 case JXL_CHANNEL_SPOT_COLOR:
353 return QString("JXL-SpotColor");
354 case JXL_CHANNEL_SELECTION_MASK:
355 return QString("JXL-SelectionMask");
356 case JXL_CHANNEL_BLACK:
357 return QString("JXL-Black");
358 case JXL_CHANNEL_CFA:
359 return QString("JXL-CFA");
360 case JXL_CHANNEL_THERMAL:
361 return QString("JXL-Thermal");
362 default:
363 return QString("JXL-UNKNOWN");
364 }
365 }();
366
367 // List all extra channels
368 dbgFile << "index:" << i << " | type:" << channelTypeString;
369 if (d.m_extra.type == JXL_CHANNEL_BLACK) {
370 d.isCMYK = true;
371 d.cmykChannelID = i;
372 }
373 if (d.m_extra.type == JXL_CHANNEL_SPOT_COLOR) {
374 warnFile << "Spot color channels unsupported! Rewinding decoder with coalescing enabled";
375 document->setWarningMessage(i18nc("JPEG-XL errors",
376 "Detected JPEG-XL image with spot color channels, "
377 "importing flattened image."));
378 forceCoalesce = true;
379 }
380 }
381
382 dbgFile << "Info";
383 dbgFile << "Size:" << d.m_info.xsize << "x" << d.m_info.ysize;
384 dbgFile << "Depth:" << d.m_info.bits_per_sample << d.m_info.exponent_bits_per_sample;
385 dbgFile << "Number of color channels:" << d.m_info.num_color_channels;
386 dbgFile << "Number of extra channels:" << d.m_info.num_extra_channels;
387 dbgFile << "Extra channels depth:" << d.m_info.alpha_bits << d.m_info.alpha_exponent_bits;
388 dbgFile << "Has animation:" << d.m_info.have_animation << "loops:" << d.m_info.animation.num_loops
389 << "tick:" << d.m_info.animation.tps_numerator << d.m_info.animation.tps_denominator;
390 dbgFile << "Internal pixel format:" << (d.m_info.uses_original_profile ? "Original" : "XYB");
391 JxlResizableParallelRunnerSetThreads(
392 runner.get(),
393 JxlResizableParallelRunnerSuggestThreads(d.m_info.xsize, d.m_info.ysize));
394
395 if (d.m_info.exponent_bits_per_sample != 0) {
396 if (d.m_info.bits_per_sample <= 16) {
397 d.m_pixelFormat.data_type = JXL_TYPE_FLOAT16;
398 d.m_depthID = Float16BitsColorDepthID;
399 } else if (d.m_info.bits_per_sample <= 32) {
400 d.m_pixelFormat.data_type = JXL_TYPE_FLOAT;
401 d.m_depthID = Float32BitsColorDepthID;
402 } else {
403 errFile << "Unsupported JPEG-XL input depth" << d.m_info.bits_per_sample
404 << d.m_info.exponent_bits_per_sample;
406 }
407 } else if (d.m_info.bits_per_sample <= 8) {
408 d.m_pixelFormat.data_type = JXL_TYPE_UINT8;
409 d.m_depthID = Integer8BitsColorDepthID;
410 } else if (d.m_info.bits_per_sample <= 16) {
411 d.m_pixelFormat.data_type = JXL_TYPE_UINT16;
412 d.m_depthID = Integer16BitsColorDepthID;
413 } else {
414 errFile << "Unsupported JPEG-XL input depth" << d.m_info.bits_per_sample
415 << d.m_info.exponent_bits_per_sample;
417 }
418
419 if (d.m_info.num_color_channels == 1) {
420 // Grayscale
421 d.m_pixelFormat.num_channels = 2;
422 d.m_colorID = GrayAColorModelID;
423 } else if (d.m_info.num_color_channels == 3 && !d.isCMYK) {
424 // RGBA
425 d.m_pixelFormat.num_channels = 4;
426 d.m_colorID = RGBAColorModelID;
427 } else if (d.m_info.num_color_channels == 3 && d.isCMYK) {
428 // CMYKA
429 d.m_pixelFormat.num_channels = 4;
430 d.m_colorID = CMYKAColorModelID;
431 } else {
432 warnFile << "Forcing a RGBA conversion, unknown color space";
433 d.m_pixelFormat.num_channels = 4;
434 d.m_colorID = RGBAColorModelID;
435 }
436
437 if (!d.m_info.uses_original_profile) {
438 d.m_pixelFormat_target.data_type = d.m_pixelFormat.data_type;
439 d.m_pixelFormat.data_type = JXL_TYPE_FLOAT;
440 d.m_depthID_target = d.m_depthID;
441 d.m_colorID_target = d.m_colorID;
442 d.m_depthID = Float32BitsColorDepthID;
443
444 if (d.m_colorID != GrayAColorModelID) {
445 d.m_colorID = RGBAColorModelID;
446 }
447 }
448 } else if (status == JXL_DEC_FRAME) {
449 if (JXL_DEC_SUCCESS != JxlDecoderGetFrameHeader(dec.get(), &d.m_header)) {
450 errFile << "JxlDecoderGetFrameHeader failed";
452 }
453
454 const JxlBlendMode blendMode = d.m_header.layer_info.blend_info.blendmode;
455 const bool isBlendSupported =
456 std::find(supportedBlendMode.begin(), supportedBlendMode.end(), blendMode) != supportedBlendMode.end();
457
458 if (!isBlendSupported) {
459 forceCoalesce = true;
460 }
461
462 if (d.m_header.duration == 0) {
463 isMultilayer = true;
464 } else if (d.m_header.duration == 0xFFFFFFFF) {
465 isMultipage = true;
466 isAnimated = false;
467 forceCoalesce = true;
468 } else {
469 isAnimated = true;
470 isMultipage = false;
471 isMultilayer = false;
472 forceCoalesce = true;
473 }
474 } else if (status == JXL_DEC_SUCCESS) {
475 break;
476 }
477 }
478 }
479 JxlDecoderReset(dec.get());
480
481 // Set coalescing FALSE to enable layered JXL
482 if (JXL_DEC_SUCCESS != JxlDecoderSetCoalescing(dec.get(), forceCoalesce ? JXL_TRUE : JXL_FALSE)) {
483 errFile << "JxlDecoderSetCoalescing failed";
485 }
486
487 if (JXL_DEC_SUCCESS
488 != JxlDecoderSubscribeEvents(dec.get(),
489 JXL_DEC_COLOR_ENCODING | JXL_DEC_FULL_IMAGE | JXL_DEC_BOX | JXL_DEC_FRAME)) {
490 errFile << "JxlDecoderSubscribeEvents failed";
492 }
493
494 if (JXL_DEC_SUCCESS != JxlDecoderSetParallelRunner(dec.get(), JxlResizableParallelRunner, runner.get())) {
495 errFile << "JxlDecoderSetParallelRunner failed";
497 }
498
499 if (JXL_DEC_SUCCESS
500 != JxlDecoderSetInput(dec.get(),
501 reinterpret_cast<const uint8_t *>(data.constData()),
502 static_cast<size_t>(data.size()))) {
503 errFile << "JxlDecoderSetInput failed";
505 };
506 JxlDecoderCloseInput(dec.get());
507
508 if (JXL_DEC_SUCCESS != JxlDecoderSetDecompressBoxes(dec.get(), JXL_TRUE)) {
509 errFile << "JxlDecoderSetDecompressBoxes failed";
511 };
512
513 KisImageSP image{nullptr};
514 KisLayerSP layer{nullptr};
515 std::multimap<QByteArray, QByteArray> metadataBoxes;
516 std::vector<KisLayerSP> additionalLayers;
517 bool bgLayerSet = false;
518 bool needColorTransform = false;
519 bool needIntermediateTransform = false;
520 QByteArray boxType(5, 0x0);
521 QByteArray box(16384, 0x0);
522 auto boxSize = box.size();
523
524 // Basic info already parsed above, skip doing it again
525 for (;;) {
526 JxlDecoderStatus status = JxlDecoderProcessInput(dec.get());
527
528 if (status == JXL_DEC_ERROR) {
529 errFile << "Decoder error";
531 } else if (status == JXL_DEC_NEED_MORE_INPUT) {
532 errFile << "Error, already provided all input";
534 } else if (status == JXL_DEC_COLOR_ENCODING) {
535 // Determine color space information
536 const KoColorProfile *profile = nullptr;
537 const KoColorProfile *profileTarget = nullptr;
538 const KoColorProfile *profileIntermediate = nullptr;
539
540 // Chrome way of decoding JXL implies first scanning
541 // the CICP encoding for HDR, and only afterwards
542 // falling back to ICC.
543 JxlColorEncoding colorEncoding{};
544 if (JXL_DEC_SUCCESS
545 == JxlDecoderGetColorAsEncodedProfile(dec.get(),
546#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0, 9, 0)
547 nullptr,
548#endif
549 JXL_COLOR_PROFILE_TARGET_DATA,
550 &colorEncoding)) {
551 const TransferCharacteristics transferFunction = [&]() {
552 switch (colorEncoding.transfer_function) {
553 case JXL_TRANSFER_FUNCTION_PQ: {
554 dbgFile << "linearizing from PQ";
555 d.linearizePolicy = LinearizePolicy::LinearFromPQ;
556 return TRC_LINEAR;
557 }
558 case JXL_TRANSFER_FUNCTION_HLG: {
559 dbgFile << "linearizing from HLG";
560 d.linearizePolicy = LinearizePolicy::LinearFromHLG;
561 return TRC_LINEAR;
562 }
563 case JXL_TRANSFER_FUNCTION_DCI: {
564 dbgFile << "linearizing from SMPTE 428";
565 d.linearizePolicy = LinearizePolicy::LinearFromSMPTE428;
566 return TRC_LINEAR;
567 }
568 case JXL_TRANSFER_FUNCTION_709:
569 return TRC_ITU_R_BT_709_5;
570 case JXL_TRANSFER_FUNCTION_SRGB:
571 return TRC_IEC_61966_2_1;
572 case JXL_TRANSFER_FUNCTION_GAMMA: {
573 // Using roughly the same logic in KoColorProfile.
574 const double estGamma = 1.0 / colorEncoding.gamma;
575 const double error = 0.0001;
576 // ICC v2 u8Fixed8Number calculation
577 // Or can be prequantized as 1.80078125, courtesy of Elle Stone
578 if ((std::fabs(estGamma - 1.8) < error) || (std::fabs(estGamma - (461.0 / 256.0)) < error)) {
579 return TRC_GAMMA_1_8;
580 } else if (std::fabs(estGamma - 2.2) < error) {
582 } else if (std::fabs(estGamma - (563.0 / 256.0)) < error) {
583 return TRC_A98;
584 } else if (std::fabs(estGamma - 2.4) < error) {
585 return TRC_GAMMA_2_4;
586 } else if (std::fabs(estGamma - 2.8) < error) {
588 } else {
589 warnFile << "Found custom estimated gamma value for JXL color space" << estGamma;
590 return TRC_UNSPECIFIED;
591 }
592 }
593 case JXL_TRANSFER_FUNCTION_LINEAR:
594 return TRC_LINEAR;
595 case JXL_TRANSFER_FUNCTION_UNKNOWN:
596 default:
597 warnFile << "Found unknown OETF";
598 return TRC_UNSPECIFIED;
599 }
600 }();
601
602 const ColorPrimaries colorPrimaries = [&]() {
603 switch (colorEncoding.primaries) {
604 case JXL_PRIMARIES_SRGB:
606 case JXL_PRIMARIES_2100:
608 case JXL_PRIMARIES_P3:
610 default:
612 }
613 }();
614
615 const QVector<double> colorants = [&]() -> QVector<double> {
616 if (colorEncoding.primaries != JXL_PRIMARIES_CUSTOM) {
617 return {};
618 } else {
619 return {colorEncoding.white_point_xy[0],
620 colorEncoding.white_point_xy[1],
621 colorEncoding.primaries_red_xy[0],
622 colorEncoding.primaries_red_xy[1],
623 colorEncoding.primaries_green_xy[0],
624 colorEncoding.primaries_green_xy[1],
625 colorEncoding.primaries_blue_xy[0],
626 colorEncoding.primaries_blue_xy[1]};
627 }
628 }();
629
630 if (colorEncoding.rendering_intent == JXL_RENDERING_INTENT_PERCEPTUAL) {
632 } else if (colorEncoding.rendering_intent == JXL_RENDERING_INTENT_RELATIVE) {
634 } else if (colorEncoding.rendering_intent == JXL_RENDERING_INTENT_ABSOLUTE) {
636 } else if (colorEncoding.rendering_intent == JXL_RENDERING_INTENT_SATURATION) {
638 } else {
639 warnFile << "Cannot determine color rendering intent, set to Perceptual instead";
641 }
642
643 KoColorProfileQuery query(colorPrimaries, transferFunction);
644 profile = KoColorSpaceRegistry::instance()->profileFor(query);
645
646 dbgFile << "CICP profile data:" << colorants << colorPrimaries << transferFunction;
647
648 if (profile) {
649 dbgFile << "JXL CICP profile found" << profile->name();
650
651 if (d.linearizePolicy != LinearizePolicy::KeepTheSame) {
652 // Override output format!
653 d.m_depthID = Float32BitsColorDepthID;
654 d.m_pixelFormat.data_type = d.m_pixelFormat_target.data_type;
655
656 // HDR is a special case because we need to linearize in-house
657 d.cs = KoColorSpaceRegistry::instance()->colorSpace(d.m_colorID.id(), d.m_depthID.id(), profile);
658 }
659 }
660 }
661
662 if (!d.cs) {
663 size_t iccSize = 0;
664 QByteArray iccProfile;
665 if (JXL_DEC_SUCCESS
666 != JxlDecoderGetICCProfileSize(dec.get(),
667#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0,9,0)
668 nullptr,
669#endif
670 JXL_COLOR_PROFILE_TARGET_DATA,
671 &iccSize)) {
672 errFile << "ICC profile size retrieval failed";
673 document->setErrorMessage(i18nc("JPEG-XL errors", "Unable to read the image profile."));
675 }
676 iccProfile.resize(static_cast<int>(iccSize));
677 if (JXL_DEC_SUCCESS
678 != JxlDecoderGetColorAsICCProfile(dec.get(),
679#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0,9,0)
680 nullptr,
681#endif
682 JXL_COLOR_PROFILE_TARGET_DATA,
683 reinterpret_cast<uint8_t *>(iccProfile.data()),
684 static_cast<size_t>(iccProfile.size()))) {
685 document->setErrorMessage(i18nc("JPEG-XL errors", "Unable to read the image profile."));
687 }
688
689 // Get original profile if XYB is used
690 size_t iccTargetSize = 0;
691 QByteArray iccTargetProfile;
692 if (!d.m_info.uses_original_profile) {
693 if (JXL_DEC_SUCCESS
694 != JxlDecoderGetICCProfileSize(dec.get(),
695#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0,9,0)
696 nullptr,
697#endif
698 JXL_COLOR_PROFILE_TARGET_ORIGINAL,
699 &iccTargetSize)) {
700 errFile << "ICC profile size retrieval failed";
701 document->setErrorMessage(i18nc("JPEG-XL errors", "Unable to read the image profile."));
703 }
704 iccTargetProfile.resize(static_cast<int>(iccTargetSize));
705 if (JXL_DEC_SUCCESS
706 != JxlDecoderGetColorAsICCProfile(dec.get(),
707#if JPEGXL_NUMERIC_VERSION < JPEGXL_COMPUTE_NUMERIC_VERSION(0,9,0)
708 nullptr,
709#endif
710 JXL_COLOR_PROFILE_TARGET_ORIGINAL,
711 reinterpret_cast<uint8_t *>(iccTargetProfile.data()),
712 static_cast<size_t>(iccTargetProfile.size()))) {
713 document->setErrorMessage(i18nc("JPEG-XL errors", "Unable to read the image profile."));
715 }
716 }
717
718 if (iccTargetSize && (iccProfile != iccTargetProfile)) {
719 // If the icc target is not 0 and different than target data.
720 // Meaning that the JXL is in XYB format and needing to convert back to
721 // the original color profile.
722 //
723 // Here we need to provide an intermediate transform space in float to prevent
724 // gamut clipping to sRGB if the target depth is integer.
725 dbgFile << "XYB with color transform needed";
726 needColorTransform = true;
727 profile = KoColorSpaceRegistry::instance()->createColorProfile(d.m_colorID.id(),
728 d.m_depthID.id(),
729 iccProfile);
730 d.cs = KoColorSpaceRegistry::instance()->colorSpace(d.m_colorID.id(), d.m_depthID.id(), profile);
731 profileIntermediate = KoColorSpaceRegistry::instance()->createColorProfile(d.m_colorID_target.id(),
732 d.m_depthID.id(),
733 iccTargetProfile);
734 d.cs_intermediate = KoColorSpaceRegistry::instance()->colorSpace(d.m_colorID_target.id(),
735 d.m_depthID.id(),
736 profileIntermediate);
737 profileTarget = KoColorSpaceRegistry::instance()->createColorProfile(d.m_colorID_target.id(),
738 d.m_depthID_target.id(),
739 iccTargetProfile);
740 d.cs_target = KoColorSpaceRegistry::instance()->colorSpace(d.m_colorID_target.id(),
741 d.m_depthID_target.id(),
742 profileTarget);
743
744 // No need for intermediate transform on float since it won't get clipped.
745 if (!(d.m_depthID_target == Float16BitsColorDepthID
746 || d.m_depthID_target == Float32BitsColorDepthID)) {
747 needIntermediateTransform = true;
748 }
749 } else if (!d.m_info.uses_original_profile) {
750 // If XYB is used but the profiles are same, skip conversion.
751 // Also set the color depth target to default.
752 //
753 // Try to fetch profile from CICP first...
754 dbgFile << "XYB without color transform needed";
755 needColorTransform = false;
756 d.m_depthID = d.m_depthID_target;
757 d.m_colorID = d.m_colorID_target;
758 d.m_pixelFormat.data_type = d.m_pixelFormat_target.data_type;
759 d.cs = KoColorSpaceRegistry::instance()->colorSpace(d.m_colorID.id(), d.m_depthID.id(), profile);
760
761 // ...or use ICC instead if CICP fetch failed.
762 if (!d.cs) {
763 dbgFile << "JXL CICP data couldn't be handled, falling back to ICC profile retrieval";
764 profile = KoColorSpaceRegistry::instance()->createColorProfile(d.m_colorID_target.id(),
765 d.m_depthID_target.id(),
766 iccProfile);
767 d.cs = KoColorSpaceRegistry::instance()->colorSpace(d.m_colorID_target.id(),
768 d.m_depthID_target.id(),
769 profile);
770 }
771 } else {
772 // Skip conversion on original profile.
773 dbgFile << "Original without color transform needed";
774 needColorTransform = false;
775 profile = KoColorSpaceRegistry::instance()->createColorProfile(d.m_colorID.id(),
776 d.m_depthID.id(),
777 iccProfile);
778 d.cs = KoColorSpaceRegistry::instance()->colorSpace(d.m_colorID.id(), d.m_depthID.id(), profile);
779 }
780 }
781
782 if (d.cs_target) {
783 dbgFile << "Source profile:" << d.cs->profile()->name();
784 dbgFile << "Source space:" << d.cs->name() << d.cs->colorModelId() << d.cs->colorDepthId();
785 dbgFile << "Target profile:" << d.cs_target->profile()->name();
786 dbgFile << "Color space:" << d.cs_target->name() << d.cs_target->colorModelId()
787 << d.cs_target->colorDepthId();
788 } else {
789 dbgFile << "Color space:" << d.cs->name() << d.cs->colorModelId() << d.cs->colorDepthId();
790 }
791 dbgFile << "JXL depth" << d.m_pixelFormat.data_type;
792
793 d.lCoef = d.cs->lumaCoefficients();
794
795 image = new KisImage(document->createUndoStore(),
796 static_cast<int>(d.m_info.xsize),
797 static_cast<int>(d.m_info.ysize),
798 d.cs,
799 "JPEG-XL image");
800
801 layer = new KisPaintLayer(image, image->nextLayerName(), UCHAR_MAX);
802 } else if (status == JXL_DEC_NEED_IMAGE_OUT_BUFFER) {
803 d.m_currentFrame = new KisPaintDevice(image->colorSpace());
804
805 // Use raw byte buffer instead of image callback
806 size_t rawSize = 0;
807 if (JXL_DEC_SUCCESS != JxlDecoderImageOutBufferSize(dec.get(), &d.m_pixelFormat, &rawSize)) {
808 qWarning() << "JxlDecoderImageOutBufferSize failed";
810 }
811 d.m_rawData.resize(rawSize);
812 if (JXL_DEC_SUCCESS
813 != JxlDecoderSetImageOutBuffer(dec.get(),
814 &d.m_pixelFormat,
815 reinterpret_cast<uint8_t *>(d.m_rawData.data()),
816 static_cast<size_t>(d.m_rawData.size()))) {
817 qWarning() << "JxlDecoderSetImageOutBuffer failed";
819 }
820
821 if (d.isCMYK) {
822 // Prepare planar buffer for key channel
823 size_t bufferSize = 0;
824 if (JXL_DEC_SUCCESS
825 != JxlDecoderExtraChannelBufferSize(dec.get(), &d.m_pixelFormat, &bufferSize, d.cmykChannelID)) {
826 errFile << "JxlDecoderExtraChannelBufferSize failed";
828 break;
829 }
830 d.kPlane.resize(bufferSize);
831 if (JXL_DEC_SUCCESS
832 != JxlDecoderSetExtraChannelBuffer(dec.get(),
833 &d.m_pixelFormat,
834 d.kPlane.data(),
835 bufferSize,
836 d.cmykChannelID)) {
837 errFile << "JxlDecoderSetExtraChannelBuffer failed";
839 break;
840 }
841 }
842 } else if (status == JXL_DEC_FRAME) {
843 if (JXL_DEC_SUCCESS != JxlDecoderGetFrameHeader(dec.get(), &d.m_header)) {
844 errFile << "JxlDecoderGetFrameHeader failed";
846 }
847
848 const JxlBlendMode blendMode = d.m_header.layer_info.blend_info.blendmode;
849
850 if (isMultilayer || isMultipage) {
851 QString layerName;
852 QByteArray layerNameRaw;
853 if (d.m_header.name_length) {
854 KIS_SAFE_ASSERT_RECOVER(d.m_header.name_length < std::numeric_limits<int>::max())
855 {
856 document->setErrorMessage(i18nc("JPEG-XL", "Invalid JPEG-XL layer name length"));
858 }
859 layerNameRaw.resize(static_cast<int>(d.m_header.name_length + 1));
860 if (JXL_DEC_SUCCESS
861 != JxlDecoderGetFrameName(dec.get(),
862 layerNameRaw.data(),
863 static_cast<size_t>(layerNameRaw.size()))) {
864 errFile << "JxlDecoderGetFrameName failed";
865 break;
866 }
867 dbgFile << "\tlayer name:" << QString(layerNameRaw);
868
869 // do **not** include the null-termination char into the final layer name
870 layerName = QString::fromUtf8(layerNameRaw.data(), d.m_header.name_length);
871 } else {
872 layerName = QString("Layer");
873 }
874 // Set the first layer name (if any)
875 if (!bgLayerSet) {
876 if (!layerNameRaw.isEmpty()) {
877 layer->setName(layerName);
878 }
879 } else {
880 additionalLayers.emplace_back(new KisPaintLayer(image, layerName, UCHAR_MAX));
881 if (blendMode == JXL_BLEND_MULADD) {
882 additionalLayers.back()->setCompositeOpId(QString("add"));
883 }
884 }
885 }
886 } else if (status == JXL_DEC_FULL_IMAGE) {
887 // Parse raw data using existing callback function
889 const JxlLayerInfo layerInfo = d.m_header.layer_info;
890 const QRect layerBounds = QRect(static_cast<int>(layerInfo.crop_x0),
891 static_cast<int>(layerInfo.crop_y0),
892 static_cast<int>(layerInfo.xsize),
893 static_cast<int>(layerInfo.ysize));
894 if (isAnimated) {
895 dbgFile << "Importing frame @" << d.m_nextFrameTime
896 << d.m_header.duration;
897
898 // XXX: If frame header duration is set to 0xFFFFFFFF it indicates that the
899 // current animation page has ended. Since we didn't currently support
900 // multipage image/animation, this will dump the whole animation instead.
901 // Otherwise, it may cause a lockup when loading a multipage image.
902 const uint32_t frameDurationNorm = d.m_header.duration == 0xFFFFFFFF ? 1 : d.m_header.duration;
903 if (d.m_nextFrameTime == 0) {
904 dbgFile << "Animation detected, ticks per second:"
905 << d.m_info.animation.tps_numerator
906 << d.m_info.animation.tps_denominator;
907 // XXX: How many ticks per second (FPS)?
908 // If > 240, block the derivation-- it's a stock JXL and
909 // Krita only supports up to 240 FPS.
910 // We'll try to derive the framerate from the first frame
911 // instead.
912 int framerate =
913 std::lround(d.m_info.animation.tps_numerator
914 / static_cast<double>(
915 d.m_info.animation.tps_denominator));
916 if (framerate > 240) {
917 warnFile << "JXL ticks per second value exceeds 240, "
918 "approximating FPS from the duration of "
919 "the first frame";
920 document->setWarningMessage(
921 i18nc("JPEG-XL errors",
922 "The animation declares a frame rate of more "
923 "than 240 FPS."));
924 const int approximatedFramerate = std::lround(
925 1000.0 / static_cast<double>(d.m_header.duration));
926 d.m_durationFrameInTicks =
927 static_cast<int>(frameDurationNorm);
928 framerate = std::max(approximatedFramerate, 1);
929 } else {
930 d.m_durationFrameInTicks = 1;
931 }
932 dbgFile << "Framerate:" << framerate;
933 layer->enableAnimation();
934 image->animationInterface()->setDocumentRangeStartFrame(0);
935 image->animationInterface()->setFramerate(framerate);
936 }
937
938 const int currentFrameTime = std::lround(
939 static_cast<double>(d.m_nextFrameTime)
940 / static_cast<double>(d.m_durationFrameInTicks));
941
942 auto *channel = layer->getKeyframeChannel(KisKeyframeChannel::Raster.id(), true);
943 auto *frame = dynamic_cast<KisRasterKeyframeChannel *>(channel);
944 image->animationInterface()->setDocumentRangeEndFrame(
945 std::lround(static_cast<double>(d.m_nextFrameTime
946 + frameDurationNorm)
947 / static_cast<double>(d.m_durationFrameInTicks))
948 - 1);
949 frame->importFrame(currentFrameTime, d.m_currentFrame, nullptr);
950 d.m_nextFrameTime += static_cast<int>(frameDurationNorm);
951 } else {
952 if (d.isCMYK && d.m_info.uses_original_profile) {
953 QVector<quint8 *> planes = d.m_currentFrame->readPlanarBytes(layerBounds.x(),
954 layerBounds.y(),
955 layerBounds.width(),
956 layerBounds.height());
957
958 // Planar buffer insertion for key channel
959 planes[3] = reinterpret_cast<quint8 *>(d.kPlane.data());
960 d.m_currentFrame->writePlanarBytes(planes,
961 layerBounds.x(),
962 layerBounds.y(),
963 layerBounds.width(),
964 layerBounds.height());
965
966 // JPEG-XL decode outputs an inverted CMYK colors
967 // This one I took from kis_filter_test for inverting the colors..
968 const KisFilterSP f = KisFilterRegistry::instance()->value("invert");
969 KIS_ASSERT(f);
970 const KisFilterConfigurationSP kfc =
971 f->defaultConfiguration(KisGlobalResourcesInterface::instance());
972 KIS_ASSERT(kfc);
973 f->process(d.m_currentFrame, layerBounds, kfc->cloneWithResourcesSnapshot());
974 }
975 if (!bgLayerSet) {
976 layer->paintDevice()->makeCloneFrom(d.m_currentFrame, layerBounds);
977 bgLayerSet = true;
978 } else {
979 additionalLayers.back()->paintDevice()->makeCloneFrom(d.m_currentFrame, layerBounds);
980 }
981 }
982 } else if (status == JXL_DEC_SUCCESS || status == JXL_DEC_BOX) {
983 if (std::strlen(boxType.data()) != 0) {
984 // Release buffer and get its final size.
985 const auto availOut = JxlDecoderReleaseBoxBuffer(dec.get());
986 const int finalSize = box.size() - static_cast<int>(availOut);
987 // Only resize and write boxes if it's not empty.
988 // And only input metadata boxes while skipping other boxes.
989 QByteArray type = boxType.toLower();
990 if ((std::equal(exifTag.begin(), exifTag.end(), type.constBegin())
991 || std::equal(xmpTag.begin(), xmpTag.end(), type.constBegin()))
992 && finalSize != 0) {
993 metadataBoxes.emplace(type, QByteArray(box.data(), finalSize));
994 }
995 // Preemptively zero the box type out to prevent dangling
996 // boxes.
997 boxType.fill('\0');
998 }
999 if (status == JXL_DEC_SUCCESS) {
1000 // All decoding successfully finished.
1001
1002 // Insert layer metadata if available (delayed
1003 // in case the boxes came before the BASIC_INFO event)
1004 for (auto &metaBox : metadataBoxes) {
1005 const QByteArray &type = metaBox.first;
1006 QByteArray &value = metaBox.second;
1007 QBuffer buf(&value);
1008 if (std::equal(exifTag.begin(), exifTag.end(), type.constBegin())) {
1009 dbgFile << "Loading EXIF data. Size: " << value.size();
1010
1011 const auto *backend =
1013 "exif");
1014
1015 backend->loadFrom(layer->metaData(), &buf);
1016 } else if (std::equal(xmpTag.begin(), xmpTag.end(), type.constBegin())) {
1017 dbgFile << "Loading XMP or IPTC data. Size: " << value.size();
1018
1019 const auto *xmpBackend =
1021 "xmp");
1022
1023 if (!xmpBackend->loadFrom(layer->metaData(), &buf)) {
1024 const KisMetaData::IOBackend *iptcBackend =
1026 "iptc");
1027 iptcBackend->loadFrom(layer->metaData(), &buf);
1028 }
1029 }
1030 }
1031
1032 // It's not required to call JxlDecoderReleaseInput(dec.get()) here since
1033 // the decoder will be destroyed.
1034 image->addNode(layer, image->rootLayer().data());
1035 // Slip additional layers into layer stack
1036 for (const KisLayerSP &addLayer : additionalLayers) {
1037 image->addNode(addLayer, image->rootLayer().data());
1038 }
1039 if (needColorTransform) {
1040 if (needIntermediateTransform) {
1041 dbgFile << "Transforming to intermediate color space";
1042 image->convertImageColorSpace(d.cs_intermediate,
1043 d.m_intent,
1045 image->waitForDone();
1046 }
1047 dbgFile << "Transforming to target color space";
1048 image->convertImageColorSpace(d.cs_target,
1049 d.m_intent,
1051 image->waitForDone();
1052 }
1053 document->setCurrentImage(image);
1054 return ImportExportCodes::OK;
1055 } else {
1056 if (JxlDecoderGetBoxType(dec.get(), boxType.data(), JXL_TRUE) != JXL_DEC_SUCCESS) {
1057 errFile << "JxlDecoderGetBoxType failed";
1059 }
1060 const QByteArray type = boxType.toLower();
1061 if (std::equal(exifTag.begin(), exifTag.end(), type.constBegin())
1062 || std::equal(xmpTag.begin(), xmpTag.end(), type.constBegin())) {
1063 if (JxlDecoderSetBoxBuffer(
1064 dec.get(),
1065 reinterpret_cast<uint8_t *>(box.data()),
1066 static_cast<size_t>(box.size()))
1067 != JXL_DEC_SUCCESS) {
1068 errFile << "JxlDecoderSetBoxBuffer failed";
1070 }
1071 } else {
1072 dbgFile << "Skipping box" << boxType.data();
1073 }
1074 }
1075 } else if (status == JXL_DEC_BOX_NEED_MORE_OUTPUT) {
1076 // Update the box size if it was truncated in a previous buffering.
1077 boxSize = box.size();
1078 box.resize(boxSize * 2);
1079 // Release buffer before setting it up again
1080 JxlDecoderReleaseBoxBuffer(dec.get());
1081 if (JxlDecoderSetBoxBuffer(
1082 dec.get(),
1083 reinterpret_cast<uint8_t *>(box.data() + boxSize),
1084 static_cast<size_t>(box.size() - boxSize))
1085 != JXL_DEC_SUCCESS) {
1086 errFile << "JxlDecoderGetBoxType failed";
1088 }
1089 } else {
1090 errFile << "Unknown decoder status" << status;
1092 }
1093 }
1094
1095 return ImportExportCodes::OK;
1096}
static constexpr std::array< char, 4 > exifTag
float value(const T *src, size_t ch)
static constexpr std::array< char, 4 > xmpTag
void generateCallback(JPEGXLImportData &d)
const KoID Float32BitsColorDepthID("F32", ki18n("32-bit float/channel"))
const KoID GrayAColorModelID("GRAYA", ki18n("Grayscale/Alpha"))
const KoID Float16BitsColorDepthID("F16", ki18n("16-bit float/channel"))
const KoID Integer8BitsColorDepthID("U8", ki18n("8-bit integer/channel"))
const KoID Integer16BitsColorDepthID("U16", ki18n("16-bit integer/channel"))
const KoID CMYKAColorModelID("CMYKA", ki18n("CMYK/Alpha"))
const KoID RGBAColorModelID("RGBA", ki18n("RGB/Alpha"))
ColorPrimaries
The colorPrimaries enum Enum of colorants, follows ITU H.273 for values 0 to 255, and has extra known...
@ PRIMARIES_ITU_R_BT_2020_2_AND_2100_0
@ PRIMARIES_UNSPECIFIED
@ PRIMARIES_SMPTE_RP_431_2
@ PRIMARIES_ITU_R_BT_709_5
TransferCharacteristics
The transferCharacteristics enum Enum of transfer characteristics, follows ITU H.273 for values 0 to ...
@ TRC_ITU_R_BT_470_6_SYSTEM_M
@ TRC_ITU_R_BT_470_6_SYSTEM_B_G
@ TRC_IEC_61966_2_1
@ TRC_ITU_R_BT_709_5
static KisFilterRegistry * instance()
static KisResourcesInterfaceSP instance()
static const KoID Raster
virtual bool loadFrom(Store *store, QIODevice *ioDevice) const =0
static KisMetadataBackendRegistry * instance()
The KisRasterKeyframeChannel is a concrete KisKeyframeChannel subclass that stores and manages KisRas...
void importFrame(int time, KisPaintDeviceSP sourceDevice, KUndo2Command *parentCommand)
const T value(const QString &id) const
#define KIS_SAFE_ASSERT_RECOVER(cond)
Definition kis_assert.h:126
#define KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE(cond, val)
Definition kis_assert.h:129
#define KIS_ASSERT(cond)
Definition kis_assert.h:33
#define warnFile
Definition kis_debug.h:102
#define errFile
Definition kis_debug.h:123
#define dbgFile
Definition kis_debug.h:57
The KoColorProfileQuery struct.
const KoColorSpace * colorSpace(const QString &colorModelId, const QString &colorDepthId, const KoColorProfile *profile)
static KoColorSpaceRegistry * instance()
const KoColorProfile * profileFor(const KoColorProfileQuery &query, const bool generate=true) const
profileFor tries to find the profile that matches these characteristics, if no such profile is found,...
const KoColorProfile * createColorProfile(const QString &colorModelId, const QString &colorDepthId, const QByteArray &rawData)

References CMYKAColorModelID, KoColorSpaceRegistry::colorSpace(), KoColorSpaceRegistry::createColorProfile(), KisImportExportFilter::d, dbgFile, errFile, ImportExportCodes::ErrorWhileReading, exifTag, ImportExportCodes::FileFormatIncorrect, Float16BitsColorDepthID, Float32BitsColorDepthID, ImportExportCodes::FormatFeaturesUnsupported, generateCallback(), GrayAColorModelID, KisRasterKeyframeChannel::importFrame(), KisFilterRegistry::instance(), KisMetadataBackendRegistry::instance(), KoColorSpaceRegistry::instance(), KisGlobalResourcesInterface::instance(), Integer16BitsColorDepthID, Integer8BitsColorDepthID, KoColorConversionTransformation::IntentAbsoluteColorimetric, KoColorConversionTransformation::IntentPerceptual, KoColorConversionTransformation::IntentRelativeColorimetric, KoColorConversionTransformation::IntentSaturation, KoColorConversionTransformation::internalConversionFlags(), ImportExportCodes::InternalError, KeepTheSame, KIS_ASSERT, KIS_SAFE_ASSERT_RECOVER, KIS_SAFE_ASSERT_RECOVER_RETURN_VALUE, LinearFromHLG, LinearFromPQ, LinearFromSMPTE428, KisMetaData::IOBackend::loadFrom(), KoColorProfile::name, ImportExportCodes::NoAccessToRead, ImportExportCodes::OK, PRIMARIES_ITU_R_BT_2020_2_AND_2100_0, PRIMARIES_ITU_R_BT_709_5, PRIMARIES_SMPTE_RP_431_2, PRIMARIES_UNSPECIFIED, KoColorSpaceRegistry::profileFor(), KisKeyframeChannel::Raster, RGBAColorModelID, TRC_A98, TRC_GAMMA_1_8, TRC_GAMMA_2_4, TRC_IEC_61966_2_1, TRC_ITU_R_BT_470_6_SYSTEM_B_G, TRC_ITU_R_BT_470_6_SYSTEM_M, TRC_ITU_R_BT_709_5, TRC_LINEAR, TRC_UNSPECIFIED, KoGenericRegistry< T >::value(), value(), warnFile, and xmpTag.

◆ supportsIO()

bool JPEGXLImport::supportsIO ( ) const
inlineoverridevirtual

Override and return false for the filters that use a library that cannot handle file handles, only file names.

Reimplemented from KisImportExportFilter.

Definition at line 18 of file JPEGXLImport.h.

18{ return true; }

The documentation for this class was generated from the following files: