jbig2_stream.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 { isDict, isStream } from "./primitives.js";
  16. import { DecodeStream } from "./stream.js";
  17. import { Jbig2Image } from "./jbig2.js";
  18. import { shadow } from "./util.js";
  19. /**
  20. * For JBIG2's we use a library to decode these images and
  21. * the stream behaves like all the other DecodeStreams.
  22. */
  23. const Jbig2Stream = (function Jbig2StreamClosure() {
  24. // eslint-disable-next-line no-shadow
  25. function Jbig2Stream(stream, maybeLength, dict, params) {
  26. this.stream = stream;
  27. this.maybeLength = maybeLength;
  28. this.dict = dict;
  29. this.params = params;
  30. DecodeStream.call(this, maybeLength);
  31. }
  32. Jbig2Stream.prototype = Object.create(DecodeStream.prototype);
  33. Object.defineProperty(Jbig2Stream.prototype, "bytes", {
  34. get() {
  35. // If `this.maybeLength` is null, we'll get the entire stream.
  36. return shadow(this, "bytes", this.stream.getBytes(this.maybeLength));
  37. },
  38. configurable: true,
  39. });
  40. Jbig2Stream.prototype.ensureBuffer = function (requested) {
  41. // No-op, since `this.readBlock` will always parse the entire image and
  42. // directly insert all of its data into `this.buffer`.
  43. };
  44. Jbig2Stream.prototype.readBlock = function () {
  45. if (this.eof) {
  46. return;
  47. }
  48. const jbig2Image = new Jbig2Image();
  49. const chunks = [];
  50. if (isDict(this.params)) {
  51. const globalsStream = this.params.get("JBIG2Globals");
  52. if (isStream(globalsStream)) {
  53. const globals = globalsStream.getBytes();
  54. chunks.push({ data: globals, start: 0, end: globals.length });
  55. }
  56. }
  57. chunks.push({ data: this.bytes, start: 0, end: this.bytes.length });
  58. const data = jbig2Image.parseChunks(chunks);
  59. const dataLength = data.length;
  60. // JBIG2 had black as 1 and white as 0, inverting the colors
  61. for (let i = 0; i < dataLength; i++) {
  62. data[i] ^= 0xff;
  63. }
  64. this.buffer = data;
  65. this.bufferLength = dataLength;
  66. this.eof = true;
  67. };
  68. return Jbig2Stream;
  69. })();
  70. export { Jbig2Stream };