chunked_stream.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. /**
  2. * @licstart The following is the entire license notice for the
  3. * Javascript code in this page
  4. *
  5. * Copyright 2020 Mozilla Foundation
  6. *
  7. * Licensed under the Apache License, Version 2.0 (the "License");
  8. * you may not use this file except in compliance with the License.
  9. * You may obtain a copy of the License at
  10. *
  11. * http://www.apache.org/licenses/LICENSE-2.0
  12. *
  13. * Unless required by applicable law or agreed to in writing, software
  14. * distributed under the License is distributed on an "AS IS" BASIS,
  15. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. * See the License for the specific language governing permissions and
  17. * limitations under the License.
  18. *
  19. * @licend The above is the entire license notice for the
  20. * Javascript code in this page
  21. */
  22. "use strict";
  23. Object.defineProperty(exports, "__esModule", {
  24. value: true
  25. });
  26. exports.ChunkedStreamManager = exports.ChunkedStream = void 0;
  27. var _util = require("../shared/util.js");
  28. var _core_utils = require("./core_utils.js");
  29. class ChunkedStream {
  30. constructor(length, chunkSize, manager) {
  31. this.bytes = new Uint8Array(length);
  32. this.start = 0;
  33. this.pos = 0;
  34. this.end = length;
  35. this.chunkSize = chunkSize;
  36. this.loadedChunks = [];
  37. this.numChunksLoaded = 0;
  38. this.numChunks = Math.ceil(length / chunkSize);
  39. this.manager = manager;
  40. this.progressiveDataLength = 0;
  41. this.lastSuccessfulEnsureByteChunk = -1;
  42. }
  43. getMissingChunks() {
  44. const chunks = [];
  45. for (let chunk = 0, n = this.numChunks; chunk < n; ++chunk) {
  46. if (!this.loadedChunks[chunk]) {
  47. chunks.push(chunk);
  48. }
  49. }
  50. return chunks;
  51. }
  52. getBaseStreams() {
  53. return [this];
  54. }
  55. allChunksLoaded() {
  56. return this.numChunksLoaded === this.numChunks;
  57. }
  58. onReceiveData(begin, chunk) {
  59. const chunkSize = this.chunkSize;
  60. if (begin % chunkSize !== 0) {
  61. throw new Error(`Bad begin offset: ${begin}`);
  62. }
  63. const end = begin + chunk.byteLength;
  64. if (end % chunkSize !== 0 && end !== this.bytes.length) {
  65. throw new Error(`Bad end offset: ${end}`);
  66. }
  67. this.bytes.set(new Uint8Array(chunk), begin);
  68. const beginChunk = Math.floor(begin / chunkSize);
  69. const endChunk = Math.floor((end - 1) / chunkSize) + 1;
  70. for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  71. if (!this.loadedChunks[curChunk]) {
  72. this.loadedChunks[curChunk] = true;
  73. ++this.numChunksLoaded;
  74. }
  75. }
  76. }
  77. onReceiveProgressiveData(data) {
  78. let position = this.progressiveDataLength;
  79. const beginChunk = Math.floor(position / this.chunkSize);
  80. this.bytes.set(new Uint8Array(data), position);
  81. position += data.byteLength;
  82. this.progressiveDataLength = position;
  83. const endChunk = position >= this.end ? this.numChunks : Math.floor(position / this.chunkSize);
  84. for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  85. if (!this.loadedChunks[curChunk]) {
  86. this.loadedChunks[curChunk] = true;
  87. ++this.numChunksLoaded;
  88. }
  89. }
  90. }
  91. ensureByte(pos) {
  92. if (pos < this.progressiveDataLength) {
  93. return;
  94. }
  95. const chunk = Math.floor(pos / this.chunkSize);
  96. if (chunk === this.lastSuccessfulEnsureByteChunk) {
  97. return;
  98. }
  99. if (!this.loadedChunks[chunk]) {
  100. throw new _core_utils.MissingDataException(pos, pos + 1);
  101. }
  102. this.lastSuccessfulEnsureByteChunk = chunk;
  103. }
  104. ensureRange(begin, end) {
  105. if (begin >= end) {
  106. return;
  107. }
  108. if (end <= this.progressiveDataLength) {
  109. return;
  110. }
  111. const chunkSize = this.chunkSize;
  112. const beginChunk = Math.floor(begin / chunkSize);
  113. const endChunk = Math.floor((end - 1) / chunkSize) + 1;
  114. for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
  115. if (!this.loadedChunks[chunk]) {
  116. throw new _core_utils.MissingDataException(begin, end);
  117. }
  118. }
  119. }
  120. nextEmptyChunk(beginChunk) {
  121. const numChunks = this.numChunks;
  122. for (let i = 0; i < numChunks; ++i) {
  123. const chunk = (beginChunk + i) % numChunks;
  124. if (!this.loadedChunks[chunk]) {
  125. return chunk;
  126. }
  127. }
  128. return null;
  129. }
  130. hasChunk(chunk) {
  131. return !!this.loadedChunks[chunk];
  132. }
  133. get length() {
  134. return this.end - this.start;
  135. }
  136. get isEmpty() {
  137. return this.length === 0;
  138. }
  139. getByte() {
  140. const pos = this.pos;
  141. if (pos >= this.end) {
  142. return -1;
  143. }
  144. if (pos >= this.progressiveDataLength) {
  145. this.ensureByte(pos);
  146. }
  147. return this.bytes[this.pos++];
  148. }
  149. getUint16() {
  150. const b0 = this.getByte();
  151. const b1 = this.getByte();
  152. if (b0 === -1 || b1 === -1) {
  153. return -1;
  154. }
  155. return (b0 << 8) + b1;
  156. }
  157. getInt32() {
  158. const b0 = this.getByte();
  159. const b1 = this.getByte();
  160. const b2 = this.getByte();
  161. const b3 = this.getByte();
  162. return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3;
  163. }
  164. getBytes(length, forceClamped = false) {
  165. const bytes = this.bytes;
  166. const pos = this.pos;
  167. const strEnd = this.end;
  168. if (!length) {
  169. if (strEnd > this.progressiveDataLength) {
  170. this.ensureRange(pos, strEnd);
  171. }
  172. const subarray = bytes.subarray(pos, strEnd);
  173. return forceClamped ? new Uint8ClampedArray(subarray) : subarray;
  174. }
  175. let end = pos + length;
  176. if (end > strEnd) {
  177. end = strEnd;
  178. }
  179. if (end > this.progressiveDataLength) {
  180. this.ensureRange(pos, end);
  181. }
  182. this.pos = end;
  183. const subarray = bytes.subarray(pos, end);
  184. return forceClamped ? new Uint8ClampedArray(subarray) : subarray;
  185. }
  186. peekByte() {
  187. const peekedByte = this.getByte();
  188. if (peekedByte !== -1) {
  189. this.pos--;
  190. }
  191. return peekedByte;
  192. }
  193. peekBytes(length, forceClamped = false) {
  194. const bytes = this.getBytes(length, forceClamped);
  195. this.pos -= bytes.length;
  196. return bytes;
  197. }
  198. getByteRange(begin, end) {
  199. if (begin < 0) {
  200. begin = 0;
  201. }
  202. if (end > this.end) {
  203. end = this.end;
  204. }
  205. if (end > this.progressiveDataLength) {
  206. this.ensureRange(begin, end);
  207. }
  208. return this.bytes.subarray(begin, end);
  209. }
  210. skip(n) {
  211. if (!n) {
  212. n = 1;
  213. }
  214. this.pos += n;
  215. }
  216. reset() {
  217. this.pos = this.start;
  218. }
  219. moveStart() {
  220. this.start = this.pos;
  221. }
  222. makeSubStream(start, length, dict) {
  223. if (length) {
  224. if (start + length > this.progressiveDataLength) {
  225. this.ensureRange(start, start + length);
  226. }
  227. } else {
  228. if (start >= this.progressiveDataLength) {
  229. this.ensureByte(start);
  230. }
  231. }
  232. function ChunkedStreamSubstream() {}
  233. ChunkedStreamSubstream.prototype = Object.create(this);
  234. ChunkedStreamSubstream.prototype.getMissingChunks = function () {
  235. const chunkSize = this.chunkSize;
  236. const beginChunk = Math.floor(this.start / chunkSize);
  237. const endChunk = Math.floor((this.end - 1) / chunkSize) + 1;
  238. const missingChunks = [];
  239. for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
  240. if (!this.loadedChunks[chunk]) {
  241. missingChunks.push(chunk);
  242. }
  243. }
  244. return missingChunks;
  245. };
  246. ChunkedStreamSubstream.prototype.allChunksLoaded = function () {
  247. if (this.numChunksLoaded === this.numChunks) {
  248. return true;
  249. }
  250. return this.getMissingChunks().length === 0;
  251. };
  252. const subStream = new ChunkedStreamSubstream();
  253. subStream.pos = subStream.start = start;
  254. subStream.end = start + length || this.end;
  255. subStream.dict = dict;
  256. return subStream;
  257. }
  258. }
  259. exports.ChunkedStream = ChunkedStream;
  260. class ChunkedStreamManager {
  261. constructor(pdfNetworkStream, args) {
  262. this.length = args.length;
  263. this.chunkSize = args.rangeChunkSize;
  264. this.stream = new ChunkedStream(this.length, this.chunkSize, this);
  265. this.pdfNetworkStream = pdfNetworkStream;
  266. this.disableAutoFetch = args.disableAutoFetch;
  267. this.msgHandler = args.msgHandler;
  268. this.currRequestId = 0;
  269. this.chunksNeededByRequest = Object.create(null);
  270. this.requestsByChunk = Object.create(null);
  271. this.promisesByRequest = Object.create(null);
  272. this.progressiveDataLength = 0;
  273. this.aborted = false;
  274. this._loadedStreamCapability = (0, _util.createPromiseCapability)();
  275. }
  276. onLoadedStream() {
  277. return this._loadedStreamCapability.promise;
  278. }
  279. sendRequest(begin, end) {
  280. const rangeReader = this.pdfNetworkStream.getRangeReader(begin, end);
  281. if (!rangeReader.isStreamingSupported) {
  282. rangeReader.onProgress = this.onProgress.bind(this);
  283. }
  284. let chunks = [],
  285. loaded = 0;
  286. const promise = new Promise((resolve, reject) => {
  287. const readChunk = chunk => {
  288. try {
  289. if (!chunk.done) {
  290. const data = chunk.value;
  291. chunks.push(data);
  292. loaded += (0, _util.arrayByteLength)(data);
  293. if (rangeReader.isStreamingSupported) {
  294. this.onProgress({
  295. loaded
  296. });
  297. }
  298. rangeReader.read().then(readChunk, reject);
  299. return;
  300. }
  301. const chunkData = (0, _util.arraysToBytes)(chunks);
  302. chunks = null;
  303. resolve(chunkData);
  304. } catch (e) {
  305. reject(e);
  306. }
  307. };
  308. rangeReader.read().then(readChunk, reject);
  309. });
  310. promise.then(data => {
  311. if (this.aborted) {
  312. return;
  313. }
  314. this.onReceiveData({
  315. chunk: data,
  316. begin
  317. });
  318. });
  319. }
  320. requestAllChunks() {
  321. const missingChunks = this.stream.getMissingChunks();
  322. this._requestChunks(missingChunks);
  323. return this._loadedStreamCapability.promise;
  324. }
  325. _requestChunks(chunks) {
  326. const requestId = this.currRequestId++;
  327. const chunksNeeded = Object.create(null);
  328. this.chunksNeededByRequest[requestId] = chunksNeeded;
  329. for (const chunk of chunks) {
  330. if (!this.stream.hasChunk(chunk)) {
  331. chunksNeeded[chunk] = true;
  332. }
  333. }
  334. if ((0, _util.isEmptyObj)(chunksNeeded)) {
  335. return Promise.resolve();
  336. }
  337. const capability = (0, _util.createPromiseCapability)();
  338. this.promisesByRequest[requestId] = capability;
  339. const chunksToRequest = [];
  340. for (let chunk in chunksNeeded) {
  341. chunk = chunk | 0;
  342. if (!(chunk in this.requestsByChunk)) {
  343. this.requestsByChunk[chunk] = [];
  344. chunksToRequest.push(chunk);
  345. }
  346. this.requestsByChunk[chunk].push(requestId);
  347. }
  348. if (!chunksToRequest.length) {
  349. return capability.promise;
  350. }
  351. const groupedChunksToRequest = this.groupChunks(chunksToRequest);
  352. for (const groupedChunk of groupedChunksToRequest) {
  353. const begin = groupedChunk.beginChunk * this.chunkSize;
  354. const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
  355. this.sendRequest(begin, end);
  356. }
  357. return capability.promise;
  358. }
  359. getStream() {
  360. return this.stream;
  361. }
  362. requestRange(begin, end) {
  363. end = Math.min(end, this.length);
  364. const beginChunk = this.getBeginChunk(begin);
  365. const endChunk = this.getEndChunk(end);
  366. const chunks = [];
  367. for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
  368. chunks.push(chunk);
  369. }
  370. return this._requestChunks(chunks);
  371. }
  372. requestRanges(ranges = []) {
  373. const chunksToRequest = [];
  374. for (const range of ranges) {
  375. const beginChunk = this.getBeginChunk(range.begin);
  376. const endChunk = this.getEndChunk(range.end);
  377. for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
  378. if (!chunksToRequest.includes(chunk)) {
  379. chunksToRequest.push(chunk);
  380. }
  381. }
  382. }
  383. chunksToRequest.sort(function (a, b) {
  384. return a - b;
  385. });
  386. return this._requestChunks(chunksToRequest);
  387. }
  388. groupChunks(chunks) {
  389. const groupedChunks = [];
  390. let beginChunk = -1;
  391. let prevChunk = -1;
  392. for (let i = 0, ii = chunks.length; i < ii; ++i) {
  393. const chunk = chunks[i];
  394. if (beginChunk < 0) {
  395. beginChunk = chunk;
  396. }
  397. if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
  398. groupedChunks.push({
  399. beginChunk,
  400. endChunk: prevChunk + 1
  401. });
  402. beginChunk = chunk;
  403. }
  404. if (i + 1 === chunks.length) {
  405. groupedChunks.push({
  406. beginChunk,
  407. endChunk: chunk + 1
  408. });
  409. }
  410. prevChunk = chunk;
  411. }
  412. return groupedChunks;
  413. }
  414. onProgress(args) {
  415. this.msgHandler.send("DocProgress", {
  416. loaded: this.stream.numChunksLoaded * this.chunkSize + args.loaded,
  417. total: this.length
  418. });
  419. }
  420. onReceiveData(args) {
  421. const chunk = args.chunk;
  422. const isProgressive = args.begin === undefined;
  423. const begin = isProgressive ? this.progressiveDataLength : args.begin;
  424. const end = begin + chunk.byteLength;
  425. const beginChunk = Math.floor(begin / this.chunkSize);
  426. const endChunk = end < this.length ? Math.floor(end / this.chunkSize) : Math.ceil(end / this.chunkSize);
  427. if (isProgressive) {
  428. this.stream.onReceiveProgressiveData(chunk);
  429. this.progressiveDataLength = end;
  430. } else {
  431. this.stream.onReceiveData(begin, chunk);
  432. }
  433. if (this.stream.allChunksLoaded()) {
  434. this._loadedStreamCapability.resolve(this.stream);
  435. }
  436. const loadedRequests = [];
  437. for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
  438. const requestIds = this.requestsByChunk[chunk] || [];
  439. delete this.requestsByChunk[chunk];
  440. for (const requestId of requestIds) {
  441. const chunksNeeded = this.chunksNeededByRequest[requestId];
  442. if (chunk in chunksNeeded) {
  443. delete chunksNeeded[chunk];
  444. }
  445. if (!(0, _util.isEmptyObj)(chunksNeeded)) {
  446. continue;
  447. }
  448. loadedRequests.push(requestId);
  449. }
  450. }
  451. if (!this.disableAutoFetch && (0, _util.isEmptyObj)(this.requestsByChunk)) {
  452. let nextEmptyChunk;
  453. if (this.stream.numChunksLoaded === 1) {
  454. const lastChunk = this.stream.numChunks - 1;
  455. if (!this.stream.hasChunk(lastChunk)) {
  456. nextEmptyChunk = lastChunk;
  457. }
  458. } else {
  459. nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
  460. }
  461. if (Number.isInteger(nextEmptyChunk)) {
  462. this._requestChunks([nextEmptyChunk]);
  463. }
  464. }
  465. for (const requestId of loadedRequests) {
  466. const capability = this.promisesByRequest[requestId];
  467. delete this.promisesByRequest[requestId];
  468. capability.resolve();
  469. }
  470. this.msgHandler.send("DocProgress", {
  471. loaded: this.stream.numChunksLoaded * this.chunkSize,
  472. total: this.length
  473. });
  474. }
  475. onError(err) {
  476. this._loadedStreamCapability.reject(err);
  477. }
  478. getBeginChunk(begin) {
  479. return Math.floor(begin / this.chunkSize);
  480. }
  481. getEndChunk(end) {
  482. return Math.floor((end - 1) / this.chunkSize) + 1;
  483. }
  484. abort(reason) {
  485. this.aborted = true;
  486. if (this.pdfNetworkStream) {
  487. this.pdfNetworkStream.cancelAllRequests(reason);
  488. }
  489. for (const requestId in this.promisesByRequest) {
  490. this.promisesByRequest[requestId].reject(reason);
  491. }
  492. }
  493. }
  494. exports.ChunkedStreamManager = ChunkedStreamManager;