github.com/rohankumardubey/syslog-redirector-golang@v0.0.0-20140320174030-4859f03d829a/src/pkg/image/jpeg/scan.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package jpeg
     6  
     7  import (
     8  	"image"
     9  	"io"
    10  )
    11  
    12  // makeImg allocates and initializes the destination image.
    13  func (d *decoder) makeImg(h0, v0, mxx, myy int) {
    14  	if d.nComp == nGrayComponent {
    15  		m := image.NewGray(image.Rect(0, 0, 8*mxx, 8*myy))
    16  		d.img1 = m.SubImage(image.Rect(0, 0, d.width, d.height)).(*image.Gray)
    17  		return
    18  	}
    19  	var subsampleRatio image.YCbCrSubsampleRatio
    20  	switch {
    21  	case h0 == 1 && v0 == 1:
    22  		subsampleRatio = image.YCbCrSubsampleRatio444
    23  	case h0 == 1 && v0 == 2:
    24  		subsampleRatio = image.YCbCrSubsampleRatio440
    25  	case h0 == 2 && v0 == 1:
    26  		subsampleRatio = image.YCbCrSubsampleRatio422
    27  	case h0 == 2 && v0 == 2:
    28  		subsampleRatio = image.YCbCrSubsampleRatio420
    29  	default:
    30  		panic("unreachable")
    31  	}
    32  	m := image.NewYCbCr(image.Rect(0, 0, 8*h0*mxx, 8*v0*myy), subsampleRatio)
    33  	d.img3 = m.SubImage(image.Rect(0, 0, d.width, d.height)).(*image.YCbCr)
    34  }
    35  
    36  // Specified in section B.2.3.
    37  func (d *decoder) processSOS(n int) error {
    38  	if d.nComp == 0 {
    39  		return FormatError("missing SOF marker")
    40  	}
    41  	if n < 6 || 4+2*d.nComp < n || n%2 != 0 {
    42  		return FormatError("SOS has wrong length")
    43  	}
    44  	_, err := io.ReadFull(d.r, d.tmp[:n])
    45  	if err != nil {
    46  		return err
    47  	}
    48  	nComp := int(d.tmp[0])
    49  	if n != 4+2*nComp {
    50  		return FormatError("SOS length inconsistent with number of components")
    51  	}
    52  	var scan [nColorComponent]struct {
    53  		compIndex uint8
    54  		td        uint8 // DC table selector.
    55  		ta        uint8 // AC table selector.
    56  	}
    57  	for i := 0; i < nComp; i++ {
    58  		cs := d.tmp[1+2*i] // Component selector.
    59  		compIndex := -1
    60  		for j, comp := range d.comp {
    61  			if cs == comp.c {
    62  				compIndex = j
    63  			}
    64  		}
    65  		if compIndex < 0 {
    66  			return FormatError("unknown component selector")
    67  		}
    68  		scan[i].compIndex = uint8(compIndex)
    69  		scan[i].td = d.tmp[2+2*i] >> 4
    70  		scan[i].ta = d.tmp[2+2*i] & 0x0f
    71  	}
    72  
    73  	// zigStart and zigEnd are the spectral selection bounds.
    74  	// ah and al are the successive approximation high and low values.
    75  	// The spec calls these values Ss, Se, Ah and Al.
    76  	//
    77  	// For progressive JPEGs, these are the two more-or-less independent
    78  	// aspects of progression. Spectral selection progression is when not
    79  	// all of a block's 64 DCT coefficients are transmitted in one pass.
    80  	// For example, three passes could transmit coefficient 0 (the DC
    81  	// component), coefficients 1-5, and coefficients 6-63, in zig-zag
    82  	// order. Successive approximation is when not all of the bits of a
    83  	// band of coefficients are transmitted in one pass. For example,
    84  	// three passes could transmit the 6 most significant bits, followed
    85  	// by the second-least significant bit, followed by the least
    86  	// significant bit.
    87  	//
    88  	// For baseline JPEGs, these parameters are hard-coded to 0/63/0/0.
    89  	zigStart, zigEnd, ah, al := int32(0), int32(blockSize-1), uint32(0), uint32(0)
    90  	if d.progressive {
    91  		zigStart = int32(d.tmp[1+2*nComp])
    92  		zigEnd = int32(d.tmp[2+2*nComp])
    93  		ah = uint32(d.tmp[3+2*nComp] >> 4)
    94  		al = uint32(d.tmp[3+2*nComp] & 0x0f)
    95  		if (zigStart == 0 && zigEnd != 0) || zigStart > zigEnd || blockSize <= zigEnd {
    96  			return FormatError("bad spectral selection bounds")
    97  		}
    98  		if zigStart != 0 && nComp != 1 {
    99  			return FormatError("progressive AC coefficients for more than one component")
   100  		}
   101  		if ah != 0 && ah != al+1 {
   102  			return FormatError("bad successive approximation values")
   103  		}
   104  	}
   105  
   106  	// mxx and myy are the number of MCUs (Minimum Coded Units) in the image.
   107  	h0, v0 := d.comp[0].h, d.comp[0].v // The h and v values from the Y components.
   108  	mxx := (d.width + 8*h0 - 1) / (8 * h0)
   109  	myy := (d.height + 8*v0 - 1) / (8 * v0)
   110  	if d.img1 == nil && d.img3 == nil {
   111  		d.makeImg(h0, v0, mxx, myy)
   112  	}
   113  	if d.progressive {
   114  		for i := 0; i < nComp; i++ {
   115  			compIndex := scan[i].compIndex
   116  			if d.progCoeffs[compIndex] == nil {
   117  				d.progCoeffs[compIndex] = make([]block, mxx*myy*d.comp[compIndex].h*d.comp[compIndex].v)
   118  			}
   119  		}
   120  	}
   121  
   122  	d.b = bits{}
   123  	mcu, expectedRST := 0, uint8(rst0Marker)
   124  	var (
   125  		// b is the decoded coefficients, in natural (not zig-zag) order.
   126  		b  block
   127  		dc [nColorComponent]int32
   128  		// mx0 and my0 are the location of the current (in terms of 8x8 blocks).
   129  		// For example, with 4:2:0 chroma subsampling, the block whose top left
   130  		// pixel co-ordinates are (16, 8) is the third block in the first row:
   131  		// mx0 is 2 and my0 is 0, even though the pixel is in the second MCU.
   132  		// TODO(nigeltao): rename mx0 and my0 to bx and by?
   133  		mx0, my0   int
   134  		blockCount int
   135  	)
   136  	for my := 0; my < myy; my++ {
   137  		for mx := 0; mx < mxx; mx++ {
   138  			for i := 0; i < nComp; i++ {
   139  				compIndex := scan[i].compIndex
   140  				qt := &d.quant[d.comp[compIndex].tq]
   141  				for j := 0; j < d.comp[compIndex].h*d.comp[compIndex].v; j++ {
   142  					// The blocks are traversed one MCU at a time. For 4:2:0 chroma
   143  					// subsampling, there are four Y 8x8 blocks in every 16x16 MCU.
   144  					// For a baseline 32x16 pixel image, the Y blocks visiting order is:
   145  					//	0 1 4 5
   146  					//	2 3 6 7
   147  					//
   148  					// For progressive images, the DC data blocks (zigStart == 0) are traversed
   149  					// as above, but AC data blocks are traversed left to right, top to bottom:
   150  					//	0 1 2 3
   151  					//	4 5 6 7
   152  					//
   153  					// To further complicate matters, there is no AC data for any blocks that
   154  					// are inside the image at the MCU level but outside the image at the pixel
   155  					// level. For example, a 24x16 pixel 4:2:0 progressive image consists of
   156  					// two 16x16 MCUs. The earlier scans will process 8 Y blocks:
   157  					//	0 1 4 5
   158  					//	2 3 6 7
   159  					// The later scans will process only 6 Y blocks:
   160  					//	0 1 2
   161  					//	3 4 5
   162  					if zigStart == 0 {
   163  						mx0, my0 = d.comp[compIndex].h*mx, d.comp[compIndex].v*my
   164  						if h0 == 1 {
   165  							my0 += j
   166  						} else {
   167  							mx0 += j % 2
   168  							my0 += j / 2
   169  						}
   170  					} else {
   171  						q := mxx * d.comp[compIndex].h
   172  						mx0 = blockCount % q
   173  						my0 = blockCount / q
   174  						blockCount++
   175  						if mx0*8 >= d.width || my0*8 >= d.height {
   176  							continue
   177  						}
   178  					}
   179  
   180  					// Load the previous partially decoded coefficients, if applicable.
   181  					if d.progressive {
   182  						b = d.progCoeffs[compIndex][my0*mxx*d.comp[compIndex].h+mx0]
   183  					} else {
   184  						b = block{}
   185  					}
   186  
   187  					if ah != 0 {
   188  						if err := d.refine(&b, &d.huff[acTable][scan[i].ta], zigStart, zigEnd, 1<<al); err != nil {
   189  							return err
   190  						}
   191  					} else {
   192  						zig := zigStart
   193  						if zig == 0 {
   194  							zig++
   195  							// Decode the DC coefficient, as specified in section F.2.2.1.
   196  							value, err := d.decodeHuffman(&d.huff[dcTable][scan[i].td])
   197  							if err != nil {
   198  								return err
   199  							}
   200  							if value > 16 {
   201  								return UnsupportedError("excessive DC component")
   202  							}
   203  							dcDelta, err := d.receiveExtend(value)
   204  							if err != nil {
   205  								return err
   206  							}
   207  							dc[compIndex] += dcDelta
   208  							b[0] = dc[compIndex] << al
   209  						}
   210  
   211  						if zig <= zigEnd && d.eobRun > 0 {
   212  							d.eobRun--
   213  						} else {
   214  							// Decode the AC coefficients, as specified in section F.2.2.2.
   215  							for ; zig <= zigEnd; zig++ {
   216  								value, err := d.decodeHuffman(&d.huff[acTable][scan[i].ta])
   217  								if err != nil {
   218  									return err
   219  								}
   220  								val0 := value >> 4
   221  								val1 := value & 0x0f
   222  								if val1 != 0 {
   223  									zig += int32(val0)
   224  									if zig > zigEnd {
   225  										break
   226  									}
   227  									ac, err := d.receiveExtend(val1)
   228  									if err != nil {
   229  										return err
   230  									}
   231  									b[unzig[zig]] = ac << al
   232  								} else {
   233  									if val0 != 0x0f {
   234  										d.eobRun = uint16(1 << val0)
   235  										if val0 != 0 {
   236  											bits, err := d.decodeBits(int(val0))
   237  											if err != nil {
   238  												return err
   239  											}
   240  											d.eobRun |= uint16(bits)
   241  										}
   242  										d.eobRun--
   243  										break
   244  									}
   245  									zig += 0x0f
   246  								}
   247  							}
   248  						}
   249  					}
   250  
   251  					if d.progressive {
   252  						if zigEnd != blockSize-1 || al != 0 {
   253  							// We haven't completely decoded this 8x8 block. Save the coefficients.
   254  							d.progCoeffs[compIndex][my0*mxx*d.comp[compIndex].h+mx0] = b
   255  							// At this point, we could execute the rest of the loop body to dequantize and
   256  							// perform the inverse DCT, to save early stages of a progressive image to the
   257  							// *image.YCbCr buffers (the whole point of progressive encoding), but in Go,
   258  							// the jpeg.Decode function does not return until the entire image is decoded,
   259  							// so we "continue" here to avoid wasted computation.
   260  							continue
   261  						}
   262  					}
   263  
   264  					// Dequantize, perform the inverse DCT and store the block to the image.
   265  					for zig := 0; zig < blockSize; zig++ {
   266  						b[unzig[zig]] *= qt[zig]
   267  					}
   268  					idct(&b)
   269  					dst, stride := []byte(nil), 0
   270  					if d.nComp == nGrayComponent {
   271  						dst, stride = d.img1.Pix[8*(my0*d.img1.Stride+mx0):], d.img1.Stride
   272  					} else {
   273  						switch compIndex {
   274  						case 0:
   275  							dst, stride = d.img3.Y[8*(my0*d.img3.YStride+mx0):], d.img3.YStride
   276  						case 1:
   277  							dst, stride = d.img3.Cb[8*(my0*d.img3.CStride+mx0):], d.img3.CStride
   278  						case 2:
   279  							dst, stride = d.img3.Cr[8*(my0*d.img3.CStride+mx0):], d.img3.CStride
   280  						default:
   281  							return UnsupportedError("too many components")
   282  						}
   283  					}
   284  					// Level shift by +128, clip to [0, 255], and write to dst.
   285  					for y := 0; y < 8; y++ {
   286  						y8 := y * 8
   287  						yStride := y * stride
   288  						for x := 0; x < 8; x++ {
   289  							c := b[y8+x]
   290  							if c < -128 {
   291  								c = 0
   292  							} else if c > 127 {
   293  								c = 255
   294  							} else {
   295  								c += 128
   296  							}
   297  							dst[yStride+x] = uint8(c)
   298  						}
   299  					}
   300  				} // for j
   301  			} // for i
   302  			mcu++
   303  			if d.ri > 0 && mcu%d.ri == 0 && mcu < mxx*myy {
   304  				// A more sophisticated decoder could use RST[0-7] markers to resynchronize from corrupt input,
   305  				// but this one assumes well-formed input, and hence the restart marker follows immediately.
   306  				_, err := io.ReadFull(d.r, d.tmp[0:2])
   307  				if err != nil {
   308  					return err
   309  				}
   310  				if d.tmp[0] != 0xff || d.tmp[1] != expectedRST {
   311  					return FormatError("bad RST marker")
   312  				}
   313  				expectedRST++
   314  				if expectedRST == rst7Marker+1 {
   315  					expectedRST = rst0Marker
   316  				}
   317  				// Reset the Huffman decoder.
   318  				d.b = bits{}
   319  				// Reset the DC components, as per section F.2.1.3.1.
   320  				dc = [nColorComponent]int32{}
   321  				// Reset the progressive decoder state, as per section G.1.2.2.
   322  				d.eobRun = 0
   323  			}
   324  		} // for mx
   325  	} // for my
   326  
   327  	return nil
   328  }
   329  
   330  // refine decodes a successive approximation refinement block, as specified in
   331  // section G.1.2.
   332  func (d *decoder) refine(b *block, h *huffman, zigStart, zigEnd, delta int32) error {
   333  	// Refining a DC component is trivial.
   334  	if zigStart == 0 {
   335  		if zigEnd != 0 {
   336  			panic("unreachable")
   337  		}
   338  		bit, err := d.decodeBit()
   339  		if err != nil {
   340  			return err
   341  		}
   342  		if bit {
   343  			b[0] |= delta
   344  		}
   345  		return nil
   346  	}
   347  
   348  	// Refining AC components is more complicated; see sections G.1.2.2 and G.1.2.3.
   349  	zig := zigStart
   350  	if d.eobRun == 0 {
   351  	loop:
   352  		for ; zig <= zigEnd; zig++ {
   353  			z := int32(0)
   354  			value, err := d.decodeHuffman(h)
   355  			if err != nil {
   356  				return err
   357  			}
   358  			val0 := value >> 4
   359  			val1 := value & 0x0f
   360  
   361  			switch val1 {
   362  			case 0:
   363  				if val0 != 0x0f {
   364  					d.eobRun = uint16(1 << val0)
   365  					if val0 != 0 {
   366  						bits, err := d.decodeBits(int(val0))
   367  						if err != nil {
   368  							return err
   369  						}
   370  						d.eobRun |= uint16(bits)
   371  					}
   372  					break loop
   373  				}
   374  			case 1:
   375  				z = delta
   376  				bit, err := d.decodeBit()
   377  				if err != nil {
   378  					return err
   379  				}
   380  				if !bit {
   381  					z = -z
   382  				}
   383  			default:
   384  				return FormatError("unexpected Huffman code")
   385  			}
   386  
   387  			zig, err = d.refineNonZeroes(b, zig, zigEnd, int32(val0), delta)
   388  			if err != nil {
   389  				return err
   390  			}
   391  			if zig > zigEnd {
   392  				return FormatError("too many coefficients")
   393  			}
   394  			if z != 0 {
   395  				b[unzig[zig]] = z
   396  			}
   397  		}
   398  	}
   399  	if d.eobRun > 0 {
   400  		d.eobRun--
   401  		if _, err := d.refineNonZeroes(b, zig, zigEnd, -1, delta); err != nil {
   402  			return err
   403  		}
   404  	}
   405  	return nil
   406  }
   407  
   408  // refineNonZeroes refines non-zero entries of b in zig-zag order. If nz >= 0,
   409  // the first nz zero entries are skipped over.
   410  func (d *decoder) refineNonZeroes(b *block, zig, zigEnd, nz, delta int32) (int32, error) {
   411  	for ; zig <= zigEnd; zig++ {
   412  		u := unzig[zig]
   413  		if b[u] == 0 {
   414  			if nz == 0 {
   415  				break
   416  			}
   417  			nz--
   418  			continue
   419  		}
   420  		bit, err := d.decodeBit()
   421  		if err != nil {
   422  			return 0, err
   423  		}
   424  		if !bit {
   425  			continue
   426  		}
   427  		if b[u] >= 0 {
   428  			b[u] += delta
   429  		} else {
   430  			b[u] -= delta
   431  		}
   432  	}
   433  	return zig, nil
   434  }