JPGLoader.cpp 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334
  1. /*
  2. * Copyright (c) 2020, The SerenityOS developers.
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/Bitmap.h>
  27. #include <AK/BufferStream.h>
  28. #include <AK/ByteBuffer.h>
  29. #include <AK/LexicalPath.h>
  30. #include <AK/MappedFile.h>
  31. #include <AK/String.h>
  32. #include <AK/Vector.h>
  33. #include <LibGfx/Bitmap.h>
  34. #include <LibGfx/JPGLoader.h>
  35. #include <math.h>
  36. #define JPG_DBG 0
  37. #define jpg_dbg(x) \
  38. if (JPG_DBG) \
  39. dbg() << x
  40. #define JPG_INVALID 0X0000
  41. #define JPG_APPN0 0XFFE0
  42. #define JPG_APPN1 0XFFE1
  43. #define JPG_APPN2 0XFFE2
  44. #define JPG_APPN3 0XFFE3
  45. #define JPG_APPN4 0XFFE4
  46. #define JPG_APPN5 0XFFE5
  47. #define JPG_APPN6 0XFFE6
  48. #define JPG_APPN7 0XFFE7
  49. #define JPG_APPN8 0XFFE8
  50. #define JPG_APPN9 0XFFE9
  51. #define JPG_APPNA 0XFFEA
  52. #define JPG_APPNB 0XFFEB
  53. #define JPG_APPNC 0XFFEC
  54. #define JPG_APPND 0XFFED
  55. #define JPG_APPNE 0xFFEE
  56. #define JPG_APPNF 0xFFEF
  57. #define JPG_RESERVED1 0xFFF1
  58. #define JPG_RESERVED2 0xFFF2
  59. #define JPG_RESERVED3 0xFFF3
  60. #define JPG_RESERVED4 0xFFF4
  61. #define JPG_RESERVED5 0xFFF5
  62. #define JPG_RESERVED6 0xFFF6
  63. #define JPG_RESERVED7 0xFFF7
  64. #define JPG_RESERVED8 0xFFF8
  65. #define JPG_RESERVED9 0xFFF9
  66. #define JPG_RESERVEDA 0xFFFA
  67. #define JPG_RESERVEDB 0xFFFB
  68. #define JPG_RESERVEDC 0xFFFC
  69. #define JPG_RESERVEDD 0xFFFD
  70. #define JPG_RST0 0xFFD0
  71. #define JPG_RST1 0xFFD1
  72. #define JPG_RST2 0xFFD2
  73. #define JPG_RST3 0xFFD3
  74. #define JPG_RST4 0xFFD4
  75. #define JPG_RST5 0xFFD5
  76. #define JPG_RST6 0xFFD6
  77. #define JPG_RST7 0xFFD7
  78. #define JPG_DHP 0xFFDE
  79. #define JPG_EXP 0xFFDF
  80. #define JPG_DHT 0XFFC4
  81. #define JPG_DQT 0XFFDB
  82. #define JPG_EOI 0xFFD9
  83. #define JPG_RST 0XFFDD
  84. #define JPG_SOF0 0XFFC0
  85. #define JPG_SOF2 0xFFC2
  86. #define JPG_SOI 0XFFD8
  87. #define JPG_SOS 0XFFDA
  88. #define JPG_COM 0xFFFE
  89. namespace Gfx {
  90. constexpr static u8 zigzag_map[64] {
  91. 0, 1, 8, 16, 9, 2, 3, 10,
  92. 17, 24, 32, 25, 18, 11, 4, 5,
  93. 12, 19, 26, 33, 40, 48, 41, 34,
  94. 27, 20, 13, 6, 7, 14, 21, 28,
  95. 35, 42, 49, 56, 57, 50, 43, 36,
  96. 29, 22, 15, 23, 30, 37, 44, 51,
  97. 58, 59, 52, 45, 38, 31, 39, 46,
  98. 53, 60, 61, 54, 47, 55, 62, 63
  99. };
  100. using Marker = u16;
  101. /**
  102. * MCU means group of data units that are coded together. A data unit is an 8x8
  103. * block of component data. In interleaved scans, number of non-interleaved data
  104. * units of a component C is Ch * Cv, where Ch and Cv represent the horizontal &
  105. * vertical subsampling factors of the component, respectively. A MacroBlock is
  106. * an 8x8 block of RGB values before encoding, and 8x8 block of YCbCr values when
  107. * we're done decoding the huffman stream.
  108. */
  109. struct Macroblock {
  110. union {
  111. i32 y[64] = { 0 };
  112. i32 r[64];
  113. };
  114. union {
  115. i32 cb[64] = { 0 };
  116. i32 g[64];
  117. };
  118. union {
  119. i32 cr[64] = { 0 };
  120. i32 b[64];
  121. };
  122. };
  123. struct MacroblockMeta {
  124. u32 total { 0 };
  125. u32 padded_total { 0 };
  126. u32 hcount { 0 };
  127. u32 vcount { 0 };
  128. u32 hpadded_count { 0 };
  129. u32 vpadded_count { 0 };
  130. };
  131. struct ComponentSpec {
  132. i8 id { -1 };
  133. u8 hsample_factor { 1 }; // Horizontal sampling factor.
  134. u8 vsample_factor { 1 }; // Vertical sampling factor.
  135. u8 ac_destination_id { 0 };
  136. u8 dc_destination_id { 0 };
  137. u8 qtable_id { 0 }; // Quantization table id.
  138. };
  139. struct StartOfFrame {
  140. // Of these, only the first 3 are in mainstream use, and refers to SOF0-2.
  141. enum class FrameType {
  142. Baseline_DCT = 0,
  143. Extended_Sequential_DCT = 1,
  144. Progressive_DCT = 2,
  145. Sequential_Lossless = 3,
  146. Differential_Sequential_DCT = 5,
  147. Differential_Progressive_DCT = 6,
  148. Differential_Sequential_Lossless = 7,
  149. Extended_Sequential_DCT_Arithmetic = 9,
  150. Progressive_DCT_Arithmetic = 10,
  151. Sequential_Lossless_Arithmetic = 11,
  152. Differential_Sequential_DCT_Arithmetic = 13,
  153. Differential_Progressive_DCT_Arithmetic = 14,
  154. Differential_Sequential_Lossless_Arithmetic = 15,
  155. };
  156. FrameType type { FrameType::Baseline_DCT };
  157. u8 precision { 0 };
  158. u16 height { 0 };
  159. u16 width { 0 };
  160. };
  161. struct HuffmanTableSpec {
  162. u8 type { 0 };
  163. u8 destination_id { 0 };
  164. u8 code_counts[16] = { 0 };
  165. Vector<u8> symbols;
  166. Vector<u16> codes;
  167. };
  168. struct HuffmanStreamState {
  169. Vector<u8> stream;
  170. u8 bit_offset { 0 };
  171. size_t byte_offset { 0 };
  172. };
  173. struct JPGLoadingContext {
  174. enum State {
  175. NotDecoded = 0,
  176. Error,
  177. FrameDecoded,
  178. BitmapDecoded
  179. };
  180. State state { State::NotDecoded };
  181. const u8* data { nullptr };
  182. size_t data_size { 0 };
  183. u32 luma_table[64] = { 0 };
  184. u32 chroma_table[64] = { 0 };
  185. StartOfFrame frame;
  186. u8 hsample_factor { 0 };
  187. u8 vsample_factor { 0 };
  188. bool has_zero_based_ids { false };
  189. u8 component_count { 0 };
  190. ComponentSpec components[3];
  191. RefPtr<Gfx::Bitmap> bitmap;
  192. u16 dc_reset_interval { 0 };
  193. Vector<HuffmanTableSpec> dc_tables;
  194. Vector<HuffmanTableSpec> ac_tables;
  195. HuffmanStreamState huffman_stream;
  196. i32 previous_dc_values[3] = { 0 };
  197. MacroblockMeta mblock_meta;
  198. };
  199. static void generate_huffman_codes(HuffmanTableSpec& table)
  200. {
  201. unsigned code = 0;
  202. for (auto number_of_codes : table.code_counts) {
  203. for (int i = 0; i < number_of_codes; i++)
  204. table.codes.append(code++);
  205. code <<= 1;
  206. }
  207. }
  208. static Optional<size_t> read_huffman_bits(HuffmanStreamState& hstream, size_t count = 1)
  209. {
  210. if (count > (8 * sizeof(size_t))) {
  211. dbg() << String::format("Can't read %i bits at once!", count);
  212. return {};
  213. }
  214. size_t value = 0;
  215. while (count--) {
  216. if (hstream.byte_offset >= hstream.stream.size()) {
  217. dbg() << String::format("Huffman stream exhausted. This could be an error!");
  218. return {};
  219. }
  220. u8 current_byte = hstream.stream[hstream.byte_offset];
  221. u8 current_bit = 1u & (u32)(current_byte >> (7 - hstream.bit_offset)); // MSB first.
  222. hstream.bit_offset++;
  223. value = (value << 1) | (size_t)current_bit;
  224. if (hstream.bit_offset == 8) {
  225. hstream.byte_offset++;
  226. hstream.bit_offset = 0;
  227. }
  228. }
  229. return value;
  230. }
  231. static Optional<u8> get_next_symbol(HuffmanStreamState& hstream, const HuffmanTableSpec& table)
  232. {
  233. unsigned code = 0;
  234. size_t code_cursor = 0;
  235. for (int i = 0; i < 16; i++) { // Codes can't be longer than 16 bits.
  236. auto result = read_huffman_bits(hstream);
  237. if (!result.has_value())
  238. return {};
  239. code = (code << 1) | (i32)result.release_value();
  240. for (int j = 0; j < table.code_counts[i]; j++) {
  241. if (code == table.codes[code_cursor])
  242. return table.symbols[code_cursor];
  243. code_cursor++;
  244. }
  245. }
  246. dbg() << "If you're seeing this...the jpeg decoder needs to support more kinds of JPEGs!";
  247. return {};
  248. }
  249. /**
  250. * Build the macroblocks possible by reading single (MCU) subsampled pair of CbCr.
  251. * Depending on the sampling factors, we may not see triples of y, cb, cr in that
  252. * order. If sample factors differ from one, we'll read more than one block of y-
  253. * coefficients before we get to read a cb-cr block.
  254. * In the function below, `hcursor` and `vcursor` denote the location of the block
  255. * we're building in the macroblock matrix. `vfactor_i` and `hfactor_i` are cursors
  256. * that iterate over the vertical and horizontal subsampling factors, respectively.
  257. * When we finish one iteration of the innermost loop, we'll have the coefficients
  258. * of one of the components of block at position `mb_index`. When the outermost loop
  259. * finishes first iteration, we'll have all the luminance coefficients for all the
  260. * macroblocks that share the chrominance data. Next two iterations (assuming that
  261. * we are dealing with three components) will fill up the blocks with chroma data.
  262. */
  263. static bool build_macroblocks(JPGLoadingContext& context, Vector<Macroblock>& macroblocks, u8 hcursor, u8 vcursor)
  264. {
  265. for (u32 cindex = 0; cindex < context.component_count; cindex++) {
  266. auto& component = context.components[cindex];
  267. for (u8 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) {
  268. for (u8 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) {
  269. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  270. Macroblock& block = macroblocks[mb_index];
  271. auto& dc_table = context.dc_tables[component.dc_destination_id];
  272. auto& ac_table = context.ac_tables[component.ac_destination_id];
  273. auto symbol_or_error = get_next_symbol(context.huffman_stream, dc_table);
  274. if (!symbol_or_error.has_value())
  275. return false;
  276. // For DC coefficients, symbol encodes the length of the coefficient.
  277. auto dc_length = symbol_or_error.release_value();
  278. if (dc_length > 11) {
  279. dbg() << String::format("DC coefficient too long: %i!", dc_length);
  280. return false;
  281. }
  282. auto coeff_or_error = read_huffman_bits(context.huffman_stream, dc_length);
  283. if (!coeff_or_error.has_value())
  284. return false;
  285. // DC coefficients are encoded as the difference between previous and current DC values.
  286. i32 dc_diff = coeff_or_error.release_value();
  287. // If MSB in diff is 0, the difference is -ve. Otherwise +ve.
  288. if (dc_length != 0 && dc_diff < (1 << (dc_length - 1)))
  289. dc_diff -= (1 << dc_length) - 1;
  290. i32* select_component = component.id == 1 ? block.y : (component.id == 2 ? block.cb : block.cr);
  291. auto& previous_dc = context.previous_dc_values[cindex];
  292. select_component[0] = previous_dc += dc_diff;
  293. // Compute the AC coefficients.
  294. for (int j = 1; j < 64;) {
  295. symbol_or_error = get_next_symbol(context.huffman_stream, ac_table);
  296. if (!symbol_or_error.has_value())
  297. return false;
  298. // AC symbols encode 2 pieces of information, the high 4 bits represent
  299. // number of zeroes to be stuffed before reading the coefficient. Low 4
  300. // bits represent the magnitude of the coefficient.
  301. auto ac_symbol = symbol_or_error.release_value();
  302. if (ac_symbol == 0)
  303. break;
  304. // ac_symbol = 0xF0 means we need to skip 16 zeroes.
  305. u8 run_length = ac_symbol == 0xF0 ? 16 : ac_symbol >> 4;
  306. j += run_length;
  307. if (j >= 64) {
  308. dbg() << String::format("Run-length exceeded boundaries. Cursor: %i, Skipping: %i!", j, run_length);
  309. return false;
  310. }
  311. u8 coeff_length = ac_symbol & 0x0F;
  312. if (coeff_length > 10) {
  313. dbg() << String::format("AC coefficient too long: %i!", coeff_length);
  314. return false;
  315. }
  316. if (coeff_length != 0) {
  317. coeff_or_error = read_huffman_bits(context.huffman_stream, coeff_length);
  318. if (!coeff_or_error.has_value())
  319. return false;
  320. i32 ac_coefficient = coeff_or_error.release_value();
  321. if (ac_coefficient < (1 << (coeff_length - 1)))
  322. ac_coefficient -= (1 << coeff_length) - 1;
  323. select_component[zigzag_map[j++]] = ac_coefficient;
  324. }
  325. }
  326. }
  327. }
  328. }
  329. return true;
  330. }
  331. static Optional<Vector<Macroblock>> decode_huffman_stream(JPGLoadingContext& context)
  332. {
  333. Vector<Macroblock> macroblocks;
  334. macroblocks.resize(context.mblock_meta.padded_total);
  335. jpg_dbg("Image width: " << context.frame.width);
  336. jpg_dbg("Image height: " << context.frame.height);
  337. jpg_dbg("Macroblocks in a row: " << context.mblock_meta.hpadded_count);
  338. jpg_dbg("Macroblocks in a column: " << context.mblock_meta.vpadded_count);
  339. // Compute huffman codes for DC and AC tables.
  340. for (auto& dc_table : context.dc_tables)
  341. generate_huffman_codes(dc_table);
  342. for (auto& ac_table : context.ac_tables)
  343. generate_huffman_codes(ac_table);
  344. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  345. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  346. u32 i = vcursor * context.mblock_meta.hpadded_count + hcursor;
  347. if (context.dc_reset_interval > 0) {
  348. if (i % context.dc_reset_interval == 0) {
  349. context.previous_dc_values[0] = 0;
  350. context.previous_dc_values[1] = 0;
  351. context.previous_dc_values[2] = 0;
  352. // Restart markers are stored in byte boundaries. Advance the huffman stream cursor to
  353. // the 0th bit of the next byte.
  354. if (context.huffman_stream.byte_offset < context.huffman_stream.stream.size()) {
  355. if (context.huffman_stream.bit_offset > 0) {
  356. context.huffman_stream.bit_offset = 0;
  357. context.huffman_stream.byte_offset++;
  358. }
  359. // Skip the restart marker (RSTn).
  360. context.huffman_stream.byte_offset++;
  361. }
  362. }
  363. }
  364. if (!build_macroblocks(context, macroblocks, hcursor, vcursor)) {
  365. dbg() << "Failed to build Macroblock " << i;
  366. dbg() << "Huffman stream byte offset " << context.huffman_stream.byte_offset;
  367. dbg() << "Huffman stream bit offset " << context.huffman_stream.bit_offset;
  368. return {};
  369. }
  370. }
  371. }
  372. return macroblocks;
  373. }
  374. static inline bool bounds_okay(const size_t cursor, const size_t delta, const size_t bound)
  375. {
  376. return (delta + cursor) < bound;
  377. }
  378. static inline bool is_valid_marker(const Marker marker)
  379. {
  380. if (marker >= JPG_APPN0 && marker <= JPG_APPNF) {
  381. if (marker != JPG_APPN0)
  382. dbg() << String::format("%04x not supported yet. The decoder may fail!", marker);
  383. return true;
  384. }
  385. if (marker >= JPG_RESERVED1 && marker <= JPG_RESERVEDD)
  386. return true;
  387. if (marker >= JPG_RST0 && marker <= JPG_RST7)
  388. return true;
  389. switch (marker) {
  390. case JPG_COM:
  391. case JPG_DHP:
  392. case JPG_EXP:
  393. case JPG_DHT:
  394. case JPG_DQT:
  395. case JPG_RST:
  396. case JPG_SOF0:
  397. case JPG_SOI:
  398. case JPG_SOS:
  399. return true;
  400. }
  401. if (marker >= 0xFFC0 && marker <= 0xFFCF) {
  402. if (marker != 0xFFC4 && marker != 0xFFC8 && marker != 0xFFCC) {
  403. dbg() << "Decoding this frame-type (SOF" << (marker & 0xf) << ") is not currently supported. Decoder will fail!";
  404. return false;
  405. }
  406. }
  407. return false;
  408. }
  409. static inline u16 read_be_word(BufferStream& stream)
  410. {
  411. u8 tmp1 = 0, tmp2 = 0;
  412. stream >> tmp1 >> tmp2;
  413. return ((u16)tmp1 << 8) | ((u16)tmp2);
  414. }
  415. static inline Marker read_marker_at_cursor(BufferStream& stream)
  416. {
  417. u16 marker = read_be_word(stream);
  418. if (stream.handle_read_failure())
  419. return JPG_INVALID;
  420. if (is_valid_marker(marker))
  421. return marker;
  422. if (marker != 0xFFFF)
  423. return JPG_INVALID;
  424. u8 next;
  425. do {
  426. stream >> next;
  427. if (stream.handle_read_failure() || next == 0x00)
  428. return JPG_INVALID;
  429. } while (next == 0xFF);
  430. marker = 0xFF00 | (u16)next;
  431. return is_valid_marker(marker) ? marker : JPG_INVALID;
  432. }
  433. static bool read_start_of_scan(BufferStream& stream, JPGLoadingContext& context)
  434. {
  435. if (context.state < JPGLoadingContext::State::FrameDecoded) {
  436. dbg() << stream.offset() << ": SOS found before reading a SOF!";
  437. return false;
  438. }
  439. u16 bytes_to_read = read_be_word(stream);
  440. if (stream.handle_read_failure())
  441. return false;
  442. bytes_to_read -= 2;
  443. if (!bounds_okay(stream.offset(), bytes_to_read, context.data_size))
  444. return false;
  445. u8 component_count;
  446. stream >> component_count;
  447. if (stream.handle_read_failure())
  448. return false;
  449. if (component_count != context.component_count) {
  450. dbg() << stream.offset()
  451. << String::format(": Unsupported number of components: %i!", component_count);
  452. return false;
  453. }
  454. for (int i = 0; i < component_count; i++) {
  455. ComponentSpec* component = nullptr;
  456. u8 component_id;
  457. stream >> component_id;
  458. if (stream.handle_read_failure())
  459. return false;
  460. component_id += context.has_zero_based_ids ? 1 : 0;
  461. if (component_id == context.components[0].id)
  462. component = &context.components[0];
  463. else if (component_id == context.components[1].id)
  464. component = &context.components[1];
  465. else if (component_id == context.components[2].id)
  466. component = &context.components[2];
  467. else {
  468. dbg() << stream.offset() << String::format(": Unsupported component id: %i!", component_id);
  469. return false;
  470. }
  471. u8 table_ids;
  472. stream >> table_ids;
  473. if (stream.handle_read_failure())
  474. return false;
  475. component->dc_destination_id = table_ids >> 4;
  476. component->ac_destination_id = table_ids & 0x0F;
  477. if (context.dc_tables.size() != context.ac_tables.size()) {
  478. dbg() << stream.offset() << ": DC & AC table count mismatch!";
  479. return false;
  480. }
  481. bool dc_table_exists = false;
  482. bool ac_table_exists = false;
  483. for (unsigned t = 0; t < context.dc_tables.size(); t++) {
  484. dc_table_exists = dc_table_exists || (context.dc_tables[t].destination_id == component->dc_destination_id);
  485. ac_table_exists = ac_table_exists || (context.ac_tables[t].destination_id == component->ac_destination_id);
  486. }
  487. if (!dc_table_exists) {
  488. dbg() << stream.offset() << ": Invalid DC huffman table destination id: " << component->dc_destination_id;
  489. return false;
  490. }
  491. if (!ac_table_exists) {
  492. dbg() << stream.offset() << ": Invalid AC huffman table destination id: " << component->ac_destination_id;
  493. return false;
  494. }
  495. }
  496. u8 spectral_selection_start;
  497. stream >> spectral_selection_start;
  498. if (stream.handle_read_failure())
  499. return false;
  500. u8 spectral_selection_end;
  501. stream >> spectral_selection_end;
  502. if (stream.handle_read_failure())
  503. return false;
  504. u8 successive_approximation;
  505. stream >> successive_approximation;
  506. if (stream.handle_read_failure())
  507. return false;
  508. // The three values should be fixed for baseline JPEGs utilizing sequential DCT.
  509. if (spectral_selection_start != 0 || spectral_selection_end != 63 || successive_approximation != 0) {
  510. dbg() << stream.offset() << ": ERROR! Start of Selection: " << spectral_selection_start
  511. << ", End of Selection: " << spectral_selection_end
  512. << ", Successive Approximation: " << successive_approximation << "!";
  513. return false;
  514. }
  515. return true;
  516. }
  517. static bool read_reset_marker(BufferStream& stream, JPGLoadingContext& context)
  518. {
  519. u16 bytes_to_read = read_be_word(stream);
  520. if (stream.handle_read_failure())
  521. return false;
  522. bytes_to_read -= 2;
  523. if (bytes_to_read != 2) {
  524. dbg() << stream.offset() << ": Malformed reset marker found!";
  525. return false;
  526. }
  527. context.dc_reset_interval = read_be_word(stream);
  528. return true;
  529. }
  530. static bool huffman_table_reset_helper(HuffmanTableSpec& src, JPGLoadingContext& context)
  531. {
  532. auto& table = src.type == 0 ? context.dc_tables : context.ac_tables;
  533. if (src.destination_id == 0) {
  534. if (table.is_empty())
  535. table.append(move(src));
  536. else
  537. table[0] = move(src);
  538. return true;
  539. }
  540. if (src.destination_id == 1) {
  541. if (table.size() < 1) {
  542. String table_str = src.type == 0 ? "DC" : "AC";
  543. dbg() << table_str << "[1] showed up before " << table_str << "[0]!";
  544. return false;
  545. }
  546. if (table.size() == 1)
  547. table.append(move(src));
  548. else
  549. table[1] = move(src);
  550. return true;
  551. }
  552. dbg() << "Unsupported huffman table destination id: " << src.destination_id;
  553. return false;
  554. }
  555. static bool read_huffman_table(BufferStream& stream, JPGLoadingContext& context)
  556. {
  557. i32 bytes_to_read = read_be_word(stream);
  558. if (!bounds_okay(stream.offset(), bytes_to_read, context.data_size))
  559. return false;
  560. bytes_to_read -= 2;
  561. while (bytes_to_read > 0) {
  562. HuffmanTableSpec table;
  563. u8 table_info;
  564. stream >> table_info;
  565. if (stream.handle_read_failure())
  566. return false;
  567. u8 table_type = table_info >> 4;
  568. u8 table_destination_id = table_info & 0x0F;
  569. if (table_type > 1) {
  570. dbg() << stream.offset() << String::format(": Unrecognized huffman table: %i!", table_type);
  571. return false;
  572. }
  573. if (table_destination_id > 1) {
  574. dbg() << stream.offset()
  575. << String::format(": Invalid huffman table destination id: %i!", table_destination_id);
  576. return false;
  577. }
  578. table.type = table_type;
  579. table.destination_id = table_destination_id;
  580. u32 total_codes = 0;
  581. // Read code counts. At each index K, the value represents the number of K+1 bit codes in this header.
  582. for (int i = 0; i < 16; i++) {
  583. u8 count;
  584. stream >> count;
  585. if (stream.handle_read_failure())
  586. return false;
  587. total_codes += count;
  588. table.code_counts[i] = count;
  589. }
  590. table.codes.ensure_capacity(total_codes);
  591. // Read symbols. Read X bytes, where X is the sum of the counts of codes read in the previous step.
  592. for (u32 i = 0; i < total_codes; i++) {
  593. u8 symbol = 0;
  594. stream >> symbol;
  595. table.symbols.append(symbol);
  596. }
  597. if (stream.handle_read_failure())
  598. return false;
  599. if (!huffman_table_reset_helper(table, context))
  600. return false;
  601. bytes_to_read -= 1 + 16 + total_codes;
  602. }
  603. if (bytes_to_read != 0) {
  604. dbg() << stream.offset() << ": Extra bytes detected in huffman header!";
  605. return false;
  606. }
  607. return true;
  608. }
  609. static inline bool validate_luma_and_modify_context(const ComponentSpec& luma, JPGLoadingContext& context)
  610. {
  611. if ((luma.hsample_factor == 1 || luma.hsample_factor == 2) && (luma.vsample_factor == 1 || luma.vsample_factor == 2)) {
  612. context.mblock_meta.hpadded_count += luma.hsample_factor == 1 ? 0 : context.mblock_meta.hcount % 2;
  613. context.mblock_meta.vpadded_count += luma.vsample_factor == 1 ? 0 : context.mblock_meta.vcount % 2;
  614. context.mblock_meta.padded_total = context.mblock_meta.hpadded_count * context.mblock_meta.vpadded_count;
  615. // For easy reference to relevant sample factors.
  616. context.hsample_factor = luma.hsample_factor;
  617. context.vsample_factor = luma.vsample_factor;
  618. jpg_dbg(String::format("Horizontal Subsampling Factor: %i", luma.hsample_factor));
  619. jpg_dbg(String::format("Vertical Subsampling Factor: %i", luma.vsample_factor));
  620. return true;
  621. }
  622. return false;
  623. }
  624. static inline void set_macroblock_metadata(JPGLoadingContext& context)
  625. {
  626. context.mblock_meta.hcount = (context.frame.width + 7) / 8;
  627. context.mblock_meta.vcount = (context.frame.height + 7) / 8;
  628. context.mblock_meta.hpadded_count = context.mblock_meta.hcount;
  629. context.mblock_meta.vpadded_count = context.mblock_meta.vcount;
  630. context.mblock_meta.total = context.mblock_meta.hcount * context.mblock_meta.vcount;
  631. }
  632. static bool read_start_of_frame(BufferStream& stream, JPGLoadingContext& context)
  633. {
  634. if (context.state == JPGLoadingContext::FrameDecoded) {
  635. dbg() << stream.offset() << ": SOF repeated!";
  636. return false;
  637. }
  638. i32 bytes_to_read = read_be_word(stream);
  639. if (stream.handle_read_failure())
  640. return false;
  641. bytes_to_read -= 2;
  642. if (!bounds_okay(stream.offset(), bytes_to_read, context.data_size))
  643. return false;
  644. stream >> context.frame.precision;
  645. if (context.frame.precision != 8) {
  646. dbg() << stream.offset() << ": SOF precision != 8!";
  647. return false;
  648. }
  649. context.frame.height = read_be_word(stream);
  650. context.frame.width = read_be_word(stream);
  651. if (!context.frame.width || !context.frame.height) {
  652. dbg() << stream.offset() << ": ERROR! Image height: " << context.frame.height << ", Image width: "
  653. << context.frame.width << "!";
  654. return false;
  655. }
  656. set_macroblock_metadata(context);
  657. stream >> context.component_count;
  658. if (context.component_count != 1 && context.component_count != 3) {
  659. dbg() << stream.offset() << ": Unsupported number of components in SOF: "
  660. << context.component_count << "!";
  661. return false;
  662. }
  663. for (int i = 0; i < context.component_count; i++) {
  664. ComponentSpec& component = context.components[i];
  665. stream >> component.id;
  666. if (i == 0)
  667. context.has_zero_based_ids = component.id == 0;
  668. component.id += context.has_zero_based_ids ? 1 : 0;
  669. u8 subsample_factors = 0;
  670. stream >> subsample_factors;
  671. if (stream.handle_read_failure())
  672. return false;
  673. component.hsample_factor = subsample_factors >> 4;
  674. component.vsample_factor = subsample_factors & 0x0F;
  675. if (component.id == 1) {
  676. // By convention, downsampling is applied only on chroma components. So we should
  677. // hope to see the maximum sampling factor in the luma component.
  678. if (!validate_luma_and_modify_context(component, context)) {
  679. dbg() << stream.offset() << ": Unsupported luma subsampling factors: "
  680. << "horizontal: " << component.hsample_factor << ", vertical: " << component.vsample_factor;
  681. return false;
  682. }
  683. } else {
  684. if (component.hsample_factor != 1 || component.vsample_factor != 1) {
  685. dbg() << stream.offset() << ": Unsupported chroma subsampling factors: "
  686. << "horizontal: " << component.hsample_factor << ", vertical: " << component.vsample_factor;
  687. return false;
  688. }
  689. }
  690. stream >> component.qtable_id;
  691. if (component.qtable_id > 1) {
  692. dbg() << stream.offset() << ": Unsupported quantization table id: "
  693. << component.qtable_id << "!";
  694. return false;
  695. }
  696. }
  697. return true;
  698. }
  699. static bool read_quantization_table(BufferStream& stream, JPGLoadingContext& context)
  700. {
  701. i32 bytes_to_read = read_be_word(stream);
  702. if (stream.handle_read_failure())
  703. return false;
  704. bytes_to_read -= 2;
  705. if (!bounds_okay(stream.offset(), bytes_to_read, context.data_size))
  706. return false;
  707. while (bytes_to_read > 0) {
  708. u8 info_byte;
  709. stream >> info_byte;
  710. if (stream.handle_read_failure())
  711. return false;
  712. u8 element_unit_hint = info_byte >> 4;
  713. if (element_unit_hint > 1) {
  714. dbg() << stream.offset()
  715. << String::format(": Unsupported unit hint in quantization table: %i!", element_unit_hint);
  716. return false;
  717. }
  718. u8 table_id = info_byte & 0x0F;
  719. if (table_id > 1) {
  720. dbg() << stream.offset() << String::format(": Unsupported quantization table id: %i!", table_id);
  721. return false;
  722. }
  723. u32* table = table_id == 0 ? context.luma_table : context.chroma_table;
  724. for (int i = 0; i < 64; i++) {
  725. if (element_unit_hint == 0) {
  726. u8 tmp = 0;
  727. stream >> tmp;
  728. table[zigzag_map[i]] = tmp;
  729. } else
  730. table[zigzag_map[i]] = read_be_word(stream);
  731. }
  732. if (stream.handle_read_failure())
  733. return false;
  734. bytes_to_read -= 1 + (element_unit_hint == 0 ? 64 : 128);
  735. }
  736. if (bytes_to_read != 0) {
  737. dbg() << stream.offset() << ": Invalid length for one or more quantization tables!";
  738. return false;
  739. }
  740. return true;
  741. }
  742. static bool skip_marker_with_length(BufferStream& stream)
  743. {
  744. u16 bytes_to_skip = read_be_word(stream);
  745. bytes_to_skip -= 2;
  746. if (stream.handle_read_failure())
  747. return false;
  748. stream.advance(bytes_to_skip);
  749. return !stream.handle_read_failure();
  750. }
  751. static void dequantize(JPGLoadingContext& context, Vector<Macroblock>& macroblocks)
  752. {
  753. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  754. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  755. for (u8 cindex = 0; cindex < context.component_count; cindex++) {
  756. auto& component = context.components[cindex];
  757. const u32* table = component.qtable_id == 0 ? context.luma_table : context.chroma_table;
  758. for (u32 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) {
  759. for (u32 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) {
  760. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  761. Macroblock& block = macroblocks[mb_index];
  762. int* block_component = cindex == 0 ? block.y : (cindex == 1 ? block.cb : block.cr);
  763. for (u32 k = 0; k < 64; k++)
  764. block_component[k] *= table[k];
  765. }
  766. }
  767. }
  768. }
  769. }
  770. }
  771. static void inverse_dct(const JPGLoadingContext& context, Vector<Macroblock>& macroblocks)
  772. {
  773. static const float m0 = 2.0 * cos(1.0 / 16.0 * 2.0 * M_PI);
  774. static const float m1 = 2.0 * cos(2.0 / 16.0 * 2.0 * M_PI);
  775. static const float m3 = 2.0 * cos(2.0 / 16.0 * 2.0 * M_PI);
  776. static const float m5 = 2.0 * cos(3.0 / 16.0 * 2.0 * M_PI);
  777. static const float m2 = m0 - m5;
  778. static const float m4 = m0 + m5;
  779. static const float s0 = cos(0.0 / 16.0 * M_PI) / sqrt(8);
  780. static const float s1 = cos(1.0 / 16.0 * M_PI) / 2.0;
  781. static const float s2 = cos(2.0 / 16.0 * M_PI) / 2.0;
  782. static const float s3 = cos(3.0 / 16.0 * M_PI) / 2.0;
  783. static const float s4 = cos(4.0 / 16.0 * M_PI) / 2.0;
  784. static const float s5 = cos(5.0 / 16.0 * M_PI) / 2.0;
  785. static const float s6 = cos(6.0 / 16.0 * M_PI) / 2.0;
  786. static const float s7 = cos(7.0 / 16.0 * M_PI) / 2.0;
  787. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  788. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  789. for (u8 cindex = 0; cindex < context.component_count; cindex++) {
  790. auto& component = context.components[cindex];
  791. for (u8 vfactor_i = 0; vfactor_i < component.vsample_factor; vfactor_i++) {
  792. for (u8 hfactor_i = 0; hfactor_i < component.hsample_factor; hfactor_i++) {
  793. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hfactor_i + hcursor);
  794. Macroblock& block = macroblocks[mb_index];
  795. i32* block_component = cindex == 0 ? block.y : (cindex == 1 ? block.cb : block.cr);
  796. for (u32 k = 0; k < 8; ++k) {
  797. const float g0 = block_component[0 * 8 + k] * s0;
  798. const float g1 = block_component[4 * 8 + k] * s4;
  799. const float g2 = block_component[2 * 8 + k] * s2;
  800. const float g3 = block_component[6 * 8 + k] * s6;
  801. const float g4 = block_component[5 * 8 + k] * s5;
  802. const float g5 = block_component[1 * 8 + k] * s1;
  803. const float g6 = block_component[7 * 8 + k] * s7;
  804. const float g7 = block_component[3 * 8 + k] * s3;
  805. const float f0 = g0;
  806. const float f1 = g1;
  807. const float f2 = g2;
  808. const float f3 = g3;
  809. const float f4 = g4 - g7;
  810. const float f5 = g5 + g6;
  811. const float f6 = g5 - g6;
  812. const float f7 = g4 + g7;
  813. const float e0 = f0;
  814. const float e1 = f1;
  815. const float e2 = f2 - f3;
  816. const float e3 = f2 + f3;
  817. const float e4 = f4;
  818. const float e5 = f5 - f7;
  819. const float e6 = f6;
  820. const float e7 = f5 + f7;
  821. const float e8 = f4 + f6;
  822. const float d0 = e0;
  823. const float d1 = e1;
  824. const float d2 = e2 * m1;
  825. const float d3 = e3;
  826. const float d4 = e4 * m2;
  827. const float d5 = e5 * m3;
  828. const float d6 = e6 * m4;
  829. const float d7 = e7;
  830. const float d8 = e8 * m5;
  831. const float c0 = d0 + d1;
  832. const float c1 = d0 - d1;
  833. const float c2 = d2 - d3;
  834. const float c3 = d3;
  835. const float c4 = d4 + d8;
  836. const float c5 = d5 + d7;
  837. const float c6 = d6 - d8;
  838. const float c7 = d7;
  839. const float c8 = c5 - c6;
  840. const float b0 = c0 + c3;
  841. const float b1 = c1 + c2;
  842. const float b2 = c1 - c2;
  843. const float b3 = c0 - c3;
  844. const float b4 = c4 - c8;
  845. const float b5 = c8;
  846. const float b6 = c6 - c7;
  847. const float b7 = c7;
  848. block_component[0 * 8 + k] = b0 + b7;
  849. block_component[1 * 8 + k] = b1 + b6;
  850. block_component[2 * 8 + k] = b2 + b5;
  851. block_component[3 * 8 + k] = b3 + b4;
  852. block_component[4 * 8 + k] = b3 - b4;
  853. block_component[5 * 8 + k] = b2 - b5;
  854. block_component[6 * 8 + k] = b1 - b6;
  855. block_component[7 * 8 + k] = b0 - b7;
  856. }
  857. for (u32 l = 0; l < 8; ++l) {
  858. const float g0 = block_component[l * 8 + 0] * s0;
  859. const float g1 = block_component[l * 8 + 4] * s4;
  860. const float g2 = block_component[l * 8 + 2] * s2;
  861. const float g3 = block_component[l * 8 + 6] * s6;
  862. const float g4 = block_component[l * 8 + 5] * s5;
  863. const float g5 = block_component[l * 8 + 1] * s1;
  864. const float g6 = block_component[l * 8 + 7] * s7;
  865. const float g7 = block_component[l * 8 + 3] * s3;
  866. const float f0 = g0;
  867. const float f1 = g1;
  868. const float f2 = g2;
  869. const float f3 = g3;
  870. const float f4 = g4 - g7;
  871. const float f5 = g5 + g6;
  872. const float f6 = g5 - g6;
  873. const float f7 = g4 + g7;
  874. const float e0 = f0;
  875. const float e1 = f1;
  876. const float e2 = f2 - f3;
  877. const float e3 = f2 + f3;
  878. const float e4 = f4;
  879. const float e5 = f5 - f7;
  880. const float e6 = f6;
  881. const float e7 = f5 + f7;
  882. const float e8 = f4 + f6;
  883. const float d0 = e0;
  884. const float d1 = e1;
  885. const float d2 = e2 * m1;
  886. const float d3 = e3;
  887. const float d4 = e4 * m2;
  888. const float d5 = e5 * m3;
  889. const float d6 = e6 * m4;
  890. const float d7 = e7;
  891. const float d8 = e8 * m5;
  892. const float c0 = d0 + d1;
  893. const float c1 = d0 - d1;
  894. const float c2 = d2 - d3;
  895. const float c3 = d3;
  896. const float c4 = d4 + d8;
  897. const float c5 = d5 + d7;
  898. const float c6 = d6 - d8;
  899. const float c7 = d7;
  900. const float c8 = c5 - c6;
  901. const float b0 = c0 + c3;
  902. const float b1 = c1 + c2;
  903. const float b2 = c1 - c2;
  904. const float b3 = c0 - c3;
  905. const float b4 = c4 - c8;
  906. const float b5 = c8;
  907. const float b6 = c6 - c7;
  908. const float b7 = c7;
  909. block_component[l * 8 + 0] = b0 + b7;
  910. block_component[l * 8 + 1] = b1 + b6;
  911. block_component[l * 8 + 2] = b2 + b5;
  912. block_component[l * 8 + 3] = b3 + b4;
  913. block_component[l * 8 + 4] = b3 - b4;
  914. block_component[l * 8 + 5] = b2 - b5;
  915. block_component[l * 8 + 6] = b1 - b6;
  916. block_component[l * 8 + 7] = b0 - b7;
  917. }
  918. }
  919. }
  920. }
  921. }
  922. }
  923. }
  924. static void ycbcr_to_rgb(const JPGLoadingContext& context, Vector<Macroblock>& macroblocks)
  925. {
  926. for (u32 vcursor = 0; vcursor < context.mblock_meta.vcount; vcursor += context.vsample_factor) {
  927. for (u32 hcursor = 0; hcursor < context.mblock_meta.hcount; hcursor += context.hsample_factor) {
  928. const u32 chroma_block_index = vcursor * context.mblock_meta.hpadded_count + hcursor;
  929. const Macroblock& chroma = macroblocks[chroma_block_index];
  930. // Overflows are intentional.
  931. for (u8 vfactor_i = context.vsample_factor - 1; vfactor_i < context.vsample_factor; --vfactor_i) {
  932. for (u8 hfactor_i = context.hsample_factor - 1; hfactor_i < context.hsample_factor; --hfactor_i) {
  933. u32 mb_index = (vcursor + vfactor_i) * context.mblock_meta.hpadded_count + (hcursor + hfactor_i);
  934. i32* y = macroblocks[mb_index].y;
  935. i32* cb = macroblocks[mb_index].cb;
  936. i32* cr = macroblocks[mb_index].cr;
  937. for (u8 i = 7; i < 8; --i) {
  938. for (u8 j = 7; j < 8; --j) {
  939. const u8 pixel = i * 8 + j;
  940. const u32 chroma_pxrow = (i / context.vsample_factor) + 4 * vfactor_i;
  941. const u32 chroma_pxcol = (j / context.hsample_factor) + 4 * hfactor_i;
  942. const u32 chroma_pixel = chroma_pxrow * 8 + chroma_pxcol;
  943. int r = y[pixel] + 1.402f * chroma.cr[chroma_pixel] + 128;
  944. int g = y[pixel] - 0.344f * chroma.cb[chroma_pixel] - 0.714f * chroma.cr[chroma_pixel] + 128;
  945. int b = y[pixel] + 1.772f * chroma.cb[chroma_pixel] + 128;
  946. y[pixel] = r < 0 ? 0 : (r > 255 ? 255 : r);
  947. cb[pixel] = g < 0 ? 0 : (g > 255 ? 255 : g);
  948. cr[pixel] = b < 0 ? 0 : (b > 255 ? 255 : b);
  949. }
  950. }
  951. }
  952. }
  953. }
  954. }
  955. }
  956. static void compose_bitmap(JPGLoadingContext& context, const Vector<Macroblock>& macroblocks)
  957. {
  958. context.bitmap = Bitmap::create_purgeable(BitmapFormat::RGB32, { context.frame.width, context.frame.height });
  959. for (u32 y = context.frame.height - 1; y < context.frame.height; y--) {
  960. const u32 block_row = y / 8;
  961. const u32 pixel_row = y % 8;
  962. for (u32 x = 0; x < context.frame.width; x++) {
  963. const u32 block_column = x / 8;
  964. auto& block = macroblocks[block_row * context.mblock_meta.hpadded_count + block_column];
  965. const u32 pixel_column = x % 8;
  966. const u32 pixel_index = pixel_row * 8 + pixel_column;
  967. const Color color { (u8)block.y[pixel_index], (u8)block.cb[pixel_index], (u8)block.cr[pixel_index] };
  968. context.bitmap->set_pixel(x, y, color);
  969. }
  970. }
  971. }
  972. static bool parse_header(BufferStream& stream, JPGLoadingContext& context)
  973. {
  974. auto marker = read_marker_at_cursor(stream);
  975. if (stream.handle_read_failure())
  976. return false;
  977. if (marker != JPG_SOI) {
  978. dbg() << stream.offset() << String::format(": SOI not found: %x!", marker);
  979. return false;
  980. }
  981. for (;;) {
  982. marker = read_marker_at_cursor(stream);
  983. // Set frame type if the marker marks a new frame.
  984. if (marker >= 0xFFC0 && marker <= 0xFFCF) {
  985. // Ignore interleaved markers.
  986. if (marker != 0xFFC4 && marker != 0xFFC8 && marker != 0xFFCC) {
  987. context.frame.type = static_cast<StartOfFrame::FrameType>(marker & 0xF);
  988. }
  989. }
  990. switch (marker) {
  991. case JPG_INVALID:
  992. case JPG_RST0:
  993. case JPG_RST1:
  994. case JPG_RST2:
  995. case JPG_RST3:
  996. case JPG_RST4:
  997. case JPG_RST5:
  998. case JPG_RST6:
  999. case JPG_RST7:
  1000. case JPG_SOI:
  1001. case JPG_EOI:
  1002. dbg() << stream.offset() << String::format(": Unexpected marker %x!", marker);
  1003. return false;
  1004. case JPG_SOF0:
  1005. if (!read_start_of_frame(stream, context))
  1006. return false;
  1007. context.state = JPGLoadingContext::FrameDecoded;
  1008. break;
  1009. case JPG_DQT:
  1010. if (!read_quantization_table(stream, context))
  1011. return false;
  1012. break;
  1013. case JPG_RST:
  1014. if (!read_reset_marker(stream, context))
  1015. return false;
  1016. break;
  1017. case JPG_DHT:
  1018. if (!read_huffman_table(stream, context))
  1019. return false;
  1020. break;
  1021. case JPG_SOS:
  1022. return read_start_of_scan(stream, context);
  1023. default:
  1024. if (!skip_marker_with_length(stream)) {
  1025. dbg() << stream.offset() << String::format(": Error skipping marker: %x!", marker);
  1026. return false;
  1027. }
  1028. break;
  1029. }
  1030. }
  1031. ASSERT_NOT_REACHED();
  1032. }
  1033. static bool scan_huffman_stream(BufferStream& stream, JPGLoadingContext& context)
  1034. {
  1035. u8 last_byte;
  1036. u8 current_byte;
  1037. stream >> current_byte;
  1038. if (stream.handle_read_failure())
  1039. return false;
  1040. for (;;) {
  1041. last_byte = current_byte;
  1042. stream >> current_byte;
  1043. if (stream.handle_read_failure()) {
  1044. dbg() << stream.offset() << ": EOI not found!";
  1045. return false;
  1046. }
  1047. if (last_byte == 0xFF) {
  1048. if (current_byte == 0xFF)
  1049. continue;
  1050. if (current_byte == 0x00) {
  1051. stream >> current_byte;
  1052. context.huffman_stream.stream.append(last_byte);
  1053. continue;
  1054. }
  1055. Marker marker = 0xFF00 | current_byte;
  1056. if (marker == JPG_EOI)
  1057. return true;
  1058. if (marker >= JPG_RST0 && marker <= JPG_RST7) {
  1059. context.huffman_stream.stream.append(marker);
  1060. stream >> current_byte;
  1061. continue;
  1062. }
  1063. dbg() << stream.offset() << String::format(": Invalid marker: %x!", marker);
  1064. return false;
  1065. } else {
  1066. context.huffman_stream.stream.append(last_byte);
  1067. }
  1068. }
  1069. ASSERT_NOT_REACHED();
  1070. }
  1071. static bool decode_jpg(JPGLoadingContext& context)
  1072. {
  1073. ByteBuffer buffer = ByteBuffer::wrap(const_cast<u8*>(context.data), context.data_size);
  1074. BufferStream stream(buffer);
  1075. if (!parse_header(stream, context))
  1076. return false;
  1077. if (!scan_huffman_stream(stream, context))
  1078. return false;
  1079. auto result = decode_huffman_stream(context);
  1080. if (!result.has_value()) {
  1081. dbg() << stream.offset() << ": Failed to decode Macroblocks!";
  1082. return false;
  1083. }
  1084. auto macroblocks = result.release_value();
  1085. dbg() << String::format("%i macroblocks decoded successfully :^)", macroblocks.size());
  1086. dequantize(context, macroblocks);
  1087. inverse_dct(context, macroblocks);
  1088. ycbcr_to_rgb(context, macroblocks);
  1089. compose_bitmap(context, macroblocks);
  1090. return true;
  1091. }
  1092. static RefPtr<Gfx::Bitmap> load_jpg_impl(const u8* data, size_t data_size)
  1093. {
  1094. JPGLoadingContext context;
  1095. context.data = data;
  1096. context.data_size = data_size;
  1097. if (!decode_jpg(context))
  1098. return nullptr;
  1099. return context.bitmap;
  1100. }
  1101. RefPtr<Gfx::Bitmap> load_jpg(const StringView& path)
  1102. {
  1103. MappedFile mapped_file(path);
  1104. if (!mapped_file.is_valid()) {
  1105. return nullptr;
  1106. }
  1107. auto bitmap = load_jpg_impl((const u8*)mapped_file.data(), mapped_file.size());
  1108. if (bitmap)
  1109. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded JPG: %s", bitmap->width(), bitmap->height(), LexicalPath::canonicalized_path(path).characters()));
  1110. return bitmap;
  1111. }
  1112. RefPtr<Gfx::Bitmap> load_jpg_from_memory(const u8* data, size_t length)
  1113. {
  1114. auto bitmap = load_jpg_impl(data, length);
  1115. if (bitmap)
  1116. bitmap->set_mmap_name(String::format("Gfx::Bitmap [%dx%d] - Decoded jpg: <memory>", bitmap->width(), bitmap->height()));
  1117. return bitmap;
  1118. }
  1119. JPGImageDecoderPlugin::JPGImageDecoderPlugin(const u8* data, size_t size)
  1120. {
  1121. m_context = make<JPGLoadingContext>();
  1122. m_context->data = data;
  1123. m_context->data_size = size;
  1124. m_context->huffman_stream.stream.ensure_capacity(50 * KiB);
  1125. }
  1126. JPGImageDecoderPlugin::~JPGImageDecoderPlugin()
  1127. {
  1128. }
  1129. IntSize JPGImageDecoderPlugin::size()
  1130. {
  1131. if (m_context->state == JPGLoadingContext::State::Error)
  1132. return {};
  1133. if (m_context->state >= JPGLoadingContext::State::FrameDecoded)
  1134. return { m_context->frame.width, m_context->frame.height };
  1135. return {};
  1136. }
  1137. RefPtr<Gfx::Bitmap> JPGImageDecoderPlugin::bitmap()
  1138. {
  1139. if (m_context->state == JPGLoadingContext::State::Error)
  1140. return nullptr;
  1141. if (m_context->state < JPGLoadingContext::State::BitmapDecoded) {
  1142. if (!decode_jpg(*m_context)) {
  1143. m_context->state = JPGLoadingContext::State::Error;
  1144. return nullptr;
  1145. }
  1146. m_context->state = JPGLoadingContext::State::BitmapDecoded;
  1147. }
  1148. return m_context->bitmap;
  1149. }
  1150. void JPGImageDecoderPlugin::set_volatile()
  1151. {
  1152. if (m_context->bitmap)
  1153. m_context->bitmap->set_volatile();
  1154. }
  1155. bool JPGImageDecoderPlugin::set_nonvolatile()
  1156. {
  1157. if (!m_context->bitmap)
  1158. return false;
  1159. return m_context->bitmap->set_nonvolatile();
  1160. }
  1161. bool JPGImageDecoderPlugin::sniff()
  1162. {
  1163. return m_context->data_size > 3
  1164. && m_context->data[0] == 0xFF
  1165. && m_context->data[1] == 0xD8
  1166. && m_context->data[2] == 0xFF;
  1167. }
  1168. bool JPGImageDecoderPlugin::is_animated()
  1169. {
  1170. return false;
  1171. }
  1172. size_t JPGImageDecoderPlugin::loop_count()
  1173. {
  1174. return 0;
  1175. }
  1176. size_t JPGImageDecoderPlugin::frame_count()
  1177. {
  1178. return 1;
  1179. }
  1180. ImageFrameDescriptor JPGImageDecoderPlugin::frame(size_t i)
  1181. {
  1182. if (i > 0) {
  1183. return { bitmap(), 0 };
  1184. }
  1185. return {};
  1186. }
  1187. }