JPEGLoader.cpp 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * Copyright (c) 2022-2023, Lucas Chollet <lucas.chollet@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Debug.h>
  8. #include <AK/Endian.h>
  9. #include <AK/Error.h>
  10. #include <AK/FixedArray.h>
  11. #include <AK/HashMap.h>
  12. #include <AK/Math.h>
  13. #include <AK/MemoryStream.h>
  14. #include <AK/NumericLimits.h>
  15. #include <AK/String.h>
  16. #include <AK/Try.h>
  17. #include <AK/Vector.h>
  18. #include <LibGfx/ImageFormats/JPEGLoader.h>
  19. #include <LibGfx/ImageFormats/JPEGShared.h>
  20. #include <LibGfx/ImageFormats/TIFFLoader.h>
  21. #include <LibGfx/ImageFormats/TIFFMetadata.h>
  22. namespace Gfx {
  23. struct MacroblockMeta {
  24. u32 total { 0 };
  25. u32 padded_total { 0 };
  26. u32 hcount { 0 };
  27. u32 vcount { 0 };
  28. u32 hpadded_count { 0 };
  29. u32 vpadded_count { 0 };
  30. };
  31. struct SamplingFactors {
  32. u8 horizontal {};
  33. u8 vertical {};
  34. bool operator==(SamplingFactors const&) const = default;
  35. };
  36. // In the JPEG format, components are defined first at the frame level, then
  37. // referenced in each scan and aggregated with scan-specific information. The
  38. // two following structs mimic this hierarchy.
  39. struct Component {
  40. // B.2.2 - Frame header syntax
  41. u8 id { 0 }; // Ci, Component identifier
  42. SamplingFactors sampling_factors { 1, 1 }; // Hi, Horizontal sampling factor and Vi, Vertical sampling factor
  43. u8 quantization_table_id { 0 }; // Tqi, Quantization table destination selector
  44. // The JPEG specification does not specify which component corresponds to
  45. // Y, Cb or Cr. This field (actually the index in the parent Vector) will
  46. // act as an authority to determine the *real* component.
  47. // Please note that this is implementation specific.
  48. u8 index { 0 };
  49. };
  50. struct ScanComponent {
  51. // B.2.3 - Scan header syntax
  52. Component& component;
  53. u8 dc_destination_id { 0 }; // Tdj, DC entropy coding table destination selector
  54. u8 ac_destination_id { 0 }; // Taj, AC entropy coding table destination selector
  55. };
  56. struct StartOfFrame {
  57. // Of these, only the first 3 are in mainstream use, and refers to SOF0-2.
  58. enum class FrameType {
  59. Baseline_DCT = 0,
  60. Extended_Sequential_DCT = 1,
  61. Progressive_DCT = 2,
  62. Sequential_Lossless = 3,
  63. Differential_Sequential_DCT = 5,
  64. Differential_Progressive_DCT = 6,
  65. Differential_Sequential_Lossless = 7,
  66. Extended_Sequential_DCT_Arithmetic = 9,
  67. Progressive_DCT_Arithmetic = 10,
  68. Sequential_Lossless_Arithmetic = 11,
  69. Differential_Sequential_DCT_Arithmetic = 13,
  70. Differential_Progressive_DCT_Arithmetic = 14,
  71. Differential_Sequential_Lossless_Arithmetic = 15,
  72. };
  73. FrameType type { FrameType::Baseline_DCT };
  74. u8 precision { 0 };
  75. u16 height { 0 };
  76. u16 width { 0 };
  77. };
  78. struct HuffmanTable {
  79. u8 type { 0 };
  80. u8 destination_id { 0 };
  81. u8 code_counts[16] = { 0 };
  82. Vector<u8> symbols;
  83. Vector<u16> codes;
  84. // Note: The value 8 is chosen quite arbitrarily, the only current constraint
  85. // is that both the symbol and the size fit in an u16. I've tested more
  86. // values but none stand out, and 8 is the value used by libjpeg-turbo.
  87. static constexpr u8 bits_per_cached_code = 8;
  88. static constexpr u8 maximum_bits_per_code = 16;
  89. u8 first_non_cached_code_index {};
  90. ErrorOr<void> generate_codes()
  91. {
  92. unsigned code = 0;
  93. for (auto number_of_codes : code_counts) {
  94. for (int i = 0; i < number_of_codes; i++)
  95. codes.append(code++);
  96. code <<= 1;
  97. }
  98. TRY(generate_lookup_table());
  99. return {};
  100. }
  101. struct SymbolAndSize {
  102. u8 symbol {};
  103. u8 size {};
  104. };
  105. ErrorOr<SymbolAndSize> symbol_from_code(u16 code) const
  106. {
  107. static constexpr u8 shift_for_cache = maximum_bits_per_code - bits_per_cached_code;
  108. if (lookup_table[code >> shift_for_cache] != invalid_entry) {
  109. u8 const code_length = lookup_table[code >> shift_for_cache] >> bits_per_cached_code;
  110. return SymbolAndSize { static_cast<u8>(lookup_table[code >> shift_for_cache]), code_length };
  111. }
  112. u64 code_cursor = first_non_cached_code_index;
  113. for (u8 i = HuffmanTable::bits_per_cached_code; i < 16; i++) {
  114. auto const result = code >> (maximum_bits_per_code - 1 - i);
  115. for (u32 j = 0; j < code_counts[i]; j++) {
  116. if (result == codes[code_cursor])
  117. return SymbolAndSize { symbols[code_cursor], static_cast<u8>(i + 1) };
  118. code_cursor++;
  119. }
  120. }
  121. return Error::from_string_literal("This kind of JPEG is not yet supported by the decoder");
  122. }
  123. private:
  124. static constexpr u16 invalid_entry = 0xFF;
  125. ErrorOr<void> generate_lookup_table()
  126. {
  127. lookup_table.fill(invalid_entry);
  128. u32 code_offset = 0;
  129. for (u8 code_length = 1; code_length <= bits_per_cached_code; code_length++) {
  130. for (u32 i = 0; i < code_counts[code_length - 1]; i++, code_offset++) {
  131. u32 code_key = codes[code_offset] << (bits_per_cached_code - code_length);
  132. u8 duplicate_count = 1 << (bits_per_cached_code - code_length);
  133. if (code_key + duplicate_count >= lookup_table.size())
  134. return Error::from_string_literal("Malformed Huffman table");
  135. for (; duplicate_count > 0; duplicate_count--) {
  136. lookup_table[code_key] = (code_length << bits_per_cached_code) | symbols[code_offset];
  137. code_key++;
  138. }
  139. }
  140. }
  141. return {};
  142. }
  143. Array<u16, 1 << bits_per_cached_code> lookup_table {};
  144. };
  145. class HuffmanStream;
  146. class JPEGStream {
  147. public:
  148. static ErrorOr<JPEGStream> create(NonnullOwnPtr<Stream> stream)
  149. {
  150. Vector<u8> buffer;
  151. TRY(buffer.try_resize(buffer_size));
  152. JPEGStream jpeg_stream { move(stream), move(buffer) };
  153. TRY(jpeg_stream.refill_buffer());
  154. jpeg_stream.m_offset_from_start = 0;
  155. return jpeg_stream;
  156. }
  157. ALWAYS_INLINE ErrorOr<u8> read_u8()
  158. {
  159. if (m_byte_offset == m_current_size)
  160. TRY(refill_buffer());
  161. return m_buffer[m_byte_offset++];
  162. }
  163. ALWAYS_INLINE ErrorOr<u16> read_u16()
  164. {
  165. if (m_saved_marker.has_value())
  166. return m_saved_marker.release_value();
  167. return (static_cast<u16>(TRY(read_u8())) << 8) | TRY(read_u8());
  168. }
  169. ALWAYS_INLINE ErrorOr<void> discard(u64 bytes)
  170. {
  171. auto const discarded_from_buffer = min(m_current_size - m_byte_offset, bytes);
  172. m_byte_offset += discarded_from_buffer;
  173. if (discarded_from_buffer < bytes) {
  174. m_offset_from_start += bytes - discarded_from_buffer;
  175. TRY(m_stream->discard(bytes - discarded_from_buffer));
  176. }
  177. return {};
  178. }
  179. ErrorOr<void> read_until_filled(Bytes bytes)
  180. {
  181. auto const copied = m_buffer.span().slice(m_byte_offset).copy_trimmed_to(bytes);
  182. m_byte_offset += copied;
  183. if (copied < bytes.size()) {
  184. m_offset_from_start += bytes.size() - copied;
  185. TRY(m_stream->read_until_filled(bytes.slice(copied)));
  186. }
  187. return {};
  188. }
  189. Optional<u16>& saved_marker(Badge<HuffmanStream>)
  190. {
  191. return m_saved_marker;
  192. }
  193. u64 byte_offset() const
  194. {
  195. return m_offset_from_start + m_byte_offset;
  196. }
  197. private:
  198. JPEGStream(NonnullOwnPtr<Stream> stream, Vector<u8> buffer)
  199. : m_stream(move(stream))
  200. , m_buffer(move(buffer))
  201. {
  202. }
  203. ErrorOr<void> refill_buffer()
  204. {
  205. VERIFY(m_byte_offset == m_current_size);
  206. m_offset_from_start += m_byte_offset;
  207. m_current_size = TRY(m_stream->read_some(m_buffer.span())).size();
  208. if (m_current_size == 0)
  209. return Error::from_string_literal("Unexpected end of file");
  210. m_byte_offset = 0;
  211. return {};
  212. }
  213. static constexpr auto buffer_size = 4096;
  214. NonnullOwnPtr<Stream> m_stream;
  215. Optional<u16> m_saved_marker {};
  216. Vector<u8> m_buffer {};
  217. u64 m_offset_from_start { 0 };
  218. u64 m_byte_offset { buffer_size };
  219. u64 m_current_size { buffer_size };
  220. };
  221. class HuffmanStream {
  222. public:
  223. ALWAYS_INLINE ErrorOr<u8> next_symbol(HuffmanTable const& table)
  224. {
  225. u16 const code = TRY(peek_bits(HuffmanTable::maximum_bits_per_code));
  226. auto const symbol_and_size = TRY(table.symbol_from_code(code));
  227. TRY(discard_bits(symbol_and_size.size));
  228. return symbol_and_size.symbol;
  229. }
  230. ALWAYS_INLINE ErrorOr<u16> read_bits(u8 count = 1)
  231. {
  232. if (count > NumericLimits<u16>::digits()) {
  233. dbgln_if(JPEG_DEBUG, "Can't read {} bits at once!", count);
  234. return Error::from_string_literal("Reading too much huffman bits at once");
  235. }
  236. u16 const value = TRY(peek_bits(count));
  237. TRY(discard_bits(count));
  238. return value;
  239. }
  240. ALWAYS_INLINE ErrorOr<u16> peek_bits(u8 count)
  241. {
  242. if (count == 0)
  243. return 0;
  244. if (count + m_bit_offset > bits_in_reservoir)
  245. TRY(refill_reservoir());
  246. auto const mask = NumericLimits<u16>::max() >> (NumericLimits<u16>::digits() - count);
  247. return static_cast<u16>((m_bit_reservoir >> (bits_in_reservoir - m_bit_offset - count)) & mask);
  248. }
  249. ALWAYS_INLINE ErrorOr<void> discard_bits(u8 count)
  250. {
  251. m_bit_offset += count;
  252. if (m_bit_offset > bits_in_reservoir)
  253. TRY(refill_reservoir());
  254. return {};
  255. }
  256. ErrorOr<void> advance_to_byte_boundary()
  257. {
  258. if (auto remainder = m_bit_offset % 8; remainder != 0)
  259. TRY(discard_bits(bits_per_byte - remainder));
  260. return {};
  261. }
  262. HuffmanStream(JPEGStream& stream)
  263. : jpeg_stream(stream)
  264. {
  265. }
  266. private:
  267. ALWAYS_INLINE ErrorOr<void> refill_reservoir()
  268. {
  269. auto const bytes_needed = m_bit_offset / bits_per_byte;
  270. u8 bytes_added {};
  271. auto const append_byte = [&](u8 byte) {
  272. m_last_byte_was_ff = false;
  273. m_bit_reservoir <<= 8;
  274. m_bit_reservoir |= byte;
  275. m_bit_offset -= 8;
  276. bytes_added++;
  277. };
  278. do {
  279. // Note: We fake zeroes when we have reached another segment
  280. // It allows us to continue peeking seamlessly.
  281. u8 const next_byte = jpeg_stream.saved_marker({}).has_value() ? 0 : TRY(jpeg_stream.read_u8());
  282. if (m_last_byte_was_ff) {
  283. if (next_byte == 0xFF)
  284. continue;
  285. if (next_byte == 0x00) {
  286. append_byte(0xFF);
  287. continue;
  288. }
  289. Marker const marker = 0xFF00 | next_byte;
  290. if (marker < JPEG_RST0 || marker > JPEG_RST7) {
  291. // Note: The only way to know that we reached the end of a segment is to read
  292. // the marker of the following one. So we store it for later use.
  293. jpeg_stream.saved_marker({}) = marker;
  294. m_last_byte_was_ff = false;
  295. continue;
  296. }
  297. }
  298. if (next_byte == 0xFF) {
  299. m_last_byte_was_ff = true;
  300. continue;
  301. }
  302. append_byte(next_byte);
  303. } while (bytes_added < bytes_needed);
  304. return {};
  305. }
  306. JPEGStream& jpeg_stream;
  307. using Reservoir = u64;
  308. static constexpr auto bits_per_byte = 8;
  309. static constexpr auto bits_in_reservoir = sizeof(Reservoir) * bits_per_byte;
  310. Reservoir m_bit_reservoir {};
  311. u8 m_bit_offset { bits_in_reservoir };
  312. bool m_last_byte_was_ff { false };
  313. };
  314. struct ICCMultiChunkState {
  315. u8 seen_number_of_icc_chunks { 0 };
  316. FixedArray<ByteBuffer> chunks;
  317. };
  318. struct Scan {
  319. Scan(HuffmanStream stream)
  320. : huffman_stream(stream)
  321. {
  322. }
  323. // B.2.3 - Scan header syntax
  324. Vector<ScanComponent, 4> components;
  325. u8 spectral_selection_start {}; // Ss
  326. u8 spectral_selection_end {}; // Se
  327. u8 successive_approximation_high {}; // Ah
  328. u8 successive_approximation_low {}; // Al
  329. HuffmanStream huffman_stream;
  330. u64 end_of_bands_run_count { 0 };
  331. // See the note on Figure B.4 - Scan header syntax
  332. bool are_components_interleaved() const
  333. {
  334. return components.size() != 1;
  335. }
  336. };
  337. enum class ColorTransform {
  338. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.872-201206-I!!PDF-E&type=items
  339. // 6.5.3 - APP14 marker segment for colour encoding
  340. CmykOrRgb = 0,
  341. YCbCr = 1,
  342. YCCK = 2,
  343. };
  344. struct JPEGLoadingContext {
  345. JPEGLoadingContext(JPEGStream jpeg_stream, JPEGDecoderOptions options)
  346. : stream(move(jpeg_stream))
  347. , options(options)
  348. {
  349. }
  350. static ErrorOr<NonnullOwnPtr<JPEGLoadingContext>> create(NonnullOwnPtr<Stream> stream, JPEGDecoderOptions options)
  351. {
  352. auto jpeg_stream = TRY(JPEGStream::create(move(stream)));
  353. return make<JPEGLoadingContext>(move(jpeg_stream), options);
  354. }
  355. enum State {
  356. NotDecoded = 0,
  357. Error,
  358. FrameDecoded,
  359. HeaderDecoded,
  360. BitmapDecoded
  361. };
  362. State state { State::NotDecoded };
  363. Array<Optional<Array<u16, 64>>, 4> quantization_tables {};
  364. StartOfFrame frame;
  365. SamplingFactors sampling_factors {};
  366. Optional<Scan> current_scan {};
  367. Vector<Component, 4> components;
  368. RefPtr<Gfx::Bitmap> bitmap;
  369. RefPtr<Gfx::CMYKBitmap> cmyk_bitmap;
  370. u16 dc_restart_interval { 0 };
  371. HashMap<u8, HuffmanTable> dc_tables;
  372. HashMap<u8, HuffmanTable> ac_tables;
  373. Array<i16, 4> previous_dc_values {};
  374. MacroblockMeta mblock_meta;
  375. JPEGStream stream;
  376. JPEGDecoderOptions options;
  377. Optional<ColorTransform> color_transform {};
  378. OwnPtr<ExifMetadata> exif_metadata {};
  379. Optional<ICCMultiChunkState> icc_multi_chunk_state;
  380. Optional<ByteBuffer> icc_data;
  381. };
  382. static inline auto* get_component(Macroblock& block, unsigned component)
  383. {
  384. switch (component) {
  385. case 0:
  386. return block.y;
  387. case 1:
  388. return block.cb;
  389. case 2:
  390. return block.cr;
  391. case 3:
  392. return block.k;
  393. default:
  394. VERIFY_NOT_REACHED();
  395. }
  396. }
  397. static ErrorOr<void> refine_coefficient(Scan& scan, auto& coefficient)
  398. {
  399. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  400. // See the correction bit from rule b.
  401. u8 const bit = TRY(scan.huffman_stream.read_bits(1));
  402. if (bit == 1)
  403. coefficient |= 1 << scan.successive_approximation_low;
  404. return {};
  405. }
  406. enum class JPEGDecodingMode {
  407. Sequential,
  408. Progressive
  409. };
  410. template<JPEGDecodingMode DecodingMode>
  411. static ErrorOr<void> add_dc(JPEGLoadingContext& context, Macroblock& macroblock, ScanComponent const& scan_component)
  412. {
  413. auto maybe_table = context.dc_tables.get(scan_component.dc_destination_id);
  414. if (!maybe_table.has_value()) {
  415. dbgln_if(JPEG_DEBUG, "Unable to find a DC table with id: {}", scan_component.dc_destination_id);
  416. return Error::from_string_literal("Unable to find corresponding DC table");
  417. }
  418. auto& dc_table = maybe_table.value();
  419. auto& scan = *context.current_scan;
  420. auto* select_component = get_component(macroblock, scan_component.component.index);
  421. auto& coefficient = select_component[0];
  422. if (DecodingMode == JPEGDecodingMode::Progressive && scan.successive_approximation_high > 0) {
  423. TRY(refine_coefficient(scan, coefficient));
  424. return {};
  425. }
  426. // For DC coefficients, symbol encodes the length of the coefficient.
  427. auto dc_length = TRY(scan.huffman_stream.next_symbol(dc_table));
  428. // F.1.2.1.2 - Defining Huffman tables for the DC coefficients
  429. // F.1.5.1 - Structure of DC code table for 12-bit sample precision
  430. if ((context.frame.precision == 8 && dc_length > 11)
  431. || (context.frame.precision == 12 && dc_length > 15)) {
  432. dbgln_if(JPEG_DEBUG, "DC coefficient too long: {}!", dc_length);
  433. return Error::from_string_literal("DC coefficient too long");
  434. }
  435. // DC coefficients are encoded as the difference between previous and current DC values.
  436. i16 dc_diff = TRY(scan.huffman_stream.read_bits(dc_length));
  437. // If MSB in diff is 0, the difference is -ve. Otherwise +ve.
  438. if (dc_length != 0 && dc_diff < (1 << (dc_length - 1)))
  439. dc_diff -= (1 << dc_length) - 1;
  440. auto& previous_dc = context.previous_dc_values[scan_component.component.index];
  441. previous_dc += dc_diff;
  442. coefficient = previous_dc << scan.successive_approximation_low;
  443. return {};
  444. }
  445. template<JPEGDecodingMode DecodingMode>
  446. static ALWAYS_INLINE ErrorOr<bool> read_eob(Scan& scan, u32 symbol)
  447. {
  448. // OPTIMIZATION: This is a fast path for sequential JPEGs, these
  449. // only supports EOB with a value of one block.
  450. if constexpr (DecodingMode == JPEGDecodingMode::Sequential)
  451. return symbol == 0x00;
  452. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  453. // Note: We also use it for non-progressive encoding as it supports both EOB and ZRL
  454. if (auto const eob = symbol & 0x0F; eob == 0 && symbol != JPEG_ZRL) {
  455. // We encountered an EOB marker
  456. auto const eob_base = symbol >> 4;
  457. auto const additional_value = TRY(scan.huffman_stream.read_bits(eob_base));
  458. scan.end_of_bands_run_count = additional_value + (1 << eob_base) - 1;
  459. // end_of_bands_run_count is decremented at the end of `build_macroblocks`.
  460. // And we need to now that we reached End of Block in `add_ac`.
  461. ++scan.end_of_bands_run_count;
  462. return true;
  463. }
  464. return false;
  465. }
  466. static bool is_progressive(StartOfFrame::FrameType frame_type)
  467. {
  468. return frame_type == StartOfFrame::FrameType::Progressive_DCT
  469. || frame_type == StartOfFrame::FrameType::Progressive_DCT_Arithmetic
  470. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT
  471. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT_Arithmetic;
  472. }
  473. template<JPEGDecodingMode DecodingMode>
  474. static ErrorOr<void> add_ac(JPEGLoadingContext& context, Macroblock& macroblock, ScanComponent const& scan_component)
  475. {
  476. auto maybe_table = context.ac_tables.get(scan_component.ac_destination_id);
  477. if (!maybe_table.has_value()) {
  478. dbgln_if(JPEG_DEBUG, "Unable to find a AC table with id: {}", scan_component.ac_destination_id);
  479. return Error::from_string_literal("Unable to find corresponding AC table");
  480. }
  481. auto& ac_table = maybe_table.value();
  482. auto* select_component = get_component(macroblock, scan_component.component.index);
  483. auto& scan = *context.current_scan;
  484. // Compute the AC coefficients.
  485. // 0th coefficient is the dc, which is already handled
  486. auto first_coefficient = max(1, scan.spectral_selection_start);
  487. u32 to_skip = 0;
  488. Optional<u8> saved_symbol;
  489. Optional<u8> saved_bit_for_rule_a;
  490. bool in_zrl = false;
  491. for (int j = first_coefficient; j <= scan.spectral_selection_end; ++j) {
  492. auto& coefficient = select_component[zigzag_map[j]];
  493. // AC symbols encode 2 pieces of information, the high 4 bits represent
  494. // number of zeroes to be stuffed before reading the coefficient. Low 4
  495. // bits represent the magnitude of the coefficient.
  496. if (!in_zrl && scan.end_of_bands_run_count == 0 && !saved_symbol.has_value()) {
  497. saved_symbol = TRY(scan.huffman_stream.next_symbol(ac_table));
  498. if (!TRY(read_eob<DecodingMode>(scan, *saved_symbol))) {
  499. to_skip = *saved_symbol >> 4;
  500. in_zrl = *saved_symbol == JPEG_ZRL;
  501. if (in_zrl) {
  502. to_skip++;
  503. saved_symbol.clear();
  504. }
  505. if constexpr (DecodingMode == JPEGDecodingMode::Sequential) {
  506. j += to_skip - 1;
  507. to_skip = 0;
  508. in_zrl = false;
  509. continue;
  510. }
  511. if constexpr (DecodingMode == JPEGDecodingMode::Progressive) {
  512. if (!in_zrl && scan.successive_approximation_high != 0) {
  513. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  514. // Bit sign from rule a
  515. saved_bit_for_rule_a = TRY(scan.huffman_stream.read_bits(1));
  516. }
  517. }
  518. } else if constexpr (DecodingMode == JPEGDecodingMode::Sequential) {
  519. break;
  520. }
  521. }
  522. if constexpr (DecodingMode == JPEGDecodingMode::Progressive) {
  523. if (coefficient != 0) {
  524. TRY(refine_coefficient(scan, coefficient));
  525. continue;
  526. }
  527. }
  528. if (to_skip > 0) {
  529. --to_skip;
  530. if (to_skip == 0)
  531. in_zrl = false;
  532. continue;
  533. }
  534. if (scan.end_of_bands_run_count > 0)
  535. continue;
  536. if (DecodingMode == JPEGDecodingMode::Progressive && scan.successive_approximation_high != 0) {
  537. // G.1.2.3 - Coding model for subsequent scans of successive approximation
  538. if (auto const low_bits = *saved_symbol & 0x0F; low_bits != 1) {
  539. dbgln_if(JPEG_DEBUG, "AC coefficient low bits isn't equal to 1: {}!", low_bits);
  540. return Error::from_string_literal("AC coefficient low bits isn't equal to 1");
  541. }
  542. coefficient = (*saved_bit_for_rule_a == 0 ? -1 : 1) << scan.successive_approximation_low;
  543. saved_bit_for_rule_a.clear();
  544. } else {
  545. // F.1.2.2 - Huffman encoding of AC coefficients
  546. u8 const coeff_length = *saved_symbol & 0x0F;
  547. // F.1.2.2.1 - Structure of AC code table
  548. // F.1.5.2 - Structure of AC code table for 12-bit sample precision
  549. if ((context.frame.precision == 8 && coeff_length > 10)
  550. || (context.frame.precision == 12 && coeff_length > 14)) {
  551. dbgln_if(JPEG_DEBUG, "AC coefficient too long: {}!", coeff_length);
  552. return Error::from_string_literal("AC coefficient too long");
  553. }
  554. if (coeff_length != 0) {
  555. i32 ac_coefficient = TRY(scan.huffman_stream.read_bits(coeff_length));
  556. if (ac_coefficient < (1 << (coeff_length - 1)))
  557. ac_coefficient -= (1 << coeff_length) - 1;
  558. coefficient = ac_coefficient * (1 << scan.successive_approximation_low);
  559. }
  560. }
  561. saved_symbol.clear();
  562. }
  563. if (to_skip > 0) {
  564. dbgln_if(JPEG_DEBUG, "Run-length exceeded boundaries. Cursor: {}, Skipping: {}!", scan.spectral_selection_end + to_skip, to_skip);
  565. return Error::from_string_literal("Run-length exceeded boundaries");
  566. }
  567. return {};
  568. }
  569. /**
  570. * Build the macroblocks possible by reading single (MCU) subsampled pair of CbCr.
  571. * Depending on the sampling factors, we may not see triples of y, cb, cr in that
  572. * order. If sample factors differ from one, we'll read more than one block of y-
  573. * coefficients before we get to read a cb-cr block.
  574. * In the function below, `hcursor` and `vcursor` denote the location of the block
  575. * we're building in the macroblock matrix. `vfactor_i` and `hfactor_i` are cursors
  576. * that iterate over the vertical and horizontal subsampling factors, respectively.
  577. * When we finish one iteration of the innermost loop, we'll have the coefficients
  578. * of one of the components of block at position `macroblock_index`. When the outermost
  579. * loop finishes first iteration, we'll have all the luminance coefficients for all the
  580. * macroblocks that share the chrominance data. Next two iterations (assuming that
  581. * we are dealing with three components) will fill up the blocks with chroma data.
  582. */
  583. template<JPEGDecodingMode DecodingMode>
  584. static ErrorOr<void> build_macroblocks(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks, u32 hcursor, u32 vcursor)
  585. {
  586. for (auto const& scan_component : context.current_scan->components) {
  587. for (u8 vfactor_i = 0; vfactor_i < scan_component.component.sampling_factors.vertical; vfactor_i++) {
  588. for (u8 hfactor_i = 0; hfactor_i < scan_component.component.sampling_factors.horizontal; hfactor_i++) {
  589. // A.2.3 - Interleaved order
  590. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  591. if (!context.current_scan->are_components_interleaved()) {
  592. macroblock_index = vcursor * context.mblock_meta.hpadded_count + (hfactor_i + (hcursor * scan_component.component.sampling_factors.vertical) + (vfactor_i * scan_component.component.sampling_factors.horizontal));
  593. // A.2.4 Completion of partial MCU
  594. // If the component is [and only if!] to be interleaved, the encoding process
  595. // shall also extend the number of samples by one or more additional blocks.
  596. // Horizontally
  597. if (macroblock_index >= context.mblock_meta.hcount && macroblock_index % context.mblock_meta.hpadded_count >= context.mblock_meta.hcount)
  598. continue;
  599. // Vertically
  600. if (macroblock_index >= context.mblock_meta.hpadded_count * context.mblock_meta.vcount)
  601. continue;
  602. }
  603. Macroblock& block = macroblocks[macroblock_index];
  604. if constexpr (DecodingMode == JPEGDecodingMode::Sequential) {
  605. TRY(add_dc<DecodingMode>(context, block, scan_component));
  606. TRY(add_ac<DecodingMode>(context, block, scan_component));
  607. } else {
  608. if (context.current_scan->spectral_selection_start == 0)
  609. TRY(add_dc<DecodingMode>(context, block, scan_component));
  610. if (context.current_scan->spectral_selection_end != 0)
  611. TRY(add_ac<DecodingMode>(context, block, scan_component));
  612. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  613. if (context.current_scan->end_of_bands_run_count > 0) {
  614. --context.current_scan->end_of_bands_run_count;
  615. continue;
  616. }
  617. }
  618. }
  619. }
  620. }
  621. return {};
  622. }
  623. static bool is_dct_based(StartOfFrame::FrameType frame_type)
  624. {
  625. return frame_type == StartOfFrame::FrameType::Baseline_DCT
  626. || frame_type == StartOfFrame::FrameType::Extended_Sequential_DCT
  627. || frame_type == StartOfFrame::FrameType::Progressive_DCT
  628. || frame_type == StartOfFrame::FrameType::Differential_Sequential_DCT
  629. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT
  630. || frame_type == StartOfFrame::FrameType::Progressive_DCT_Arithmetic
  631. || frame_type == StartOfFrame::FrameType::Differential_Sequential_DCT_Arithmetic
  632. || frame_type == StartOfFrame::FrameType::Differential_Progressive_DCT_Arithmetic;
  633. }
  634. static void reset_decoder(JPEGLoadingContext& context)
  635. {
  636. // G.1.2.2 - Progressive encoding of AC coefficients with Huffman coding
  637. context.current_scan->end_of_bands_run_count = 0;
  638. // E.2.4 Control procedure for decoding a restart interval
  639. if (is_dct_based(context.frame.type)) {
  640. context.previous_dc_values = {};
  641. return;
  642. }
  643. VERIFY_NOT_REACHED();
  644. }
  645. static ErrorOr<void> decode_huffman_stream(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks)
  646. {
  647. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  648. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  649. // FIXME: This is likely wrong for non-interleaved scans.
  650. VERIFY(context.mblock_meta.hpadded_count % context.sampling_factors.horizontal == 0);
  651. u32 number_of_mcus_decoded_so_far = ((vcursor / context.sampling_factors.vertical) * context.mblock_meta.hpadded_count + hcursor) / context.sampling_factors.horizontal;
  652. auto& huffman_stream = context.current_scan->huffman_stream;
  653. if (context.dc_restart_interval > 0) {
  654. if (number_of_mcus_decoded_so_far != 0 && number_of_mcus_decoded_so_far % context.dc_restart_interval == 0) {
  655. reset_decoder(context);
  656. // Restart markers are stored in byte boundaries. Advance the huffman stream cursor to
  657. // the 0th bit of the next byte.
  658. TRY(huffman_stream.advance_to_byte_boundary());
  659. // Skip the restart marker (RSTn).
  660. TRY(huffman_stream.discard_bits(8));
  661. }
  662. }
  663. auto result = [&]() {
  664. if (is_progressive(context.frame.type))
  665. return build_macroblocks<JPEGDecodingMode::Progressive>(context, macroblocks, hcursor, vcursor);
  666. return build_macroblocks<JPEGDecodingMode::Sequential>(context, macroblocks, hcursor, vcursor);
  667. }();
  668. if (result.is_error()) {
  669. if constexpr (JPEG_DEBUG) {
  670. dbgln("Failed to build Macroblock {}: {}", number_of_mcus_decoded_so_far, result.error());
  671. dbgln("Huffman stream byte offset {:#x}", context.stream.byte_offset());
  672. }
  673. return result.release_error();
  674. }
  675. }
  676. }
  677. return {};
  678. }
  679. static bool is_frame_marker(Marker const marker)
  680. {
  681. // B.1.1.3 - Marker assignments
  682. bool const is_sof_marker = marker >= JPEG_SOF0 && marker <= JPEG_SOF15;
  683. // Start of frame markers are valid for JPEG_SOF0 to JPEG_SOF15 except number 4, 8 (reserved) and 12.
  684. bool const is_defined_marker = marker != JPEG_DHT && marker != 0xFFC8 && marker != JPEG_DAC;
  685. return is_sof_marker && is_defined_marker;
  686. }
  687. static inline bool is_supported_marker(Marker const marker)
  688. {
  689. if (marker >= JPEG_APPN0 && marker <= JPEG_APPN15) {
  690. if (marker != JPEG_APPN0 && marker != JPEG_APPN14)
  691. dbgln_if(JPEG_DEBUG, "{:#04x} not supported yet. The decoder may fail!", marker);
  692. return true;
  693. }
  694. if (marker >= JPEG_RESERVED1 && marker <= JPEG_RESERVEDD)
  695. return true;
  696. if (marker >= JPEG_RST0 && marker <= JPEG_RST7)
  697. return true;
  698. switch (marker) {
  699. case JPEG_COM:
  700. case JPEG_DHP:
  701. case JPEG_EXP:
  702. case JPEG_DHT:
  703. case JPEG_DQT:
  704. case JPEG_DRI:
  705. case JPEG_EOI:
  706. case JPEG_SOF0:
  707. case JPEG_SOF1:
  708. case JPEG_SOF2:
  709. case JPEG_SOI:
  710. case JPEG_SOS:
  711. return true;
  712. }
  713. if (is_frame_marker(marker))
  714. dbgln_if(JPEG_DEBUG, "Decoding this frame-type (SOF{}) is not currently supported. Decoder will fail!", marker & 0xf);
  715. return false;
  716. }
  717. static inline ErrorOr<Marker> read_marker_at_cursor(JPEGStream& stream)
  718. {
  719. u16 marker = TRY(stream.read_u16());
  720. if (marker == 0xFFFF) {
  721. u8 next { 0xFF };
  722. while (next == 0xFF)
  723. next = TRY(stream.read_u8());
  724. marker = 0xFF00 | next;
  725. }
  726. if (is_supported_marker(marker))
  727. return marker;
  728. dbgln_if(JPEG_DEBUG, "Unsupported marker: {:#04x} around offset {:#x}", marker, stream.byte_offset());
  729. return Error::from_string_literal("Reached an unsupported marker");
  730. }
  731. static ErrorOr<u16> read_effective_chunk_size(JPEGStream& stream)
  732. {
  733. // The stored chunk size includes the size of `stored_size` itself.
  734. u16 const stored_size = TRY(stream.read_u16());
  735. if (stored_size < 2)
  736. return Error::from_string_literal("Stored chunk size is too small");
  737. return stored_size - 2;
  738. }
  739. static ErrorOr<void> read_start_of_scan(JPEGStream& stream, JPEGLoadingContext& context)
  740. {
  741. // B.2.3 - Scan header syntax
  742. if (context.state < JPEGLoadingContext::State::FrameDecoded)
  743. return Error::from_string_literal("SOS found before reading a SOF");
  744. [[maybe_unused]] u16 const bytes_to_read = TRY(read_effective_chunk_size(stream));
  745. u8 const component_count = TRY(stream.read_u8());
  746. Scan current_scan(HuffmanStream { context.stream });
  747. Optional<u8> last_read;
  748. u8 component_read = 0;
  749. for (auto& component : context.components) {
  750. // See the Csj paragraph:
  751. // [...] the ordering in the scan header shall follow the ordering in the frame header.
  752. if (component_read == component_count)
  753. break;
  754. if (!last_read.has_value())
  755. last_read = TRY(stream.read_u8());
  756. if (component.id != *last_read)
  757. continue;
  758. u8 const table_ids = TRY(stream.read_u8());
  759. current_scan.components.empend(component, static_cast<u8>(table_ids >> 4), static_cast<u8>(table_ids & 0x0F));
  760. component_read++;
  761. last_read.clear();
  762. }
  763. if constexpr (JPEG_DEBUG) {
  764. StringBuilder builder;
  765. TRY(builder.try_append("Components in scan: "sv));
  766. for (auto const& scan_component : current_scan.components) {
  767. TRY(builder.try_append(TRY(String::number(scan_component.component.id))));
  768. TRY(builder.try_append(' '));
  769. }
  770. dbgln(builder.string_view());
  771. }
  772. current_scan.spectral_selection_start = TRY(stream.read_u8());
  773. current_scan.spectral_selection_end = TRY(stream.read_u8());
  774. auto const successive_approximation = TRY(stream.read_u8());
  775. current_scan.successive_approximation_high = successive_approximation >> 4;
  776. current_scan.successive_approximation_low = successive_approximation & 0x0F;
  777. dbgln_if(JPEG_DEBUG, "Start of Selection: {}, End of Selection: {}, Successive Approximation High: {}, Successive Approximation Low: {}",
  778. current_scan.spectral_selection_start,
  779. current_scan.spectral_selection_end,
  780. current_scan.successive_approximation_high,
  781. current_scan.successive_approximation_low);
  782. if (current_scan.spectral_selection_start > 63 || current_scan.spectral_selection_end > 63 || current_scan.successive_approximation_high > 13 || current_scan.successive_approximation_low > 13) {
  783. dbgln_if(JPEG_DEBUG, "ERROR! Start of Selection: {}, End of Selection: {}, Successive Approximation High: {}, Successive Approximation Low: {}!",
  784. current_scan.spectral_selection_start,
  785. current_scan.spectral_selection_end,
  786. current_scan.successive_approximation_high,
  787. current_scan.successive_approximation_low);
  788. return Error::from_string_literal("Spectral selection is not [0,63] or successive approximation is not null");
  789. }
  790. context.current_scan = move(current_scan);
  791. return {};
  792. }
  793. static ErrorOr<void> read_restart_interval(JPEGStream& stream, JPEGLoadingContext& context)
  794. {
  795. // B.2.4.4 - Restart interval definition syntax
  796. u16 bytes_to_read = TRY(read_effective_chunk_size(stream));
  797. if (bytes_to_read != 2) {
  798. dbgln_if(JPEG_DEBUG, "Malformed DRI marker found!");
  799. return Error::from_string_literal("Malformed DRI marker found");
  800. }
  801. context.dc_restart_interval = TRY(stream.read_u16());
  802. dbgln_if(JPEG_DEBUG, "Restart marker: {}", context.dc_restart_interval);
  803. return {};
  804. }
  805. static ErrorOr<void> read_huffman_table(JPEGStream& stream, JPEGLoadingContext& context)
  806. {
  807. // B.2.4.2 - Huffman table-specification syntax
  808. u16 bytes_to_read = TRY(read_effective_chunk_size(stream));
  809. while (bytes_to_read > 0) {
  810. HuffmanTable table;
  811. u8 const table_info = TRY(stream.read_u8());
  812. u8 const table_type = table_info >> 4;
  813. u8 const table_destination_id = table_info & 0x0F;
  814. if (table_type > 1) {
  815. dbgln_if(JPEG_DEBUG, "Unrecognized huffman table: {}!", table_type);
  816. return Error::from_string_literal("Unrecognized huffman table");
  817. }
  818. if ((context.frame.type == StartOfFrame::FrameType::Baseline_DCT && table_destination_id > 1)
  819. || (context.frame.type != StartOfFrame::FrameType::Baseline_DCT && table_destination_id > 3)) {
  820. dbgln_if(JPEG_DEBUG, "Invalid huffman table destination id: {}!", table_destination_id);
  821. return Error::from_string_literal("Invalid huffman table destination id");
  822. }
  823. table.type = table_type;
  824. table.destination_id = table_destination_id;
  825. u32 total_codes = 0;
  826. // Read code counts. At each index K, the value represents the number of K+1 bit codes in this header.
  827. for (int i = 0; i < 16; i++) {
  828. if (i == HuffmanTable::bits_per_cached_code)
  829. table.first_non_cached_code_index = total_codes;
  830. u8 const count = TRY(stream.read_u8());
  831. total_codes += count;
  832. table.code_counts[i] = count;
  833. }
  834. table.codes.ensure_capacity(total_codes);
  835. table.symbols.ensure_capacity(total_codes);
  836. // Read symbols. Read X bytes, where X is the sum of the counts of codes read in the previous step.
  837. for (u32 i = 0; i < total_codes; i++) {
  838. u8 symbol = TRY(stream.read_u8());
  839. table.symbols.append(symbol);
  840. }
  841. TRY(table.generate_codes());
  842. auto& huffman_table = table.type == 0 ? context.dc_tables : context.ac_tables;
  843. huffman_table.set(table.destination_id, table);
  844. bytes_to_read -= 1 + 16 + total_codes;
  845. }
  846. if (bytes_to_read != 0) {
  847. dbgln_if(JPEG_DEBUG, "Extra bytes detected in huffman header!");
  848. return Error::from_string_literal("Extra bytes detected in huffman header");
  849. }
  850. return {};
  851. }
  852. static ErrorOr<void> read_icc_profile(JPEGStream& stream, JPEGLoadingContext& context, int bytes_to_read)
  853. {
  854. // https://www.color.org/technotes/ICC-Technote-ProfileEmbedding.pdf, page 5, "JFIF".
  855. if (bytes_to_read <= 2) {
  856. dbgln_if(JPEG_DEBUG, "icc marker too small");
  857. TRY(stream.discard(bytes_to_read));
  858. return {};
  859. }
  860. auto chunk_sequence_number = TRY(stream.read_u8()); // 1-based
  861. auto number_of_chunks = TRY(stream.read_u8());
  862. bytes_to_read -= 2;
  863. if (!context.icc_multi_chunk_state.has_value())
  864. context.icc_multi_chunk_state.emplace(ICCMultiChunkState { 0, TRY(FixedArray<ByteBuffer>::create(number_of_chunks)) });
  865. auto& chunk_state = context.icc_multi_chunk_state;
  866. u8 index {};
  867. auto const ensure_correctness = [&]() -> ErrorOr<void> {
  868. if (chunk_state->seen_number_of_icc_chunks >= number_of_chunks)
  869. return Error::from_string_literal("Too many ICC chunks");
  870. if (chunk_state->chunks.size() != number_of_chunks)
  871. return Error::from_string_literal("Inconsistent number of total ICC chunks");
  872. if (chunk_sequence_number == 0)
  873. return Error::from_string_literal("ICC chunk sequence number not 1 based");
  874. index = chunk_sequence_number - 1;
  875. if (index >= chunk_state->chunks.size())
  876. return Error::from_string_literal("ICC chunk sequence number larger than number of chunks");
  877. if (!chunk_state->chunks[index].is_empty())
  878. return Error::from_string_literal("Duplicate ICC chunk at sequence number");
  879. return {};
  880. };
  881. if (auto result = ensure_correctness(); result.is_error()) {
  882. dbgln_if(JPEG_DEBUG, "JPEG: {}", result.release_error());
  883. TRY(stream.discard(bytes_to_read));
  884. return {};
  885. }
  886. chunk_state->chunks[index] = TRY(ByteBuffer::create_zeroed(bytes_to_read));
  887. TRY(stream.read_until_filled(chunk_state->chunks[index]));
  888. chunk_state->seen_number_of_icc_chunks++;
  889. if (chunk_state->seen_number_of_icc_chunks != chunk_state->chunks.size())
  890. return {};
  891. if (number_of_chunks == 1) {
  892. context.icc_data = move(chunk_state->chunks[0]);
  893. return {};
  894. }
  895. size_t total_size = 0;
  896. for (auto const& chunk : chunk_state->chunks)
  897. total_size += chunk.size();
  898. auto icc_bytes = TRY(ByteBuffer::create_zeroed(total_size));
  899. size_t start = 0;
  900. for (auto const& chunk : chunk_state->chunks) {
  901. memcpy(icc_bytes.data() + start, chunk.data(), chunk.size());
  902. start += chunk.size();
  903. }
  904. context.icc_data = move(icc_bytes);
  905. return {};
  906. }
  907. static ErrorOr<void> read_colour_encoding(JPEGStream& stream, [[maybe_unused]] JPEGLoadingContext& context, int bytes_to_read)
  908. {
  909. // The App 14 segment is application specific in the first JPEG standard.
  910. // However, the Adobe implementation is globally accepted and the value of the color transform
  911. // was latter standardized as a JPEG-1 extension.
  912. // For the structure of the App 14 segment, see:
  913. // https://www.pdfa.org/norm-refs/5116.DCT_Filter.pdf
  914. // 18 Adobe Application-Specific JPEG Marker
  915. // For the value of color_transform, see:
  916. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.872-201206-I!!PDF-E&type=items
  917. // 6.5.3 - APP14 marker segment for colour encoding
  918. if (bytes_to_read < 6)
  919. return Error::from_string_literal("App14 segment too small");
  920. [[maybe_unused]] auto const version = TRY(stream.read_u8());
  921. [[maybe_unused]] u16 const flag0 = TRY(stream.read_u16());
  922. [[maybe_unused]] u16 const flag1 = TRY(stream.read_u16());
  923. auto const color_transform = TRY(stream.read_u8());
  924. if (bytes_to_read > 6) {
  925. dbgln_if(JPEG_DEBUG, "Unread bytes in App14 segment: {}", bytes_to_read - 6);
  926. TRY(stream.discard(bytes_to_read - 6));
  927. }
  928. switch (color_transform) {
  929. case 0:
  930. context.color_transform = ColorTransform::CmykOrRgb;
  931. break;
  932. case 1:
  933. context.color_transform = ColorTransform::YCbCr;
  934. break;
  935. case 2:
  936. context.color_transform = ColorTransform::YCCK;
  937. break;
  938. default:
  939. dbgln("{:#x} is not a specified transform flag value, ignoring", color_transform);
  940. }
  941. return {};
  942. }
  943. static ErrorOr<void> read_exif(JPEGStream& stream, JPEGLoadingContext& context, int bytes_to_read)
  944. {
  945. // This refers to Exif's specification, see TIFFLoader for more information.
  946. // 4.7.2.2. - APP1 internal structure
  947. if (bytes_to_read <= 1) {
  948. TRY(stream.discard(bytes_to_read));
  949. return {};
  950. }
  951. // Discard padding byte
  952. TRY(stream.discard(1));
  953. auto exif_buffer = TRY(ByteBuffer::create_uninitialized(bytes_to_read - 1));
  954. TRY(stream.read_until_filled(exif_buffer));
  955. context.exif_metadata = TRY(TIFFImageDecoderPlugin::read_exif_metadata(exif_buffer));
  956. return {};
  957. }
  958. static ErrorOr<void> read_app_marker(JPEGStream& stream, JPEGLoadingContext& context, int app_marker_number)
  959. {
  960. // B.2.4.6 - Application data syntax
  961. u16 bytes_to_read = TRY(read_effective_chunk_size(stream));
  962. StringBuilder builder;
  963. for (;;) {
  964. if (bytes_to_read == 0) {
  965. dbgln_if(JPEG_DEBUG, "app marker {} does not start with zero-terminated string", app_marker_number);
  966. return {};
  967. }
  968. auto c = TRY(stream.read_u8());
  969. bytes_to_read--;
  970. if (c == '\0')
  971. break;
  972. TRY(builder.try_append(c));
  973. }
  974. auto app_id = TRY(builder.to_string());
  975. if (app_marker_number == 1 && app_id == "Exif"sv)
  976. return read_exif(stream, context, bytes_to_read);
  977. if (app_marker_number == 2 && app_id == "ICC_PROFILE"sv)
  978. return read_icc_profile(stream, context, bytes_to_read);
  979. if (app_marker_number == 14 && app_id == "Adobe"sv)
  980. return read_colour_encoding(stream, context, bytes_to_read);
  981. return stream.discard(bytes_to_read);
  982. }
  983. static inline bool validate_sampling_factors_and_modify_context(SamplingFactors const& sampling_factors, JPEGLoadingContext& context)
  984. {
  985. if ((sampling_factors.horizontal == 1 || sampling_factors.horizontal == 2) && (sampling_factors.vertical == 1 || sampling_factors.vertical == 2)) {
  986. context.mblock_meta.hpadded_count += sampling_factors.horizontal == 1 ? 0 : context.mblock_meta.hcount % 2;
  987. context.mblock_meta.vpadded_count += sampling_factors.vertical == 1 ? 0 : context.mblock_meta.vcount % 2;
  988. context.mblock_meta.padded_total = context.mblock_meta.hpadded_count * context.mblock_meta.vpadded_count;
  989. // For easy reference to relevant sample factors.
  990. context.sampling_factors = sampling_factors;
  991. return true;
  992. }
  993. return false;
  994. }
  995. static inline void set_macroblock_metadata(JPEGLoadingContext& context)
  996. {
  997. context.mblock_meta.hcount = ceil_div<u32>(context.frame.width, 8);
  998. context.mblock_meta.vcount = ceil_div<u32>(context.frame.height, 8);
  999. context.mblock_meta.hpadded_count = context.mblock_meta.hcount;
  1000. context.mblock_meta.vpadded_count = context.mblock_meta.vcount;
  1001. context.mblock_meta.total = context.mblock_meta.hcount * context.mblock_meta.vcount;
  1002. }
  1003. static ErrorOr<void> ensure_standard_precision(StartOfFrame const& frame)
  1004. {
  1005. // B.2.2 - Frame header syntax
  1006. // Table B.2 - Frame header parameter sizes and values
  1007. if (frame.precision == 8)
  1008. return {};
  1009. if (frame.type == StartOfFrame::FrameType::Extended_Sequential_DCT && frame.precision == 12)
  1010. return {};
  1011. if (frame.type == StartOfFrame::FrameType::Progressive_DCT && frame.precision == 12)
  1012. return {};
  1013. dbgln_if(JPEG_DEBUG, "Unsupported precision: {}, for SOF type: {}!", frame.precision, static_cast<int>(frame.type));
  1014. return Error::from_string_literal("Unsupported SOF precision.");
  1015. }
  1016. static ErrorOr<void> read_start_of_frame(JPEGStream& stream, JPEGLoadingContext& context)
  1017. {
  1018. if (context.state == JPEGLoadingContext::FrameDecoded) {
  1019. dbgln_if(JPEG_DEBUG, "SOF repeated!");
  1020. return Error::from_string_literal("SOF repeated");
  1021. }
  1022. // B.2.2 Frame header syntax
  1023. [[maybe_unused]] u16 const bytes_to_read = TRY(read_effective_chunk_size(stream));
  1024. context.frame.precision = TRY(stream.read_u8());
  1025. TRY(ensure_standard_precision(context.frame));
  1026. context.frame.height = TRY(stream.read_u16());
  1027. context.frame.width = TRY(stream.read_u16());
  1028. if (!context.frame.width || !context.frame.height) {
  1029. dbgln_if(JPEG_DEBUG, "ERROR! Image height: {}, Image width: {}!", context.frame.height, context.frame.width);
  1030. return Error::from_string_literal("Image frame height of width null");
  1031. }
  1032. set_macroblock_metadata(context);
  1033. auto component_count = TRY(stream.read_u8());
  1034. if (component_count != 1 && component_count != 3 && component_count != 4) {
  1035. dbgln_if(JPEG_DEBUG, "Unsupported number of components in SOF: {}!", component_count);
  1036. return Error::from_string_literal("Unsupported number of components in SOF");
  1037. }
  1038. for (u8 i = 0; i < component_count; i++) {
  1039. Component component;
  1040. component.id = TRY(stream.read_u8());
  1041. component.index = i;
  1042. u8 subsample_factors = TRY(stream.read_u8());
  1043. component.sampling_factors.horizontal = subsample_factors >> 4;
  1044. component.sampling_factors.vertical = subsample_factors & 0x0F;
  1045. if (component_count == 1) {
  1046. // 4.8.2 Minimum coded unit: "If the compressed image data is non-interleaved, the MCU is defined to be one data unit."
  1047. component.sampling_factors = { 1, 1 };
  1048. }
  1049. dbgln_if(JPEG_DEBUG, "Component subsampling: {}, {}", component.sampling_factors.horizontal, component.sampling_factors.vertical);
  1050. if (i == 0) {
  1051. // By convention, downsampling is applied only on chroma components. So we should
  1052. // hope to see the maximum sampling factor in the luma component.
  1053. if (!validate_sampling_factors_and_modify_context(component.sampling_factors, context)) {
  1054. dbgln_if(JPEG_DEBUG, "Unsupported luma subsampling factors: horizontal: {}, vertical: {}",
  1055. component.sampling_factors.horizontal,
  1056. component.sampling_factors.vertical);
  1057. return Error::from_string_literal("Unsupported luma subsampling factors");
  1058. }
  1059. } else {
  1060. auto const& y_component = context.components[0];
  1061. if (y_component.sampling_factors.horizontal % component.sampling_factors.horizontal != 0
  1062. || y_component.sampling_factors.vertical % component.sampling_factors.vertical != 0) {
  1063. dbgln_if(JPEG_DEBUG, "Unsupported chroma subsampling factors: horizontal: {}, vertical: {}",
  1064. component.sampling_factors.horizontal,
  1065. component.sampling_factors.vertical);
  1066. return Error::from_string_literal("Unsupported chroma subsampling factors");
  1067. }
  1068. }
  1069. component.quantization_table_id = TRY(stream.read_u8());
  1070. context.components.append(move(component));
  1071. }
  1072. return {};
  1073. }
  1074. static ErrorOr<void> read_quantization_table(JPEGStream& stream, JPEGLoadingContext& context)
  1075. {
  1076. // B.2.4.1 - Quantization table-specification syntax
  1077. u16 bytes_to_read = TRY(read_effective_chunk_size(stream));
  1078. while (bytes_to_read > 0) {
  1079. u8 const info_byte = TRY(stream.read_u8());
  1080. u8 const element_unit_hint = info_byte >> 4;
  1081. if (element_unit_hint > 1) {
  1082. dbgln_if(JPEG_DEBUG, "Unsupported unit hint in quantization table: {}!", element_unit_hint);
  1083. return Error::from_string_literal("Unsupported unit hint in quantization table");
  1084. }
  1085. u8 const table_id = info_byte & 0x0F;
  1086. if (table_id > 3) {
  1087. dbgln_if(JPEG_DEBUG, "Unsupported quantization table id: {}!", table_id);
  1088. return Error::from_string_literal("Unsupported quantization table id");
  1089. }
  1090. auto& maybe_table = context.quantization_tables[table_id];
  1091. if (!maybe_table.has_value())
  1092. maybe_table = Array<u16, 64> {};
  1093. auto& table = maybe_table.value();
  1094. for (int i = 0; i < 64; i++) {
  1095. if (element_unit_hint == 0)
  1096. table[zigzag_map[i]] = TRY(stream.read_u8());
  1097. else
  1098. table[zigzag_map[i]] = TRY(stream.read_u16());
  1099. }
  1100. bytes_to_read -= 1 + (element_unit_hint == 0 ? 64 : 128);
  1101. }
  1102. if (bytes_to_read != 0) {
  1103. dbgln_if(JPEG_DEBUG, "Invalid length for one or more quantization tables!");
  1104. return Error::from_string_literal("Invalid length for one or more quantization tables");
  1105. }
  1106. return {};
  1107. }
  1108. static ErrorOr<void> skip_segment(JPEGStream& stream)
  1109. {
  1110. u16 bytes_to_skip = TRY(read_effective_chunk_size(stream));
  1111. TRY(stream.discard(bytes_to_skip));
  1112. return {};
  1113. }
  1114. static ErrorOr<void> dequantize(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks)
  1115. {
  1116. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1117. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1118. for (u32 i = 0; i < context.components.size(); i++) {
  1119. auto const& component = context.components[i];
  1120. if (!context.quantization_tables[component.quantization_table_id].has_value()) {
  1121. dbgln_if(JPEG_DEBUG, "Unknown quantization table id: {}!", component.quantization_table_id);
  1122. return Error::from_string_literal("Unknown quantization table id");
  1123. }
  1124. auto const& table = context.quantization_tables[component.quantization_table_id].value();
  1125. for (u32 vfactor_i = 0; vfactor_i < component.sampling_factors.vertical; vfactor_i++) {
  1126. for (u32 hfactor_i = 0; hfactor_i < component.sampling_factors.horizontal; hfactor_i++) {
  1127. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  1128. Macroblock& block = macroblocks[macroblock_index];
  1129. auto* block_component = get_component(block, i);
  1130. for (u32 k = 0; k < 64; k++)
  1131. block_component[k] *= table[k];
  1132. }
  1133. }
  1134. }
  1135. }
  1136. }
  1137. return {};
  1138. }
  1139. static void inverse_dct_8x8(i16* block_component)
  1140. {
  1141. static float const m0 = 2.0f * AK::cos(1.0f / 16.0f * 2.0f * AK::Pi<float>);
  1142. static float const m1 = 2.0f * AK::cos(2.0f / 16.0f * 2.0f * AK::Pi<float>);
  1143. static float const m3 = 2.0f * AK::cos(2.0f / 16.0f * 2.0f * AK::Pi<float>);
  1144. static float const m5 = 2.0f * AK::cos(3.0f / 16.0f * 2.0f * AK::Pi<float>);
  1145. static float const m2 = m0 - m5;
  1146. static float const m4 = m0 + m5;
  1147. static float const s0 = AK::cos(0.0f / 16.0f * AK::Pi<float>) / AK::sqrt(8.0f);
  1148. static float const s1 = AK::cos(1.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1149. static float const s2 = AK::cos(2.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1150. static float const s3 = AK::cos(3.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1151. static float const s4 = AK::cos(4.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1152. static float const s5 = AK::cos(5.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1153. static float const s6 = AK::cos(6.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1154. static float const s7 = AK::cos(7.0f / 16.0f * AK::Pi<float>) / 2.0f;
  1155. for (u32 k = 0; k < 8; ++k) {
  1156. float const g0 = block_component[0 * 8 + k] * s0;
  1157. float const g1 = block_component[4 * 8 + k] * s4;
  1158. float const g2 = block_component[2 * 8 + k] * s2;
  1159. float const g3 = block_component[6 * 8 + k] * s6;
  1160. float const g4 = block_component[5 * 8 + k] * s5;
  1161. float const g5 = block_component[1 * 8 + k] * s1;
  1162. float const g6 = block_component[7 * 8 + k] * s7;
  1163. float const g7 = block_component[3 * 8 + k] * s3;
  1164. float const f0 = g0;
  1165. float const f1 = g1;
  1166. float const f2 = g2;
  1167. float const f3 = g3;
  1168. float const f4 = g4 - g7;
  1169. float const f5 = g5 + g6;
  1170. float const f6 = g5 - g6;
  1171. float const f7 = g4 + g7;
  1172. float const e0 = f0;
  1173. float const e1 = f1;
  1174. float const e2 = f2 - f3;
  1175. float const e3 = f2 + f3;
  1176. float const e4 = f4;
  1177. float const e5 = f5 - f7;
  1178. float const e6 = f6;
  1179. float const e7 = f5 + f7;
  1180. float const e8 = f4 + f6;
  1181. float const d0 = e0;
  1182. float const d1 = e1;
  1183. float const d2 = e2 * m1;
  1184. float const d3 = e3;
  1185. float const d4 = e4 * m2;
  1186. float const d5 = e5 * m3;
  1187. float const d6 = e6 * m4;
  1188. float const d7 = e7;
  1189. float const d8 = e8 * m5;
  1190. float const c0 = d0 + d1;
  1191. float const c1 = d0 - d1;
  1192. float const c2 = d2 - d3;
  1193. float const c3 = d3;
  1194. float const c4 = d4 + d8;
  1195. float const c5 = d5 + d7;
  1196. float const c6 = d6 - d8;
  1197. float const c7 = d7;
  1198. float const c8 = c5 - c6;
  1199. float const b0 = c0 + c3;
  1200. float const b1 = c1 + c2;
  1201. float const b2 = c1 - c2;
  1202. float const b3 = c0 - c3;
  1203. float const b4 = c4 - c8;
  1204. float const b5 = c8;
  1205. float const b6 = c6 - c7;
  1206. float const b7 = c7;
  1207. block_component[0 * 8 + k] = b0 + b7;
  1208. block_component[1 * 8 + k] = b1 + b6;
  1209. block_component[2 * 8 + k] = b2 + b5;
  1210. block_component[3 * 8 + k] = b3 + b4;
  1211. block_component[4 * 8 + k] = b3 - b4;
  1212. block_component[5 * 8 + k] = b2 - b5;
  1213. block_component[6 * 8 + k] = b1 - b6;
  1214. block_component[7 * 8 + k] = b0 - b7;
  1215. }
  1216. for (u32 l = 0; l < 8; ++l) {
  1217. float const g0 = block_component[l * 8 + 0] * s0;
  1218. float const g1 = block_component[l * 8 + 4] * s4;
  1219. float const g2 = block_component[l * 8 + 2] * s2;
  1220. float const g3 = block_component[l * 8 + 6] * s6;
  1221. float const g4 = block_component[l * 8 + 5] * s5;
  1222. float const g5 = block_component[l * 8 + 1] * s1;
  1223. float const g6 = block_component[l * 8 + 7] * s7;
  1224. float const g7 = block_component[l * 8 + 3] * s3;
  1225. float const f0 = g0;
  1226. float const f1 = g1;
  1227. float const f2 = g2;
  1228. float const f3 = g3;
  1229. float const f4 = g4 - g7;
  1230. float const f5 = g5 + g6;
  1231. float const f6 = g5 - g6;
  1232. float const f7 = g4 + g7;
  1233. float const e0 = f0;
  1234. float const e1 = f1;
  1235. float const e2 = f2 - f3;
  1236. float const e3 = f2 + f3;
  1237. float const e4 = f4;
  1238. float const e5 = f5 - f7;
  1239. float const e6 = f6;
  1240. float const e7 = f5 + f7;
  1241. float const e8 = f4 + f6;
  1242. float const d0 = e0;
  1243. float const d1 = e1;
  1244. float const d2 = e2 * m1;
  1245. float const d3 = e3;
  1246. float const d4 = e4 * m2;
  1247. float const d5 = e5 * m3;
  1248. float const d6 = e6 * m4;
  1249. float const d7 = e7;
  1250. float const d8 = e8 * m5;
  1251. float const c0 = d0 + d1;
  1252. float const c1 = d0 - d1;
  1253. float const c2 = d2 - d3;
  1254. float const c3 = d3;
  1255. float const c4 = d4 + d8;
  1256. float const c5 = d5 + d7;
  1257. float const c6 = d6 - d8;
  1258. float const c7 = d7;
  1259. float const c8 = c5 - c6;
  1260. float const b0 = c0 + c3;
  1261. float const b1 = c1 + c2;
  1262. float const b2 = c1 - c2;
  1263. float const b3 = c0 - c3;
  1264. float const b4 = c4 - c8;
  1265. float const b5 = c8;
  1266. float const b6 = c6 - c7;
  1267. float const b7 = c7;
  1268. block_component[l * 8 + 0] = b0 + b7;
  1269. block_component[l * 8 + 1] = b1 + b6;
  1270. block_component[l * 8 + 2] = b2 + b5;
  1271. block_component[l * 8 + 3] = b3 + b4;
  1272. block_component[l * 8 + 4] = b3 - b4;
  1273. block_component[l * 8 + 5] = b2 - b5;
  1274. block_component[l * 8 + 6] = b1 - b6;
  1275. block_component[l * 8 + 7] = b0 - b7;
  1276. }
  1277. }
  1278. static void inverse_dct(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1279. {
  1280. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1281. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1282. for (u32 component_i = 0; component_i < context.components.size(); component_i++) {
  1283. auto& component = context.components[component_i];
  1284. for (u8 vfactor_i = 0; vfactor_i < component.sampling_factors.vertical; vfactor_i++) {
  1285. for (u8 hfactor_i = 0; hfactor_i < component.sampling_factors.horizontal; hfactor_i++) {
  1286. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  1287. Macroblock& block = macroblocks[macroblock_index];
  1288. auto* block_component = get_component(block, component_i);
  1289. inverse_dct_8x8(block_component);
  1290. }
  1291. }
  1292. }
  1293. }
  1294. }
  1295. // F.2.1.5 - Inverse DCT (IDCT)
  1296. auto const level_shift = 1 << (context.frame.precision - 1);
  1297. auto const max_value = (1 << context.frame.precision) - 1;
  1298. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1299. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1300. for (u8 vfactor_i = 0; vfactor_i < context.sampling_factors.vertical; ++vfactor_i) {
  1301. for (u8 hfactor_i = 0; hfactor_i < context.sampling_factors.horizontal; ++hfactor_i) {
  1302. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  1303. for (u8 i = 0; i < 8; ++i) {
  1304. for (u8 j = 0; j < 8; ++j) {
  1305. // FIXME: This just truncate all coefficients, it's an easy way to support (read hack)
  1306. // 12 bits JPEGs without rewriting all color transformations.
  1307. auto const clamp_to_8_bits = [&](u16 color) -> u8 {
  1308. if (context.frame.precision == 8)
  1309. return static_cast<u8>(color);
  1310. return static_cast<u8>(color >> 4);
  1311. };
  1312. macroblocks[mb_index].r[i * 8 + j] = clamp_to_8_bits(clamp(macroblocks[mb_index].r[i * 8 + j] + level_shift, 0, max_value));
  1313. macroblocks[mb_index].g[i * 8 + j] = clamp_to_8_bits(clamp(macroblocks[mb_index].g[i * 8 + j] + level_shift, 0, max_value));
  1314. macroblocks[mb_index].b[i * 8 + j] = clamp_to_8_bits(clamp(macroblocks[mb_index].b[i * 8 + j] + level_shift, 0, max_value));
  1315. macroblocks[mb_index].k[i * 8 + j] = clamp_to_8_bits(clamp(macroblocks[mb_index].k[i * 8 + j] + level_shift, 0, max_value));
  1316. }
  1317. }
  1318. }
  1319. }
  1320. }
  1321. }
  1322. }
  1323. static void undo_subsampling(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1324. {
  1325. // The first component has sampling factors of context.sampling_factors, while the others
  1326. // divide the first component's sampling factors. This is enforced by read_start_of_frame().
  1327. // This function undoes the subsampling by duplicating the values of the smaller components.
  1328. // See https://www.w3.org/Graphics/JPEG/itu-t81.pdf, A.2 Order of source image data encoding.
  1329. //
  1330. // FIXME: Allow more combinations of sampling factors.
  1331. // See https://calendar.perfplanet.com/2015/why-arent-your-images-using-chroma-subsampling/ for
  1332. // subsampling factors visble on the web. In PDF files, YCCK 2111 and 2112 and CMYK 2111 and 2112 are also present.
  1333. for (u32 component_i = 0; component_i < context.components.size(); component_i++) {
  1334. auto& component = context.components[component_i];
  1335. if (component.sampling_factors == context.sampling_factors)
  1336. continue;
  1337. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.sampling_factors.vertical) {
  1338. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.sampling_factors.horizontal) {
  1339. u32 const component_block_index = vcursor * context.mblock_meta.hpadded_count + hcursor;
  1340. Macroblock& component_block = macroblocks[component_block_index];
  1341. auto* block_component_source = get_component(component_block, component_i);
  1342. // Overflows are intentional.
  1343. for (u8 vfactor_i = context.sampling_factors.vertical - 1; vfactor_i < context.sampling_factors.vertical; --vfactor_i) {
  1344. for (u8 hfactor_i = context.sampling_factors.horizontal - 1; hfactor_i < context.sampling_factors.horizontal; --hfactor_i) {
  1345. u32 macroblock_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  1346. Macroblock& block = macroblocks[macroblock_index];
  1347. auto* block_component_destination = get_component(block, component_i);
  1348. for (u8 i = 7; i < 8; --i) {
  1349. for (u8 j = 7; j < 8; --j) {
  1350. u8 const pixel = i * 8 + j;
  1351. // The component is 8x8 subsampled 2x2. Upsample its 2x2 4x4 tiles.
  1352. u32 const component_pxrow = (i / context.sampling_factors.vertical) + 4 * vfactor_i;
  1353. u32 const component_pxcol = (j / context.sampling_factors.horizontal) + 4 * hfactor_i;
  1354. u32 const component_pixel = component_pxrow * 8 + component_pxcol;
  1355. block_component_destination[pixel] = block_component_source[component_pixel];
  1356. }
  1357. }
  1358. }
  1359. }
  1360. }
  1361. }
  1362. }
  1363. }
  1364. static void ycbcr_to_rgb(Vector<Macroblock>& macroblocks)
  1365. {
  1366. // Conversion from YCbCr to RGB isn't specified in the first JPEG specification but in the JFIF extension:
  1367. // See: https://www.itu.int/rec/dologin_pub.asp?lang=f&id=T-REC-T.871-201105-I!!PDF-E&type=items
  1368. // 7 - Conversion to and from RGB
  1369. for (auto& macroblock : macroblocks) {
  1370. auto* y = macroblock.y;
  1371. auto* cb = macroblock.cb;
  1372. auto* cr = macroblock.cr;
  1373. for (u8 i = 0; i < 64; ++i) {
  1374. int r = y[i] + 1.402f * (cr[i] - 128);
  1375. int g = y[i] - 0.3441f * (cb[i] - 128) - 0.7141f * (cr[i] - 128);
  1376. int b = y[i] + 1.772f * (cb[i] - 128);
  1377. y[i] = clamp(r, 0, 255);
  1378. cb[i] = clamp(g, 0, 255);
  1379. cr[i] = clamp(b, 0, 255);
  1380. }
  1381. }
  1382. }
  1383. static void invert_colors_for_adobe_images(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1384. {
  1385. if (!context.color_transform.has_value())
  1386. return;
  1387. // From libjpeg-turbo's libjpeg.txt:
  1388. // https://github.com/libjpeg-turbo/libjpeg-turbo/blob/main/libjpeg.txt
  1389. // CAUTION: it appears that Adobe Photoshop writes inverted data in CMYK JPEG
  1390. // files: 0 represents 100% ink coverage, rather than 0% ink as you'd expect.
  1391. // This is arguably a bug in Photoshop, but if you need to work with Photoshop
  1392. // CMYK files, you will have to deal with it in your application.
  1393. for (auto& macroblock : macroblocks) {
  1394. for (u8 i = 0; i < 64; ++i) {
  1395. macroblock.r[i] = 255 - macroblock.r[i];
  1396. macroblock.g[i] = 255 - macroblock.g[i];
  1397. macroblock.b[i] = 255 - macroblock.b[i];
  1398. macroblock.k[i] = 255 - macroblock.k[i];
  1399. }
  1400. }
  1401. }
  1402. static void ycck_to_cmyk(Vector<Macroblock>& macroblocks)
  1403. {
  1404. // 7 - Conversions between colour encodings
  1405. // YCCK is obtained from CMYK by converting the CMY channels to YCC channel.
  1406. // To convert back into RGB, we only need the 3 first components, which are baseline YCbCr
  1407. ycbcr_to_rgb(macroblocks);
  1408. // RGB to CMY, as mentioned in https://www.smcm.iqfr.csic.es/docs/intel/ipp/ipp_manual/IPPI/ippi_ch15/functn_YCCKToCMYK_JPEG.htm#functn_YCCKToCMYK_JPEG
  1409. for (auto& macroblock : macroblocks) {
  1410. for (u8 i = 0; i < 64; ++i) {
  1411. macroblock.r[i] = 255 - macroblock.r[i];
  1412. macroblock.g[i] = 255 - macroblock.g[i];
  1413. macroblock.b[i] = 255 - macroblock.b[i];
  1414. }
  1415. }
  1416. }
  1417. static ErrorOr<void> handle_color_transform(JPEGLoadingContext const& context, Vector<Macroblock>& macroblocks)
  1418. {
  1419. // Note: This is non-standard but some encoder still add the App14 segment for grayscale images.
  1420. // So let's ignore the color transform value if we only have one component.
  1421. if (context.color_transform.has_value() && context.components.size() != 1) {
  1422. // https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-T.872-201206-I!!PDF-E&type=items
  1423. // 6.5.3 - APP14 marker segment for colour encoding
  1424. switch (*context.color_transform) {
  1425. case ColorTransform::CmykOrRgb:
  1426. if (context.components.size() == 4) {
  1427. // Nothing to do here.
  1428. } else if (context.components.size() == 3) {
  1429. // Note: components.size() == 3 means that we have an RGB image, so no color transformation is needed.
  1430. } else {
  1431. return Error::from_string_literal("Wrong number of components for CMYK or RGB, aborting.");
  1432. }
  1433. break;
  1434. case ColorTransform::YCbCr:
  1435. ycbcr_to_rgb(macroblocks);
  1436. break;
  1437. case ColorTransform::YCCK:
  1438. ycck_to_cmyk(macroblocks);
  1439. break;
  1440. }
  1441. return {};
  1442. }
  1443. // No App14 segment is present, assuming :
  1444. // - 1 components means grayscale
  1445. // - 3 components means YCbCr
  1446. // - 4 components means CMYK (Nothing to do here).
  1447. if (context.components.size() == 3)
  1448. ycbcr_to_rgb(macroblocks);
  1449. if (context.components.size() == 1) {
  1450. // With Cb and Cr being equal to zero, this function assign the Y
  1451. // value (luminosity) to R, G and B. Providing a proper conversion
  1452. // from grayscale to RGB.
  1453. ycbcr_to_rgb(macroblocks);
  1454. }
  1455. return {};
  1456. }
  1457. static ErrorOr<void> compose_bitmap(JPEGLoadingContext& context, Vector<Macroblock> const& macroblocks)
  1458. {
  1459. context.bitmap = TRY(Bitmap::create(BitmapFormat::BGRx8888, { context.frame.width, context.frame.height }));
  1460. for (u32 y = context.frame.height - 1; y < context.frame.height; y--) {
  1461. u32 const block_row = y / 8;
  1462. u32 const pixel_row = y % 8;
  1463. for (u32 x = 0; x < context.frame.width; x++) {
  1464. u32 const block_column = x / 8;
  1465. auto& block = macroblocks[block_row * context.mblock_meta.hpadded_count + block_column];
  1466. u32 const pixel_column = x % 8;
  1467. u32 const pixel_index = pixel_row * 8 + pixel_column;
  1468. Color const color { (u8)block.y[pixel_index], (u8)block.cb[pixel_index], (u8)block.cr[pixel_index] };
  1469. context.bitmap->set_pixel(x, y, color);
  1470. }
  1471. }
  1472. return {};
  1473. }
  1474. static ErrorOr<void> compose_cmyk_bitmap(JPEGLoadingContext& context, Vector<Macroblock>& macroblocks)
  1475. {
  1476. if (context.options.cmyk == JPEGDecoderOptions::CMYK::Normal)
  1477. invert_colors_for_adobe_images(context, macroblocks);
  1478. context.cmyk_bitmap = TRY(Gfx::CMYKBitmap::create_with_size({ context.frame.width, context.frame.height }));
  1479. for (u32 y = context.frame.height - 1; y < context.frame.height; y--) {
  1480. u32 const block_row = y / 8;
  1481. u32 const pixel_row = y % 8;
  1482. for (u32 x = 0; x < context.frame.width; x++) {
  1483. u32 const block_column = x / 8;
  1484. auto& block = macroblocks[block_row * context.mblock_meta.hpadded_count + block_column];
  1485. u32 const pixel_column = x % 8;
  1486. u32 const pixel_index = pixel_row * 8 + pixel_column;
  1487. context.cmyk_bitmap->scanline(y)[x] = { (u8)block.y[pixel_index], (u8)block.cb[pixel_index], (u8)block.cr[pixel_index], (u8)block.k[pixel_index] };
  1488. }
  1489. }
  1490. return {};
  1491. }
  1492. static bool is_app_marker(Marker const marker)
  1493. {
  1494. return marker >= JPEG_APPN0 && marker <= JPEG_APPN15;
  1495. }
  1496. static bool is_miscellaneous_or_table_marker(Marker const marker)
  1497. {
  1498. // B.2.4 - Table-specification and miscellaneous marker segment syntax
  1499. // See also B.6 - Summary: Figure B.17 – Flow of marker segment
  1500. bool const is_misc = marker == JPEG_COM || marker == JPEG_DRI || is_app_marker(marker);
  1501. bool const is_table = marker == JPEG_DQT || marker == JPEG_DAC || marker == JPEG_DHT;
  1502. return is_misc || is_table;
  1503. }
  1504. static ErrorOr<void> handle_miscellaneous_or_table(JPEGStream& stream, JPEGLoadingContext& context, Marker const marker)
  1505. {
  1506. if (is_app_marker(marker)) {
  1507. TRY(read_app_marker(stream, context, marker - JPEG_APPN0));
  1508. return {};
  1509. }
  1510. switch (marker) {
  1511. case JPEG_COM:
  1512. case JPEG_DAC:
  1513. dbgln_if(JPEG_DEBUG, "TODO: implement marker \"{:x}\"", marker);
  1514. if (auto result = skip_segment(stream); result.is_error()) {
  1515. dbgln_if(JPEG_DEBUG, "Error skipping marker: {:x}!", marker);
  1516. return result.release_error();
  1517. }
  1518. break;
  1519. case JPEG_DHT:
  1520. TRY(read_huffman_table(stream, context));
  1521. break;
  1522. case JPEG_DQT:
  1523. TRY(read_quantization_table(stream, context));
  1524. break;
  1525. case JPEG_DRI:
  1526. TRY(read_restart_interval(stream, context));
  1527. break;
  1528. default:
  1529. dbgln("Unexpected marker: {:x}", marker);
  1530. VERIFY_NOT_REACHED();
  1531. }
  1532. return {};
  1533. }
  1534. static ErrorOr<void> parse_header(JPEGStream& stream, JPEGLoadingContext& context)
  1535. {
  1536. auto marker = TRY(read_marker_at_cursor(stream));
  1537. if (marker != JPEG_SOI) {
  1538. dbgln_if(JPEG_DEBUG, "SOI not found: {:x}!", marker);
  1539. return Error::from_string_literal("SOI not found");
  1540. }
  1541. for (;;) {
  1542. marker = TRY(read_marker_at_cursor(stream));
  1543. if (is_miscellaneous_or_table_marker(marker)) {
  1544. TRY(handle_miscellaneous_or_table(stream, context, marker));
  1545. continue;
  1546. }
  1547. // Set frame type if the marker marks a new frame.
  1548. if (is_frame_marker(marker))
  1549. context.frame.type = static_cast<StartOfFrame::FrameType>(marker & 0xF);
  1550. switch (marker) {
  1551. case JPEG_RST0:
  1552. case JPEG_RST1:
  1553. case JPEG_RST2:
  1554. case JPEG_RST3:
  1555. case JPEG_RST4:
  1556. case JPEG_RST5:
  1557. case JPEG_RST6:
  1558. case JPEG_RST7:
  1559. case JPEG_SOI:
  1560. case JPEG_EOI:
  1561. dbgln_if(JPEG_DEBUG, "Unexpected marker {:x}!", marker);
  1562. return Error::from_string_literal("Unexpected marker");
  1563. case JPEG_SOF0:
  1564. case JPEG_SOF1:
  1565. case JPEG_SOF2:
  1566. TRY(read_start_of_frame(stream, context));
  1567. context.state = JPEGLoadingContext::FrameDecoded;
  1568. return {};
  1569. default:
  1570. if (auto result = skip_segment(stream); result.is_error()) {
  1571. dbgln_if(JPEG_DEBUG, "Error skipping marker: {:x}!", marker);
  1572. return result.release_error();
  1573. }
  1574. break;
  1575. }
  1576. }
  1577. VERIFY_NOT_REACHED();
  1578. }
  1579. static ErrorOr<void> decode_header(JPEGLoadingContext& context)
  1580. {
  1581. VERIFY(context.state < JPEGLoadingContext::State::HeaderDecoded);
  1582. TRY(parse_header(context.stream, context));
  1583. if constexpr (JPEG_DEBUG) {
  1584. dbgln("Image width: {}", context.frame.width);
  1585. dbgln("Image height: {}", context.frame.height);
  1586. dbgln("Macroblocks in a row: {}", context.mblock_meta.hpadded_count);
  1587. dbgln("Macroblocks in a column: {}", context.mblock_meta.vpadded_count);
  1588. dbgln("Macroblock meta padded total: {}", context.mblock_meta.padded_total);
  1589. }
  1590. context.state = JPEGLoadingContext::State::HeaderDecoded;
  1591. return {};
  1592. }
  1593. static ErrorOr<Vector<Macroblock>> construct_macroblocks(JPEGLoadingContext& context)
  1594. {
  1595. // B.6 - Summary
  1596. // See: Figure B.16 – Flow of compressed data syntax
  1597. // This function handles the "Multi-scan" loop.
  1598. Vector<Macroblock> macroblocks;
  1599. TRY(macroblocks.try_resize(context.mblock_meta.padded_total));
  1600. Marker marker = TRY(read_marker_at_cursor(context.stream));
  1601. while (true) {
  1602. if (is_miscellaneous_or_table_marker(marker)) {
  1603. TRY(handle_miscellaneous_or_table(context.stream, context, marker));
  1604. } else if (marker == JPEG_SOS) {
  1605. TRY(read_start_of_scan(context.stream, context));
  1606. TRY(decode_huffman_stream(context, macroblocks));
  1607. } else if (marker == JPEG_EOI) {
  1608. return macroblocks;
  1609. } else {
  1610. dbgln_if(JPEG_DEBUG, "Unexpected marker {:x}!", marker);
  1611. return Error::from_string_literal("Unexpected marker");
  1612. }
  1613. marker = TRY(read_marker_at_cursor(context.stream));
  1614. }
  1615. }
  1616. static ErrorOr<void> decode_jpeg(JPEGLoadingContext& context)
  1617. {
  1618. auto macroblocks = TRY(construct_macroblocks(context));
  1619. TRY(dequantize(context, macroblocks));
  1620. inverse_dct(context, macroblocks);
  1621. undo_subsampling(context, macroblocks);
  1622. TRY(handle_color_transform(context, macroblocks));
  1623. if (context.components.size() == 4)
  1624. TRY(compose_cmyk_bitmap(context, macroblocks));
  1625. else
  1626. TRY(compose_bitmap(context, macroblocks));
  1627. return {};
  1628. }
  1629. JPEGImageDecoderPlugin::JPEGImageDecoderPlugin(NonnullOwnPtr<JPEGLoadingContext> context)
  1630. : m_context(move(context))
  1631. {
  1632. }
  1633. JPEGImageDecoderPlugin::~JPEGImageDecoderPlugin() = default;
  1634. IntSize JPEGImageDecoderPlugin::size()
  1635. {
  1636. return { m_context->frame.width, m_context->frame.height };
  1637. }
  1638. bool JPEGImageDecoderPlugin::sniff(ReadonlyBytes data)
  1639. {
  1640. return data.size() > 3
  1641. && data.data()[0] == 0xFF
  1642. && data.data()[1] == 0xD8
  1643. && data.data()[2] == 0xFF;
  1644. }
  1645. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGImageDecoderPlugin::create(ReadonlyBytes data)
  1646. {
  1647. return create_with_options(data, {});
  1648. }
  1649. ErrorOr<NonnullOwnPtr<ImageDecoderPlugin>> JPEGImageDecoderPlugin::create_with_options(ReadonlyBytes data, JPEGDecoderOptions options)
  1650. {
  1651. auto stream = TRY(try_make<FixedMemoryStream>(data));
  1652. auto context = TRY(JPEGLoadingContext::create(move(stream), options));
  1653. auto plugin = TRY(adopt_nonnull_own_or_enomem(new (nothrow) JPEGImageDecoderPlugin(move(context))));
  1654. TRY(decode_header(*plugin->m_context));
  1655. return plugin;
  1656. }
  1657. ErrorOr<ImageFrameDescriptor> JPEGImageDecoderPlugin::frame(size_t index, Optional<IntSize>)
  1658. {
  1659. if (index > 0)
  1660. return Error::from_string_literal("JPEGImageDecoderPlugin: Invalid frame index");
  1661. if (m_context->state == JPEGLoadingContext::State::Error)
  1662. return Error::from_string_literal("JPEGImageDecoderPlugin: Decoding failed");
  1663. if (m_context->state < JPEGLoadingContext::State::BitmapDecoded) {
  1664. if (auto result = decode_jpeg(*m_context); result.is_error()) {
  1665. m_context->state = JPEGLoadingContext::State::Error;
  1666. return result.release_error();
  1667. }
  1668. m_context->state = JPEGLoadingContext::State::BitmapDecoded;
  1669. }
  1670. if (m_context->cmyk_bitmap && !m_context->bitmap)
  1671. return ImageFrameDescriptor { TRY(m_context->cmyk_bitmap->to_low_quality_rgb()), 0 };
  1672. return ImageFrameDescriptor { m_context->bitmap, 0 };
  1673. }
  1674. Optional<Metadata const&> JPEGImageDecoderPlugin::metadata()
  1675. {
  1676. if (m_context->exif_metadata)
  1677. return *m_context->exif_metadata;
  1678. return OptionalNone {};
  1679. }
  1680. ErrorOr<Optional<ReadonlyBytes>> JPEGImageDecoderPlugin::icc_data()
  1681. {
  1682. if (m_context->icc_data.has_value())
  1683. return *m_context->icc_data;
  1684. return OptionalNone {};
  1685. }
  1686. NaturalFrameFormat JPEGImageDecoderPlugin::natural_frame_format() const
  1687. {
  1688. if (m_context->state == JPEGLoadingContext::State::Error)
  1689. return NaturalFrameFormat::RGB;
  1690. VERIFY(m_context->state >= JPEGLoadingContext::State::HeaderDecoded);
  1691. if (m_context->components.size() == 1)
  1692. return NaturalFrameFormat::Grayscale;
  1693. if (m_context->components.size() == 4)
  1694. return NaturalFrameFormat::CMYK;
  1695. return NaturalFrameFormat::RGB;
  1696. }
  1697. ErrorOr<NonnullRefPtr<CMYKBitmap>> JPEGImageDecoderPlugin::cmyk_frame()
  1698. {
  1699. VERIFY(natural_frame_format() == NaturalFrameFormat::CMYK);
  1700. if (m_context->state < JPEGLoadingContext::State::BitmapDecoded) {
  1701. if (auto result = decode_jpeg(*m_context); result.is_error()) {
  1702. m_context->state = JPEGLoadingContext::State::Error;
  1703. return result.release_error();
  1704. }
  1705. m_context->state = JPEGLoadingContext::State::BitmapDecoded;
  1706. }
  1707. return *m_context->cmyk_bitmap;
  1708. }
  1709. }