jbig2_stream.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Copyright 2012 Mozilla Foundation
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. import { BaseStream } from "./base_stream.js";
  16. import { DecodeStream } from "./decode_stream.js";
  17. import { Dict } from "./primitives.js";
  18. import { Jbig2Image } from "./jbig2.js";
  19. import { shadow } from "../shared/util.js";
  20. /**
  21. * For JBIG2's we use a library to decode these images and
  22. * the stream behaves like all the other DecodeStreams.
  23. */
  24. class Jbig2Stream extends DecodeStream {
  25. constructor(stream, maybeLength, params) {
  26. super(maybeLength);
  27. this.stream = stream;
  28. this.dict = stream.dict;
  29. this.maybeLength = maybeLength;
  30. this.params = params;
  31. }
  32. get bytes() {
  33. // If `this.maybeLength` is null, we'll get the entire stream.
  34. return shadow(this, "bytes", this.stream.getBytes(this.maybeLength));
  35. }
  36. ensureBuffer(requested) {
  37. // No-op, since `this.readBlock` will always parse the entire image and
  38. // directly insert all of its data into `this.buffer`.
  39. }
  40. readBlock() {
  41. if (this.eof) {
  42. return;
  43. }
  44. const jbig2Image = new Jbig2Image();
  45. const chunks = [];
  46. if (this.params instanceof Dict) {
  47. const globalsStream = this.params.get("JBIG2Globals");
  48. if (globalsStream instanceof BaseStream) {
  49. const globals = globalsStream.getBytes();
  50. chunks.push({ data: globals, start: 0, end: globals.length });
  51. }
  52. }
  53. chunks.push({ data: this.bytes, start: 0, end: this.bytes.length });
  54. const data = jbig2Image.parseChunks(chunks);
  55. const dataLength = data.length;
  56. // JBIG2 had black as 1 and white as 0, inverting the colors
  57. for (let i = 0; i < dataLength; i++) {
  58. data[i] ^= 0xff;
  59. }
  60. this.buffer = data;
  61. this.bufferLength = dataLength;
  62. this.eof = true;
  63. }
  64. }
  65. export { Jbig2Stream };