chunked_stream.js 14 KB

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