2
0

chunked_stream.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. 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. return 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. }).then(data => {
  262. if (this.aborted) {
  263. return;
  264. }
  265. this.onReceiveData({
  266. chunk: data,
  267. begin
  268. });
  269. });
  270. }
  271. requestAllChunks(noFetch = false) {
  272. if (!noFetch) {
  273. const missingChunks = this.stream.getMissingChunks();
  274. this._requestChunks(missingChunks);
  275. }
  276. return this._loadedStreamCapability.promise;
  277. }
  278. _requestChunks(chunks) {
  279. const requestId = this.currRequestId++;
  280. const chunksNeeded = new Set();
  281. this._chunksNeededByRequest.set(requestId, chunksNeeded);
  282. for (const chunk of chunks) {
  283. if (!this.stream.hasChunk(chunk)) {
  284. chunksNeeded.add(chunk);
  285. }
  286. }
  287. if (chunksNeeded.size === 0) {
  288. return Promise.resolve();
  289. }
  290. const capability = (0, _util.createPromiseCapability)();
  291. this._promisesByRequest.set(requestId, capability);
  292. const chunksToRequest = [];
  293. for (const chunk of chunksNeeded) {
  294. let requestIds = this._requestsByChunk.get(chunk);
  295. if (!requestIds) {
  296. requestIds = [];
  297. this._requestsByChunk.set(chunk, requestIds);
  298. chunksToRequest.push(chunk);
  299. }
  300. requestIds.push(requestId);
  301. }
  302. if (chunksToRequest.length > 0) {
  303. const groupedChunksToRequest = this.groupChunks(chunksToRequest);
  304. for (const groupedChunk of groupedChunksToRequest) {
  305. const begin = groupedChunk.beginChunk * this.chunkSize;
  306. const end = Math.min(groupedChunk.endChunk * this.chunkSize, this.length);
  307. this.sendRequest(begin, end).catch(capability.reject);
  308. }
  309. }
  310. return capability.promise.catch(reason => {
  311. if (this.aborted) {
  312. return;
  313. }
  314. throw reason;
  315. });
  316. }
  317. getStream() {
  318. return this.stream;
  319. }
  320. requestRange(begin, end) {
  321. end = Math.min(end, this.length);
  322. const beginChunk = this.getBeginChunk(begin);
  323. const endChunk = this.getEndChunk(end);
  324. const chunks = [];
  325. for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
  326. chunks.push(chunk);
  327. }
  328. return this._requestChunks(chunks);
  329. }
  330. requestRanges(ranges = []) {
  331. const chunksToRequest = [];
  332. for (const range of ranges) {
  333. const beginChunk = this.getBeginChunk(range.begin);
  334. const endChunk = this.getEndChunk(range.end);
  335. for (let chunk = beginChunk; chunk < endChunk; ++chunk) {
  336. if (!chunksToRequest.includes(chunk)) {
  337. chunksToRequest.push(chunk);
  338. }
  339. }
  340. }
  341. chunksToRequest.sort(function (a, b) {
  342. return a - b;
  343. });
  344. return this._requestChunks(chunksToRequest);
  345. }
  346. groupChunks(chunks) {
  347. const groupedChunks = [];
  348. let beginChunk = -1;
  349. let prevChunk = -1;
  350. for (let i = 0, ii = chunks.length; i < ii; ++i) {
  351. const chunk = chunks[i];
  352. if (beginChunk < 0) {
  353. beginChunk = chunk;
  354. }
  355. if (prevChunk >= 0 && prevChunk + 1 !== chunk) {
  356. groupedChunks.push({
  357. beginChunk,
  358. endChunk: prevChunk + 1
  359. });
  360. beginChunk = chunk;
  361. }
  362. if (i + 1 === chunks.length) {
  363. groupedChunks.push({
  364. beginChunk,
  365. endChunk: chunk + 1
  366. });
  367. }
  368. prevChunk = chunk;
  369. }
  370. return groupedChunks;
  371. }
  372. onProgress(args) {
  373. this.msgHandler.send("DocProgress", {
  374. loaded: this.stream.numChunksLoaded * this.chunkSize + args.loaded,
  375. total: this.length
  376. });
  377. }
  378. onReceiveData(args) {
  379. const chunk = args.chunk;
  380. const isProgressive = args.begin === undefined;
  381. const begin = isProgressive ? this.progressiveDataLength : args.begin;
  382. const end = begin + chunk.byteLength;
  383. const beginChunk = Math.floor(begin / this.chunkSize);
  384. const endChunk = end < this.length ? Math.floor(end / this.chunkSize) : Math.ceil(end / this.chunkSize);
  385. if (isProgressive) {
  386. this.stream.onReceiveProgressiveData(chunk);
  387. this.progressiveDataLength = end;
  388. } else {
  389. this.stream.onReceiveData(begin, chunk);
  390. }
  391. if (this.stream.isDataLoaded) {
  392. this._loadedStreamCapability.resolve(this.stream);
  393. }
  394. const loadedRequests = [];
  395. for (let curChunk = beginChunk; curChunk < endChunk; ++curChunk) {
  396. const requestIds = this._requestsByChunk.get(curChunk);
  397. if (!requestIds) {
  398. continue;
  399. }
  400. this._requestsByChunk.delete(curChunk);
  401. for (const requestId of requestIds) {
  402. const chunksNeeded = this._chunksNeededByRequest.get(requestId);
  403. if (chunksNeeded.has(curChunk)) {
  404. chunksNeeded.delete(curChunk);
  405. }
  406. if (chunksNeeded.size > 0) {
  407. continue;
  408. }
  409. loadedRequests.push(requestId);
  410. }
  411. }
  412. if (!this.disableAutoFetch && this._requestsByChunk.size === 0) {
  413. let nextEmptyChunk;
  414. if (this.stream.numChunksLoaded === 1) {
  415. const lastChunk = this.stream.numChunks - 1;
  416. if (!this.stream.hasChunk(lastChunk)) {
  417. nextEmptyChunk = lastChunk;
  418. }
  419. } else {
  420. nextEmptyChunk = this.stream.nextEmptyChunk(endChunk);
  421. }
  422. if (Number.isInteger(nextEmptyChunk)) {
  423. this._requestChunks([nextEmptyChunk]);
  424. }
  425. }
  426. for (const requestId of loadedRequests) {
  427. const capability = this._promisesByRequest.get(requestId);
  428. this._promisesByRequest.delete(requestId);
  429. capability.resolve();
  430. }
  431. this.msgHandler.send("DocProgress", {
  432. loaded: this.stream.numChunksLoaded * this.chunkSize,
  433. total: this.length
  434. });
  435. }
  436. onError(err) {
  437. this._loadedStreamCapability.reject(err);
  438. }
  439. getBeginChunk(begin) {
  440. return Math.floor(begin / this.chunkSize);
  441. }
  442. getEndChunk(end) {
  443. return Math.floor((end - 1) / this.chunkSize) + 1;
  444. }
  445. abort(reason) {
  446. this.aborted = true;
  447. if (this.pdfNetworkStream) {
  448. this.pdfNetworkStream.cancelAllRequests(reason);
  449. }
  450. for (const capability of this._promisesByRequest.values()) {
  451. capability.reject(reason);
  452. }
  453. }
  454. }
  455. exports.ChunkedStreamManager = ChunkedStreamManager;