BitMiracle.LibJpeg.Classic.Internal.jpeg_decomp_master.prepare_range_limit_table C# (CSharp) Method

prepare_range_limit_table() private method

Allocate and fill in the sample_range_limit table. Several decompression processes need to range-limit values to the range 0..MAXJSAMPLE; the input value may fall somewhat outside this range due to noise introduced by quantization, roundoff error, etc. These processes are inner loops and need to be as fast as possible. On most machines, particularly CPUs with pipelines or instruction prefetch, a (subscript-check-less) C table lookup x = sample_range_limit[x]; is faster than explicit tests if (x & 0) x = 0; else if (x > MAXJSAMPLE) x = MAXJSAMPLE; These processes all use a common table prepared by the routine below. For most steps we can mathematically guarantee that the initial value of x is within 2*(MAXJSAMPLE+1) of the legal range, so a table running from -2*(MAXJSAMPLE+1) to 3*MAXJSAMPLE+2 is sufficient.But for the initial limiting step(just after the IDCT), a wildly out-of-range value is possible if the input data is corrupt.To avoid any chance of indexing off the end of memory and getting a bad-pointer trap, we perform the post-IDCT limiting thus: x = (sample_range_limit - SUBSET)[(x + CENTER) & MASK]; where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit samples. Under normal circumstances this is more than enough range and a correct output will be generated; with bogus input data the mask will cause wraparound, and we will safely generate a bogus-but-in-range output. For the post-IDCT step, we want to convert the data from signed to unsigned representation by adding CENTERJSAMPLE at the same time that we limit it. This is accomplished with SUBSET = CENTER - CENTERJSAMPLE. Note that the table is allocated in near data space on PCs; it's small enough and used often enough to justify this.
private prepare_range_limit_table ( ) : void
return void
        private void prepare_range_limit_table()
        {
            byte[] table = new byte[5 * (JpegConstants.MAXJSAMPLE + 1)];
            /* First segment of range limit table: limit[x] = 0 for x < 0 */

            /* allow negative subscripts of simple table */
            int tableOffset = 2 * (JpegConstants.MAXJSAMPLE + 1);
            m_cinfo.m_sample_range_limit = table;
            m_cinfo.m_sampleRangeLimitOffset = tableOffset;

            /* Main part of range limit table: limit[x] = x */
            int i;
            for (i = 0; i <= JpegConstants.MAXJSAMPLE; i++)
                table[tableOffset + i] = (byte) i;

            /* End of range limit table: limit[x] = MAXJSAMPLE for x > MAXJSAMPLE */
            for (; i < 3 * (JpegConstants.MAXJSAMPLE + 1); i++)
                table[tableOffset + i] = JpegConstants.MAXJSAMPLE;
        }
    }