exifreader 4.39.1 → 4.40.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -27,31 +27,60 @@ export const TYPE_TIME = 'tIME';
27
27
  export const TYPE_EXIF = 'eXIf';
28
28
  export const TYPE_ICCP = 'iCCP';
29
29
 
30
+ /**
31
+ * Checks if the provided data view represents a PNG file.
32
+ *
33
+ * @param {DataView} dataView The data view to check.
34
+ * @returns {boolean} True if the data view starts with the PNG signature.
35
+ */
30
36
  function isPngFile(dataView) {
31
37
  return !!dataView && getStringFromDataView(dataView, 0, PNG_ID.length) === PNG_ID;
32
38
  }
33
39
 
34
- function findPngOffsets(dataView, async) {
40
+ /**
41
+ * Walks the PNG chunk list and reports the offsets ExifReader needs.
42
+ *
43
+ * @param {DataView} dataView The data view to find offsets in.
44
+ * @param {boolean} async Whether async parsing is enabled (gates zTXt/iCCP).
45
+ * @param {Array<Object>=} metadataBlocks Optional out-array. When provided,
46
+ * receives one block per recognized chunk and gets `truncated` set to
47
+ * true if the loop never saw an IEND chunk.
48
+ * @returns {Object} Per-section offsets plus `hasAppMarkers`.
49
+ */
50
+ function findPngOffsets(dataView, async, metadataBlocks) {
35
51
  const PNG_CRC_SIZE = 4;
52
+ const TYPE_IEND = 'IEND';
36
53
 
37
54
  const offsets = {
38
55
  hasAppMarkers: false
39
56
  };
40
57
 
41
58
  let offset = PNG_ID.length;
59
+ let sawIEnd = false;
42
60
 
43
61
  while (offset + PNG_CHUNK_LENGTH_SIZE + PNG_CHUNK_TYPE_SIZE <= dataView.byteLength) {
62
+ let blockType;
63
+ const chunkDataLength = dataView.getUint32(offset + PNG_CHUNK_LENGTH_OFFSET);
64
+
65
+ // The IEND check is only needed for the truncation signal, so skip
66
+ // the per-chunk string read for default callers.
67
+ if (metadataBlocks
68
+ && getStringFromDataView(dataView, offset + PNG_CHUNK_TYPE_OFFSET, PNG_CHUNK_TYPE_SIZE) === TYPE_IEND) {
69
+ sawIEnd = true;
70
+ }
44
71
  if (Constants.USE_PNG_FILE && isPngImageHeaderChunk(dataView, offset)) {
45
72
  offsets.hasAppMarkers = true;
46
73
  offsets.pngHeaderOffset = offset + PNG_CHUNK_DATA_OFFSET;
74
+ blockType = 'file';
47
75
  } else if (Constants.USE_XMP && isPngXmpChunk(dataView, offset)) {
48
76
  const dataOffset = getPngXmpDataOffset(dataView, offset);
49
77
  if (dataOffset !== undefined) {
50
78
  offsets.hasAppMarkers = true;
51
79
  offsets.xmpChunks = [{
52
80
  dataOffset,
53
- length: dataView.getUint32(offset + PNG_CHUNK_LENGTH_OFFSET) - (dataOffset - (offset + PNG_CHUNK_DATA_OFFSET))
81
+ length: chunkDataLength - (dataOffset - (offset + PNG_CHUNK_DATA_OFFSET))
54
82
  }];
83
+ blockType = 'xmp';
55
84
  }
56
85
  } else if (isPngTextChunk(dataView, offset, async)) {
57
86
  offsets.hasAppMarkers = true;
@@ -60,41 +89,60 @@ function findPngOffsets(dataView, async) {
60
89
  offsets.pngTextChunks = [];
61
90
  }
62
91
  offsets.pngTextChunks.push({
63
- length: dataView.getUint32(offset + PNG_CHUNK_LENGTH_OFFSET),
92
+ length: chunkDataLength,
64
93
  type: chunkType,
65
94
  offset: offset + PNG_CHUNK_DATA_OFFSET
66
95
  });
96
+ blockType = 'png';
67
97
  } else if (isPngExifChunk(dataView, offset)) {
68
98
  offsets.hasAppMarkers = true;
69
99
  offsets.tiffHeaderOffset = offset + PNG_CHUNK_DATA_OFFSET;
100
+ blockType = 'exif';
70
101
  } else if (Constants.USE_ICC && async && isPngIccpChunk(dataView, offset)) {
71
- offsets.hasAppMarkers = true;
72
- const chunkDataLength = dataView.getUint32(offset + PNG_CHUNK_LENGTH_OFFSET);
73
102
  const iccHeaderOffset = offset + PNG_CHUNK_DATA_OFFSET;
74
- const {profileName, compressionMethod, compressedProfileOffset} = parseIccHeader(dataView, iccHeaderOffset);
75
- if (!offsets.iccChunks) {
76
- offsets.iccChunks = [];
103
+ const iccHeader = parseIccHeader(dataView, iccHeaderOffset);
104
+ if (iccHeader !== undefined) {
105
+ offsets.hasAppMarkers = true;
106
+ if (!offsets.iccChunks) {
107
+ offsets.iccChunks = [];
108
+ }
109
+ offsets.iccChunks.push({
110
+ offset: iccHeader.compressedProfileOffset,
111
+ length: chunkDataLength - (iccHeader.compressedProfileOffset - iccHeaderOffset),
112
+ chunkNumber: 1,
113
+ chunksTotal: 1,
114
+ profileName: iccHeader.profileName,
115
+ compressionMethod: iccHeader.compressionMethod
116
+ });
117
+ blockType = 'icc';
77
118
  }
78
- offsets.iccChunks.push({
79
- offset: compressedProfileOffset,
80
- length: chunkDataLength - (compressedProfileOffset - iccHeaderOffset),
81
- chunkNumber: 1,
82
- chunksTotal: 1,
83
- profileName,
84
- compressionMethod
85
- });
86
119
  } else if (isPngChunk(dataView, offset)) {
87
120
  offsets.hasAppMarkers = true;
88
121
  if (!offsets.pngChunkOffsets) {
89
122
  offsets.pngChunkOffsets = [];
90
123
  }
91
124
  offsets.pngChunkOffsets.push(offset + PNG_CHUNK_LENGTH_OFFSET);
125
+ blockType = 'png';
92
126
  }
93
127
 
94
- offset += dataView.getUint32(offset + PNG_CHUNK_LENGTH_OFFSET)
128
+ const chunkTotalSize = chunkDataLength
95
129
  + PNG_CHUNK_LENGTH_SIZE
96
130
  + PNG_CHUNK_TYPE_SIZE
97
131
  + PNG_CRC_SIZE;
132
+
133
+ if (metadataBlocks && blockType) {
134
+ metadataBlocks.push({
135
+ type: blockType,
136
+ start: offset,
137
+ end: offset + chunkTotalSize,
138
+ });
139
+ }
140
+
141
+ offset += chunkTotalSize;
142
+ }
143
+
144
+ if (metadataBlocks) {
145
+ metadataBlocks.truncated = !sawIEnd;
98
146
  }
99
147
 
100
148
  return offsets;
@@ -155,6 +203,9 @@ function parseIccHeader(dataView, offset) {
155
203
  const profileName = getNullTerminatedStringFromDataView(dataView, offset);
156
204
  offset += profileName.length + NULL_SEPARATOR_SIZE;
157
205
 
206
+ if (offset + COMPRESSION_METHOD_SIZE > dataView.byteLength) {
207
+ return undefined;
208
+ }
158
209
  const compressionMethod = dataView.getUint8(offset);
159
210
  offset += COMPRESSION_METHOD_SIZE;
160
211
 
@@ -10,6 +10,12 @@ export default {
10
10
  findOffsets
11
11
  };
12
12
 
13
+ /**
14
+ * Checks if the provided data view represents a WebP file.
15
+ *
16
+ * @param {DataView} dataView The data view to check.
17
+ * @returns {boolean} True for a RIFF container with the WEBP marker.
18
+ */
13
19
  function isWebpFile(dataView) {
14
20
  const RIFF_ID_OFFSET = 0;
15
21
  const RIFF_ID = 'RIFF';
@@ -20,7 +26,16 @@ function isWebpFile(dataView) {
20
26
  && getStringFromDataView(dataView, WEBP_MARKER_OFFSET, WEBP_MARKER.length) === WEBP_MARKER;
21
27
  }
22
28
 
23
- function findOffsets(dataView) {
29
+ /**
30
+ * Finds the offsets of metadata chunks in a WebP file.
31
+ *
32
+ * @param {DataView} dataView The data view to find offsets in.
33
+ * @param {Array<Object>=} metadataBlocks Optional out-array. When provided,
34
+ * receives one block per recognized chunk (EXIF/XMP/ICCP/VP8X) with
35
+ * `start` and `end` covering the full RIFF chunk header and content.
36
+ * @returns {Object} hasAppMarkers and the per-section offsets.
37
+ */
38
+ function findOffsets(dataView, metadataBlocks) {
24
39
  const SUB_CHUNK_START_OFFSET = 12;
25
40
  const CHUNK_SIZE_OFFSET = 4;
26
41
  const EXIF_IDENTIFIER = 'Exif\x00\x00';
@@ -36,6 +51,7 @@ function findOffsets(dataView) {
36
51
  while (offset + CHUNK_HEADER_SIZE < dataView.byteLength) {
37
52
  const chunkId = getStringFromDataView(dataView, offset, 4);
38
53
  const chunkSize = dataView.getUint32(offset + CHUNK_SIZE_OFFSET, true);
54
+ let blockType;
39
55
 
40
56
  if (Constants.USE_EXIF && (chunkId === 'EXIF')) {
41
57
  hasAppMarkers = true;
@@ -44,12 +60,14 @@ function findOffsets(dataView) {
44
60
  } else {
45
61
  tiffHeaderOffset = offset + CHUNK_HEADER_SIZE;
46
62
  }
63
+ blockType = 'exif';
47
64
  } else if (Constants.USE_XMP && (chunkId === 'XMP ')) {
48
65
  hasAppMarkers = true;
49
66
  xmpChunks = [{
50
67
  dataOffset: offset + CHUNK_HEADER_SIZE,
51
68
  length: chunkSize
52
69
  }];
70
+ blockType = 'xmp';
53
71
  } else if (Constants.USE_ICC && (chunkId === 'ICCP')) {
54
72
  hasAppMarkers = true;
55
73
  iccChunks = [{
@@ -58,12 +76,24 @@ function findOffsets(dataView) {
58
76
  chunkNumber: 1,
59
77
  chunksTotal: 1
60
78
  }];
79
+ blockType = 'icc';
61
80
  } else if (chunkId === 'VP8X') {
62
81
  hasAppMarkers = true;
63
82
  vp8xChunkOffset = offset + CHUNK_HEADER_SIZE;
83
+ blockType = 'riff';
64
84
  }
65
85
 
66
- offset += CHUNK_HEADER_SIZE + (chunkSize % 2 === 0 ? chunkSize : chunkSize + 1);
86
+ const chunkTotalSize = CHUNK_HEADER_SIZE + (chunkSize % 2 === 0 ? chunkSize : chunkSize + 1);
87
+
88
+ if (metadataBlocks && blockType) {
89
+ metadataBlocks.push({
90
+ type: blockType,
91
+ start: offset,
92
+ end: offset + chunkTotalSize,
93
+ });
94
+ }
95
+
96
+ offset += chunkTotalSize;
67
97
  }
68
98
 
69
99
  return {
@@ -18,46 +18,66 @@ export default {
18
18
  parseAppMarkers
19
19
  };
20
20
 
21
- function parseAppMarkers(dataView, async) {
21
+ /**
22
+ * Detects the image format and delegates to the matching finder.
23
+ *
24
+ * @param {DataView} dataView The data view to inspect.
25
+ * @param {boolean=} async Whether async parsing is enabled.
26
+ * @param {boolean=} includeMetadataBlocks When true, the finder collects a
27
+ * block list describing where metadata sits in the file. The result
28
+ * gains `metadataBlocks` and `metadataTruncated` fields.
29
+ * @returns {Object} Per-format offsets plus `fileType`.
30
+ * @throws {Error} When the data view is not a recognized image format.
31
+ */
32
+ function parseAppMarkers(dataView, async, includeMetadataBlocks) {
33
+ const metadataBlocks = includeMetadataBlocks ? [] : undefined;
34
+
22
35
  if (Constants.USE_TIFF && Tiff.isTiffFile(dataView)) {
23
- return addFileType(Tiff.findTiffOffsets(), 'tiff', 'TIFF');
36
+ return finalize(Tiff.findTiffOffsets(), 'tiff', 'TIFF', metadataBlocks);
24
37
  }
25
38
 
26
39
  if (Constants.USE_JPEG && Jpeg.isJpegFile(dataView)) {
27
- return addFileType(Jpeg.findJpegOffsets(dataView), 'jpeg', 'JPEG');
40
+ return finalize(Jpeg.findJpegOffsets(dataView, metadataBlocks), 'jpeg', 'JPEG', metadataBlocks);
28
41
  }
29
42
 
30
43
  if (Constants.USE_PNG && Png.isPngFile(dataView)) {
31
- return addFileType(Png.findPngOffsets(dataView, async), 'png', 'PNG');
44
+ return finalize(Png.findPngOffsets(dataView, async, metadataBlocks), 'png', 'PNG', metadataBlocks);
32
45
  }
33
46
 
34
47
  if (Constants.USE_HEIC && Heic.isHeicFile(dataView)) {
35
- return addFileType(Heic.findHeicOffsets(dataView), 'heic', 'HEIC');
48
+ return finalize(Heic.findHeicOffsets(dataView, metadataBlocks), 'heic', 'HEIC', metadataBlocks);
36
49
  }
37
50
 
38
51
  if (Constants.USE_AVIF && Avif.isAvifFile(dataView)) {
39
- return addFileType(Avif.findAvifOffsets(dataView), 'avif', 'AVIF');
52
+ return finalize(Avif.findAvifOffsets(dataView, metadataBlocks), 'avif', 'AVIF', metadataBlocks);
40
53
  }
41
54
 
42
55
  if (Constants.USE_JXL && Jxl.isJxlFile(dataView)) {
43
- return addFileType(Jxl.findJxlOffsets(dataView), 'jxl', 'JPEG XL');
56
+ return finalize(Jxl.findJxlOffsets(dataView, metadataBlocks), 'jxl', 'JPEG XL', metadataBlocks);
44
57
  }
45
58
 
46
59
  if (Constants.USE_WEBP && Webp.isWebpFile(dataView)) {
47
- return addFileType(Webp.findOffsets(dataView), 'webp', 'WebP');
60
+ return finalize(Webp.findOffsets(dataView, metadataBlocks), 'webp', 'WebP', metadataBlocks);
48
61
  }
49
62
 
50
63
  if (Constants.USE_GIF && Gif.isGifFile(dataView)) {
51
- return addFileType(Gif.findOffsets(dataView), 'gif', 'GIF');
64
+ return finalize(Gif.findOffsets(dataView, metadataBlocks), 'gif', 'GIF', metadataBlocks);
52
65
  }
53
66
 
54
67
  if (Constants.USE_XMP && Xml.isXMLFile(dataView)) {
55
- return addFileType(Xml.findOffsets(dataView), 'xml', 'XML');
68
+ return finalize(Xml.findOffsets(dataView, metadataBlocks), 'xml', 'XML', metadataBlocks);
56
69
  }
57
70
 
58
71
  throw new Error('Invalid image format');
59
72
  }
60
73
 
61
- function addFileType(offsets, fileType, fileTypeDescription) {
62
- return objectAssign({}, offsets, {fileType: {value: fileType, description: fileTypeDescription}});
74
+ function finalize(offsets, fileType, fileTypeDescription, metadataBlocks) {
75
+ const result = objectAssign({}, offsets, {fileType: {value: fileType, description: fileTypeDescription}});
76
+ if (metadataBlocks !== undefined) {
77
+ result.metadataBlocks = metadataBlocks;
78
+ // Surface the finder's .truncated array convention as a sibling
79
+ // field so consumers don't depend on properties on the array.
80
+ result.metadataTruncated = !!metadataBlocks.truncated;
81
+ }
82
+ return result;
63
83
  }
@@ -0,0 +1,305 @@
1
+ /* This Source Code Form is subject to the terms of the Mozilla Public
2
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
3
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
+
5
+ /* global Buffer, SharedArrayBuffer */
6
+
7
+ import {
8
+ fetchRange, nodeGetRange, readLocalFileRange, readFileObjectRange,
9
+ concatBuffers, isFilePathOrURL, isBrowserFileObject, isDataUri,
10
+ HTTP_STATUS_OK, HTTP_STATUS_RANGE_NOT_SATISFIABLE,
11
+ } from './file-loaders.js';
12
+ import {objectAssign, dataUriToBuffer} from './utils.js';
13
+
14
+ const AUTO_INITIAL_LENGTH = 128 * 1024;
15
+ const AUTO_MAX_ITERATIONS = 4;
16
+ const AUTO_UNSUPPORTED_ERROR =
17
+ 'length: "auto" could not locate metadata in this file '
18
+ + '(no metadata blocks found after reading the file — e.g. plain TIFF, '
19
+ + 'bare JPEG XL codestream, or a file with no recognizable metadata).';
20
+ const AUTO_MEMORY_UNSUPPORTED_ERROR =
21
+ 'length: "auto" is not supported for this file type '
22
+ + '(no leading metadata container — e.g. plain TIFF or bare JPEG XL codestream).';
23
+
24
+ /**
25
+ * Throws synchronously if `length: 'auto'` is missing `expanded: true`
26
+ * and/or `includeOffsets: true`.
27
+ *
28
+ * @param {object} options
29
+ */
30
+ export function validateAutoOptions(options) {
31
+ if (options.expanded !== true || options.includeOffsets !== true) {
32
+ throw new Error('length: "auto" requires both expanded: true and includeOffsets: true.');
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Builds a `loadAuto(data, options)` bound to `loadFromData`. Factory
38
+ * to avoid a circular import with `exif-reader.js`.
39
+ *
40
+ * @param {(data: any, options: object) => any} loadFromData
41
+ * @returns {(data: any, options: object) => Promise<object>}
42
+ */
43
+ export function makeLoadAuto(loadFromData) {
44
+ return function loadAuto(data, options) {
45
+ if (typeof Promise === 'undefined') {
46
+ throw new Error('Promise is required when async mode is enabled.');
47
+ }
48
+ const asyncOptions = objectAssign({}, options, {async: true});
49
+ if (isFilePathOrURL(data)) {
50
+ return loadAdaptiveFromFilenameOrUrl(data, asyncOptions);
51
+ }
52
+ if (isBrowserFileObject(data)) {
53
+ return loadAdaptiveFromFileObject(data, asyncOptions);
54
+ }
55
+ return loadAdaptiveFromMemory(data, asyncOptions);
56
+ };
57
+
58
+ function loadAdaptiveFromFilenameOrUrl(filename, options) {
59
+ if (/^\w+:\/\//.test(filename)) {
60
+ if (typeof fetch !== 'undefined') {
61
+ return adaptiveLoop({
62
+ readRange: (start, end) => fetchRange(filename, {start, end}),
63
+ options,
64
+ });
65
+ }
66
+ return adaptiveLoop({
67
+ readRange: (start, end) => nodeGetRange(filename, {start, end}),
68
+ options,
69
+ });
70
+ }
71
+ if (isDataUri(filename)) {
72
+ return loadAdaptiveFromMemory(dataUriToBuffer(filename), options);
73
+ }
74
+ return adaptiveLoop({
75
+ readRange: (start, end, ctx) => readLocalFileRange(filename, {
76
+ start, end, totalSize: ctx ? ctx.totalSize : undefined
77
+ }),
78
+ options,
79
+ });
80
+ }
81
+
82
+ function loadAdaptiveFromFileObject(file, options) {
83
+ return adaptiveLoop({
84
+ readRange: (start, end) => readFileObjectRange(file, {start, end}),
85
+ options,
86
+ });
87
+ }
88
+
89
+ function loadAdaptiveFromMemory(data, options) {
90
+ return Promise.resolve()
91
+ .then(() => loadFromData(data, options))
92
+ .then((tags) => {
93
+ if (!tags || !tags.metadataRange) {
94
+ throw new Error(AUTO_MEMORY_UNSUPPORTED_ERROR);
95
+ }
96
+ const end = tags.metadataRange.end;
97
+ tags.metadataRange.buffer = sliceInputBuffer(data, end);
98
+ tags.metadataRange.fetched = bufferByteLength(tags.metadataRange.buffer);
99
+ tags.metadataRange.requests = 0;
100
+ return tags;
101
+ });
102
+ }
103
+
104
+ function adaptiveLoop({readRange, options}) {
105
+ return runAdaptiveIteration({
106
+ readRange,
107
+ options,
108
+ buffer: null,
109
+ fetched: 0,
110
+ requests: 0,
111
+ totalSize: undefined,
112
+ need: AUTO_INITIAL_LENGTH,
113
+ iter: 0,
114
+ });
115
+ }
116
+
117
+ function runAdaptiveIteration(state) {
118
+ if (state.iter >= AUTO_MAX_ITERATIONS) {
119
+ return runAdaptiveFallback(state);
120
+ }
121
+ if (state.totalSize !== undefined) {
122
+ state.need = Math.min(state.need, state.totalSize);
123
+ }
124
+ if (state.need <= state.fetched) {
125
+ return runAdaptiveFallback(state);
126
+ }
127
+ return state.readRange(state.fetched, state.need, {totalSize: state.totalSize})
128
+ .then((chunk) => {
129
+ state.requests++;
130
+ // Fall back to a full GET when the server cannot satisfy
131
+ // the requested range.
132
+ if (chunk.status === HTTP_STATUS_RANGE_NOT_SATISFIABLE) {
133
+ return handleAdaptive416(state);
134
+ }
135
+ mergeAdaptiveChunk(state, chunk);
136
+ return Promise.resolve(loadFromData(state.buffer, state.options))
137
+ .then((tags) => decideAdaptiveNext(state, tags));
138
+ });
139
+ }
140
+
141
+ function decideAdaptiveNext(state, tags) {
142
+ const range = tags && tags.metadataRange;
143
+ if (range && range.complete) {
144
+ return attachAdaptiveFields(tags, state.buffer, state.fetched, state.requests);
145
+ }
146
+
147
+ // No metadataRange yet does not mean unsupported. The `meta` box
148
+ // may be past the current buffer in ISO-BMFF. Only reject after
149
+ // a full-file read.
150
+ const reachedEnd = state.totalSize !== undefined && state.fetched >= state.totalSize;
151
+ if (!range && reachedEnd) {
152
+ throw new Error(AUTO_UNSUPPORTED_ERROR);
153
+ }
154
+
155
+ const nextNeed = pickNextNeed({range, totalSize: state.totalSize, fetched: state.fetched});
156
+ if (nextNeed <= state.fetched) {
157
+ if (range) {
158
+ return attachAdaptiveFields(tags, state.buffer, state.fetched, state.requests);
159
+ }
160
+ throw new Error(AUTO_UNSUPPORTED_ERROR);
161
+ }
162
+ state.need = nextNeed;
163
+ state.iter++;
164
+ return runAdaptiveIteration(state);
165
+ }
166
+
167
+ function handleAdaptive416(state) {
168
+ return state.readRange(0, Infinity, {totalSize: undefined})
169
+ .then((full) => {
170
+ state.requests++;
171
+ state.buffer = full.buffer;
172
+ state.fetched = bufferByteLength(state.buffer);
173
+ if (full.totalSize !== undefined) {
174
+ state.totalSize = full.totalSize;
175
+ }
176
+ return Promise.resolve(loadFromData(state.buffer, state.options));
177
+ })
178
+ .then((tags) => {
179
+ if (!tags || !tags.metadataRange) {
180
+ throw new Error(AUTO_UNSUPPORTED_ERROR);
181
+ }
182
+ return attachAdaptiveFields(tags, state.buffer, state.fetched, state.requests);
183
+ });
184
+ }
185
+
186
+ function runAdaptiveFallback(state) {
187
+ // Iteration cap reached. Fall back to full read for correctness.
188
+ console.warn( // eslint-disable-line no-console
189
+ `ExifReader: length:"auto" did not converge in ${AUTO_MAX_ITERATIONS} iterations; falling back to full read.`
190
+ );
191
+ let chunkPromise;
192
+ if (state.totalSize !== undefined && state.fetched < state.totalSize) {
193
+ chunkPromise = state.readRange(state.fetched, state.totalSize, {totalSize: state.totalSize})
194
+ .then((chunk) => {
195
+ state.requests++;
196
+ mergeAdaptiveChunk(state, chunk);
197
+ });
198
+ } else if (state.totalSize === undefined) {
199
+ chunkPromise = state.readRange(state.fetched, Infinity, {totalSize: state.totalSize})
200
+ .then((chunk) => {
201
+ state.requests++;
202
+ mergeAdaptiveChunk(state, chunk);
203
+ });
204
+ } else {
205
+ chunkPromise = Promise.resolve();
206
+ }
207
+ return chunkPromise
208
+ .then(() => Promise.resolve(loadFromData(state.buffer, state.options)))
209
+ .then((tags) => {
210
+ if (!tags || !tags.metadataRange) {
211
+ throw new Error(AUTO_UNSUPPORTED_ERROR);
212
+ }
213
+ return attachAdaptiveFields(tags, state.buffer, state.fetched, state.requests);
214
+ });
215
+ }
216
+ }
217
+
218
+ function mergeAdaptiveChunk(state, chunk) {
219
+ // HTTP 200 on a Range request means the server ignored Range and
220
+ // sent the full body. Replace the buffer instead of concatenating to
221
+ // avoid corrupting offsets.
222
+ if (chunk.status === HTTP_STATUS_OK && state.fetched > 0) {
223
+ state.buffer = chunk.buffer;
224
+ state.fetched = bufferByteLength(state.buffer);
225
+ if (chunk.totalSize !== undefined) {
226
+ state.totalSize = chunk.totalSize;
227
+ }
228
+ return;
229
+ }
230
+ if (chunk.totalSize !== undefined && state.totalSize === undefined) {
231
+ state.totalSize = chunk.totalSize;
232
+ }
233
+ state.buffer = concatBuffers(state.buffer, chunk.buffer);
234
+ state.fetched = bufferByteLength(state.buffer);
235
+ }
236
+
237
+ function attachAdaptiveFields(tags, buffer, fetched, requests) {
238
+ const end = tags.metadataRange.end;
239
+ // `buffer` = minimal slice for re-extraction. `fetched` = bytes
240
+ // actually read (may exceed `end` due to fixed-size chunks).
241
+ tags.metadataRange.buffer = sliceBufferToEnd(buffer, end);
242
+ tags.metadataRange.fetched = fetched;
243
+ tags.metadataRange.requests = requests;
244
+ return tags;
245
+ }
246
+
247
+ function pickNextNeed({range, totalSize, fetched}) {
248
+ if (range) {
249
+ return Math.min(
250
+ Math.max(range.end, fetched * 2),
251
+ totalSize !== undefined ? totalSize : Infinity
252
+ );
253
+ }
254
+ // No blocks yet. Jump straight to EOF if known. Avoids burning the
255
+ // iteration cap on ISO-BMFF where `meta` sits near EOF.
256
+ if (totalSize !== undefined) {
257
+ return totalSize;
258
+ }
259
+ return fetched * 2;
260
+ }
261
+
262
+ function sliceBufferToEnd(buffer, end) {
263
+ if (!buffer || typeof end !== 'number' || end < 0) {
264
+ return buffer;
265
+ }
266
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(buffer)) {
267
+ return Buffer.from(buffer.subarray(0, Math.min(end, buffer.length)));
268
+ }
269
+ if (buffer instanceof ArrayBuffer) {
270
+ return buffer.slice(0, Math.min(end, buffer.byteLength));
271
+ }
272
+ if (typeof SharedArrayBuffer !== 'undefined' && buffer instanceof SharedArrayBuffer) {
273
+ return buffer.slice(0, Math.min(end, buffer.byteLength));
274
+ }
275
+ return buffer;
276
+ }
277
+
278
+ function sliceInputBuffer(data, end) {
279
+ if (typeof Buffer !== 'undefined' && Buffer.isBuffer(data)) {
280
+ return Buffer.from(data.subarray(0, end));
281
+ }
282
+ if (data instanceof ArrayBuffer) {
283
+ return data.slice(0, end);
284
+ }
285
+ if (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer) {
286
+ return data.slice(0, end);
287
+ }
288
+ if (ArrayBuffer.isView(data)) {
289
+ return data.buffer.slice(data.byteOffset, data.byteOffset + end);
290
+ }
291
+ return data;
292
+ }
293
+
294
+ function bufferByteLength(buffer) {
295
+ if (!buffer) {
296
+ return 0;
297
+ }
298
+ if (typeof buffer.byteLength === 'number') {
299
+ return buffer.byteLength;
300
+ }
301
+ if (typeof buffer.length === 'number') {
302
+ return buffer.length;
303
+ }
304
+ return 0;
305
+ }