blob: acc61f077e9cf2ffbe30f8f620e7b50266f82f5d [file] [log] [blame]
Austin Schuh3333ec72022-12-29 16:21:06 -08001/* Copyright (C) 2013-2016, The Regents of The University of Michigan.
2All rights reserved.
3This software was developed in the APRIL Robotics Lab under the
4direction of Edwin Olson, ebolson@umich.edu. This software may be
5available under alternative licensing terms; contact the address above.
6Redistribution and use in source and binary forms, with or without
7modification, are permitted provided that the following conditions are met:
81. Redistributions of source code must retain the above copyright notice, this
9 list of conditions and the following disclaimer.
102. Redistributions in binary form must reproduce the above copyright notice,
11 this list of conditions and the following disclaimer in the documentation
12 and/or other materials provided with the distribution.
13THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
14ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
17ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
19LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
20ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
22SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23The views and conclusions contained in the software and documentation are those
24of the authors and should not be interpreted as representing official policies,
25either expressed or implied, of the Regents of The University of Michigan.
26*/
27
28#include <stdio.h>
29#include <stdlib.h>
30#include <assert.h>
31#include <stdint.h>
32#include <string.h>
33
34#include "pjpeg.h"
35
36#include "image_u8.h"
37#include "image_u8x3.h"
38#include "debug_print.h"
39
40// https://www.w3.org/Graphics/JPEG/itu-t81.pdf
41
42void pjpeg_idct_2D_double(int32_t in[64], uint8_t *out, uint32_t outstride);
43void pjpeg_idct_2D_u32(int32_t in[64], uint8_t *out, uint32_t outstride);
44void pjpeg_idct_2D_nanojpeg(int32_t in[64], uint8_t *out, uint32_t outstride);
45
46struct pjpeg_huffman_code
47{
48 uint8_t nbits; // how many bits should we actually consume?
49 uint8_t code; // what is the symbol that was encoded? (not actually a DCT coefficient; see encoding)
50};
51
52struct pjpeg_decode_state
53{
54 int error;
55
56 uint32_t width, height;
57 uint8_t *in;
58 uint32_t inlen;
59
60 uint32_t flags;
61
62 // to decode, we load the next 16 bits of input (generally more
63 // than we need). We then look up in our code book how many bits
64 // we have actually consumed. For example, if there was a code
65 // whose bit sequence was "0", the first 32768 entries would all
66 // be copies of {.bits=1, .value=XX}; no matter what the following
67 // 15 bits are, we would get the correct decode.
68 //
69 // Can be up to 8 tables; computed as (ACDC * 2 + htidx)
70 struct pjpeg_huffman_code huff_codes[4][65536];
71 int huff_codes_present[4];
72
73 uint8_t qtab[4][64];
74
75 int ncomponents;
76 pjpeg_component_t *components;
77
78 int reset_interval;
79 int reset_count;
80 int reset_next; // What reset marker do we expect next? (add 0xd0)
81
82 int debug;
83};
84
85// from K.3.3.1 (page 158)
86static uint8_t mjpeg_dht[] = { // header
87 0xFF,0xC4,0x01,0xA2,
88
89 /////////////////////////////////////////////////////////////
90 // luminance dc coefficients.
91 // DC table 0
92 0x00,
93 // code lengths
94 0x00,0x01,0x05,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
95 // values
96 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,
97
98 /////////////////////////////////////////////////////////////
99 // chrominance DC coefficents
100 // DC table 1
101 0x01,
102 // code lengths
103 0x00,0x03,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,
104 // values
105 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,
106
107 /////////////////////////////////////////////////////////////
108 // luminance AC coefficients
109 // AC table 0
110 0x10,
111 // code lengths
112 0x00,0x02,0x01,0x03,0x03,0x02,0x04,0x03,0x05,0x05,0x04,0x04,0x00,0x00,0x01,0x7D,
113 // codes
114 0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,
115 0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xA1,0x08,0x23,0x42,0xB1,0xC1,0x15,0x52,0xD1,0xF0,0x24,
116 0x33,0x62,0x72,0x82,0x09,0x0A,0x16,0x17,0x18,0x19,0x1A,0x25,0x26,0x27,0x28,0x29,0x2A,0x34,
117 0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,
118 0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,
119 0x79,0x7A,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,
120 0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,
121 0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,
122 0xDA,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,
123 0xF8,0xF9,0xFA,
124
125 /////////////////////////////////////////////////////////////
126 // chrominance DC coefficients
127 // DC table 1
128 0x11,
129 // code lengths
130 0x00,0x02,0x01,0x02,0x04,0x04,0x03,0x04,0x07,0x05,0x04,0x04,0x00,0x01,0x02,0x77,
131 // values
132 0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,
133 0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xA1,0xB1,0xC1,0x09,0x23,0x33,0x52,0xF0,0x15,0x62,
134 0x72,0xD1,0x0A,0x16,0x24,0x34,0xE1,0x25,0xF1,0x17,0x18,0x19,0x1A,0x26,0x27,0x28,0x29,0x2A,
135 0x35,0x36,0x37,0x38,0x39,0x3A,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x53,0x54,0x55,0x56,
136 0x57,0x58,0x59,0x5A,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x73,0x74,0x75,0x76,0x77,0x78,
137 0x79,0x7A,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x92,0x93,0x94,0x95,0x96,0x97,0x98,
138 0x99,0x9A,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,
139 0xB9,0xBA,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,
140 0xD9,0xDA,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,
141 0xF9,0xFA
142};
143
144static inline uint8_t max_u8(uint8_t a, uint8_t b)
145{
146 return a > b ? a : b;
147}
148
149// order of coefficients in each DC block
150static const char ZZ[64] = { 0, 1, 8, 16, 9, 2, 3, 10,
151 17, 24, 32, 25, 18, 11, 4, 5,
152 12, 19, 26, 33, 40, 48, 41, 34,
153 27, 20, 13, 6, 7, 14, 21, 28,
154 35, 42, 49, 56, 57, 50, 43, 36,
155 29, 22, 15, 23, 30, 37, 44, 51,
156 58, 59, 52, 45, 38, 31, 39, 46,
157 53, 60, 61, 54, 47, 55, 62, 63 };
158
159
160
161struct bit_decoder
162{
163 uint8_t *in;
164 uint32_t inpos;
165 uint32_t inlen;
166
167 uint32_t bits; // the low order bits contain the next nbits_avail bits.
168
169 int nbits_avail; // how many bits in 'bits' (left aligned) are valid?
170
171 int error;
172};
173
174// ensure that at least 'nbits' of data is available in the bit decoder.
175static inline void bd_ensure(struct bit_decoder *bd, int nbits)
176{
177 while (bd->nbits_avail < nbits) {
178
179 if (bd->inpos >= bd->inlen) {
180 printf("hallucinating 1s!\n");
181 // we hit end of stream hallucinate an infinite stream of 1s
182 bd->bits = (bd->bits << 8) | 0xff;
183 bd->nbits_avail += 8;
184 continue;
185 }
186
187 uint8_t nextbyte = bd->in[bd->inpos];
188 bd->inpos++;
189
190 if (nextbyte == 0xff && bd->inpos < bd->inlen && bd->in[bd->inpos] == 0x00) {
191 // a stuffed byte
192 nextbyte = 0xff;
193 bd->inpos++;
194 }
195
196 // it's an ordinary byte
197 bd->bits = (bd->bits << 8) | nextbyte;
198 bd->nbits_avail += 8;
199 }
200}
201
202static inline uint32_t bd_peek_bits(struct bit_decoder *bd, int nbits)
203{
204 bd_ensure(bd, nbits);
205
206 return (bd->bits >> (bd->nbits_avail - nbits)) & ((1 << nbits) - 1);
207}
208
209static inline uint32_t bd_consume_bits(struct bit_decoder *bd, int nbits)
210{
211 assert(nbits < 32);
212
213 bd_ensure(bd, nbits);
214
215 uint32_t v = (bd->bits >> (bd->nbits_avail - nbits)) & ((1 << nbits) - 1);
216
217 bd->nbits_avail -= nbits;
218
219 return v;
220}
221
222// discard without regard for byte stuffing!
223static inline void bd_discard_bytes(struct bit_decoder *bd, int nbytes)
224{
225 assert(bd->nbits_avail == 0);
226 bd->inpos += nbytes;
227}
228
229static inline int bd_has_more(struct bit_decoder *bd)
230{
231 return bd->nbits_avail > 0 || bd->inpos < bd->inlen;
232}
233
234// throw away up to 7 bits of data so that the next data returned
235// began on a byte boundary.
236static inline void bd_discard_to_byte_boundary(struct bit_decoder *bd)
237{
238 bd->nbits_avail -= (bd->nbits_avail & 7);
239}
240
241static inline uint32_t bd_get_offset(struct bit_decoder *bd)
242{
243 return bd->inpos - bd->nbits_avail / 8;
244}
245
246static int pjpeg_decode_buffer(struct pjpeg_decode_state *pjd)
247{
248 // XXX TODO Include sanity check that this is actually a JPG
249
250 struct bit_decoder bd;
251 memset(&bd, 0, sizeof(struct bit_decoder));
252 bd.in = pjd->in;
253 bd.inpos = 0;
254 bd.inlen = pjd->inlen;
255
256 int marker_sync_skipped = 0;
257 int marker_sync_skipped_from_offset = 0;
258
259 while (bd_has_more(&bd)) {
260
261 uint32_t marker_offset = bd_get_offset(&bd);
262
263 // Look for the 0xff that signifies the beginning of a marker
264 bd_discard_to_byte_boundary(&bd);
265
266 while (bd_consume_bits(&bd, 8) != 0xff) {
267 if (marker_sync_skipped == 0)
268 marker_sync_skipped_from_offset = marker_offset;
269 marker_sync_skipped++;
270 continue;
271 }
272
273 if (marker_sync_skipped) {
274 printf("%08x: skipped %04x bytes\n", marker_sync_skipped_from_offset, marker_sync_skipped);
275 marker_sync_skipped = 0;
276 }
277
278 uint8_t marker = bd_consume_bits(&bd, 8);
279
280// printf("marker %08x : %02x\n", marker_offset, marker);
281
282 switch (marker) {
283
284 case 0xd8: // start of image. Great, continue.
285 continue;
286
287 // below are the markers that A) we don't care about
288 // that B) encode length as two bytes.
289 //
290 // Note: Other unknown fields should not be added since
291 // we should be able to skip over them by looking for
292 // the next marker byte.
293 case 0xe0: // JFIF header.
294 case 0xe1: // EXIF header (Yuck: Payload may contain 0xff 0xff!)
295 case 0xe2: // ICC Profile. (Yuck: payload may contain 0xff 0xff!)
296 case 0xe6: // some other common header
297 case 0xfe: // Comment
298 {
299 uint16_t length = bd_consume_bits(&bd, 16);
300 bd_discard_bytes(&bd, length - 2);
301 continue;
302 }
303
304 case 0xdb: { // DQT Define Quantization Table
305 uint16_t length = bd_consume_bits(&bd, 16);
306
307 if (((length-2) % 65) != 0)
308 return PJPEG_ERR_DQT;
309
310 // can contain multiple DQTs
311 for (int offset = 0; offset < length - 2; offset += 65) {
312
313 // pq: quant table element precision. 0=8bit, 1=16bit.
314 // tq: quant table destination id.
315 uint8_t pqtq = bd_consume_bits(&bd, 8);
316
317 if ((pqtq & 0xf0) != 0 || (pqtq & 0x0f) >= 4)
318 return PJPEG_ERR_DQT;
319
320 uint8_t id = pqtq & 3;
321
322 for (int i = 0; i < 64; i++)
323 pjd->qtab[id][i] = bd_consume_bits(&bd, 8);
324 }
325
326 break;
327 }
328
329 case 0xc0: { // SOF, non-differential, huffman, baseline
330 uint16_t length = bd_consume_bits(&bd, 16);
331 (void) length;
332
333 uint8_t p = bd_consume_bits(&bd, 8); // precision
334 if (p != 8)
335 return PJPEG_ERR_SOF;
336
337 pjd->height = bd_consume_bits(&bd, 16);
338 pjd->width = bd_consume_bits(&bd, 16);
339
340// printf("%d x %d\n", pjd->height, pjd->width);
341
342 int nf = bd_consume_bits(&bd, 8); // # image components
343
344 if (nf < 1 || nf > 3)
345 return PJPEG_ERR_SOF;
346
347 pjd->ncomponents = nf;
348 pjd->components = calloc(nf, sizeof(struct pjpeg_component));
349
350 for (int i = 0; i < nf; i++) {
351 // comp. identifier
352 pjd->components[i].id = bd_consume_bits(&bd, 8);
353
354 // horiz/vert sampling
355 pjd->components[i].hv = bd_consume_bits(&bd, 8);
356 pjd->components[i].scaley = pjd->components[i].hv & 0x0f;
357 pjd->components[i].scalex = pjd->components[i].hv >> 4;
358
359 // which quant table?
360 pjd->components[i].tq = bd_consume_bits(&bd, 8);
361 }
362 break;
363 }
364
365 case 0xc1: // SOF, non-differential, huffman, extended DCT
366 case 0xc2: // SOF, non-differential, huffman, progressive DCT
367 case 0xc3: // SOF, non-differential, huffman, lossless
368 case 0xc5: // SOF, differential, huffman, baseline DCT
369 case 0xc6: // SOF, differential, huffman, progressive
370 case 0xc7: // SOF, differential, huffman, lossless
371 case 0xc8: // reserved
372 case 0xc9: // SOF, non-differential, arithmetic, extended
373 case 0xca: // SOF, non-differential, arithmetic, progressive
374 case 0xcb: // SOF, non-differential, arithmetic, lossless
375 case 0xcd: // SOF, differential, arithmetic, sequential
376 case 0xce: // SOF, differential, arithmetic, progressive
377 case 0xcf: // SOF, differential, arithmetic, lossless
378 {
379 printf("pjepg.c: unsupported JPEG type %02x\n", marker);
380 return PJEPG_ERR_UNSUPPORTED;
381 }
382
383 case 0xc4: { // DHT Define Huffman Tables
384 // [ED: the encoding of these tables is really quite
385 // clever!]
386 uint16_t length = bd_consume_bits(&bd, 16);
387 length = length - 2;
388
389 while (length > 0) {
390 uint8_t TcTh = bd_consume_bits(&bd, 8);
391 length--;
392 uint8_t Tc = (TcTh >> 4);
393 int Th = TcTh & 0x0f; // which index are we using?
394
395 if (Tc >= 2 || Th >= 2)
396 // Tc must be either AC=1 or DC=0.
397 // Th must be less than 2
398 return PJPEG_ERR_DHT;
399
400 int htidx = Tc*2 + Th;
401
402 uint8_t L[17]; // how many symbols of each bit length?
403 L[0] = 0; // no 0 bit codes :)
404 for (int nbits = 1; nbits <= 16; nbits++) {
405 L[nbits] = bd_consume_bits(&bd, 8);
406 length -= L[nbits];
407 }
408 length -= 16;
409
410 uint32_t code_pos = 0;
411
412 for (int nbits = 1; nbits <= 16; nbits++) {
413 int nvalues = L[nbits];
414
415 // how many entries will we fill?
416 // (a 1 bit code will fill 32768, a 2 bit code 16384, ...)
417 uint32_t ncodes = (1 << (16 - nbits));
418
419 // consume the values...
420 for (int vi = 0; vi < nvalues; vi++) {
421 uint8_t code = bd_consume_bits(&bd, 8);
422
423 if (code_pos + ncodes > 0xffff)
424 return PJPEG_ERR_DHT;
425
426 for (int ci = 0; ci < ncodes; ci++) {
427 pjd->huff_codes[htidx][code_pos].nbits = nbits;
428 pjd->huff_codes[htidx][code_pos].code = code;
429 code_pos++;
430 }
431 }
432 }
433 pjd->huff_codes_present[htidx] = 1;
434 }
435 break;
436 }
437
438 // a sequentially-encoded JPG has one SOS segment. A
439 // progressive JPG will have multiple SOS segments.
440 case 0xda: { // Start Of Scan (SOS)
441
442 // Note that this marker frame (and its encoded
443 // length) does NOT include the bitstream that
444 // follows.
445
446 uint16_t length = bd_consume_bits(&bd, 16);
447 (void) length;
448
449 // number of components in this scan
450 uint8_t ns = bd_consume_bits(&bd, 8);
451
452 // for each component, what is the index into our pjd->components[] array?
453 uint8_t *comp_idx = calloc(ns, sizeof(uint8_t));
454
455 for (int i = 0; i < ns; i++) {
456 // component name
457 uint8_t cs = bd_consume_bits(&bd, 8);
458
459 int found = 0;
460 for (int j = 0; j < pjd->ncomponents; j++) {
461
462 if (cs == pjd->components[j].id) {
463 // which huff tables will we use for
464 // DC (high 4 bits) and AC (low 4 bits)
465 pjd->components[j].tda = bd_consume_bits(&bd, 8);
466 comp_idx[i] = j;
467 found = 1;
468 break;
469 }
470 }
471
472 if (!found)
473 return PJPEG_ERR_SOS;
474 }
475
476 // start of spectral selection. baseline == 0
477 uint8_t ss = bd_consume_bits(&bd, 8);
478
479 // end of spectral selection. baseline == 0x3f
480 uint8_t se = bd_consume_bits(&bd, 8);
481
482 // successive approximation bits. baseline == 0
483 uint8_t Ahl = bd_consume_bits(&bd, 8);
484
485 if (ss != 0 || se != 0x3f || Ahl != 0x00)
486 return PJPEG_ERR_SOS;
487
488 // compute the dimensions of each MCU in pixels
489 int maxmcux = 0, maxmcuy = 0;
490 for (int i = 0; i < ns; i++) {
491 struct pjpeg_component *comp = &pjd->components[comp_idx[i]];
492
493 maxmcux = max_u8(maxmcux, comp->scalex * 8);
494 maxmcuy = max_u8(maxmcuy, comp->scaley * 8);
495 }
496
497 // how many MCU blocks are required to encode the whole image?
498 int mcus_x = (pjd->width + maxmcux - 1) / maxmcux;
499 int mcus_y = (pjd->height + maxmcuy - 1) / maxmcuy;
500
501 if (0)
502 printf("Image has %d x %d MCU blocks, each %d x %d pixels\n",
503 mcus_x, mcus_y, maxmcux, maxmcuy);
504
505 // allocate output storage
506 for (int i = 0; i < ns; i++) {
507 struct pjpeg_component *comp = &pjd->components[comp_idx[i]];
508 comp->width = mcus_x * comp->scalex * 8;
509 comp->height = mcus_y * comp->scaley * 8;
510 comp->stride = comp->width;
511
512 int alignment = 32;
513 if ((comp->stride % alignment) != 0)
514 comp->stride += alignment - (comp->stride % alignment);
515
516 comp->data = calloc(comp->height * comp->stride, 1);
517 }
518
519
520 // each component has its own DC prediction
521 int32_t *dcpred = calloc(ns, sizeof(int32_t));
522
523 pjd->reset_count = 0;
524
525 for (int mcu_y = 0; mcu_y < mcus_y; mcu_y++) {
526 for (int mcu_x = 0; mcu_x < mcus_x; mcu_x++) {
527
528 // the next two bytes in the input stream
529 // should be 0xff 0xdN, where N is the next
530 // reset counter.
531 //
532 // Our bit decoder may have already shifted
533 // these into the buffer. Consequently, we
534 // want to use our bit decoding functions to
535 // check for the marker. But we must first
536 // discard any fractional bits left.
537 if (pjd->reset_interval > 0 && pjd->reset_count == pjd->reset_interval) {
538
539 // RST markers are byte-aligned, so force
540 // the bit-decoder to the next byte
541 // boundary.
542 bd_discard_to_byte_boundary(&bd);
543
544 while (1) {
545 int32_t value = bd_consume_bits(&bd, 8);
546 if (bd.inpos > bd.inlen)
547 return PJPEG_ERR_EOF;
548 if (value == 0xff)
549 break;
550 printf("RST SYNC\n");
551 }
552
553 int32_t marker_32 = bd_consume_bits(&bd, 8);
554
555// printf("%04x: RESET? %02x\n", *bd.inpos, marker_32);
556 if (marker_32 != (0xd0 + pjd->reset_next))
557 return PJPEG_ERR_RESET;
558
559 pjd->reset_count = 0;
560 pjd->reset_next = (pjd->reset_next + 1) & 0x7;
561
562 memset(dcpred, 0, sizeof(*dcpred));
563 }
564
565 for (int nsidx = 0; nsidx < ns; nsidx++) {
566
567 struct pjpeg_component *comp = &pjd->components[comp_idx[nsidx]];
568
569 int32_t block[64];
570
571 int qtabidx = comp->tq; // which quant table?
572
573 for (int sby = 0; sby < comp->scaley; sby++) {
574 for (int sbx = 0; sbx < comp->scalex; sbx++) {
575 // decode block for component nsidx
576 memset(block, 0, sizeof(block));
577
578 int dc_huff_table_idx = comp->tda >> 4;
579 int ac_huff_table_idx = 2 + (comp->tda & 0x0f);
580
581 if (!pjd->huff_codes_present[dc_huff_table_idx] ||
582 !pjd->huff_codes_present[ac_huff_table_idx])
583 return PJPEG_ERR_MISSING_DHT; // probably an MJPEG.
584
585
586 if (1) {
587 // do DC coefficient
588 uint32_t next16 = bd_peek_bits(&bd, 16);
589 struct pjpeg_huffman_code *huff_code = &pjd->huff_codes[dc_huff_table_idx][next16];
590 bd_consume_bits(&bd, huff_code->nbits);
591
592 int ssss = huff_code->code & 0x0f; // ssss == number of additional bits to read
593 int32_t value = bd_consume_bits(&bd, ssss);
594
595 // if high bit is clear, it's negative
596 if ((value & (1 << (ssss-1))) == 0)
597 value += ((-1) << ssss) + 1;
598
599 dcpred[nsidx] += value;
600 block[0] = dcpred[nsidx] * pjd->qtab[qtabidx][0];
601 }
602
603 if (1) {
604 // do AC coefficients
605 for (int coeff = 1; coeff < 64; coeff++) {
606
607 uint32_t next16 = bd_peek_bits(&bd, 16);
608
609 struct pjpeg_huffman_code *huff_code = &pjd->huff_codes[ac_huff_table_idx][next16];
610 bd_consume_bits(&bd, huff_code->nbits);
611
612 if (huff_code->code == 0) {
613 break; // EOB
614 }
615
616 int rrrr = huff_code->code >> 4; // run length of zeros
617 int ssss = huff_code->code & 0x0f;
618
619 int32_t value = bd_consume_bits(&bd, ssss);
620
621 // if high bit is clear, it's negative
622 if ((value & (1 << (ssss-1))) == 0)
623 value += ((-1) << ssss) + 1;
624
625 coeff += rrrr;
626
627 block[(int) ZZ[coeff]] = value * pjd->qtab[qtabidx][coeff];
628 }
629 }
630
631 // do IDCT
632
633 // output block's upper-left
634 // coordinate (in pixels) is
635 // (comp_x, comp_y).
636 uint32_t comp_x = (mcu_x * comp->scalex + sbx) * 8;
637 uint32_t comp_y = (mcu_y * comp->scaley + sby) * 8;
638 uint32_t dataidx = comp_y * comp->stride + comp_x;
639
640// pjpeg_idct_2D_u32(block, &comp->data[dataidx], comp->stride);
641 pjpeg_idct_2D_nanojpeg(block, &comp->data[dataidx], comp->stride);
642 }
643 }
644 }
645
646 pjd->reset_count++;
647// printf("%04x: reset count %d / %d\n", pjd->inpos, pjd->reset_count, pjd->reset_interval);
648
649 }
650 }
651
652 free(dcpred);
653 free(comp_idx);
654
655 break;
656 }
657
658 case 0xd9: { // EOI End of Image
659 goto got_end_of_image;
660 }
661
662 case 0xdd: { // Define Restart Interval
663 uint16_t length = bd_consume_bits(&bd, 16);
664 if (length != 4)
665 return PJPEG_ERR_DRI;
666
667 // reset interval measured in the number of MCUs
668 pjd->reset_interval = bd_consume_bits(&bd, 16);
669
670 break;
671 }
672
673 default: {
674 printf("pjepg: Unknown marker %02x at offset %04x\n", marker, marker_offset);
675
676 // try to skip it.
677 uint16_t length = bd_consume_bits(&bd, 16);
678 bd_discard_bytes(&bd, length - 2);
679 continue;
680 }
681 } // switch (marker)
682 } // while inpos < inlen
683
684 got_end_of_image:
685
686 return PJPEG_OKAY;
687}
688
689void pjpeg_destroy(pjpeg_t *pj)
690{
691 if (!pj)
692 return;
693
694 for (int i = 0; i < pj->ncomponents; i++)
695 free(pj->components[i].data);
696 free(pj->components);
697
698 free(pj);
699}
700
701
702// just grab the first component.
703image_u8_t *pjpeg_to_u8_baseline(pjpeg_t *pj)
704{
705 assert(pj->ncomponents > 0);
706
707 pjpeg_component_t *comp = &pj->components[0];
708
709 assert(comp->width >= pj->width && comp->height >= pj->height);
710
711 image_u8_t *im = image_u8_create(pj->width, pj->height);
712 for (int y = 0; y < im->height; y++)
713 memcpy(&im->buf[y*im->stride], &comp->data[y*comp->stride], pj->width);
714
715 return im;
716}
717
718static inline uint8_t clampd(double v)
719{
720 if (v < 0)
721 return 0;
722 if (v > 255)
723 return 255;
724
725 return (uint8_t) v;
726}
727
728static inline uint8_t clamp_u8(int32_t v)
729{
730 if (v < 0)
731 return 0;
732 if (v > 255)
733 return 255;
734 return v;
735}
736
737// color conversion formulas taken from JFIF spec v 1.02
738image_u8x3_t *pjpeg_to_u8x3_baseline(pjpeg_t *pj)
739{
740 assert(pj->ncomponents == 3);
741
742 pjpeg_component_t *Y = &pj->components[0];
743 pjpeg_component_t *Cb = &pj->components[1];
744 pjpeg_component_t *Cr = &pj->components[2];
745
746 int Cb_factor_y = Y->height / Cb->height;
747 int Cb_factor_x = Y->width / Cb->width;
748
749 int Cr_factor_y = Y->height / Cr->height;
750 int Cr_factor_x = Y->width / Cr->width;
751
752 image_u8x3_t *im = image_u8x3_create(pj->width, pj->height);
753
754 if (Cr_factor_y == 1 && Cr_factor_x == 1 && Cb_factor_y == 1 && Cb_factor_x == 1) {
755
756 for (int y = 0; y < pj->height; y++) {
757 for (int x = 0; x < pj->width; x++) {
758 int32_t y_val = Y->data[y*Y->stride + x] * 65536;
759 int32_t cb_val = Cb->data[y*Cb->stride + x] - 128;
760 int32_t cr_val = Cr->data[y*Cr->stride + x] - 128;
761
762 int32_t r_val = y_val + 91881 * cr_val;
763 int32_t g_val = y_val + -22554 * cb_val - 46802 * cr_val;
764 int32_t b_val = y_val + 116130 * cb_val;
765
766 im->buf[y*im->stride + 3*x + 0 ] = clamp_u8(r_val >> 16);
767 im->buf[y*im->stride + 3*x + 1 ] = clamp_u8(g_val >> 16);
768 im->buf[y*im->stride + 3*x + 2 ] = clamp_u8(b_val >> 16);
769 }
770 }
771 } else if (Cb_factor_y == Cr_factor_y && Cb_factor_x == Cr_factor_x) {
772 for (int by = 0; by < pj->height / Cb_factor_y; by++) {
773 for (int bx = 0; bx < pj->width / Cb_factor_x; bx++) {
774
775 int32_t cb_val = Cb->data[by*Cb->stride + bx] - 128;
776 int32_t cr_val = Cr->data[by*Cr->stride + bx] - 128;
777
778 int32_t r0 = 91881 * cr_val;
779 int32_t g0 = -22554 * cb_val - 46802 * cr_val;
780 int32_t b0 = 116130 * cb_val;
781
782 for (int dy = 0; dy < Cb_factor_y; dy++) {
783 int y = by*Cb_factor_y + dy;
784
785 for (int dx = 0; dx < Cb_factor_x; dx++) {
786 int x = bx*Cb_factor_x + dx;
787
788 int32_t y_val = Y->data[y*Y->stride + x] * 65536;
789
790 int32_t r_val = r0 + y_val;
791 int32_t g_val = g0 + y_val;
792 int32_t b_val = b0 + y_val;
793
794 im->buf[y*im->stride + 3*x + 0 ] = clamp_u8(r_val >> 16);
795 im->buf[y*im->stride + 3*x + 1 ] = clamp_u8(g_val >> 16);
796 im->buf[y*im->stride + 3*x + 2 ] = clamp_u8(b_val >> 16);
797 }
798 }
799 }
800 }
801 } else {
802
803 for (int y = 0; y < pj->height; y++) {
804 for (int x = 0; x < pj->width; x++) {
805 int32_t y_val = Y->data[y*Y->stride + x];
806 int32_t cb_val = Cb->data[(y / Cb_factor_y)*Cb->stride + (x / Cb_factor_x)] - 128;
807 int32_t cr_val = Cr->data[(y / Cr_factor_y)*Cr->stride + (x / Cr_factor_x)] - 128;
808
809 uint8_t r_val = clampd(y_val + 1.402 * cr_val);
810 uint8_t g_val = clampd(y_val - 0.34414 * cb_val - 0.71414 * cr_val);
811 uint8_t b_val = clampd(y_val + 1.772 * cb_val);
812
813 im->buf[y*im->stride + 3*x + 0 ] = r_val;
814 im->buf[y*im->stride + 3*x + 1 ] = g_val;
815 im->buf[y*im->stride + 3*x + 2 ] = b_val;
816 }
817 }
818 }
819
820 return im;
821}
822
823///////////////////////////////////////////////////////////////////
824// returns NULL if file loading fails.
825pjpeg_t *pjpeg_create_from_file(const char *path, uint32_t flags, int *error)
826{
827 FILE *f = fopen(path, "rb");
828 if (f == NULL)
829 return NULL;
830
831 fseek(f, 0, SEEK_END);
832 long buflen = ftell(f);
833
834 uint8_t *buf = malloc(buflen);
835 fseek(f, 0, SEEK_SET);
836 int res = fread(buf, 1, buflen, f);
837
838 if ( ferror(f) ){
839 debug_print ("Read failed");
840 clearerr(f);
841 }
842
843 fclose(f);
844 if (res != buflen) {
845 free(buf);
846 if (error)
847 *error = PJPEG_ERR_FILE;
848 return NULL;
849 }
850
851 pjpeg_t *pj = pjpeg_create_from_buffer(buf, buflen, flags, error);
852
853 free(buf);
854 return pj;
855}
856
857pjpeg_t *pjpeg_create_from_buffer(uint8_t *buf, int buflen, uint32_t flags, int *error)
858{
859 struct pjpeg_decode_state pjd;
860 memset(&pjd, 0, sizeof(pjd));
861
862 if (flags & PJPEG_MJPEG) {
863 pjd.in = mjpeg_dht;
864 pjd.inlen = sizeof(mjpeg_dht);
865 int result = pjpeg_decode_buffer(&pjd);
866 assert(result == 0);
867 }
868
869 pjd.in = buf;
870 pjd.inlen = buflen;
871 pjd.flags = flags;
872
873 int result = pjpeg_decode_buffer(&pjd);
874 if (error)
875 *error = result;
876
877 if (result) {
878 for (int i = 0; i < pjd.ncomponents; i++)
879 free(pjd.components[i].data);
880 free(pjd.components);
881
882 return NULL;
883 }
884
885 pjpeg_t *pj = calloc(1, sizeof(pjpeg_t));
886
887 pj->width = pjd.width;
888 pj->height = pjd.height;
889 pj->ncomponents = pjd.ncomponents;
890 pj->components = pjd.components;
891
892 return pj;
893}