2
0

chunked_stream.js 14 KB

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