reader.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795
  1. // Copyright 2019 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. //go:generate go run gen.go
  5. // Package ccitt implements a CCITT (fax) image decoder.
  6. package ccitt
  7. import (
  8. "encoding/binary"
  9. "errors"
  10. "image"
  11. "io"
  12. "math/bits"
  13. )
  14. var (
  15. errIncompleteCode = errors.New("ccitt: incomplete code")
  16. errInvalidBounds = errors.New("ccitt: invalid bounds")
  17. errInvalidCode = errors.New("ccitt: invalid code")
  18. errInvalidMode = errors.New("ccitt: invalid mode")
  19. errInvalidOffset = errors.New("ccitt: invalid offset")
  20. errMissingEOL = errors.New("ccitt: missing End-of-Line")
  21. errRunLengthOverflowsWidth = errors.New("ccitt: run length overflows width")
  22. errRunLengthTooLong = errors.New("ccitt: run length too long")
  23. errUnsupportedMode = errors.New("ccitt: unsupported mode")
  24. errUnsupportedSubFormat = errors.New("ccitt: unsupported sub-format")
  25. errUnsupportedWidth = errors.New("ccitt: unsupported width")
  26. )
  27. // Order specifies the bit ordering in a CCITT data stream.
  28. type Order uint32
  29. const (
  30. // LSB means Least Significant Bits first.
  31. LSB Order = iota
  32. // MSB means Most Significant Bits first.
  33. MSB
  34. )
  35. // SubFormat represents that the CCITT format consists of a number of
  36. // sub-formats. Decoding or encoding a CCITT data stream requires knowing the
  37. // sub-format context. It is not represented in the data stream per se.
  38. type SubFormat uint32
  39. const (
  40. Group3 SubFormat = iota
  41. Group4
  42. )
  43. // AutoDetectHeight is passed as the height argument to NewReader to indicate
  44. // that the image height (the number of rows) is not known in advance.
  45. const AutoDetectHeight = -1
  46. // Options are optional parameters.
  47. type Options struct {
  48. // Align means that some variable-bit-width codes are byte-aligned.
  49. Align bool
  50. // Invert means that black is the 1 bit or 0xFF byte, and white is 0.
  51. Invert bool
  52. }
  53. // maxWidth is the maximum (inclusive) supported width. This is a limitation of
  54. // this implementation, to guard against integer overflow, and not anything
  55. // inherent to the CCITT format.
  56. const maxWidth = 1 << 20
  57. func invertBytes(b []byte) {
  58. for i, c := range b {
  59. b[i] = ^c
  60. }
  61. }
  62. func reverseBitsWithinBytes(b []byte) {
  63. for i, c := range b {
  64. b[i] = bits.Reverse8(c)
  65. }
  66. }
  67. // highBits writes to dst (1 bit per pixel, most significant bit first) the
  68. // high (0x80) bits from src (1 byte per pixel). It returns the number of bytes
  69. // written and read such that dst[:d] is the packed form of src[:s].
  70. //
  71. // For example, if src starts with the 8 bytes [0x7D, 0x7E, 0x7F, 0x80, 0x81,
  72. // 0x82, 0x00, 0xFF] then 0x1D will be written to dst[0].
  73. //
  74. // If src has (8 * len(dst)) or more bytes then only len(dst) bytes are
  75. // written, (8 * len(dst)) bytes are read, and invert is ignored.
  76. //
  77. // Otherwise, if len(src) is not a multiple of 8 then the final byte written to
  78. // dst is padded with 1 bits (if invert is true) or 0 bits. If inverted, the 1s
  79. // are typically temporary, e.g. they will be flipped back to 0s by an
  80. // invertBytes call in the highBits caller, reader.Read.
  81. func highBits(dst []byte, src []byte, invert bool) (d int, s int) {
  82. // Pack as many complete groups of 8 src bytes as we can.
  83. n := len(src) / 8
  84. if n > len(dst) {
  85. n = len(dst)
  86. }
  87. dstN := dst[:n]
  88. for i := range dstN {
  89. src8 := src[i*8 : i*8+8]
  90. dstN[i] = ((src8[0] & 0x80) >> 0) |
  91. ((src8[1] & 0x80) >> 1) |
  92. ((src8[2] & 0x80) >> 2) |
  93. ((src8[3] & 0x80) >> 3) |
  94. ((src8[4] & 0x80) >> 4) |
  95. ((src8[5] & 0x80) >> 5) |
  96. ((src8[6] & 0x80) >> 6) |
  97. ((src8[7] & 0x80) >> 7)
  98. }
  99. d, s = n, 8*n
  100. dst, src = dst[d:], src[s:]
  101. // Pack up to 7 remaining src bytes, if there's room in dst.
  102. if (len(dst) > 0) && (len(src) > 0) {
  103. dstByte := byte(0)
  104. if invert {
  105. dstByte = 0xFF >> uint(len(src))
  106. }
  107. for n, srcByte := range src {
  108. dstByte |= (srcByte & 0x80) >> uint(n)
  109. }
  110. dst[0] = dstByte
  111. d, s = d+1, s+len(src)
  112. }
  113. return d, s
  114. }
  115. type bitReader struct {
  116. r io.Reader
  117. // readErr is the error returned from the most recent r.Read call. As the
  118. // io.Reader documentation says, when r.Read returns (n, err), "always
  119. // process the n > 0 bytes returned before considering the error err".
  120. readErr error
  121. // order is whether to process r's bytes LSB first or MSB first.
  122. order Order
  123. // The high nBits bits of the bits field hold upcoming bits in MSB order.
  124. bits uint64
  125. nBits uint32
  126. // bytes[br:bw] holds bytes read from r but not yet loaded into bits.
  127. br uint32
  128. bw uint32
  129. bytes [1024]uint8
  130. }
  131. func (b *bitReader) alignToByteBoundary() {
  132. n := b.nBits & 7
  133. b.bits <<= n
  134. b.nBits -= n
  135. }
  136. // nextBitMaxNBits is the maximum possible value of bitReader.nBits after a
  137. // bitReader.nextBit call, provided that bitReader.nBits was not more than this
  138. // value before that call.
  139. //
  140. // Note that the decode function can unread bits, which can temporarily set the
  141. // bitReader.nBits value above nextBitMaxNBits.
  142. const nextBitMaxNBits = 31
  143. func (b *bitReader) nextBit() (uint64, error) {
  144. for {
  145. if b.nBits > 0 {
  146. bit := b.bits >> 63
  147. b.bits <<= 1
  148. b.nBits--
  149. return bit, nil
  150. }
  151. if available := b.bw - b.br; available >= 4 {
  152. // Read 32 bits, even though b.bits is a uint64, since the decode
  153. // function may need to unread up to maxCodeLength bits, putting
  154. // them back in the remaining (64 - 32) bits. TestMaxCodeLength
  155. // checks that the generated maxCodeLength constant fits.
  156. //
  157. // If changing the Uint32 call, also change nextBitMaxNBits.
  158. b.bits = uint64(binary.BigEndian.Uint32(b.bytes[b.br:])) << 32
  159. b.br += 4
  160. b.nBits = 32
  161. continue
  162. } else if available > 0 {
  163. b.bits = uint64(b.bytes[b.br]) << (7 * 8)
  164. b.br++
  165. b.nBits = 8
  166. continue
  167. }
  168. if b.readErr != nil {
  169. return 0, b.readErr
  170. }
  171. n, err := b.r.Read(b.bytes[:])
  172. b.br = 0
  173. b.bw = uint32(n)
  174. b.readErr = err
  175. if b.order != MSB {
  176. reverseBitsWithinBytes(b.bytes[:b.bw])
  177. }
  178. }
  179. }
  180. func decode(b *bitReader, decodeTable [][2]int16) (uint32, error) {
  181. nBitsRead, bitsRead, state := uint32(0), uint64(0), int32(1)
  182. for {
  183. bit, err := b.nextBit()
  184. if err != nil {
  185. if err == io.EOF {
  186. err = errIncompleteCode
  187. }
  188. return 0, err
  189. }
  190. bitsRead |= bit << (63 - nBitsRead)
  191. nBitsRead++
  192. // The "&1" is redundant, but can eliminate a bounds check.
  193. state = int32(decodeTable[state][bit&1])
  194. if state < 0 {
  195. return uint32(^state), nil
  196. } else if state == 0 {
  197. // Unread the bits we've read, then return errInvalidCode.
  198. b.bits = (b.bits >> nBitsRead) | bitsRead
  199. b.nBits += nBitsRead
  200. return 0, errInvalidCode
  201. }
  202. }
  203. }
  204. // decodeEOL decodes the 12-bit EOL code 0000_0000_0001.
  205. func decodeEOL(b *bitReader) error {
  206. nBitsRead, bitsRead := uint32(0), uint64(0)
  207. for {
  208. bit, err := b.nextBit()
  209. if err != nil {
  210. if err == io.EOF {
  211. err = errMissingEOL
  212. }
  213. return err
  214. }
  215. bitsRead |= bit << (63 - nBitsRead)
  216. nBitsRead++
  217. if nBitsRead < 12 {
  218. if bit&1 == 0 {
  219. continue
  220. }
  221. } else if bit&1 != 0 {
  222. return nil
  223. }
  224. // Unread the bits we've read, then return errMissingEOL.
  225. b.bits = (b.bits >> nBitsRead) | bitsRead
  226. b.nBits += nBitsRead
  227. return errMissingEOL
  228. }
  229. }
  230. type reader struct {
  231. br bitReader
  232. subFormat SubFormat
  233. // width is the image width in pixels.
  234. width int
  235. // rowsRemaining starts at the image height in pixels, when the reader is
  236. // driven through the io.Reader interface, and decrements to zero as rows
  237. // are decoded. Alternatively, it may be negative if the image height is
  238. // not known in advance at the time of the NewReader call.
  239. //
  240. // When driven through DecodeIntoGray, this field is unused.
  241. rowsRemaining int
  242. // curr and prev hold the current and previous rows. Each element is either
  243. // 0x00 (black) or 0xFF (white).
  244. //
  245. // prev may be nil, when processing the first row.
  246. curr []byte
  247. prev []byte
  248. // ri is the read index. curr[:ri] are those bytes of curr that have been
  249. // passed along via the Read method.
  250. //
  251. // When the reader is driven through DecodeIntoGray, instead of through the
  252. // io.Reader interface, this field is unused.
  253. ri int
  254. // wi is the write index. curr[:wi] are those bytes of curr that have
  255. // already been decoded via the decodeRow method.
  256. //
  257. // What this implementation calls wi is roughly equivalent to what the spec
  258. // calls the a0 index.
  259. wi int
  260. // These fields are copied from the *Options (which may be nil).
  261. align bool
  262. invert bool
  263. // atStartOfRow is whether we have just started the row. Some parts of the
  264. // spec say to treat this situation as if "wi = -1".
  265. atStartOfRow bool
  266. // penColorIsWhite is whether the next run is black or white.
  267. penColorIsWhite bool
  268. // seenStartOfImage is whether we've called the startDecode method.
  269. seenStartOfImage bool
  270. // truncated is whether the input is missing the final 6 consecutive EOL's
  271. // (for Group3) or 2 consecutive EOL's (for Group4). Omitting that trailer
  272. // (but otherwise padding to a byte boundary, with either all 0 bits or all
  273. // 1 bits) is invalid according to the spec, but happens in practice when
  274. // exporting from Adobe Acrobat to TIFF + CCITT. This package silently
  275. // ignores the format error for CCITT input that has been truncated in that
  276. // fashion, returning the full decoded image.
  277. //
  278. // Detecting trailer truncation (just after the final row of pixels)
  279. // requires knowing which row is the final row, and therefore does not
  280. // trigger if the image height is not known in advance.
  281. truncated bool
  282. // readErr is a sticky error for the Read method.
  283. readErr error
  284. }
  285. func (z *reader) Read(p []byte) (int, error) {
  286. if z.readErr != nil {
  287. return 0, z.readErr
  288. }
  289. originalP := p
  290. for len(p) > 0 {
  291. // Allocate buffers (and decode any start-of-image codes), if
  292. // processing the first or second row.
  293. if z.curr == nil {
  294. if !z.seenStartOfImage {
  295. if z.readErr = z.startDecode(); z.readErr != nil {
  296. break
  297. }
  298. z.atStartOfRow = true
  299. }
  300. z.curr = make([]byte, z.width)
  301. }
  302. // Decode the next row, if necessary.
  303. if z.atStartOfRow {
  304. if z.rowsRemaining < 0 {
  305. // We do not know the image height in advance. See if the next
  306. // code is an EOL. If it is, it is consumed. If it isn't, the
  307. // bitReader shouldn't advance along the bit stream, and we
  308. // simply decode another row of pixel data.
  309. //
  310. // For the Group4 subFormat, we may need to align to a byte
  311. // boundary. For the Group3 subFormat, the previous z.decodeRow
  312. // call (or z.startDecode call) has already consumed one of the
  313. // 6 consecutive EOL's. The next EOL is actually the second of
  314. // 6, in the middle, and we shouldn't align at that point.
  315. if z.align && (z.subFormat == Group4) {
  316. z.br.alignToByteBoundary()
  317. }
  318. if err := z.decodeEOL(); err == errMissingEOL {
  319. // No-op. It's another row of pixel data.
  320. } else if err != nil {
  321. z.readErr = err
  322. break
  323. } else {
  324. if z.readErr = z.finishDecode(true); z.readErr != nil {
  325. break
  326. }
  327. z.readErr = io.EOF
  328. break
  329. }
  330. } else if z.rowsRemaining == 0 {
  331. // We do know the image height in advance, and we have already
  332. // decoded exactly that many rows.
  333. if z.readErr = z.finishDecode(false); z.readErr != nil {
  334. break
  335. }
  336. z.readErr = io.EOF
  337. break
  338. } else {
  339. z.rowsRemaining--
  340. }
  341. if z.readErr = z.decodeRow(z.rowsRemaining == 0); z.readErr != nil {
  342. break
  343. }
  344. }
  345. // Pack from z.curr (1 byte per pixel) to p (1 bit per pixel).
  346. packD, packS := highBits(p, z.curr[z.ri:], z.invert)
  347. p = p[packD:]
  348. z.ri += packS
  349. // Prepare to decode the next row, if necessary.
  350. if z.ri == len(z.curr) {
  351. z.ri, z.curr, z.prev = 0, z.prev, z.curr
  352. z.atStartOfRow = true
  353. }
  354. }
  355. n := len(originalP) - len(p)
  356. if z.invert {
  357. invertBytes(originalP[:n])
  358. }
  359. return n, z.readErr
  360. }
  361. func (z *reader) penColor() byte {
  362. if z.penColorIsWhite {
  363. return 0xFF
  364. }
  365. return 0x00
  366. }
  367. func (z *reader) startDecode() error {
  368. switch z.subFormat {
  369. case Group3:
  370. if err := z.decodeEOL(); err != nil {
  371. return err
  372. }
  373. case Group4:
  374. // No-op.
  375. default:
  376. return errUnsupportedSubFormat
  377. }
  378. z.seenStartOfImage = true
  379. return nil
  380. }
  381. func (z *reader) finishDecode(alreadySeenEOL bool) error {
  382. numberOfEOLs := 0
  383. switch z.subFormat {
  384. case Group3:
  385. if z.truncated {
  386. return nil
  387. }
  388. // The stream ends with a RTC (Return To Control) of 6 consecutive
  389. // EOL's, but we should have already just seen an EOL, either in
  390. // z.startDecode (for a zero-height image) or in z.decodeRow.
  391. numberOfEOLs = 5
  392. case Group4:
  393. autoDetectHeight := z.rowsRemaining < 0
  394. if autoDetectHeight {
  395. // Aligning to a byte boundary was already handled by reader.Read.
  396. } else if z.align {
  397. z.br.alignToByteBoundary()
  398. }
  399. // The stream ends with two EOL's. If the first one is missing, and we
  400. // had an explicit image height, we just assume that the trailing two
  401. // EOL's were truncated and return a nil error.
  402. if err := z.decodeEOL(); err != nil {
  403. if (err == errMissingEOL) && !autoDetectHeight {
  404. z.truncated = true
  405. return nil
  406. }
  407. return err
  408. }
  409. numberOfEOLs = 1
  410. default:
  411. return errUnsupportedSubFormat
  412. }
  413. if alreadySeenEOL {
  414. numberOfEOLs--
  415. }
  416. for ; numberOfEOLs > 0; numberOfEOLs-- {
  417. if err := z.decodeEOL(); err != nil {
  418. return err
  419. }
  420. }
  421. return nil
  422. }
  423. func (z *reader) decodeEOL() error {
  424. return decodeEOL(&z.br)
  425. }
  426. func (z *reader) decodeRow(finalRow bool) error {
  427. z.wi = 0
  428. z.atStartOfRow = true
  429. z.penColorIsWhite = true
  430. if z.align {
  431. z.br.alignToByteBoundary()
  432. }
  433. switch z.subFormat {
  434. case Group3:
  435. for ; z.wi < len(z.curr); z.atStartOfRow = false {
  436. if err := z.decodeRun(); err != nil {
  437. return err
  438. }
  439. }
  440. err := z.decodeEOL()
  441. if finalRow && (err == errMissingEOL) {
  442. z.truncated = true
  443. return nil
  444. }
  445. return err
  446. case Group4:
  447. for ; z.wi < len(z.curr); z.atStartOfRow = false {
  448. mode, err := decode(&z.br, modeDecodeTable[:])
  449. if err != nil {
  450. return err
  451. }
  452. rm := readerMode{}
  453. if mode < uint32(len(readerModes)) {
  454. rm = readerModes[mode]
  455. }
  456. if rm.function == nil {
  457. return errInvalidMode
  458. }
  459. if err := rm.function(z, rm.arg); err != nil {
  460. return err
  461. }
  462. }
  463. return nil
  464. }
  465. return errUnsupportedSubFormat
  466. }
  467. func (z *reader) decodeRun() error {
  468. table := blackDecodeTable[:]
  469. if z.penColorIsWhite {
  470. table = whiteDecodeTable[:]
  471. }
  472. total := 0
  473. for {
  474. n, err := decode(&z.br, table)
  475. if err != nil {
  476. return err
  477. }
  478. if n > maxWidth {
  479. panic("unreachable")
  480. }
  481. total += int(n)
  482. if total > maxWidth {
  483. return errRunLengthTooLong
  484. }
  485. // Anything 0x3F or below is a terminal code.
  486. if n <= 0x3F {
  487. break
  488. }
  489. }
  490. if total > (len(z.curr) - z.wi) {
  491. return errRunLengthOverflowsWidth
  492. }
  493. dst := z.curr[z.wi : z.wi+total]
  494. penColor := z.penColor()
  495. for i := range dst {
  496. dst[i] = penColor
  497. }
  498. z.wi += total
  499. z.penColorIsWhite = !z.penColorIsWhite
  500. return nil
  501. }
  502. // The various modes' semantics are based on determining a row of pixels'
  503. // "changing elements": those pixels whose color differs from the one on its
  504. // immediate left.
  505. //
  506. // The row above the first row is implicitly all white. Similarly, the column
  507. // to the left of the first column is implicitly all white.
  508. //
  509. // For example, here's Figure 1 in "ITU-T Recommendation T.6", where the
  510. // current and previous rows contain black (B) and white (w) pixels. The a?
  511. // indexes point into curr, the b? indexes point into prev.
  512. //
  513. // b1 b2
  514. // v v
  515. // prev: BBBBBwwwwwBBBwwwww
  516. // curr: BBBwwwwwBBBBBBwwww
  517. // ^ ^ ^
  518. // a0 a1 a2
  519. //
  520. // a0 is the "reference element" or current decoder position, roughly
  521. // equivalent to what this implementation calls reader.wi.
  522. //
  523. // a1 is the next changing element to the right of a0, on the "coding line"
  524. // (the current row).
  525. //
  526. // a2 is the next changing element to the right of a1, again on curr.
  527. //
  528. // b1 is the first changing element on the "reference line" (the previous row)
  529. // to the right of a0 and of opposite color to a0.
  530. //
  531. // b2 is the next changing element to the right of b1, again on prev.
  532. //
  533. // The various modes calculate a1 (and a2, for modeH):
  534. // - modePass calculates that a1 is at or to the right of b2.
  535. // - modeH calculates a1 and a2 without considering b1 or b2.
  536. // - modeV* calculates a1 to be b1 plus an adjustment (between -3 and +3).
  537. const (
  538. findB1 = false
  539. findB2 = true
  540. )
  541. // findB finds either the b1 or b2 value.
  542. func (z *reader) findB(whichB bool) int {
  543. // The initial row is a special case. The previous row is implicitly all
  544. // white, so that there are no changing pixel elements. We return b1 or b2
  545. // to be at the end of the row.
  546. if len(z.prev) != len(z.curr) {
  547. return len(z.curr)
  548. }
  549. i := z.wi
  550. if z.atStartOfRow {
  551. // a0 is implicitly at -1, on a white pixel. b1 is the first black
  552. // pixel in the previous row. b2 is the first white pixel after that.
  553. for ; (i < len(z.prev)) && (z.prev[i] == 0xFF); i++ {
  554. }
  555. if whichB == findB2 {
  556. for ; (i < len(z.prev)) && (z.prev[i] == 0x00); i++ {
  557. }
  558. }
  559. return i
  560. }
  561. // As per figure 1 above, assume that the current pen color is white.
  562. // First, walk past every contiguous black pixel in prev, starting at a0.
  563. oppositeColor := ^z.penColor()
  564. for ; (i < len(z.prev)) && (z.prev[i] == oppositeColor); i++ {
  565. }
  566. // Then walk past every contiguous white pixel.
  567. penColor := ^oppositeColor
  568. for ; (i < len(z.prev)) && (z.prev[i] == penColor); i++ {
  569. }
  570. // We're now at a black pixel (or at the end of the row). That's b1.
  571. if whichB == findB2 {
  572. // If we're looking for b2, walk past every contiguous black pixel
  573. // again.
  574. oppositeColor := ^penColor
  575. for ; (i < len(z.prev)) && (z.prev[i] == oppositeColor); i++ {
  576. }
  577. }
  578. return i
  579. }
  580. type readerMode struct {
  581. function func(z *reader, arg int) error
  582. arg int
  583. }
  584. var readerModes = [...]readerMode{
  585. modePass: {function: readerModePass},
  586. modeH: {function: readerModeH},
  587. modeV0: {function: readerModeV, arg: +0},
  588. modeVR1: {function: readerModeV, arg: +1},
  589. modeVR2: {function: readerModeV, arg: +2},
  590. modeVR3: {function: readerModeV, arg: +3},
  591. modeVL1: {function: readerModeV, arg: -1},
  592. modeVL2: {function: readerModeV, arg: -2},
  593. modeVL3: {function: readerModeV, arg: -3},
  594. modeExt: {function: readerModeExt},
  595. }
  596. func readerModePass(z *reader, arg int) error {
  597. b2 := z.findB(findB2)
  598. if (b2 < z.wi) || (len(z.curr) < b2) {
  599. return errInvalidOffset
  600. }
  601. dst := z.curr[z.wi:b2]
  602. penColor := z.penColor()
  603. for i := range dst {
  604. dst[i] = penColor
  605. }
  606. z.wi = b2
  607. return nil
  608. }
  609. func readerModeH(z *reader, arg int) error {
  610. // The first iteration finds a1. The second finds a2.
  611. for i := 0; i < 2; i++ {
  612. if err := z.decodeRun(); err != nil {
  613. return err
  614. }
  615. }
  616. return nil
  617. }
  618. func readerModeV(z *reader, arg int) error {
  619. a1 := z.findB(findB1) + arg
  620. if (a1 < z.wi) || (len(z.curr) < a1) {
  621. return errInvalidOffset
  622. }
  623. dst := z.curr[z.wi:a1]
  624. penColor := z.penColor()
  625. for i := range dst {
  626. dst[i] = penColor
  627. }
  628. z.wi = a1
  629. z.penColorIsWhite = !z.penColorIsWhite
  630. return nil
  631. }
  632. func readerModeExt(z *reader, arg int) error {
  633. return errUnsupportedMode
  634. }
  635. // DecodeIntoGray decodes the CCITT-formatted data in r into dst.
  636. //
  637. // It returns an error if dst's width and height don't match the implied width
  638. // and height of CCITT-formatted data.
  639. func DecodeIntoGray(dst *image.Gray, r io.Reader, order Order, sf SubFormat, opts *Options) error {
  640. bounds := dst.Bounds()
  641. if (bounds.Dx() < 0) || (bounds.Dy() < 0) {
  642. return errInvalidBounds
  643. }
  644. if bounds.Dx() > maxWidth {
  645. return errUnsupportedWidth
  646. }
  647. z := reader{
  648. br: bitReader{r: r, order: order},
  649. subFormat: sf,
  650. align: (opts != nil) && opts.Align,
  651. invert: (opts != nil) && opts.Invert,
  652. width: bounds.Dx(),
  653. }
  654. if err := z.startDecode(); err != nil {
  655. return err
  656. }
  657. width := bounds.Dx()
  658. for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
  659. p := (y - bounds.Min.Y) * dst.Stride
  660. z.curr = dst.Pix[p : p+width]
  661. if err := z.decodeRow(y+1 == bounds.Max.Y); err != nil {
  662. return err
  663. }
  664. z.curr, z.prev = nil, z.curr
  665. }
  666. if err := z.finishDecode(false); err != nil {
  667. return err
  668. }
  669. if z.invert {
  670. for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
  671. p := (y - bounds.Min.Y) * dst.Stride
  672. invertBytes(dst.Pix[p : p+width])
  673. }
  674. }
  675. return nil
  676. }
  677. // NewReader returns an io.Reader that decodes the CCITT-formatted data in r.
  678. // The resultant byte stream is one bit per pixel (MSB first), with 1 meaning
  679. // white and 0 meaning black. Each row in the result is byte-aligned.
  680. //
  681. // A negative height, such as passing AutoDetectHeight, means that the image
  682. // height is not known in advance. A negative width is invalid.
  683. func NewReader(r io.Reader, order Order, sf SubFormat, width int, height int, opts *Options) io.Reader {
  684. readErr := error(nil)
  685. if width < 0 {
  686. readErr = errInvalidBounds
  687. } else if width > maxWidth {
  688. readErr = errUnsupportedWidth
  689. }
  690. return &reader{
  691. br: bitReader{r: r, order: order},
  692. subFormat: sf,
  693. align: (opts != nil) && opts.Align,
  694. invert: (opts != nil) && opts.Invert,
  695. width: width,
  696. rowsRemaining: height,
  697. readErr: readErr,
  698. }
  699. }