chunked_stream.js 15 KB

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