chunked_stream.js 14 KB

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