chunked_stream.js 14 KB

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