JPEGLoader.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. * Copyright (c) 2024, Andreas Kling <andreas@ladybird.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibGfx/CMYKBitmap.h>
  7. #include <LibGfx/ImageFormats/JPEGLoader.h>
  8. #include <jpeglib.h>
  9. #include <setjmp.h>
  10. namespace Gfx {
  11. struct JPEGLoadingContext {
  12. enum class State {
  13. NotDecoded,
  14. Error,
  15. Decoded,
  16. };
  17. State state { State::NotDecoded };
  18. RefPtr<Gfx::Bitmap> rgb_bitmap;
  19. RefPtr<Gfx::CMYKBitmap> cmyk_bitmap;
  20. ReadonlyBytes data;
  21. Vector<u8> icc_data;
  22. JPEGLoadingContext(ReadonlyBytes data)
  23. : data(data)
  24. {
  25. }
  26. ErrorOr<void> decode();
  27. };
  28. struct JPEGErrorManager : jpeg_error_mgr {
  29. jmp_buf setjmp_buffer {};
  30. };
  31. ErrorOr<void> JPEGLoadingContext::decode()
  32. {
  33. struct jpeg_decompress_struct cinfo;
  34. struct JPEGErrorManager jerr;
  35. cinfo.err = jpeg_std_error(&jerr);
  36. jpeg_source_mgr source_manager {};
  37. if (setjmp(jerr.setjmp_buffer)) {
  38. jpeg_destroy_decompress(&cinfo);
  39. state = State::Error;
  40. return Error::from_string_literal("Failed to decode JPEG");
  41. }
  42. jerr.error_exit = [](j_common_ptr cinfo) {
  43. char buffer[JMSG_LENGTH_MAX];
  44. (*cinfo->err->format_message)(cinfo, buffer);
  45. dbgln("JPEG error: {}", buffer);
  46. longjmp(static_cast<JPEGErrorManager*>(cinfo->err)->setjmp_buffer, 1);
  47. };
  48. jpeg_create_decompress(&cinfo);
  49. source_manager.next_input_byte = data.data();
  50. source_manager.bytes_in_buffer = data.size();
  51. source_manager.init_source = [](j_decompress_ptr) {};
  52. source_manager.fill_input_buffer = [](j_decompress_ptr) -> boolean { return false; };
  53. source_manager.skip_input_data = [](j_decompress_ptr context, long num_bytes) {
  54. if (num_bytes > static_cast<long>(context->src->bytes_in_buffer)) {
  55. context->src->bytes_in_buffer = 0;
  56. return;
  57. }
  58. context->src->next_input_byte += num_bytes;
  59. context->src->bytes_in_buffer -= num_bytes;
  60. };
  61. source_manager.resync_to_restart = jpeg_resync_to_restart;
  62. source_manager.term_source = [](j_decompress_ptr) {};
  63. cinfo.src = &source_manager;
  64. jpeg_save_markers(&cinfo, JPEG_APP0 + 2, 0xFFFF);
  65. if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) {
  66. jpeg_destroy_decompress(&cinfo);
  67. return Error::from_string_literal("Failed to read JPEG header");
  68. }
  69. if (cinfo.jpeg_color_space == JCS_CMYK || cinfo.jpeg_color_space == JCS_YCCK) {
  70. cinfo.out_color_space = JCS_CMYK;
  71. } else {
  72. cinfo.out_color_space = JCS_EXT_BGRX;
  73. }
  74. jpeg_start_decompress(&cinfo);
  75. bool could_read_all_scanlines = true;
  76. if (cinfo.out_color_space == JCS_EXT_BGRX) {
  77. rgb_bitmap = TRY(Gfx::Bitmap::create(Gfx::BitmapFormat::BGRx8888, { static_cast<int>(cinfo.output_width), static_cast<int>(cinfo.output_height) }));
  78. while (cinfo.output_scanline < cinfo.output_height) {
  79. auto* row_ptr = (u8*)rgb_bitmap->scanline(cinfo.output_scanline);
  80. auto out_size = jpeg_read_scanlines(&cinfo, &row_ptr, 1);
  81. if (cinfo.output_scanline < cinfo.output_height && out_size == 0) {
  82. dbgln("JPEG Warning: Decoding produced no more scanlines in scanline {}/{}.", cinfo.output_scanline, cinfo.output_height);
  83. could_read_all_scanlines = false;
  84. break;
  85. }
  86. }
  87. } else {
  88. cmyk_bitmap = TRY(CMYKBitmap::create_with_size({ static_cast<int>(cinfo.output_width), static_cast<int>(cinfo.output_height) }));
  89. while (cinfo.output_scanline < cinfo.output_height) {
  90. auto* row_ptr = (u8*)cmyk_bitmap->scanline(cinfo.output_scanline);
  91. auto out_size = jpeg_read_scanlines(&cinfo, &row_ptr, 1);
  92. if (cinfo.output_scanline < cinfo.output_height && out_size == 0) {
  93. dbgln("JPEG Warning: Decoding produced no more scanlines in scanline {}/{}.", cinfo.output_scanline, cinfo.output_height);
  94. could_read_all_scanlines = false;
  95. break;
  96. }
  97. }
  98. }
  99. JOCTET* icc_data_ptr = nullptr;
  100. unsigned int icc_data_length = 0;
  101. if (jpeg_read_icc_profile(&cinfo, &icc_data_ptr, &icc_data_length)) {
  102. icc_data.resize(icc_data_length);
  103. memcpy(icc_data.data(), icc_data_ptr, icc_data_length);
  104. free(icc_data_ptr);
  105. }
  106. if (could_read_all_scanlines)
  107. jpeg_finish_decompress(&cinfo);
  108. else
  109. jpeg_abort_decompress(&cinfo);
  110. jpeg_destroy_decompress(&cinfo);
  111. if (cmyk_bitmap && !rgb_bitmap)
  112. rgb_bitmap = TRY(cmyk_bitmap->to_low_quality_rgb());
  113. state = State::Decoded;
  114. return {};
  115. }
  116. JPEGImageDecoderPlugin::JPEGImageDecoderPlugin(NonnullOwnPtr<JPEGLoadingContext> context)
  117. : m_context(move(context))
  118. {
  119. }
  120. JPEGImageDecoderPlugin::~JPEGImageDecoderPlugin() = default;
  121. IntSize JPEGImageDecoderPlugin::size()
  122. {
  123. if (m_context->state == JPEGLoadingContext::State::NotDecoded)
  124. (void)frame(0);
  125. if (m_context->state == JPEGLoadingContext::State::Error)
  126. return {};
  127. if (m_context->rgb_bitmap)
  128. return m_context->rgb_bitmap->size();
  129. if (m_context->cmyk_bitmap)
  130. return m_context->cmyk_bitmap->size();
  131. return {};
  132. }
  133. bool JPEGImageDecoderPlugin::sniff(ReadonlyBytes data)
  134. {
  135. return data.size() > 3
  136. && data.data()[0] == 0xFF
  137. && data.data()[1] == 0xD8
  138. && data.data()[2] == 0xFF;
  139. }
  140. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGImageDecoderPlugin::create(ReadonlyBytes data)
  141. {
  142. return adopt_own(*new JPEGImageDecoderPlugin(make<JPEGLoadingContext>(data)));
  143. }
  144. ErrorOr<ImageFrameDescriptor> JPEGImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  145. {
  146. if (index > 0)
  147. return Error::from_string_literal("JPEGImageDecoderPlugin: Invalid frame index");
  148. if (m_context->state == JPEGLoadingContext::State::Error)
  149. return Error::from_string_literal("JPEGImageDecoderPlugin: Decoding failed");
  150. if (m_context->state < JPEGLoadingContext::State::Decoded) {
  151. TRY(m_context->decode());
  152. m_context->state = JPEGLoadingContext::State::Decoded;
  153. }
  154. return ImageFrameDescriptor { m_context->rgb_bitmap, 0 };
  155. }
  156. Optional<Metadata const&> JPEGImageDecoderPlugin::metadata()
  157. {
  158. return OptionalNone {};
  159. }
  160. ErrorOr<Optional<ReadonlyBytes>> JPEGImageDecoderPlugin::icc_data()
  161. {
  162. if (m_context->state == JPEGLoadingContext::State::NotDecoded)
  163. (void)frame(0);
  164. if (!m_context->icc_data.is_empty())
  165. return m_context->icc_data;
  166. return OptionalNone {};
  167. }
  168. NaturalFrameFormat JPEGImageDecoderPlugin::natural_frame_format() const
  169. {
  170. if (m_context->state == JPEGLoadingContext::State::NotDecoded)
  171. (void)const_cast<JPEGImageDecoderPlugin&>(*this).frame(0);
  172. if (m_context->cmyk_bitmap)
  173. return NaturalFrameFormat::CMYK;
  174. return NaturalFrameFormat::RGB;
  175. }
  176. ErrorOr<NonnullRefPtr<CMYKBitmap>> JPEGImageDecoderPlugin::cmyk_frame()
  177. {
  178. if (m_context->state == JPEGLoadingContext::State::NotDecoded)
  179. (void)frame(0);
  180. if (m_context->state == JPEGLoadingContext::State::Error)
  181. return Error::from_string_literal("JPEGImageDecoderPlugin: Decoding failed");
  182. if (!m_context->cmyk_bitmap)
  183. return Error::from_string_literal("JPEGImageDecoderPlugin: No CMYK data available");
  184. return *m_context->cmyk_bitmap;
  185. }
  186. }