ljpegdecompressor.cpp 38.6 KB
Newer Older
1 2 3
/*
 * libopenraw - ljpegdecompressor.cpp
 *
Hubert Figuiere's avatar
Hubert Figuiere committed
4
 * Copyright (C) 2007-2016 Hubert Figuiere
5
 *
6 7 8 9
 * This library is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation, either version 3 of
 * the License, or (at your option) any later version.
10 11 12 13 14 15 16
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
17 18
 * License along with this library.  If not, see
 * <http://www.gnu.org/licenses/>.
19
 */
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
/*
 * Code for JPEG lossless decoding.  Large parts are grabbed from the IJG
 * software, so:
 *
 * Copyright (C) 1991, 1992, Thomas G. Lane.
 * Part of the Independent JPEG Group's software.
 * See the file Copyright for more details.
 *
 * Copyright (c) 1993 Brian C. Smith, The Regents of the University
 * of California
 * All rights reserved.
 * 
 * Copyright (c) 1994 Kongji Huang and Brian C. Smith.
 * Cornell University
 * All rights reserved.
 * 
 * Permission to use, copy, modify, and distribute this software and its
 * documentation for any purpose, without fee, and without written agreement is
 * hereby granted, provided that the above copyright notice and the following
 * two paragraphs appear in all copies of this software.
 * 
 * IN NO EVENT SHALL CORNELL UNIVERSITY BE LIABLE TO ANY PARTY FOR
 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
 * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF CORNELL
 * UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 * CORNELL UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
 * ON AN "AS IS" BASIS, AND CORNELL UNIVERSITY HAS NO OBLIGATION TO
 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
 */
52 53


54 55 56
#include <stdlib.h>
#include <string.h>

57 58 59 60
#include <fcntl.h>
#include <algorithm>
#include <cstdint>

61
#include <boost/format.hpp>
62

63 64 65
#include <libopenraw/consts.h>
#include <libopenraw/debug.h>

Hubert Figuiere's avatar
Hubert Figuiere committed
66
#include "rawdata.hpp"
Hubert Figuiere's avatar
Hubert Figuiere committed
67 68 69 70 71
#include "exception.hpp"
#include "io/stream.hpp"
#include "trace.hpp"
#include "ljpegdecompressor.hpp"
#include "ljpegdecompressor_priv.hpp"
72

73 74
namespace OpenRaw {

Hubert Figuiere's avatar
Hubert Figuiere committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
using namespace Debug;

namespace Internals {


static void SkipVariable(IO::Stream *s);
static uint16_t Get2bytes (IO::Stream * s);
static int32_t  NextMarker(IO::Stream * );
static void GetSoi(DecompressInfo *dcPtr);
static void GetApp0(IO::Stream *);

LJpegDecompressor::LJpegDecompressor(IO::Stream *stream,
                                     RawContainer *container)
    : Decompressor(stream, container),
      m_slices(),
      m_mcuROW1(NULL), m_mcuROW2(NULL),
      m_buf1(NULL), m_buf2(NULL),
      m_bitsLeft(0),
93
      m_getBuffer(0)
Hubert Figuiere's avatar
Hubert Figuiere committed
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
{
}


LJpegDecompressor::~LJpegDecompressor()
{
    if(m_mcuROW1) {
        free(m_mcuROW1);
    }
    if(m_mcuROW2) {
        free(m_mcuROW2);
    }
    if(m_buf1) {
        free(m_buf1);
    }
    if(m_buf2) {
        free(m_buf2);
    }
}
113
		
114

Hubert Figuiere's avatar
Hubert Figuiere committed
115
void LJpegDecompressor::setSlices(const std::vector<uint16_t> & slices)
Hubert Figuiere's avatar
Hubert Figuiere committed
116
{
Hubert Figuiere's avatar
Hubert Figuiere committed
117 118 119 120 121 122
    uint16_t n = slices[0];
    m_slices.resize(n + 1);
    for(uint16_t i = 0; i < n; i++) {
        m_slices[i] = slices[1];
    }
    m_slices[n] = slices[2];
Hubert Figuiere's avatar
Hubert Figuiere committed
123
}
124
		
125 126 127


		
Hubert Figuiere's avatar
Hubert Figuiere committed
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
static uint32_t bitMask[] = {  0xffffffff, 0x7fffffff, 
                               0x3fffffff, 0x1fffffff,
                               0x0fffffff, 0x07ffffff, 
                               0x03ffffff, 0x01ffffff,
                               0x00ffffff, 0x007fffff, 
                               0x003fffff, 0x001fffff,
                               0x000fffff, 0x0007ffff, 
                               0x0003ffff, 0x0001ffff,
                               0x0000ffff, 0x00007fff, 
                               0x00003fff, 0x00001fff,
                               0x00000fff, 0x000007ff, 
                               0x000003ff, 0x000001ff,
                               0x000000ff, 0x0000007f, 
                               0x0000003f, 0x0000001f,
                               0x0000000f, 0x00000007, 
                               0x00000003, 0x00000001};
144

Hubert Figuiere's avatar
Hubert Figuiere committed
145 146
void FixHuffTbl (HuffmanTable *htbl);

147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164

/*
 *--------------------------------------------------------------
 *
 * FixHuffTbl --
 *
 *      Compute derived values for a Huffman table one the DHT marker
 *      has been processed.  This generates both the encoding and
 *      decoding tables.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      None.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
165 166 167 168 169 170 171 172 173
void
FixHuffTbl (HuffmanTable *htbl)
{
    int32_t p, i, l, lastp, si;
    char huffsize[257];
    uint16_t huffcode[257];
    uint16_t code;
    int32_t size;
    int32_t value, ll, ul;
174
			
Hubert Figuiere's avatar
Hubert Figuiere committed
175 176 177 178 179 180
    /*
     * Figure C.1: make table of Huffman code length for each symbol
     * Note that this is in code-length order.
     */
    p = 0;
    for (l = 1; l <= 16; l++) {
181
        for (i = 1; i <= (int)htbl->bits[l]; i++)
Hubert Figuiere's avatar
Hubert Figuiere committed
182 183 184 185
            huffsize[p++] = (char)l;
    }
    huffsize[p] = 0;
    lastp = p;
186 187
			
			
Hubert Figuiere's avatar
Hubert Figuiere committed
188 189 190 191 192 193 194 195
    /*
     * Figure C.2: generate the codes themselves
     * Note that this is in code-length order.
     */
    code = 0;
    si = huffsize[0];
    p = 0;
    while (huffsize[p]) {
196
        while (((int)huffsize[p]) == si) {
Hubert Figuiere's avatar
Hubert Figuiere committed
197 198
            huffcode[p++] = code;
            code++;
199 200 201
        }
        code <<= 1;
        si++;
Hubert Figuiere's avatar
Hubert Figuiere committed
202
    }
203
			
Hubert Figuiere's avatar
Hubert Figuiere committed
204 205 206 207 208 209 210
    /*
     * Figure C.3: generate encoding tables
     * These are code and size indexed by symbol value
     * Set any codeless symbols to have code length 0; this allows
     * EmitBits to detect any attempt to emit such symbols.
     */
    memset(htbl->ehufsi, 0, sizeof(htbl->ehufsi));
211
			
Hubert Figuiere's avatar
Hubert Figuiere committed
212
    for (p = 0; p < lastp; p++) {
213 214
        htbl->ehufco[htbl->huffval[p]] = huffcode[p];
        htbl->ehufsi[htbl->huffval[p]] = huffsize[p];
Hubert Figuiere's avatar
Hubert Figuiere committed
215
    }
216
			
Hubert Figuiere's avatar
Hubert Figuiere committed
217 218 219 220 221
    /*
     * Figure F.15: generate decoding tables
     */
    p = 0;
    for (l = 1; l <= 16; l++) {
222
        if (htbl->bits[l]) {
Hubert Figuiere's avatar
Hubert Figuiere committed
223 224 225 226
            htbl->valptr[l] = p;
            htbl->mincode[l] = huffcode[p];
            p += htbl->bits[l];
            htbl->maxcode[l] = huffcode[p - 1];
227
        } else {
Hubert Figuiere's avatar
Hubert Figuiere committed
228
            htbl->maxcode[l] = -1;
229
        }
Hubert Figuiere's avatar
Hubert Figuiere committed
230
    }
231
			
Hubert Figuiere's avatar
Hubert Figuiere committed
232 233 234 235
    /*
     * We put in this value to ensure HuffDecode terminates.
     */
    htbl->maxcode[17] = 0xFFFFFL;
236
			
Hubert Figuiere's avatar
Hubert Figuiere committed
237 238 239 240 241 242 243 244 245
    /*
     * Build the numbits, value lookup tables.
     * These table allow us to gather 8 bits from the bits stream,
     * and immediately lookup the size and value of the huffman codes.
     * If size is zero, it means that more than 8 bits are in the huffman
     * code (this happens about 3-4% of the time).
     */
    bzero (htbl->numbits, sizeof(htbl->numbits));
    for (p=0; p<lastp; p++) {
246 247
        size = huffsize[p];
        if (size <= 8) {
Hubert Figuiere's avatar
Hubert Figuiere committed
248 249 250 251 252 253 254 255 256 257 258 259
            value = htbl->huffval[p];
            code = huffcode[p];
            ll = code << (8-size);
            if (size < 8) {
                ul = ll | bitMask[24+size];
            } else {
                ul = ll;
            }
            for (i=ll; i<=ul; i++) {
                htbl->numbits[i] = size;
                htbl->value[i] = value;
            }
260
        }
Hubert Figuiere's avatar
Hubert Figuiere committed
261 262
    }
}
263 264 265 266 267 268 269 270 271 272


#define RST0    0xD0	/* RST0 marker code */


#if 0
/*
 * The following variables keep track of the input buffer
 * for the JPEG data, which is read by ReadJpegData.
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
273 274 275 276
uint8_t inputBuffer[JPEG_BUF_SIZE]; /* Input buffer for JPEG data */
int numInputBytes;		/* The total number of bytes in inputBuffer */
int maxInputBytes;		/* Size of inputBuffer */
int inputBufferOffset;		/* Offset of current byte */
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
#endif


/*
 * Code for extracting the next N bits from the input stream.
 * (N never exceeds 15 for JPEG data.)
 * This needs to go as fast as possible!
 *
 * We read source bytes into getBuffer and dole out bits as needed.
 * If getBuffer already contains enough bits, they are fetched in-line
 * by the macros get_bits() and get_bit().  When there aren't enough bits,
 * fillBitBuffer is called; it will attempt to fill getBuffer to the
 * "high water mark", then extract the desired number of bits.  The idea,
 * of course, is to minimize the function-call overhead cost of entering
 * fillBitBuffer.
 * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
 * of getBuffer to be used.  (On machines with wider words, an even larger
 * buffer could be used.)  
 */

297
#define BITS_PER_LONG	(8*sizeof(int32_t))
298 299 300 301 302
#define MIN_GET_BITS  (BITS_PER_LONG-7)	   /* max value for long getBuffer */
		
/*
 * bmask[n] is mask for n rightmost bits
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
303 304 305 306 307
static int32_t bmask[] = {0x0000,
                          0x0001, 0x0003, 0x0007, 0x000F,
                          0x001F, 0x003F, 0x007F, 0x00FF,
                          0x01FF, 0x03FF, 0x07FF, 0x0FFF,
                          0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF};
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
		

/*
 * Lossless JPEG specifies data precision to be from 2 to 16 bits/sample.
 */ 
#define MinPrecisionBits 2
#define MaxPrecisionBits 16


/*
 *--------------------------------------------------------------
 *
 * DecoderStructInit --
 *
 *	Initalize the rest of the fields in the decompression
 *	structure.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
333 334
void
LJpegDecompressor::DecoderStructInit (DecompressInfo *dcPtr)
335
    noexcept(false)
Hubert Figuiere's avatar
Hubert Figuiere committed
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
{
    int16_t ci,i;
    JpegComponentInfo *compPtr;
    int32_t mcuSize;

    /*
     * Check sampling factor validity.
     */
    for (ci = 0; ci < dcPtr->numComponents; ci++) {
        compPtr = &dcPtr->compInfo[ci];
        if ((compPtr->hSampFactor != 1) || (compPtr->vSampFactor != 1)) {
            throw DecodingException("Error: Downsampling is not supported.\n");
        }
    }

    /*
     * Prepare array describing MCU composition
     */
    if (dcPtr->compsInScan == 1) {
        dcPtr->MCUmembership[0] = 0;
    } else {
        if (dcPtr->compsInScan > 4) {
            throw DecodingException("Too many components for interleaved scan");
        }

        for (ci = 0; ci < dcPtr->compsInScan; ci++) {
            dcPtr->MCUmembership[ci] = ci;
        }
    }

    /*
     * Initialize mucROW1 and mcuROW2 which buffer two rows of
     * pixels for predictor calculation.
     */

    if ((m_mcuROW1 = (MCU *)malloc(dcPtr->imageWidth*sizeof(MCU)))==NULL) {
        throw DecodingException("Not enough memory for mcuROW1\n");
    }
    if ((m_mcuROW2 = (MCU *)malloc(dcPtr->imageWidth*sizeof(MCU)))==NULL) {
        throw DecodingException("Not enough memory for mcuROW2\n");
    }

    mcuSize=dcPtr->compsInScan * sizeof(ComponentType);
    if ((m_buf1 = (char *)malloc(dcPtr->imageWidth*mcuSize))==NULL) {
        throw DecodingException("Not enough memory for buf1\n");
    }
    if ((m_buf2 = (char *)malloc(dcPtr->imageWidth*mcuSize))==NULL) {
        throw DecodingException("Not enough memory for buf2\n");
    }

    for (i=0;i<dcPtr->imageWidth;i++) {
387 388
        m_mcuROW1[i]=(MCU)(m_buf1+i*mcuSize);
        m_mcuROW2[i]=(MCU)(m_buf2+i*mcuSize);
Hubert Figuiere's avatar
Hubert Figuiere committed
389 390
    }
}
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408


/*
 *--------------------------------------------------------------
 *
 * fillBitBuffer --
 *
 *	Load up the bit buffer with at least nbits
 *	Process any stuffed bytes at this time.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	The bitwise global variables are updated.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
409 410 411 412
void
LJpegDecompressor::fillBitBuffer (IO::Stream * s,uint16_t nbits)
{
    uint8_t c, c2;
413
			
Hubert Figuiere's avatar
Hubert Figuiere committed
414 415
    while (m_bitsLeft < MIN_GET_BITS) {
        c = s->readByte();
416
				
Hubert Figuiere's avatar
Hubert Figuiere committed
417 418 419 420 421
        /*
         * If it's 0xFF, check and discard stuffed zero byte
         */
        if (c == 0xFF) {
            c2 = s->readByte();
422
					
Hubert Figuiere's avatar
Hubert Figuiere committed
423
            if (c2 != 0) {
424
						
Hubert Figuiere's avatar
Hubert Figuiere committed
425 426 427 428 429
                /*
                 * Oops, it's actually a marker indicating end of
                 * compressed data.  Better put it back for use later.
                 */
                s->seek(-2, SEEK_CUR);
430
						
Hubert Figuiere's avatar
Hubert Figuiere committed
431 432 433 434 435 436
                /*
                 * There should be enough bits still left in the data
                 * segment; if so, just break out of the while loop.
                 */
                if (m_bitsLeft >= nbits)
                    break;
437
						
Hubert Figuiere's avatar
Hubert Figuiere committed
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
                /*
                 * Uh-oh.  Corrupted data: stuff zeroes into the data
                 * stream, since this sometimes occurs when we are on the
                 * last show_bits(8) during decoding of the Huffman
                 * segment.
                 */
                c = 0;
            }
        }
        /*
         * OK, load c into getBuffer
         */
        m_getBuffer = (m_getBuffer << 8) | c;
        m_bitsLeft += 8;
    }
}



inline int32_t LJpegDecompressor::QuickPredict(int32_t col, int16_t curComp,
                                               MCU *curRowBuf, 
                                               MCU *prevRowBuf,
                                               int32_t psv)
{
    int32_t left,upper,diag,leftcol;
    int32_t predictor;

    leftcol=col-1;
    upper=prevRowBuf[col][curComp];
    left=curRowBuf[leftcol][curComp];
    diag=prevRowBuf[leftcol][curComp];
469
	
Hubert Figuiere's avatar
Hubert Figuiere committed
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    /*
     * All predictor are calculated according to psv.
     */
    switch (psv) {
    case 0:
        predictor = 0;
        break;
    case 1:
        predictor = left;
        break;
    case 2:
        predictor = upper;
        break;
    case 3:
        predictor = diag;
        break;
    case 4:
        predictor = left+upper-diag;
        break;
    case 5:
        predictor = left+((upper-diag)>>1);
        break;
    case 6:
        predictor = upper+((left-diag)>>1);
        break;
    case 7:
        predictor = (left+upper)>>1;
        break;
    default:
499
        LOGWARN("Warning: Undefined PSV\n");
Hubert Figuiere's avatar
Hubert Figuiere committed
500 501 502 503 504 505
        predictor = 0;
    }
    return predictor;
}

inline
506
int32_t LJpegDecompressor::show_bits8(IO::Stream * s)
Hubert Figuiere's avatar
Hubert Figuiere committed
507 508 509 510
{
    if (m_bitsLeft < 8) {
        fillBitBuffer(s, 8);
    }
511
    return (m_getBuffer >> (m_bitsLeft-8)) & 0xff;
Hubert Figuiere's avatar
Hubert Figuiere committed
512
}
513

Hubert Figuiere's avatar
Hubert Figuiere committed
514
inline
515
void LJpegDecompressor::flush_bits(uint16_t nbits)
Hubert Figuiere's avatar
Hubert Figuiere committed
516 517 518
{
    m_bitsLeft -= (nbits);
}
519

Hubert Figuiere's avatar
Hubert Figuiere committed
520
inline
521
int32_t LJpegDecompressor::get_bits(uint16_t nbits)
Hubert Figuiere's avatar
Hubert Figuiere committed
522 523 524 525 526
{
    if (m_bitsLeft < nbits) 
        fillBitBuffer(m_stream, nbits);
    return ((m_getBuffer >> (m_bitsLeft -= (nbits)))) & bmask[nbits];
}
527
		
Hubert Figuiere's avatar
Hubert Figuiere committed
528 529 530 531 532 533 534
inline
int32_t LJpegDecompressor::get_bit() 
{
    if (!m_bitsLeft) 
        fillBitBuffer(m_stream, 1);
    return (m_getBuffer >> (--m_bitsLeft)) & 1;
}
535 536


Hubert Figuiere's avatar
Hubert Figuiere committed
537
inline
Hubert Figuiere's avatar
Hubert Figuiere committed
538 539 540 541 542 543 544
int32_t LJpegDecompressor::readBits(IO::Stream * s, uint16_t nbits)
{
    if (m_bitsLeft < nbits) {
        fillBitBuffer(s, nbits);
    }
    return ((m_getBuffer >> (m_bitsLeft -= (nbits)))) & bmask[nbits];
}
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562



/*
 *--------------------------------------------------------------
 *
 * PmPutRow --
 *
 *      Output one row of pixels stored in RowBuf.
 *
 * Results:
 *      None
 *
 * Side effects:
 *      One row of pixels are write to file pointed by outFile.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
563
inline void
Hubert Figuiere's avatar
Hubert Figuiere committed
564
LJpegDecompressor::PmPutRow(MCU* RowBuf, int32_t numComp, int32_t numCol, int32_t Pt)
Hubert Figuiere's avatar
Hubert Figuiere committed
565
{
Hubert Figuiere's avatar
Hubert Figuiere committed
566 567 568
    // TODO this might be wrong in 8 bits...
    // original code was using putc which *i think* was a problem for
    // 16bpp
Hubert Figuiere's avatar
Hubert Figuiere committed
569
    int32_t comp;
Hubert Figuiere's avatar
Hubert Figuiere committed
570 571
    int32_t col;
    uint16_t v;
Hubert Figuiere's avatar
Hubert Figuiere committed
572 573 574

    for (col = 0; col < numCol; col++) {
        for (comp = 0; comp < numComp; comp++) {
575
            v = RowBuf[col][comp]<<Pt;
Hubert Figuiere's avatar
Hubert Figuiere committed
576 577
            m_output->append(v);
        }
Hubert Figuiere's avatar
Hubert Figuiere committed
578
    }
579
//			m_output->nextRow();
Hubert Figuiere's avatar
Hubert Figuiere committed
580
}
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597

/*
 *--------------------------------------------------------------
 *
 * HuffDecode --
 *
 *	Taken from Figure F.16: extract next coded symbol from
 *	input stream.  This should becode a macro.
 *
 * Results:
 *	Next coded symbol
 *
 * Side effects:
 *	Bitstream is parsed.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
598 599 600 601 602 603
inline int32_t 
LJpegDecompressor::HuffDecode(HuffmanTable *htbl)
{
    int32_t rv;
    int32_t l, temp;
    int32_t code;
604

Hubert Figuiere's avatar
Hubert Figuiere committed
605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
    /*
     * If the huffman code is less than 8 bits, we can use the fast
     * table lookup to get its value.  It's more than 8 bits about
     * 3-4% of the time.
     */
    code = show_bits8(m_stream);
    if (htbl->numbits[code]) {
        flush_bits(htbl->numbits[code]);
        rv=htbl->value[code];
    }  else {
        flush_bits(8);
        l = 8;
        while (code > htbl->maxcode[l]) {
            temp = get_bit();
            code = (code << 1) | temp;
            l++;
        }
622

Hubert Figuiere's avatar
Hubert Figuiere committed
623 624 625
        /*
         * With garbage input we may reach the sentinel value l = 17.
         */
626

Hubert Figuiere's avatar
Hubert Figuiere committed
627
        if (l > 16) {
628
            //LOGWARN("Corrupt JPEG data: bad Huffman code %d\n", l);
Hubert Figuiere's avatar
Hubert Figuiere committed
629 630 631 632 633 634 635 636
            rv = 0;		/* fake a zero as the safest result */
        } else {
            rv = htbl->huffval[htbl->valptr[l] +
                               ((int)(code - htbl->mincode[l]))];
        }
    }
    return rv;
}
637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652

/*
 *--------------------------------------------------------------
 *
 * HuffExtend --
 *
 *	Code and table for Figure F.12: extend sign bit
 *
 * Results:
 *	The extended value.
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */
653
static const int32_t extendTest[16] =	/* entry n is 2**(n-1) */
Hubert Figuiere's avatar
Hubert Figuiere committed
654 655
{0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000};
656

Hubert Figuiere's avatar
Hubert Figuiere committed
657 658 659
// we can't bitshift -1. So we use 0xffffffff as a value.
// gcc complain about it otherwise.
#define EXTEND(n) (int32_t)(0xffffffff << n) + 1
660
static const int32_t extendOffset[16] =	/* entry n is (-1 << n) + 1 */
Hubert Figuiere's avatar
Hubert Figuiere committed
661 662 663 664 665 666
{
    0, EXTEND(1), EXTEND(2), EXTEND(3),
    EXTEND(4), EXTEND(5), EXTEND(6), EXTEND(7),
    EXTEND(8), EXTEND(9), EXTEND(10), EXTEND(11),
    EXTEND(12), EXTEND(13), EXTEND(14), EXTEND(15)
};
667

Hubert Figuiere's avatar
Hubert Figuiere committed
668
inline
669
void HuffExtend(int32_t & x, int32_t s) noexcept
Hubert Figuiere's avatar
Hubert Figuiere committed
670
{
671 672 673
    // s >= 16 is an overflow. And probably will lead to a corrupt
    // output but at least not crash.
    if (s < 16 && x < extendTest[s]) {
Hubert Figuiere's avatar
Hubert Figuiere committed
674 675 676
        (x) += extendOffset[s];
    }
}
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693

/*
 *--------------------------------------------------------------
 *
 * HuffDecoderInit --
 *
 *	Initialize for a Huffman-compressed scan.
 *	This is invoked after reading the SOS marker.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	None.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
694 695
void
LJpegDecompressor::HuffDecoderInit (DecompressInfo *dcPtr)
696
    noexcept(false)
Hubert Figuiere's avatar
Hubert Figuiere committed
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
{
    int16_t ci;
    JpegComponentInfo *compptr;

    /*
     * Initialize static variables
     */
    m_bitsLeft = 0;

    for (ci = 0; ci < dcPtr->compsInScan; ci++) {
        compptr = dcPtr->curCompInfo[ci];
        /*
         * Make sure requested tables are present
         */
        if (dcPtr->dcHuffTblPtrs[compptr->dcTblNo] == NULL) { 
            throw DecodingException("Error: Use of undefined Huffman table\n");
        }

        /*
         * Compute derived values for Huffman tables.
         * We may do this more than once for same table, but it's not a
         * big deal
         */
        FixHuffTbl (dcPtr->dcHuffTblPtrs[compptr->dcTblNo]);
    }

    /*
     * Initialize restart stuff
     */
    dcPtr->restartInRows = (dcPtr->restartInterval)/(dcPtr->imageWidth);
    dcPtr->restartRowsToGo = dcPtr->restartInRows;
    dcPtr->nextRestartNum = 0;
}
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745

/*
 *--------------------------------------------------------------
 *
 * ProcessRestart --
 *
 *	Check for a restart marker & resynchronize decoder.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	BitStream is parsed, bit buffer is reset, etc.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
746 747
void
LJpegDecompressor::ProcessRestart (DecompressInfo *dcPtr)
748
    noexcept(false)
Hubert Figuiere's avatar
Hubert Figuiere committed
749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789
{
    int32_t c, nbytes;

    /*
     * Throw away any unused bits remaining in bit buffer
     */
    nbytes = m_bitsLeft / 8;
    m_bitsLeft = 0;

    /*
     * Scan for next JPEG marker
     */
    do {
        do {			/* skip any non-FF bytes */
            nbytes++;
            c = m_stream->readByte();
        } while (c != 0xFF);
        do {			/* skip any duplicate FFs */
            /*
             * we don't increment nbytes here since extra FFs are legal
             */
            c = m_stream->readByte();
        } while (c == 0xFF);
    } while (c == 0);		/* repeat if it was a stuffed FF/00 */

    if (c != (RST0 + dcPtr->nextRestartNum)) {

        /*
         * Uh-oh, the restart markers have been messed up too.
         * Just bail out.
         */
        throw DecodingException("Error: Corrupt JPEG data. "
                                "Aborting decoding...\n");
    }

    /*
     * Update restart state
     */
    dcPtr->restartRowsToGo = dcPtr->restartInRows;
    dcPtr->nextRestartNum = (dcPtr->nextRestartNum + 1) & 7;
}
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808

/*
 *--------------------------------------------------------------
 *
 * DecodeFirstRow --
 *
 *	Decode the first raster line of samples at the start of 
 *      the scan and at the beginning of each restart interval.
 *	This includes modifying the component value so the real
 *      value, not the difference is returned.
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Bitstream is parsed.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826
void LJpegDecompressor::DecodeFirstRow(DecompressInfo *dcPtr,
                                       MCU *curRowBuf)
{
    uint16_t curComp,ci;
    int32_t s,col,compsInScan,numCOL;
    JpegComponentInfo *compptr;
    int32_t Pr,Pt,d;
    HuffmanTable *dctbl;

    Pr=dcPtr->dataPrecision;
    Pt=dcPtr->Pt;
    compsInScan=dcPtr->compsInScan;
    numCOL=dcPtr->imageWidth;

    /*
     * the start of the scan or at the beginning of restart interval.
     */
    for (curComp = 0; curComp < compsInScan; curComp++) {
827 828 829 830 831 832 833
        ci = dcPtr->MCUmembership[curComp];
        compptr = dcPtr->curCompInfo[ci];
        dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];

        /*
         * Section F.2.2.1: decode the difference
         */
834
        s = HuffDecode (dctbl);
835
        if (s) {
Hubert Figuiere's avatar
Hubert Figuiere committed
836 837 838 839
            d = get_bits(s);
            HuffExtend(d,s);
        } else {
            d = 0;
840 841 842 843 844 845
        }

        /* 
         * Add the predictor to the difference.
         */
        curRowBuf[0][curComp]=d+(1<<(Pr-Pt-1));
Hubert Figuiere's avatar
Hubert Figuiere committed
846
    }
847

Hubert Figuiere's avatar
Hubert Figuiere committed
848 849 850 851
    /*
     * the rest of the first row
     */
    for (col=1; col<numCOL; col++) {
852
        for (curComp = 0; curComp < compsInScan; curComp++) {
Hubert Figuiere's avatar
Hubert Figuiere committed
853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871
            ci = dcPtr->MCUmembership[curComp];
            compptr = dcPtr->curCompInfo[ci];
            dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];

            /*
             * Section F.2.2.1: decode the difference
             */
            s = HuffDecode (dctbl);
            if (s) {
                d = get_bits(s);
                HuffExtend(d,s);
            } else {
                d = 0;
            }

            /* 
             * Add the predictor to the difference.
             */
            curRowBuf[col][curComp]=d+curRowBuf[col-1][curComp];
872
        }
Hubert Figuiere's avatar
Hubert Figuiere committed
873
    }
874

Hubert Figuiere's avatar
Hubert Figuiere committed
875 876 877 878
    if (dcPtr->restartInRows) {
        (dcPtr->restartRowsToGo)--;
    }
}
879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896

/*
 *--------------------------------------------------------------
 *
 * DecodeImage --
 *
 *      Decode the input stream. This includes modifying
 *      the component value so the real value, not the
 *      difference is returned.
 *
 * Results:
 *      None.
 *
 * Side effects:
 *      Bitstream is parsed.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926
void
LJpegDecompressor::DecodeImage(DecompressInfo *dcPtr)
{
    int32_t s,d,col,row;
    int16_t curComp, ci;
    HuffmanTable *dctbl;
    JpegComponentInfo *compptr;
    int32_t predictor;
    int32_t numCOL,numROW,compsInScan;
    MCU *prevRowBuf,*curRowBuf;
    int32_t imagewidth,Pt,psv;

    numCOL=imagewidth=dcPtr->imageWidth;
    numROW=dcPtr->imageHeight;
    compsInScan=dcPtr->compsInScan;
    Pt=dcPtr->Pt;
    psv=dcPtr->Ss;
    prevRowBuf=m_mcuROW2;
    curRowBuf=m_mcuROW1;

    /*
     * Decode the first row of image. Output the row and
     * turn this row into a previous row for later predictor
     * calculation.
     */  
    DecodeFirstRow(dcPtr,curRowBuf);
    PmPutRow(curRowBuf,compsInScan,numCOL,Pt);
    std::swap(prevRowBuf,curRowBuf);

    for (row=1; row<numROW; row++) {
927 928 929 930 931

        /*
         * Account for restart interval, process restart marker if needed.
         */
        if (dcPtr->restartInRows) {
Hubert Figuiere's avatar
Hubert Figuiere committed
932 933
            if (dcPtr->restartRowsToGo == 0) {
                ProcessRestart (dcPtr);
934
            
Hubert Figuiere's avatar
Hubert Figuiere committed
935 936 937 938 939 940 941 942 943
                /*
                 * Reset predictors at restart.
                 */
                DecodeFirstRow(dcPtr,curRowBuf);
                PmPutRow(curRowBuf,compsInScan,numCOL,Pt);
                std::swap(prevRowBuf,curRowBuf);
                continue;
            }
            dcPtr->restartRowsToGo--;
944 945 946 947 948 949
        }

        /*
         * The upper neighbors are predictors for the first column.
         */
        for (curComp = 0; curComp < compsInScan; curComp++) {
Hubert Figuiere's avatar
Hubert Figuiere committed
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
            ci = dcPtr->MCUmembership[curComp];
            compptr = dcPtr->curCompInfo[ci];
            dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];

            /*
             * Section F.2.2.1: decode the difference
             */
            s = HuffDecode (dctbl);
            if (s) {
                d = get_bits(s);
                HuffExtend(d,s);
            } else {
                d = 0;
            }

            curRowBuf[0][curComp]=d+prevRowBuf[0][curComp];
966 967 968 969 970 971 972
        }

        /*
         * For the rest of the column on this row, predictor
         * calculations are base on PSV. 
         */
        for (col=1; col<numCOL; col++) {
Hubert Figuiere's avatar
Hubert Figuiere committed
973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992
            for (curComp = 0; curComp < compsInScan; curComp++) {
                ci = dcPtr->MCUmembership[curComp];
                compptr = dcPtr->curCompInfo[ci];
                dctbl = dcPtr->dcHuffTblPtrs[compptr->dcTblNo];

                /*
                 * Section F.2.2.1: decode the difference
                 */
                s = HuffDecode (dctbl);
                if (s) {
                    d = get_bits(s);
                    HuffExtend(d,s);
                } else {
                    d = 0;
                }
                predictor = QuickPredict(col,curComp,curRowBuf,prevRowBuf,
                                         psv);

                curRowBuf[col][curComp]=d+predictor;
            }
993
        }
Hubert Figuiere's avatar
Hubert Figuiere committed
994 995 996 997
        PmPutRow(curRowBuf,compsInScan,numCOL,Pt);
        std::swap(prevRowBuf,curRowBuf);
    }
}
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017




/*
 *--------------------------------------------------------------
 *
 * Get2bytes --
 *
 *	Get a 2-byte unsigned integer (e.g., a marker parameter length
 *	field)
 *
 * Results:
 *	Next two byte of input as an integer.
 *
 * Side effects:
 *	Bitstream is parsed.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1018 1019 1020 1021
static inline uint16_t
Get2bytes (IO::Stream * s)
{
    uint16_t a;
1022

Hubert Figuiere's avatar
Hubert Figuiere committed
1023 1024 1025
    a = s->readByte();
    return (a << 8) | s->readByte();
}
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042

/*
 *--------------------------------------------------------------
 *
 * SkipVariable --
 *
 *	Skip over an unknown or uninteresting variable-length marker
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Bitstream is parsed over marker.
 *
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1043 1044 1045
static inline void SkipVariable(IO::Stream * s)
{
    int32_t length;
1046

Hubert Figuiere's avatar
Hubert Figuiere committed
1047
    length = Get2bytes(s) - 2;
1048

Hubert Figuiere's avatar
Hubert Figuiere committed
1049 1050
    s->seek(length, SEEK_CUR);
}
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067

/*
 *--------------------------------------------------------------
 *
 * GetDht --
 *
 *	Process a DHT marker
 *
 * Results:
 *	None
 *
 * Side effects:
 *	A huffman table is read.
 *	Exits on error.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1068 1069
void
LJpegDecompressor::GetDht (DecompressInfo *dcPtr)
1070
    noexcept(false)
Hubert Figuiere's avatar
Hubert Figuiere committed
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
{
    int32_t length;
    int32_t i, index, count;

    length = Get2bytes(m_stream) - 2;

    while (length) {
        index = m_stream->readByte();

        if (index < 0 || index >= 4) {
            throw DecodingException(str(boost::format("Bogus DHT index %1%")
                                        % index));
        }

        HuffmanTable *& htblptr = dcPtr->dcHuffTblPtrs[index];
        if (htblptr == NULL) {
            htblptr = (HuffmanTable *) malloc(sizeof (HuffmanTable));
            if (htblptr==NULL) {
                throw DecodingException("Can't malloc HuffmanTable");
            }
        }

        htblptr->bits[0] = 0;
        count = 0;
        for (i = 1; i <= 16; i++) {
            htblptr->bits[i] = m_stream->readByte();
            count += htblptr->bits[i];
        }

        if (count > 256) {
            throw DecodingException("Bogus DHT counts");
        }

        for (i = 0; i < count; i++)
            htblptr->huffval[i] = m_stream->readByte();

        length -= 1 + 16 + count;
    }
}
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126

/*
 *--------------------------------------------------------------
 *
 * GetDri --
 *
 *	Process a DRI marker
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Exits on error.
 *	Bitstream is parsed.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1127 1128
void
LJpegDecompressor::GetDri(DecompressInfo *dcPtr)
1129
    noexcept(false)
Hubert Figuiere's avatar
Hubert Figuiere committed
1130 1131 1132 1133 1134 1135 1136
{
    if (Get2bytes(m_stream) != 4) {
        throw DecodingException("Bogus length in DRI");
    }

    dcPtr->restartInterval = Get2bytes(m_stream);
}
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152

/*
 *--------------------------------------------------------------
 *
 * GetApp0 --
 *
 *	Process an APP0 marker.
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Bitstream is parsed
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1153 1154 1155
static void	GetApp0(IO::Stream *s)
{
    int32_t length;
1156

Hubert Figuiere's avatar
Hubert Figuiere committed
1157 1158 1159
    length = Get2bytes(s) - 2;
    s->seek(length, SEEK_CUR);
}
1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177

/*
 *--------------------------------------------------------------
 *
 * GetSof --
 *
 *	Process a SOFn marker
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Bitstream is parsed
 *	Exits on error
 *	dcPtr structure is filled in
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1178
void
1179 1180
LJpegDecompressor::GetSof(DecompressInfo *dcPtr)
    noexcept(false)
Hubert Figuiere's avatar
Hubert Figuiere committed
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
{
    int32_t length;
    int16_t ci;
    int32_t c;
    JpegComponentInfo *compptr;

    length = Get2bytes(m_stream);

    dcPtr->dataPrecision = m_stream->readByte();
    dcPtr->imageHeight = Get2bytes(m_stream);
    dcPtr->imageWidth = Get2bytes(m_stream);
    dcPtr->numComponents = m_stream->readByte();

    /*
     * We don't support files in which the image height is initially
     * specified as 0 and is later redefined by DNL.  As long as we
     * have to check that, might as well have a general sanity check.
     */
    if ((dcPtr->imageHeight <= 0 ) ||
        (dcPtr->imageWidth <= 0) || 
        (dcPtr->numComponents <= 0)) {
        throw DecodingException("Empty JPEG image (DNL not supported)");
    }

    if ((dcPtr->dataPrecision<MinPrecisionBits) ||
        (dcPtr->dataPrecision>MaxPrecisionBits)) {
        throw DecodingException("Unsupported JPEG data precision");
    }

    if (length != (dcPtr->numComponents * 3 + 8)) {
        throw DecodingException("Bogus SOF length");
    }

    dcPtr->compInfo = (JpegComponentInfo *) malloc
        (dcPtr->numComponents * sizeof (JpegComponentInfo));

    for (ci = 0; ci < dcPtr->numComponents; ci++) {
        compptr = &dcPtr->compInfo[ci];
        compptr->componentIndex = ci;
        compptr->componentId = m_stream->readByte();
        c = m_stream->readByte();
        compptr->hSampFactor = (int16_t)((c >> 4) & 15);
        compptr->vSampFactor = (int16_t)((c) & 15);
1224
        (void) m_stream->readByte();   /* skip Tq */
Hubert Figuiere's avatar
Hubert Figuiere committed
1225 1226
    }
}
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

/*
 *--------------------------------------------------------------
 *
 * GetSos --
 *
 *	Process a SOS marker
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Bitstream is parsed.
 *	Exits on error.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1244 1245
void
LJpegDecompressor::GetSos (DecompressInfo *dcPtr)
1246
    noexcept(false)
Hubert Figuiere's avatar
Hubert Figuiere committed
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293
{
    int32_t length;
    int32_t i;
    uint16_t n, ci, c, cc;
    JpegComponentInfo *compptr;

    length = Get2bytes (m_stream);

    /* 
     * Get the number of image components.
     */
    n = m_stream->readByte();
    dcPtr->compsInScan = n;
    length -= 3;

    if (length != (n * 2 + 3) || n < 1 || n > 4) {
        throw DecodingException("Bogus SOS length");
    }


    for (i = 0; i < n; i++) {
        cc = m_stream->readByte();
        c = m_stream->readByte();
        length -= 2;

        for (ci = 0; ci < dcPtr->numComponents; ci++)
            if (cc == dcPtr->compInfo[ci].componentId) {
                break;
            }

        if (ci >= dcPtr->numComponents) {
            throw DecodingException("Invalid component number in SOS");
        }

        compptr = &dcPtr->compInfo[ci];
        dcPtr->curCompInfo[i] = compptr;
        compptr->dcTblNo = (c >> 4) & 15;
    }

    /*
     * Get the PSV, skip Se, and get the point transform parameter.
     */
    dcPtr->Ss = m_stream->readByte(); 
    (void)m_stream->readByte();
    c = m_stream->readByte(); 
    dcPtr->Pt = c & 0x0F;
}
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310

/*
 *--------------------------------------------------------------
 *
 * GetSoi --
 *
 *	Process an SOI marker
 *
 * Results:
 *	None.
 *
 * Side effects:
 *	Bitstream is parsed.
 *	Exits on error.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1311 1312 1313 1314 1315 1316 1317 1318 1319
static inline void
GetSoi (DecompressInfo *dcPtr)
{

    /*
     * Reset all parameters that are defined to be reset by SOI
     */
    dcPtr->restartInterval = 0;
}
1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336

/*
 *--------------------------------------------------------------
 *
 * NextMarker --
 *
 *      Find the next JPEG marker Note that the output might not
 *	be a valid marker code but it will never be 0 or FF
 *
 * Results:
 *	The marker found.
 *
 * Side effects:
 *	Bitstream is parsed.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
static int32_t
NextMarker(IO::Stream *s)
{
    int32_t c;

    do {
        /*
         * skip any non-FF bytes
         */
        do {
            c = s->readByte();
        } while (c != 0xFF);
        /*
         * skip any duplicate FFs without incrementing nbytes, since
         * extra FFs are legal
         */
        do {
            c = s->readByte();
        } while (c == 0xFF);
    } while (c == 0);		/* repeat if it was a stuffed FF/00 */

    return c;
}
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376

/*
 *--------------------------------------------------------------
 *
 * ProcessTables --
 *
 *	Scan and process JPEG markers that can appear in any order
 *	Return when an SOI, EOI, SOFn, or SOS is found
 *
 * Results:
 *	The marker found.
 *
 * Side effects:
 *	Bitstream is parsed.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409
LJpegDecompressor::JpegMarker
LJpegDecompressor::ProcessTables (DecompressInfo *dcPtr)
{
    int c;

    while (1) {
        c = NextMarker (m_stream);

        switch (c) {
        case M_SOF0:
        case M_SOF1:
        case M_SOF2:
        case M_SOF3:
        case M_SOF5:
        case M_SOF6:
        case M_SOF7:
        case M_JPG:
        case M_SOF9:
        case M_SOF10:
        case M_SOF11:
        case M_SOF13:
        case M_SOF14:
        case M_SOF15:
        case M_SOI:
        case M_EOI:
        case M_SOS:
            return ((JpegMarker)c);

        case M_DHT:
            GetDht (dcPtr);
            break;

        case M_DQT:
Hubert Figuiere's avatar
Hubert Figuiere committed
1410
            LOGWARN("Not a lossless JPEG file.\n");
Hubert Figuiere's avatar
Hubert Figuiere committed
1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
            break;

        case M_DRI:
            GetDri (dcPtr);
            break;

        case M_APP0:
            GetApp0(m_stream);
            break;

        case M_RST0:		/* these are all parameterless */
        case M_RST1:
        case M_RST2:
        case M_RST3:
        case M_RST4:
        case M_RST5:
        case M_RST6:
        case M_RST7:
        case M_TEM:
Hubert Figuiere's avatar
Hubert Figuiere committed
1430
            LOGWARN("Warning: unexpected marker 0x%x", c);
Hubert Figuiere's avatar
Hubert Figuiere committed
1431 1432 1433 1434 1435 1436 1437 1438 1439
            break;

        default:		/* must be DNL, DHP, EXP, APPn, JPGn, COM,
                         * or RESn */
            SkipVariable (m_stream);
            break;
        }
    }
}
1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456

/*
 *--------------------------------------------------------------
 *
 * ReadFileHeader --
 *
 *	Initialize and read the file header (everything through
 *	the SOF marker).
 *
 * Results:
 *	None
 *
 * Side effects:
 *	Exit on error.
 *
 *--------------------------------------------------------------
 */
Hubert Figuiere's avatar
Hubert Figuiere committed
1457 1458
void
LJpegDecompressor::ReadFileHeader (DecompressInfo *dcPtr)
1459
    noexcept(false)
Hubert Figuiere's avatar
Hubert Figuiere committed
1460 1461
{
    int c, c2;
1462

Hubert Figuiere's avatar
Hubert Figuiere committed
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    /*
     * Demand an SOI marker at the start of the file --- otherwise it's
     * probably not a JPEG file at all.
     */
    c = m_stream->readByte();
    c2 = m_stream->readByte();
    if ((c != 0xFF) || (c2 != M_SOI)) {
        throw DecodingException(str(boost::format("Not a JPEG file. "
                                                  "marker is %1% %2%\n")
                                    % c % c2));
    }
1474

Hubert Figuiere's avatar
Hubert Figuiere committed
1475
    GetSoi (dcPtr