exifreader 4.53.0 → 4.54.0

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.
@@ -7,7 +7,7 @@
7
7
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
8
  */
9
9
 
10
- import {objectAssign, decompress, withDecompressBudget, COMPRESSION_METHOD_BROTLI, getDataView, getDataViewFromBytes, getByteString, getStringValueFromArray, assertPromiseSupport, setProperty, isThenable, MAX_METADATA_BLOCKS} from './utils.js';
10
+ import {objectAssign, withDecompressBudget, getCompressionMethod, getDataView, getDataViewFromBytes, getByteString, getStringValueFromArray, assertPromiseSupport, isThenable, MAX_METADATA_BLOCKS} from './utils.js';
11
11
  import {isFilePathOrURL, isBrowserFileObject, loadFile, loadFileObject} from './file-loaders.js';
12
12
  import {makeLoadAuto, validateAutoOptions} from './load-auto.js';
13
13
  import Constants from './constants.js';
@@ -15,13 +15,14 @@ import {getCalculatedGpsValue} from './tag-names-utils.js';
15
15
  import ByteOrder from './byte-order.js';
16
16
  import {getTiffHeaderOffset} from './image-header-iso-bmff.js';
17
17
  import ImageHeader from './image-header.js';
18
+ import {TYPE_ZTXT} from './image-header-png.js';
18
19
  import Tags from './tags.js';
19
20
  import TagNames0thIfd from './tag-names-0th-ifd.js';
20
21
  import TagNamesExifIfd from './tag-names-exif-ifd.js';
21
22
  import TagNamesGpsIfd from './tag-names-gps-ifd.js';
22
23
  import TagNamesInteroperabilityIfd from './tag-names-interoperability-ifd.js';
23
24
  import {IFD_TYPE_0TH, IFD_TYPE_1ST, IFD_TYPE_EXIF, IFD_TYPE_GPS, IFD_TYPE_INTEROPERABILITY} from './ifd-types.js';
24
- import {getValueBudget, addDecompressedValueAllowance, takeEmbeddedExifThumbnail} from './tags-helpers.js';
25
+ import {addDecompressedValueAllowance, addDecompressedIptcAllowance} from './tags-helpers.js';
25
26
  import MpfTags from './mpf-tags.js';
26
27
  import FileTags from './file-tags.js';
27
28
  import JxlFileTags from './jxl-file-tags.js';
@@ -34,26 +35,19 @@ import IccTags from './icc-tags.js';
34
35
  import CanonTags from './canon-tags.js';
35
36
  import PentaxTags from './pentax-tags.js';
36
37
  import PngFileTags from './png-file-tags.js';
37
- import PngTextTags from './png-text-tags.js';
38
+ import PngTextTags, {hasRawIptcProfile} from './png-text-tags.js';
38
39
  import PngTags from './png-tags.js';
39
40
  import Vp8xTags from './vp8x-tags.js';
40
41
  import GifFileTags from './gif-file-tags.js';
41
42
  import Thumbnail from './thumbnail.js';
42
43
  import Composite from './composite.js';
43
- import {createTagFilter} from './tag-filter.js';
44
- import {buildTagsFromMergeSteps, EXIF_CARRIED_GROUP_ORDER} from './loadview-pipeline.js';
44
+ import {createTagFilter, filterTagsForParse, filterTagsForReturn} from './tag-filter.js';
45
+ import {getBase64Image} from './base64-image.js';
46
+ import DOMParser from './dom-parser.js';
47
+ import {buildTagsFromMergeBlocks} from './loadview-pipeline.js';
48
+ import {run, createContext, validateComposition} from './engine.js';
45
49
  import exifErrors from './errors.js';
46
50
 
47
- // Brob XMP is bounded by the file size, as brob Exif is, plus room for one JPEG
48
- // standard XMP segment so that a small file can still carry a typical packet.
49
- const BROB_XMP_SIZE_PER_INPUT_SIZE = 4;
50
- const BROB_XMP_SIZE_ALLOWANCE = 64 * 1024;
51
- // An embedded thumbnail is sliced from a decoded or decompressed view that can be
52
- // far larger than the file. A real JPEG thumbnail shrinks only a little when
53
- // compressed, so bound the embedded thumbnails of a file by twice its size in
54
- // total, plus room for a typical thumbnail.
55
- const EMBEDDED_THUMBNAIL_SIZE_PER_INPUT_SIZE = 2;
56
- const EMBEDDED_THUMBNAIL_SIZE_ALLOWANCE = 64 * 1024;
57
51
  // The USE_EXIF gate is what lets a build without Exif drop the dictionaries.
58
52
  const TAG_NAMES_0TH_AND_EXIF_IFDS = Constants.USE_EXIF ? objectAssign({}, TagNames0thIfd, TagNamesExifIfd) : {};
59
53
 
@@ -63,6 +57,8 @@ export default {
63
57
  errors: exifErrors,
64
58
  };
65
59
 
60
+ validateComposition(getDefaultComposition());
61
+
66
62
  export const errors = exifErrors;
67
63
 
68
64
  export function load(data, options = {}) {
@@ -84,9 +80,8 @@ function loadFromData(data, options) {
84
80
  return loadView(getDataViewFromBytes(data), options);
85
81
  }
86
82
 
87
- export function loadView(
88
- dataView,
89
- {
83
+ export function loadView(dataView, options = {}) {
84
+ const {
90
85
  expanded = false,
91
86
  async = false,
92
87
  computed = false,
@@ -96,728 +91,528 @@ export function loadView(
96
91
  includeTags = undefined,
97
92
  excludeTags = undefined,
98
93
  decompress: decompressConfig = undefined
99
- } = {}
100
- ) {
94
+ } = options;
101
95
  dataView = getSelfContainedDataView(dataView);
102
- decompressConfig = withDecompressBudget(decompressConfig);
103
96
 
104
- const tagFilter = createTagFilter({includeTags, excludeTags});
105
- const parsedGroups = Object.create(null);
106
- const mergeSteps = [];
107
- const deferredResults = Object.create(null);
108
- const deferredPromises = [];
109
- let pngTextIsAsync = false;
110
- let thumbnailIfdTags = undefined;
111
- let valueBudget = undefined;
112
- let embeddedXmpStepForFlat = undefined;
113
- let decompressedApplicationNotesSize = 0;
97
+ const {fileType, blocks: allBlocks, ranges, truncated} = ImageHeader.parseAppMarkers(dataView, expanded && includeOffsets);
98
+ if (async) {
99
+ assertPromiseSupport();
100
+ }
101
+ const blocks = async ? allBlocks : allBlocks.filter((block) => !isHiddenInSyncMode(block));
114
102
 
115
- const {
116
- fileType,
117
- fileDataOffset,
118
- jfifDataOffset,
119
- tiffHeaderOffset,
120
- iptcDataOffset,
121
- xmpChunks,
122
- iccChunks,
123
- mpfDataOffset,
124
- pngHeaderOffset,
125
- pngTextChunks,
126
- pngChunkOffsets,
127
- vp8xChunkOffset,
128
- gifHeaderOffset,
129
- brobExifChunk,
130
- brobXmpChunk,
131
- jxlCodestreamOffset,
132
- imageDimensionsOffset,
133
- pixelInformationOffset,
134
- metadataBlocks,
135
- metadataTruncated,
136
- exifDataView,
137
- xmpDataView
138
- } = ImageHeader.parseAppMarkers(dataView, async, expanded && includeOffsets);
139
-
140
- const fileHasMetaData = hasPotentialMetaData({
141
- fileType,
142
- fileDataOffset,
143
- jfifDataOffset,
144
- tiffHeaderOffset,
145
- iptcDataOffset,
146
- xmpChunks,
147
- iccChunks,
148
- mpfDataOffset,
149
- pngHeaderOffset,
150
- pngTextChunks,
151
- pngChunkOffsets,
152
- vp8xChunkOffset,
153
- gifHeaderOffset,
154
- jxlCodestreamOffset,
103
+ const tagFilter = createTagFilter({includeTags, excludeTags});
104
+ const context = createContext({
105
+ dataView,
106
+ options: {expanded, async, computed, includeUnknown, includeOffsets, domParser, includeTags, excludeTags},
107
+ tagFilter,
108
+ decompressConfig: withDecompressBudget(decompressConfig),
109
+ getBase64Image,
110
+ getDomParser: DOMParser.get,
155
111
  });
112
+ // The pipeline copies png into pngText only when png is returned, so the
113
+ // filter needs no check here.
114
+ const pngTextBlocks = blocks.filter(isPngTextChunkBlock);
115
+ const pngTextIsAsync = async && Constants.USE_PNG && pngTextBlocks.some(isNamedCompressedPngTextChunk);
156
116
 
157
- if (
158
- Constants.USE_JPEG
159
- && Constants.USE_FILE
160
- && fileDataOffset !== undefined
161
- && tagFilter.shouldParseGroup('file')
162
- && shouldReadFileTagsForFileTypeOnlyOptimization(includeTags)
163
- ) {
164
- const readTags = FileTags.read(dataView, fileDataOffset);
165
- const parsedFileTags = filterTagsForParse('file', readTags, tagFilter);
166
- parsedGroups.file = parsedFileTags;
167
-
168
- if (tagFilter.shouldReturnGroup('file')) {
169
- mergeSteps.push({
170
- type: 'mergeGroupAssign',
171
- groupKey: 'file',
172
- parsedTags: parsedFileTags,
173
- });
174
- }
175
- }
117
+ const result = run(getDefaultComposition(), blocks, context);
176
118
 
177
- if (
178
- Constants.USE_JPEG
179
- && Constants.USE_JFIF
180
- && jfifDataOffset !== undefined
181
- && tagFilter.shouldParseGroup('jfif')
182
- ) {
183
- const readTags = JfifTags.read(dataView, jfifDataOffset);
184
- const parsedJfifTags = filterTagsForParse('jfif', readTags, tagFilter);
185
- parsedGroups.jfif = parsedJfifTags;
186
-
187
- if (tagFilter.shouldReturnGroup('jfif')) {
188
- mergeSteps.push({
189
- type: 'mergeGroupAssign',
190
- groupKey: 'jfif',
191
- parsedTags: parsedJfifTags,
192
- });
193
- }
194
- }
119
+ return async ? result.then(finish) : finish(result);
195
120
 
196
- if (
197
- Constants.USE_EXIF
198
- && tiffHeaderOffset !== undefined
199
- && tagFilter.shouldParseGroup('exif')
200
- ) {
201
- const {tags: readTags, byteOrder, valueBudget: exifValueBudget} = readExifTagsSafely(
202
- exifDataView || dataView,
203
- tiffHeaderOffset,
204
- includeUnknown,
205
- computed,
206
- tagFilter
207
- );
208
- valueBudget = exifValueBudget;
209
- if (readTags.Thumbnail) {
210
- thumbnailIfdTags = readTags.Thumbnail;
211
- delete readTags.Thumbnail;
212
- }
121
+ function finish({mergeBlocks}) {
122
+ return buildTagsFromMergeBlocks({
123
+ mergeBlocks: combineUncompressedPngTextBlocks(mergeBlocks).concat(getDerivedBlocks({expanded, includeOffsets, async, ranges, truncated})),
124
+ parsedGroups: Object.create(null),
125
+ expanded,
126
+ tagFilter,
127
+ dataView,
128
+ fileType,
129
+ pngTextBlocks,
130
+ pngTextIsAsync,
131
+ deps: {
132
+ objectAssign,
133
+ hasPngTextData,
134
+ filterTagsForReturn,
135
+ // A plain property here would keep the function alive for the bundler,
136
+ // so a build without Exif would still carry getGpsGroupFromExifTags.
137
+ getGpsGroupFromExifTags: Constants.USE_EXIF ? getGpsGroupFromExifTags : undefined,
138
+ // A plain property here would keep the import alive for the bundler, so
139
+ // a build with neither Exif nor XMP would still carry composite.js.
140
+ Composite: (Constants.USE_EXIF || Constants.USE_XMP) ? Composite : undefined,
141
+ },
142
+ });
143
+ }
144
+ }
213
145
 
214
- const parsedExifTags = filterTagsForParse('exif', readTags, tagFilter);
215
- parsedGroups.exif = parsedExifTags;
146
+ function isNamedCompressedPngTextChunk(block) {
147
+ return block.compression !== undefined && block.text.name !== undefined;
148
+ }
216
149
 
217
- const carriedGroups = readExifCarriedGroups(
218
- parsedExifTags,
219
- exifDataView || dataView,
220
- tiffHeaderOffset,
221
- byteOrder,
222
- valueBudget,
223
- {decompressed: false, hasIptcBlock: iptcDataOffset !== undefined}
224
- );
225
- for (let i = 0; i < EXIF_CARRIED_GROUP_ORDER.length; i++) {
226
- const groupKey = EXIF_CARRIED_GROUP_ORDER[i];
227
- if (carriedGroups[groupKey] === undefined) {
228
- continue;
229
- }
230
- parsedGroups[groupKey] = carriedGroups[groupKey];
231
- if (!tagFilter.shouldReturnGroup(groupKey)) {
232
- continue;
233
- }
234
- if (groupKey === 'xmp') {
235
- const step = {
236
- type: 'mergeXmpGroupAssign',
237
- parsedTags: carriedGroups.xmp,
238
- };
239
-
240
- if (expanded) {
241
- mergeSteps.push(step);
242
- } else {
243
- embeddedXmpStepForFlat = step;
244
- }
245
- } else {
246
- mergeSteps.push({
247
- type: 'mergeGroupAssign',
248
- groupKey,
249
- parsedTags: carriedGroups[groupKey],
250
- });
251
- }
252
- }
150
+ // The groups in dispatch order, each inside its build gate so that a custom
151
+ // build folds the reader import away. Built per load, since the unit tests
152
+ // swap the Constants at runtime.
153
+ function getDefaultComposition() {
154
+ return {
155
+ groups: [
156
+ Constants.USE_JPEG && Constants.USE_FILE ? {
157
+ key: 'file',
158
+ consumes: ['file'],
159
+ emits: [],
160
+ read: readFileBlock,
161
+ merge: () => ({slot: 'file', mode: 'assign'}),
162
+ } : undefined,
163
+ Constants.USE_JPEG && Constants.USE_JFIF ? {
164
+ key: 'jfif',
165
+ consumes: ['jfif'],
166
+ emits: [],
167
+ read: (block, ctx) => parsedTags('jfif', JfifTags.read(ctx.dataView, block.dataOffset), ctx),
168
+ merge: () => ({slot: 'jfif', mode: 'assign'}),
169
+ } : undefined,
170
+ Constants.USE_EXIF ? {
171
+ key: 'exif',
172
+ consumes: ['exif'],
173
+ emits: ['iptc', 'xmp', 'photoshop', 'icc', 'makerNote', 'thumbnail'],
174
+ read: readExifBlock,
175
+ merge: getExifMergeDescriptor,
176
+ } : undefined,
177
+ Constants.USE_IPTC ? {
178
+ key: 'iptc',
179
+ consumes: ['iptc'],
180
+ emits: [],
181
+ read: readIptcBlock,
182
+ merge: (block) => getEmbeddableMergeDescriptor(block, 'iptc', 'carriedIptc'),
183
+ } : undefined,
184
+ Constants.USE_XMP ? {
185
+ key: 'xmp',
186
+ consumes: ['xmp'],
187
+ emits: [],
188
+ read: readXmpBlock,
189
+ merge: getXmpMergeDescriptor,
190
+ } : undefined,
191
+ Constants.USE_ICC ? {
192
+ key: 'icc',
193
+ consumes: ['icc'],
194
+ emits: [],
195
+ read: readIccBlock,
196
+ merge: (block) => getEmbeddableMergeDescriptor(block, 'icc', 'carriedIcc'),
197
+ } : undefined,
198
+ Constants.USE_MPF ? {
199
+ key: 'mpf',
200
+ consumes: ['mpf'],
201
+ emits: [],
202
+ read: (block, ctx) => parsedTags('mpf', MpfTags.read(
203
+ ctx.dataView,
204
+ block.dataOffset,
205
+ ctx.options.includeUnknown,
206
+ ctx.options.computed,
207
+ ctx.tagFilter,
208
+ ctx.getValueBudget(),
209
+ ctx.getBase64Image
210
+ ), ctx),
211
+ merge: () => ({slot: 'mpf', mode: 'assign'}),
212
+ } : undefined,
213
+ Constants.USE_PNG && Constants.USE_PNG_FILE ? {
214
+ key: 'png',
215
+ consumes: ['pngFile'],
216
+ emits: [],
217
+ read: (block, ctx) => parsedTags('png', PngFileTags.read(ctx.dataView, block.dataOffset), ctx),
218
+ merge: () => ({slot: 'pngFile', mode: 'pngFile'}),
219
+ } : undefined,
220
+ Constants.USE_PNG ? {
221
+ key: 'png',
222
+ consumes: ['pngText'],
223
+ emits: ['exif', 'iptc'],
224
+ read: (block, ctx) => PngTextTags.read(block, ctx),
225
+ merge: (block) => ({slot: block.compression !== undefined ? 'deferredPngText' : 'pngText', mode: 'pngTextTags'}),
226
+ } : undefined,
227
+ Constants.USE_PNG ? {
228
+ key: 'png',
229
+ consumes: ['pngChunk'],
230
+ emits: [],
231
+ read: (block, ctx) => parsedTags('png', PngTags.read(ctx.dataView, [block.dataOffset]), ctx),
232
+ merge: () => ({slot: 'pngChunk', mode: 'merge'}),
233
+ } : undefined,
234
+ Constants.USE_WEBP ? {
235
+ key: 'riff',
236
+ consumes: ['riff'],
237
+ emits: [],
238
+ read: (block, ctx) => parsedTags('riff', Vp8xTags.read(ctx.dataView, block.dataOffset), ctx),
239
+ merge: () => ({slot: 'riff', mode: 'merge'}),
240
+ } : undefined,
241
+ Constants.USE_GIF ? {
242
+ key: 'gif',
243
+ consumes: ['gif'],
244
+ emits: [],
245
+ read: (block, ctx) => parsedTags('gif', GifFileTags.read(ctx.dataView, block.dataOffset), ctx),
246
+ merge: () => ({slot: 'gif', mode: 'merge'}),
247
+ } : undefined,
248
+ Constants.USE_JXL ? {
249
+ key: 'file',
250
+ consumes: ['jxlFile'],
251
+ emits: [],
252
+ read: (block, ctx) => parsedTags('file', JxlFileTags.read(ctx.dataView, block.codestreamOffset), ctx),
253
+ merge: () => ({slot: 'jxlFile', mode: 'assign'}),
254
+ } : undefined,
255
+ Constants.USE_HEIC || Constants.USE_AVIF ? {
256
+ key: 'file',
257
+ consumes: ['isoBmffFile'],
258
+ emits: [],
259
+ read: (block, ctx) => parsedTags('file', IsoBmffFileTags.read(ctx.dataView, block.imageDimensionsOffset, block.pixelInformationOffset), ctx),
260
+ merge: () => ({slot: 'isoBmffFile', mode: 'assign'}),
261
+ } : undefined,
262
+ Constants.USE_PHOTOSHOP ? {
263
+ key: 'photoshop',
264
+ consumes: ['photoshop'],
265
+ emits: [],
266
+ read: (block, ctx) => parsedTags('photoshop', PhotoshopTags.read(block.value, ctx.options.includeUnknown, ctx.tagFilter), ctx),
267
+ merge: (block) => getEmbeddableMergeDescriptor(block, 'photoshop', 'carriedPhotoshop'),
268
+ } : undefined,
269
+ Constants.USE_MAKER_NOTES ? {
270
+ key: 'makerNotes',
271
+ consumes: ['makerNote'],
272
+ emits: [],
273
+ read: readMakerNoteBlock,
274
+ merge: (block) => getEmbeddableMergeDescriptor(block, 'makerNotes', 'carriedMakerNotes'),
275
+ } : undefined,
276
+ Constants.USE_EXIF && Constants.USE_THUMBNAIL ? {
277
+ key: 'thumbnail',
278
+ consumes: ['thumbnail'],
279
+ emits: [],
280
+ read: readThumbnailBlock,
281
+ merge: (block) => ({slot: 'thumbnail', mode: 'thumbnailCandidate', rank: block.rank}),
282
+ } : undefined,
283
+ ].filter(Boolean),
284
+ dispatchKind,
285
+ rank,
286
+ suppressions: [
287
+ {kind: 'iptc', isSuppressed: isCarriedIptcSuppressed},
288
+ {kind: 'xmp', isSuppressed: isCarriedXmpSuppressed},
289
+ {kind: 'icc', isSuppressed: isCarriedIccSuppressed},
290
+ ],
291
+ };
292
+ }
253
293
 
254
- if (tagFilter.shouldReturnGroup('exif')) {
255
- mergeSteps.push({
256
- type: 'mergeGroupAssign',
257
- groupKey: 'exif',
258
- parsedTags: parsedExifTags,
259
- });
260
- }
294
+ function parsedTags(groupKey, readTags, ctx) {
295
+ return {tags: filterTagsForParse(groupKey, readTags, ctx.tagFilter)};
296
+ }
261
297
 
262
- if (!expanded && embeddedXmpStepForFlat) {
263
- mergeSteps.push(embeddedXmpStepForFlat);
264
- embeddedXmpStepForFlat = undefined;
265
- }
298
+ function readFileBlock(block, ctx) {
299
+ if (!shouldReadFileTagsForFileTypeOnlyOptimization(ctx.options.includeTags)) {
300
+ return undefined;
266
301
  }
302
+ return parsedTags('file', FileTags.read(ctx.dataView, block.dataOffset), ctx);
303
+ }
267
304
 
268
- if (valueBudget === undefined && dataView !== undefined) {
269
- valueBudget = getValueBudget(dataView);
305
+ function shouldReadFileTagsForFileTypeOnlyOptimization(includeTagsOptions) {
306
+ if (!includeTagsOptions) {
307
+ return true;
270
308
  }
271
-
272
- if (
273
- Constants.USE_JPEG
274
- && Constants.USE_IPTC
275
- && iptcDataOffset !== undefined
276
- && tagFilter.shouldParseGroup('iptc')
277
- ) {
278
- const readTags = IptcTags.read(dataView, iptcDataOffset, includeUnknown, tagFilter, valueBudget);
279
- const parsedIptcTags = filterTagsForParse('iptc', readTags, tagFilter);
280
- parsedGroups.iptc = parsedIptcTags;
281
-
282
- if (tagFilter.shouldReturnGroup('iptc')) {
283
- mergeSteps.push({
284
- type: 'mergeGroupAssign',
285
- groupKey: 'iptc',
286
- parsedTags: parsedIptcTags,
287
- });
288
- }
309
+ const {composite, file} = includeTagsOptions;
310
+ if (composite === true || (Array.isArray(composite) && composite.length > 0)) {
311
+ return true;
289
312
  }
313
+ return !(Array.isArray(file) && file.length === 1 && file[0] === 'FileType');
314
+ }
290
315
 
291
- if (
292
- Constants.USE_XMP
293
- && hasXmpData(xmpChunks)
294
- && tagFilter.shouldParseGroup('xmp')
295
- ) {
296
- const readTags = XmpTags.read(xmpDataView || dataView, xmpChunks, domParser);
297
- const parsedXmpTags = filterTagsForParse('xmp', readTags, tagFilter);
298
- parsedGroups.xmp = parsedXmpTags;
299
-
300
- if (tagFilter.shouldReturnGroup('xmp')) {
301
- mergeSteps.push({
302
- type: 'mergeXmpGroupAssign',
303
- parsedTags: parsedXmpTags,
304
- });
305
- }
306
- }
316
+ // A raw-profile text chunk keeps its exif or iptc kind, which the suppression
317
+ // rules key on, but dispatches with the other text chunks.
318
+ function dispatchKind(block) {
319
+ return isPngTextChunkBlock(block) ? 'pngText' : block.kind;
320
+ }
307
321
 
308
- const readEmbeddedExifThumbnail = getEmbeddedExifThumbnailReader(tagFilter, dataView);
309
-
310
- if (
311
- Constants.USE_JXL
312
- && Constants.USE_EXIF
313
- && brobExifChunk
314
- && tiffHeaderOffset === undefined
315
- && tagFilter.shouldParseGroup('exif')
316
- && async
317
- ) {
318
- const compressedExifData = getBrobDataView(dataView, brobExifChunk);
319
- deferredPromises.push(
320
- decompress(compressedExifData, COMPRESSION_METHOD_BROTLI, undefined, 'dataview', decompressConfig)
321
- .then((decompressedDataView) => {
322
- const brobTiffHeaderOffset = getTiffHeaderOffset(decompressedDataView, 0);
323
- addDecompressedValueAllowance(valueBudget, decompressedDataView.byteLength);
324
- const {tags: readTags, byteOrder: brobByteOrder} = readExifTags(
325
- decompressedDataView,
326
- brobTiffHeaderOffset,
327
- includeUnknown,
328
- computed,
329
- tagFilter,
330
- valueBudget
331
- );
332
- const thumbnail = takeEmbeddedExifThumbnail(
333
- readTags,
334
- decompressedDataView,
335
- brobTiffHeaderOffset,
336
- readEmbeddedExifThumbnail
337
- );
338
- const carriedGroups = readEmbeddedExifCarriedGroups(
339
- decompressedDataView,
340
- readTags,
341
- brobTiffHeaderOffset,
342
- brobByteOrder,
343
- valueBudget,
344
- {decompressed: true, hasIptcBlock: false}
345
- );
346
- deferredResults.brobExif = {exifTags: readTags, carriedGroups, thumbnail};
347
- })
348
- .catch(() => {
349
- deferredResults.brobExif = undefined;
350
- })
351
- );
352
- mergeSteps.push({
353
- type: 'mergeBrobExifDeferred',
354
- deferredKey: 'brobExif',
355
- });
356
- }
322
+ // A brob Exif box ranks below an Exif box; a compressed raw-profile text chunk
323
+ // is not a brob, so it ranks with the eXIf chunk and the uncompressed profiles.
324
+ function rank(block) {
325
+ return block.kind === 'exif' && block.compression !== undefined && !isPngTextChunkBlock(block) ? 0 : 1;
326
+ }
357
327
 
358
- if (
359
- Constants.USE_JXL
360
- && Constants.USE_XMP
361
- && brobXmpChunk
362
- && !hasXmpData(xmpChunks)
363
- && tagFilter.shouldParseGroup('xmp')
364
- && async
365
- ) {
366
- const compressedXmpData = getBrobDataView(dataView, brobXmpChunk);
367
- deferredPromises.push(
368
- decompress(compressedXmpData, COMPRESSION_METHOD_BROTLI, undefined, 'dataview', decompressConfig)
369
- .then((decompressedDataView) => {
370
- if (exceedsBrobXmpSizeBound(decompressedDataView.byteLength, dataView)) {
371
- deferredResults.brobXmp = {};
372
- return;
373
- }
374
- deferredResults.brobXmp = XmpTags.read(
375
- decompressedDataView,
376
- [{dataOffset: 0, length: decompressedDataView.byteLength}],
377
- domParser
378
- );
379
- })
380
- .catch(() => {
381
- deferredResults.brobXmp = {};
382
- })
383
- );
384
- mergeSteps.push({
385
- type: 'mergeBrobXmpDeferred',
386
- deferredKey: 'brobXmp',
387
- });
328
+ // The main block's IPTC-NAA gives way to an IPTC segment, a raw profile's to a
329
+ // raw IPTC chunk the text reader will read, compressed or not; a brob's never
330
+ // gives way. The USE_PNG gate keeps the text reader out of a build without PNG.
331
+ // The raw IPTC scan decodes text chunks, so its verdict is kept on the context:
332
+ // the finder blocks do not change within a load, and a PNG can hold thousands
333
+ // of raw profiles.
334
+ function isCarriedIptcSuppressed(block, finderBlocks, ctx) {
335
+ if (block.carried === 'main') {
336
+ return finderBlocks.some((finderBlock) => finderBlock.kind === 'iptc' && !isPngTextChunkBlock(finderBlock));
337
+ }
338
+ if (Constants.USE_PNG && block.carried === 'rawProfile') {
339
+ if (ctx.hasRawIptcProfile === undefined) {
340
+ ctx.hasRawIptcProfile = hasRawIptcProfile(finderBlocks, ctx.dataView);
341
+ }
342
+ return ctx.hasRawIptcProfile;
388
343
  }
344
+ return false;
345
+ }
389
346
 
390
- if (
391
- Constants.USE_ICC
392
- && hasIccData(iccChunks)
393
- && tagFilter.shouldParseGroup('icc')
394
- ) {
395
- const readTags = IccTags.read(dataView, iccChunks, async, decompressConfig);
396
- if (isThenable(readTags)) {
397
- if (!async) {
398
- throw new Error('Promise is required when async mode is enabled.');
399
- }
347
+ // A brob XMP box has no chunks, so it does not suppress.
348
+ function isCarriedXmpSuppressed(block, finderBlocks) {
349
+ return block.carried !== undefined && finderBlocks.some((finderBlock) => finderBlock.kind === 'xmp' && hasXmpData(finderBlock));
350
+ }
400
351
 
401
- deferredPromises.push(readTags.then((resolvedTags) => {
402
- deferredResults.iccApp = resolvedTags;
403
- }));
404
- mergeSteps.push({
405
- type: 'mergeIccDeferred',
406
- deferredKey: 'iccApp',
407
- });
408
- } else {
409
- const parsedIccTags = filterTagsForParse('icc', readTags, tagFilter);
410
- parsedGroups.icc = parsedIccTags;
411
- if (tagFilter.shouldReturnGroup('icc')) {
412
- mergeSteps.push({
413
- type: 'mergeGroupAssign',
414
- groupKey: 'icc',
415
- parsedTags: parsedIccTags,
416
- });
417
- }
418
- }
419
- }
352
+ function isCarriedIccSuppressed(block, finderBlocks) {
353
+ return block.carried !== undefined && finderBlocks.some((finderBlock) => finderBlock.kind === 'icc' && hasIccData(finderBlock));
354
+ }
420
355
 
421
- if (
422
- Constants.USE_MPF
423
- && mpfDataOffset !== undefined
424
- && tagFilter.shouldParseGroup('mpf')
425
- ) {
426
- const readMpfTags = MpfTags.read(
427
- dataView,
428
- mpfDataOffset,
429
- includeUnknown,
430
- computed,
431
- tagFilter,
432
- valueBudget
433
- );
434
- const parsedMpfTags = filterTagsForParse('mpf', readMpfTags, tagFilter);
435
- parsedGroups.mpf = parsedMpfTags;
436
-
437
- if (tagFilter.shouldReturnGroup('mpf')) {
438
- mergeSteps.push({
439
- type: 'mergeGroupAssign',
440
- groupKey: 'mpf',
441
- parsedTags: parsedMpfTags,
442
- });
443
- }
356
+ function getEmbeddableMergeDescriptor(block, slot, carriedSlot) {
357
+ if (block.carried !== undefined) {
358
+ return {slot: carriedSlot, mode: block.carried === 'main' ? 'assign' : 'merge'};
444
359
  }
360
+ return {slot, mode: block.origin !== undefined ? 'merge' : 'assign'};
361
+ }
445
362
 
446
- if (
447
- Constants.USE_PNG
448
- && Constants.USE_PNG_FILE
449
- && pngHeaderOffset !== undefined
450
- && tagFilter.shouldParseGroup('png')
451
- ) {
452
- const readTags = PngFileTags.read(dataView, pngHeaderOffset);
453
- const parsedPngFileTags = filterTagsForParse('png', readTags, tagFilter);
454
- parsedGroups.pngFile = parsedPngFileTags;
455
-
456
- if (tagFilter.shouldReturnGroup('png')) {
457
- mergeSteps.push({
458
- type: 'mergePngFile',
459
- parsedTags: parsedPngFileTags,
460
- });
461
- }
363
+ function getXmpMergeDescriptor(block) {
364
+ if (block.compression !== undefined) {
365
+ return {slot: 'brobXmp', mode: 'brobXmp'};
462
366
  }
367
+ return getEmbeddableMergeDescriptor(block, 'xmp', 'carriedXmp');
368
+ }
463
369
 
464
- if (
465
- Constants.USE_PNG
466
- && hasPngTextData(pngTextChunks)
467
- && (
468
- tagFilter.shouldParseGroup('png')
469
- || tagFilter.shouldParseGroup('exif')
470
- || tagFilter.shouldParseGroup('iptc')
471
- )
472
- ) {
473
- const {readTags, embeddedExifTags, embeddedIptcTags, embeddedExifThumbnail, exifCarriedGroups, readTagsPromise} = PngTextTags.read(
474
- dataView,
475
- pngTextChunks,
476
- async,
477
- includeUnknown,
478
- computed,
479
- tagFilter,
480
- decompressConfig,
481
- valueBudget,
482
- readEmbeddedExifThumbnail,
483
- readEmbeddedExifCarriedGroups,
484
- {
485
- exif: Constants.USE_EXIF ? readExifTags : undefined,
486
- iptc: Constants.USE_IPTC ? IptcTags.read : undefined,
487
- }
488
- );
489
- pngTextIsAsync = !!readTagsPromise;
490
-
491
- mergeSteps.push({
492
- type: 'processPngTextReadTags',
493
- readTags,
494
- embeddedExifTags,
495
- embeddedIptcTags,
496
- embeddedExifThumbnail,
497
- exifCarriedGroups,
498
- });
499
-
500
- if (readTagsPromise) {
501
- deferredPromises.push(readTagsPromise.then((tagList) => {
502
- deferredResults.pngTextTagList = tagList;
503
- }));
504
- mergeSteps.push({
505
- type: 'processPngTextReadTagsDeferredList',
506
- deferredKey: 'pngTextTagList',
507
- });
508
- }
370
+ function getExifMergeDescriptor(block) {
371
+ if (block.compression !== undefined) {
372
+ return {slot: 'exif', mode: 'merge', outerSlot: 'brobExif'};
509
373
  }
374
+ return {slot: 'exif', mode: block.origin !== undefined ? 'merge' : 'assign'};
375
+ }
510
376
 
511
- if (
512
- Constants.USE_PNG
513
- && pngChunkOffsets !== undefined
514
- && tagFilter.shouldParseGroup('png')
515
- ) {
516
- const readTags = PngTags.read(dataView, pngChunkOffsets);
517
- const parsedPngChunkTags = filterTagsForParse('png', readTags, tagFilter);
518
- parsedGroups.pngChunk = parsedPngChunkTags;
519
-
520
- if (tagFilter.shouldReturnGroup('png')) {
521
- mergeSteps.push({
522
- type: 'mergePngChunk',
523
- parsedTags: parsedPngChunkTags,
524
- });
525
- }
377
+ function getBlockDataView(block, ctx) {
378
+ if (block.getDataView) {
379
+ return block.getDataView();
526
380
  }
381
+ return block.dataView || ctx.dataView;
382
+ }
527
383
 
528
- if (
529
- Constants.USE_WEBP
530
- && vp8xChunkOffset !== undefined
531
- && tagFilter.shouldParseGroup('riff')
532
- ) {
533
- const readTags = Vp8xTags.read(dataView, vp8xChunkOffset);
534
- const parsedRiffTags = filterTagsForParse('riff', readTags, tagFilter);
535
- parsedGroups.riff = parsedRiffTags;
536
-
537
- if (tagFilter.shouldReturnGroup('riff')) {
538
- mergeSteps.push({
539
- type: 'mergeGroupMerge',
540
- groupKey: 'riff',
541
- parsedTags: parsedRiffTags,
542
- });
384
+ // A brob Exif box decompresses through the pool; a decompression failure or a
385
+ // bad header rejects, which drops the block. A JXL Exif box too short for its
386
+ // header has no tiffHeaderOffset and reads nothing.
387
+ function readExifBlock(block, ctx) {
388
+ if (block.compression !== undefined) {
389
+ if (!Constants.USE_JXL) {
390
+ return undefined;
543
391
  }
392
+ return ctx.decompress(getBrobDataView(ctx.dataView, block), getCompressionMethod(block.compression), undefined, 'dataview')
393
+ .then((view) => readExifView(view, getTiffHeaderOffset(view, 0), ctx, {carried: 'brob', decompressed: true}));
544
394
  }
545
-
546
- if (
547
- Constants.USE_GIF
548
- && gifHeaderOffset !== undefined
549
- && tagFilter.shouldParseGroup('gif')
550
- ) {
551
- const readTags = GifFileTags.read(dataView, gifHeaderOffset);
552
- const parsedGifTags = filterTagsForParse('gif', readTags, tagFilter);
553
- parsedGroups.gif = parsedGifTags;
554
-
555
- if (tagFilter.shouldReturnGroup('gif')) {
556
- mergeSteps.push({
557
- type: 'mergeGroupMerge',
558
- groupKey: 'gif',
559
- parsedTags: parsedGifTags,
560
- });
561
- }
395
+ if (block.tiffHeaderOffset === undefined) {
396
+ return undefined;
562
397
  }
398
+ return readExifView(getBlockDataView(block, ctx), block.tiffHeaderOffset, ctx, {
399
+ carried: block.origin || 'main',
400
+ decompressed: block.decompressed === true,
401
+ });
402
+ }
563
403
 
564
- if (
565
- Constants.USE_JXL
566
- && jxlCodestreamOffset !== undefined
567
- && tagFilter.shouldParseGroup('file')
568
- ) {
569
- const readTags = JxlFileTags.read(dataView, jxlCodestreamOffset);
570
- const parsedJxlFileTags = filterTagsForParse('file', readTags, tagFilter);
571
- parsedGroups.file = parsedJxlFileTags;
572
-
573
- if (tagFilter.shouldReturnGroup('file')) {
574
- mergeSteps.push({
575
- type: 'mergeGroupAssign',
576
- groupKey: 'file',
577
- parsedTags: parsedJxlFileTags,
578
- });
579
- }
580
- }
404
+ // The main block creates the value budget from its view; an embedded block
405
+ // draws from the shared one and, when decompressed, adds its allowance.
406
+ function readExifView(view, tiffHeaderOffset, ctx, {carried, decompressed}) {
407
+ const isMain = carried === 'main';
408
+ const valueBudget = isMain ? ctx.getValueBudget(view) : ctx.getValueBudget();
409
+ if (decompressed) {
410
+ addDecompressedValueAllowance(valueBudget, view.byteLength);
411
+ }
412
+ const read = isMain ? readExifTagsSafely : readExifTags;
413
+ const {tags, byteOrder, makerNoteOffset} = read(view, tiffHeaderOffset, ctx, valueBudget);
414
+ const thumbnailIfdTags = tags.Thumbnail;
415
+ delete tags.Thumbnail;
416
+
417
+ const parsed = filterTagsForParse('exif', tags, ctx.tagFilter);
418
+ const blocks = getExifEmittedBlocks(parsed, {view, tiffHeaderOffset, byteOrder, makerNoteOffset, thumbnailIfdTags, carried, decompressed});
419
+ if (carried === 'brob' && Object.keys(parsed).length === 0) {
420
+ return {tags: undefined, blocks};
421
+ }
422
+ return {tags: parsed, blocks};
423
+ }
581
424
 
582
- if (
583
- (Constants.USE_HEIC || Constants.USE_AVIF)
584
- && (imageDimensionsOffset !== undefined || pixelInformationOffset !== undefined)
585
- && tagFilter.shouldParseGroup('file')
586
- ) {
587
- const readTags = IsoBmffFileTags.read(dataView, imageDimensionsOffset, pixelInformationOffset);
588
- const parsedIsoBmffFileTags = filterTagsForParse('file', readTags, tagFilter);
589
- parsedGroups.file = parsedIsoBmffFileTags;
590
-
591
- if (tagFilter.shouldReturnGroup('file')) {
592
- mergeSteps.push({
593
- type: 'mergeGroupAssign',
594
- groupKey: 'file',
595
- parsedTags: parsedIsoBmffFileTags,
596
- });
597
- }
598
- }
425
+ // In emission order; the engine drops a kind no composed group consumes.
426
+ function getExifEmittedBlocks(parsed, {view, tiffHeaderOffset, byteOrder, makerNoteOffset, thumbnailIfdTags, carried, decompressed}) {
427
+ const blocks = [];
599
428
 
600
- if (Constants.USE_EXIF) {
601
- mergeSteps.push({type: 'gps'});
429
+ if (parsed['IPTC-NAA']) {
430
+ blocks.push({kind: 'iptc', dataView: parsed['IPTC-NAA'].value, dataOffset: 0, carried});
602
431
  }
603
- if (Constants.USE_EXIF || Constants.USE_XMP) {
604
- mergeSteps.push({type: 'composite'});
432
+ if (parsed['ApplicationNotes'] && isNumberArray(parsed['ApplicationNotes'].value)) {
433
+ const applicationNotes = parsed['ApplicationNotes'].value;
434
+ blocks.push({kind: 'xmp', carried, decompressed, byteLength: applicationNotes.length, getDataView: () => getByteString(applicationNotes)});
605
435
  }
606
- mergeSteps.push({type: 'thumbnail'});
607
- mergeSteps.push({type: 'fileType'});
608
-
609
- if (expanded && includeOffsets) {
610
- mergeSteps.push({
611
- type: 'metadataRange',
612
- metadataBlocks: getParsedMetadataBlocks(metadataBlocks, fileType),
613
- metadataTruncated: !!metadataTruncated,
436
+ if (parsed['ImageSourceData'] && parsed['PhotoshopSettings'] && Array.isArray(parsed['PhotoshopSettings'].value)) {
437
+ blocks.push({kind: 'photoshop', value: parsed['PhotoshopSettings'].value, carried});
438
+ }
439
+ if (parsed['ICC_Profile']) {
440
+ const profile = parsed['ICC_Profile'].value;
441
+ blocks.push({kind: 'icc', dataView: profile, chunks: [{offset: 0, length: profile.length, chunkNumber: 1, chunksTotal: 1}], carried});
442
+ }
443
+ if (parsed['MakerNote'] && makerNoteOffset !== undefined) {
444
+ blocks.push({
445
+ kind: 'makerNote',
446
+ tiffView: view,
447
+ tiffHeaderOffset,
448
+ makerNoteOffset,
449
+ byteOrder,
450
+ make: parsed['Make'] && parsed['Make'].value,
451
+ bytes: parsed['MakerNote'].value,
452
+ carried,
614
453
  });
615
454
  }
616
-
617
- if (!fileHasMetaData) {
618
- throw new exifErrors.MetadataMissingError();
455
+ if (thumbnailIfdTags) {
456
+ blocks.push({kind: 'thumbnail', dataView: view, tiffHeaderOffset, ifd1Tags: thumbnailIfdTags, decompressed, rank: carried === 'main' ? 'main' : 'embedded'});
619
457
  }
620
458
 
621
- const pipelineDependencies = {
622
- objectAssign,
623
- hasPngTextData,
624
- filterTagsForParse,
625
- filterTagsForReturn,
626
- // A plain property here would keep the function alive for the bundler,
627
- // so a build without Exif would still carry getGpsGroupFromExifTags.
628
- getGpsGroupFromExifTags: Constants.USE_EXIF ? getGpsGroupFromExifTags : undefined,
629
- // A plain property here would keep the import alive for the bundler, so
630
- // a build with neither Exif nor XMP would still carry composite.js.
631
- Composite: (Constants.USE_EXIF || Constants.USE_XMP) ? Composite : undefined,
632
- // A plain property here would keep the import alive for the bundler, so
633
- // a build without Exif thumbnails would still carry thumbnail.js.
634
- Thumbnail: (Constants.USE_EXIF && Constants.USE_THUMBNAIL) ? Thumbnail : undefined,
635
- };
636
-
637
- if (async) {
638
- assertPromiseSupport();
459
+ return blocks;
460
+ }
639
461
 
640
- return Promise.all(deferredPromises).then(() => {
641
- const tags = buildTagsFromMergeSteps({
642
- mergeSteps,
643
- deferredResults,
644
- parsedGroups,
645
- expanded,
646
- tagFilter,
647
- dataView,
648
- tiffHeaderOffset,
649
- exifDataView,
650
- fileType,
651
- pngTextChunks,
652
- pngTextIsAsync,
653
- thumbnailIfdTags,
654
- deps: pipelineDependencies,
655
- });
656
-
657
- return tags;
658
- });
462
+ // A carried IPTC-NAA draws no allowance; a decompressed raw profile does.
463
+ function readIptcBlock(block, ctx) {
464
+ const view = getBlockDataView(block, ctx);
465
+ const valueBudget = ctx.getValueBudget();
466
+ if (block.origin === 'rawProfile' && block.decompressed) {
467
+ addDecompressedIptcAllowance(valueBudget, view.byteLength);
659
468
  }
469
+ return parsedTags('iptc', IptcTags.read(view, block.dataOffset, ctx.options.includeUnknown, ctx.tagFilter, valueBudget), ctx);
470
+ }
660
471
 
661
- return buildTagsFromMergeSteps({
662
- mergeSteps,
663
- deferredResults,
664
- parsedGroups,
665
- expanded,
666
- tagFilter,
667
- dataView,
668
- tiffHeaderOffset,
669
- exifDataView,
670
- fileType,
671
- pngTextChunks,
672
- pngTextIsAsync,
673
- thumbnailIfdTags,
674
- deps: pipelineDependencies,
675
- });
676
-
677
- function shouldReadFileTagsForFileTypeOnlyOptimization(includeTagsOptions) {
678
- if (!includeTagsOptions) {
679
- return true;
472
+ function readXmpBlock(block, ctx) {
473
+ const {domParser} = ctx.options;
474
+ if (block.compression !== undefined) {
475
+ if (!Constants.USE_JXL) {
476
+ return undefined;
680
477
  }
681
- const {composite, file} = includeTagsOptions;
682
- if (composite === true || (Array.isArray(composite) && composite.length > 0)) {
683
- return true;
478
+ return ctx.decompress(getBrobDataView(ctx.dataView, block), getCompressionMethod(block.compression), undefined, 'dataview')
479
+ .then((view) => readBrobXmpView(view, ctx));
480
+ }
481
+ if (block.carried !== undefined) {
482
+ if (block.decompressed && !ctx.takeDecompressedApplicationNotesAllowance(block.byteLength)) {
483
+ return undefined;
684
484
  }
685
- return !(Array.isArray(file) && file.length === 1 && file[0] === 'FileType');
485
+ return parsedTags('xmp', XmpTags.read(getBlockDataView(block, ctx), undefined, domParser, ctx.getDomParser), ctx);
686
486
  }
487
+ if (!hasXmpData(block)) {
488
+ return undefined;
489
+ }
490
+ return parsedTags('xmp', XmpTags.read(block.dataView || ctx.dataView, block.chunks, domParser, ctx.getDomParser), ctx);
491
+ }
687
492
 
688
- // Drops MakerNote.__offset once the maker note has been read, even when a
689
- // reader throws.
690
- function readExifCarriedGroups(parsedExifTags, exifTiffDataView, exifTiffHeaderOffset, exifByteOrder, exifValueBudget, source) {
691
- const groups = {};
493
+ function readBrobXmpView(view, ctx) {
494
+ if (ctx.exceedsBrobXmpSizeBound(view.byteLength)) {
495
+ return parsedTags('xmp', {}, ctx);
496
+ }
497
+ return parsedTags('xmp', XmpTags.read(view, [{dataOffset: 0, length: view.byteLength}], ctx.options.domParser, ctx.getDomParser), ctx);
498
+ }
692
499
 
693
- try {
694
- if (
695
- Constants.USE_IPTC
696
- && parsedExifTags['IPTC-NAA']
697
- && !source.hasIptcBlock
698
- && tagFilter.shouldParseGroup('iptc')
699
- ) {
700
- const readIptcTags = IptcTags.read(
701
- parsedExifTags['IPTC-NAA'].value,
702
- 0,
703
- includeUnknown,
704
- tagFilter,
705
- exifValueBudget
706
- );
707
- groups.iptc = filterTagsForParse('iptc', readIptcTags, tagFilter);
708
- }
500
+ // A compressed iCCP gives a thenable in async mode, which defers the block.
501
+ function readIccBlock(block, ctx) {
502
+ if (!hasIccData(block)) {
503
+ return undefined;
504
+ }
505
+ const readTags = IccTags.read(block.dataView || ctx.dataView, block.chunks, ctx.options.async, ctx.decompressConfig);
506
+ if (isThenable(readTags)) {
507
+ return readTags.then((resolvedTags) => parsedTags('icc', resolvedTags, ctx));
508
+ }
509
+ return parsedTags('icc', readTags, ctx);
510
+ }
709
511
 
710
- if (
711
- Constants.USE_XMP
712
- && parsedExifTags['ApplicationNotes']
713
- && isNumberArray(parsedExifTags['ApplicationNotes'].value)
714
- && !hasXmpData(xmpChunks)
715
- && tagFilter.shouldParseGroup('xmp')
716
- && (!source.decompressed || takeDecompressedApplicationNotesAllowance(parsedExifTags['ApplicationNotes'].value.length))
717
- ) {
718
- const readXmpTags = XmpTags.read(
719
- getByteString(parsedExifTags['ApplicationNotes'].value),
720
- undefined,
721
- domParser
722
- );
723
- groups.xmp = filterTagsForParse('xmp', readXmpTags, tagFilter);
724
- }
512
+ // The maker note readers filter their own tags.
513
+ function readMakerNoteBlock(block, ctx) {
514
+ const {includeUnknown, computed} = ctx.options;
515
+ if (Array.isArray(block.make) && block.make[0] === 'Canon') {
516
+ return {tags: CanonTags.read(block.tiffView, block.tiffHeaderOffset, block.makerNoteOffset, block.byteOrder, includeUnknown, computed, ctx.tagFilter, ctx.getValueBudget())};
517
+ }
518
+ if (hasPentaxType1Prefix(block.bytes)) {
519
+ return {tags: PentaxTags.read(block.tiffView, block.tiffHeaderOffset, block.makerNoteOffset, includeUnknown, computed, ctx.tagFilter, ctx.getValueBudget())};
520
+ }
521
+ return undefined;
522
+ }
725
523
 
726
- if (
727
- Constants.USE_PHOTOSHOP
728
- && parsedExifTags['ImageSourceData']
729
- && parsedExifTags['PhotoshopSettings']
730
- && Array.isArray(parsedExifTags['PhotoshopSettings'].value)
731
- && tagFilter.shouldParseGroup('photoshop')
732
- ) {
733
- const readPhotoshopTags = PhotoshopTags.read(
734
- parsedExifTags['PhotoshopSettings'].value,
735
- includeUnknown,
736
- tagFilter
737
- );
738
- groups.photoshop = filterTagsForParse('photoshop', readPhotoshopTags, tagFilter);
739
- }
524
+ function hasPentaxType1Prefix(makerNoteBytes) {
525
+ const PENTAX_ID_STRING = 'PENTAX ';
526
+ return Array.isArray(makerNoteBytes)
527
+ && makerNoteBytes.length > PENTAX_ID_STRING.length
528
+ && getStringValueFromArray(makerNoteBytes.slice(0, PENTAX_ID_STRING.length)) === PENTAX_ID_STRING;
529
+ }
740
530
 
741
- if (
742
- Constants.USE_ICC
743
- && parsedExifTags['ICC_Profile']
744
- && !hasIccData(iccChunks)
745
- && tagFilter.shouldParseGroup('icc')
746
- ) {
747
- const readIccTags = IccTags.read(
748
- parsedExifTags['ICC_Profile'].value,
749
- [{
750
- offset: 0,
751
- length: parsedExifTags['ICC_Profile'].value.length,
752
- chunkNumber: 1,
753
- chunksTotal: 1
754
- }]
755
- );
756
- groups.icc = filterTagsForParse('icc', readIccTags, tagFilter);
757
- }
531
+ // The main block's thumbnail is a candidate with or without an image. An
532
+ // embedded one is a candidate only with an image, within the copy bound, and
533
+ // not once an uncompressed block gave one; the decompressed blocks of a file
534
+ // all get to try, since they are read after the uncompressed ones.
535
+ function readThumbnailBlock(block, ctx) {
536
+ if (!ctx.tagFilter.shouldReturnTag('thumbnail', 'Thumbnail')) {
537
+ return undefined;
538
+ }
539
+ const parsed = filterTagsForParse('thumbnail', block.ifd1Tags, ctx.tagFilter);
540
+ if (block.rank === 'main') {
541
+ return {tags: Thumbnail.get(block.dataView, parsed, block.tiffHeaderOffset, ctx.getBase64Image)};
542
+ }
543
+ if (ctx.hasEmbeddedThumbnailImage) {
544
+ return undefined;
545
+ }
546
+ const lengthTag = parsed.JPEGInterchangeFormatLength;
547
+ if (!lengthTag || typeof lengthTag.value !== 'number' || lengthTag.value > ctx.embeddedThumbnailSizeBound - ctx.copiedThumbnailSize) {
548
+ return undefined;
549
+ }
550
+ const thumbnail = Thumbnail.get(block.dataView, parsed, block.tiffHeaderOffset, ctx.getBase64Image);
551
+ if (!thumbnail.image) {
552
+ return undefined;
553
+ }
554
+ ctx.copiedThumbnailSize += lengthTag.value;
555
+ if (!block.decompressed) {
556
+ ctx.hasEmbeddedThumbnailImage = true;
557
+ }
558
+ return {tags: thumbnail};
559
+ }
758
560
 
759
- if (
760
- Constants.USE_MAKER_NOTES
761
- && parsedExifTags['MakerNote']
762
- && tagFilter.shouldParseGroup('makerNotes')
763
- ) {
764
- if (hasCanonData(parsedExifTags)) {
765
- groups.makerNotes = CanonTags.read(
766
- exifTiffDataView,
767
- exifTiffHeaderOffset,
768
- parsedExifTags['MakerNote'].__offset,
769
- exifByteOrder,
770
- includeUnknown,
771
- computed,
772
- tagFilter,
773
- exifValueBudget
774
- );
775
- } else if (hasPentaxType1Data(parsedExifTags)) {
776
- groups.makerNotes = PentaxTags.read(
777
- exifTiffDataView,
778
- exifTiffHeaderOffset,
779
- parsedExifTags['MakerNote'].__offset,
780
- includeUnknown,
781
- computed,
782
- tagFilter,
783
- exifValueBudget
784
- );
785
- }
786
- }
787
- } finally {
788
- if (parsedExifTags['MakerNote']) {
789
- delete parsedExifTags['MakerNote'].__offset;
790
- }
561
+ // Every uncompressed text chunk of a PNG merges as one tier, so that the text
562
+ // tags sort after an uncompressed raw-profile Exif whatever the chunk order and
563
+ // two raw profiles merge group by group. A compressed chunk stays its own tier.
564
+ function combineUncompressedPngTextBlocks(mergeBlocks) {
565
+ const combined = [];
566
+ const leaves = [];
567
+ let tierIndex = -1;
568
+
569
+ for (let i = 0; i < mergeBlocks.length; i++) {
570
+ if (mergeBlocks[i].slot !== 'pngText') {
571
+ combined.push(mergeBlocks[i]);
572
+ continue;
573
+ }
574
+ if (tierIndex === -1) {
575
+ tierIndex = combined.length;
576
+ combined.push(undefined);
791
577
  }
578
+ collectLeafBlocks(mergeBlocks[i], leaves);
579
+ }
792
580
 
793
- return groups;
581
+ if (tierIndex !== -1) {
582
+ combined[tierIndex] = {slot: 'pngText', mode: 'nested', blocks: leaves};
794
583
  }
584
+ return combined;
585
+ }
795
586
 
796
- // The brob XMP bound covers the decompressed Exif blocks of a file together,
797
- // so that several cannot each pass it.
798
- function takeDecompressedApplicationNotesAllowance(byteLength) {
799
- if (exceedsBrobXmpSizeBound(decompressedApplicationNotesSize + byteLength, dataView)) {
800
- return false;
801
- }
802
- decompressedApplicationNotesSize += byteLength;
803
- return true;
587
+ function collectLeafBlocks(block, leaves) {
588
+ if (block.mode !== 'nested') {
589
+ leaves.push(block);
590
+ return;
591
+ }
592
+ for (let i = 0; i < block.blocks.length; i++) {
593
+ collectLeafBlocks(block.blocks[i], leaves);
804
594
  }
595
+ }
805
596
 
806
- // A maker note that throws must drop the groups, not the Exif tags already read.
807
- function readEmbeddedExifCarriedGroups(exifTiffDataView, readTags, exifTiffHeaderOffset, exifByteOrder, exifValueBudget, source) {
808
- try {
809
- return readExifCarriedGroups(
810
- filterTagsForParse('exif', readTags, tagFilter),
811
- exifTiffDataView,
812
- exifTiffHeaderOffset,
813
- exifByteOrder,
814
- exifValueBudget,
815
- source
816
- );
817
- } catch (error) {
818
- return {};
819
- }
597
+ function getDerivedBlocks({expanded, includeOffsets, async, ranges, truncated}) {
598
+ const blocks = [];
599
+ if (Constants.USE_EXIF) {
600
+ blocks.push({slot: 'gps', mode: 'gps'});
601
+ }
602
+ if (Constants.USE_EXIF || Constants.USE_XMP) {
603
+ blocks.push({slot: 'composite', mode: 'composite'});
820
604
  }
605
+ blocks.push({slot: 'thumbnail', mode: 'thumbnail'});
606
+ blocks.push({slot: 'fileType', mode: 'fileType'});
607
+ if (expanded && includeOffsets) {
608
+ blocks.push({
609
+ slot: 'metadataRange',
610
+ mode: 'metadataRange',
611
+ metadataBlocks: getMetadataRangeBlocks(ranges, async),
612
+ metadataTruncated: !!truncated,
613
+ });
614
+ }
615
+ return blocks;
821
616
  }
822
617
 
823
618
  // A caller-supplied DataView can be a window into a larger buffer. Extractors
@@ -846,45 +641,35 @@ function isDataViewLike(dataView) {
846
641
  && (typeof dataView.buffer.slice === 'function');
847
642
  }
848
643
 
849
- function getBrobDataView(dataView, brobChunk) {
644
+ function getBrobDataView(dataView, brobBlock) {
850
645
  // The box length is untrusted, so bound the view by the bytes present. The
851
646
  // JXL header parser never reports a dataOffset past the end of the view.
852
- const length = Math.max(0, Math.min(brobChunk.length, dataView.byteLength - brobChunk.dataOffset));
853
- return new DataView(dataView.buffer, dataView.byteOffset + brobChunk.dataOffset, length);
647
+ const length = Math.max(0, Math.min(brobBlock.length, dataView.byteLength - brobBlock.dataOffset));
648
+ return new DataView(dataView.buffer, dataView.byteOffset + brobBlock.dataOffset, length);
854
649
  }
855
650
 
856
- function exceedsBrobXmpSizeBound(byteLength, inputDataView) {
857
- return byteLength > BROB_XMP_SIZE_PER_INPUT_SIZE * inputDataView.byteLength + BROB_XMP_SIZE_ALLOWANCE;
858
- }
859
-
860
- function readExifTagsSafely(dataView, tiffHeaderOffset, includeUnknown, computed, tagFilter) {
861
- // Created outside the try so values decoded before a throw still count
862
- // against the budget that the maker note and MPF reads draw from. The data
863
- // view is only missing in unit tests that fake the tag readers.
864
- const valueBudget = dataView === undefined ? undefined : getValueBudget(dataView);
651
+ function readExifTagsSafely(dataView, tiffHeaderOffset, ctx, valueBudget) {
865
652
  try {
866
- const {tags, byteOrder} = readExifTags(dataView, tiffHeaderOffset, includeUnknown, computed, tagFilter, valueBudget);
867
- return {tags, byteOrder, valueBudget};
653
+ return readExifTags(dataView, tiffHeaderOffset, ctx, valueBudget);
868
654
  } catch (error) {
869
655
  // A malformed TIFF header (an out-of-bounds offset or an invalid byte
870
656
  // order marker, e.g. from a HEIC/AVIF iloc that does not point at real
871
657
  // Exif) must not abort the whole parse. Skip Exif instead, but keep the
872
- // same {tags, byteOrder, valueBudget} shape so callers can destructure
873
- // safely.
874
- return {tags: {}, byteOrder: ByteOrder.BIG_ENDIAN, valueBudget};
658
+ // same shape so callers can destructure safely.
659
+ return {tags: {}, byteOrder: ByteOrder.BIG_ENDIAN, makerNoteOffset: undefined};
875
660
  }
876
661
  }
877
662
 
878
- function readExifTags(dataView, tiffHeaderOffset, includeUnknown, computed, tagFilter, valueBudget) {
663
+ function readExifTags(dataView, tiffHeaderOffset, ctx, valueBudget) {
879
664
  return Tags.read(
880
665
  dataView,
881
666
  tiffHeaderOffset,
882
- includeUnknown,
883
- computed,
884
- tagFilter,
667
+ ctx.options.includeUnknown,
668
+ ctx.options.computed,
669
+ ctx.tagFilter,
885
670
  valueBudget,
886
671
  getExifTagNames(),
887
- shouldReadThumbnailIfd(tagFilter)
672
+ shouldReadThumbnailIfd(ctx.tagFilter)
888
673
  );
889
674
  }
890
675
 
@@ -908,23 +693,45 @@ function shouldReadThumbnailIfd(tagFilter) {
908
693
  return Constants.USE_THUMBNAIL && tagFilter.shouldParseGroup('thumbnail');
909
694
  }
910
695
 
911
- // Finders report every kind they find; list only the kinds this build parses.
912
- function getParsedMetadataBlocks(metadataBlocks, fileType) {
913
- if (!metadataBlocks) {
914
- return metadataBlocks;
696
+ // Finders report every kind they find; list only the kinds this build parses,
697
+ // and in sync mode only the blocks it reads (isHiddenInSyncMode).
698
+ function getMetadataRangeBlocks(ranges, async) {
699
+ const entries = ranges || [];
700
+ const isCapped = entries.length >= MAX_METADATA_BLOCKS;
701
+ const lastIndex = entries.length - 1;
702
+ const metadataBlocks = [];
703
+ for (let i = 0; i < entries.length; i++) {
704
+ const {block, start, end} = entries[i];
705
+ // At the cap the last entry was widened over every later block, so it
706
+ // stays whatever its own block is, hidden in sync mode or not parsed.
707
+ const isWidenedLast = isCapped && i === lastIndex;
708
+ if (isWidenedLast || ((async || !isHiddenInSyncMode(block)) && isParsedRangeType(block))) {
709
+ metadataBlocks.push({type: getRangeType(block), start, end});
710
+ }
915
711
  }
916
- const format = fileType && fileType.value;
917
- const isCapped = metadataBlocks.length >= MAX_METADATA_BLOCKS;
918
- const lastIndex = metadataBlocks.length - 1;
919
- return metadataBlocks.filter((block, index) => isParsedMetadataBlock(format, block.type)
920
- // At the cap the last block was widened over every later block, so it stays.
921
- || (isCapped && index === lastIndex));
712
+ return metadataBlocks;
922
713
  }
923
714
 
924
- function isParsedMetadataBlock(format, blockType) {
925
- switch (blockType) {
715
+ // The range types predate the block kinds and stay as they are.
716
+ function getRangeType(block) {
717
+ if (isPngTextChunkBlock(block) || block.kind === 'pngChunk') {
718
+ return 'png';
719
+ }
720
+ if (block.kind === 'pngFile') {
721
+ return 'file';
722
+ }
723
+ return block.kind;
724
+ }
725
+
726
+ function isParsedRangeType(block) {
727
+ if (isPngTextChunkBlock(block)) {
728
+ return true;
729
+ }
730
+ switch (block.kind) {
926
731
  case 'file':
927
- return format === 'png' ? Constants.USE_PNG_FILE : Constants.USE_FILE;
732
+ return Constants.USE_FILE;
733
+ case 'pngFile':
734
+ return Constants.USE_PNG_FILE;
928
735
  case 'exif':
929
736
  return Constants.USE_EXIF;
930
737
  case 'jfif':
@@ -942,169 +749,6 @@ function isParsedMetadataBlock(format, blockType) {
942
749
  }
943
750
  }
944
751
 
945
- function getEmbeddedExifThumbnailReader(tagFilter, inputDataView) {
946
- if (
947
- !Constants.USE_EXIF
948
- || !Constants.USE_THUMBNAIL
949
- || !tagFilter.shouldReturnTag('thumbnail', 'Thumbnail')
950
- ) {
951
- return undefined;
952
- }
953
- let copiedThumbnailSize = 0;
954
- return (dataView, thumbnailIfdTags, tiffHeaderOffset) => {
955
- const parsedThumbnailIfdTags = filterTagsForParse('thumbnail', thumbnailIfdTags, tagFilter);
956
- const lengthTag = parsedThumbnailIfdTags.JPEGInterchangeFormatLength;
957
- const sizeBound =
958
- EMBEDDED_THUMBNAIL_SIZE_PER_INPUT_SIZE * inputDataView.byteLength + EMBEDDED_THUMBNAIL_SIZE_ALLOWANCE;
959
- if (!hasLengthWithin(lengthTag, sizeBound - copiedThumbnailSize)) {
960
- return parsedThumbnailIfdTags;
961
- }
962
- const thumbnail = Thumbnail.get(dataView, parsedThumbnailIfdTags, tiffHeaderOffset);
963
- if (thumbnail.image) {
964
- copiedThumbnailSize += lengthTag.value;
965
- }
966
- return thumbnail;
967
- };
968
- }
969
-
970
- function hasLengthWithin(lengthTag, maxLength) {
971
- return !!lengthTag
972
- && typeof lengthTag.value === 'number'
973
- && lengthTag.value <= maxLength;
974
- }
975
-
976
- function filterTagsForParse(groupKey, readTags, tagFilter) {
977
- if (!tagFilter.isActive) {
978
- return readTags;
979
- }
980
-
981
- return filterTags(groupKey, readTags, tagFilter.shouldParseTag);
982
- }
983
-
984
- function filterTagsForReturn(groupKey, readTags, tagFilter) {
985
- if (!tagFilter.isActive) {
986
- return readTags;
987
- }
988
-
989
- return filterTags(groupKey, readTags, tagFilter.shouldReturnTag);
990
- }
991
-
992
- function filterTags(groupKey, readTags, matchesTag) {
993
- if (!readTags) {
994
- return readTags;
995
- }
996
-
997
- const filteredTags = {};
998
-
999
- for (const tagName in readTags) {
1000
- const tagValue = readTags[tagName];
1001
- const tagId = getTagId(tagValue);
1002
-
1003
- if (matchesTag(groupKey, tagName, tagId)) {
1004
- setProperty(filteredTags, tagName, tagValue);
1005
- }
1006
- }
1007
-
1008
- return filteredTags;
1009
-
1010
- function getTagId(tagValue) {
1011
- if (!tagValue) {
1012
- return undefined;
1013
- }
1014
-
1015
- if (Array.isArray(tagValue)) {
1016
- if (tagValue.length === 0) {
1017
- return undefined;
1018
- }
1019
-
1020
- return tagValue[0].id;
1021
- }
1022
-
1023
- return tagValue.id;
1024
- }
1025
- }
1026
-
1027
- function hasPotentialMetaData({
1028
- fileType,
1029
- fileDataOffset,
1030
- jfifDataOffset,
1031
- tiffHeaderOffset,
1032
- iptcDataOffset,
1033
- xmpChunks,
1034
- iccChunks,
1035
- mpfDataOffset,
1036
- pngHeaderOffset,
1037
- pngTextChunks,
1038
- pngChunkOffsets,
1039
- vp8xChunkOffset,
1040
- gifHeaderOffset,
1041
- jxlCodestreamOffset,
1042
- imageDimensionsOffset,
1043
- pixelInformationOffset,
1044
- }) {
1045
- return !!fileType
1046
- || (
1047
- Constants.USE_JPEG
1048
- && Constants.USE_FILE
1049
- && fileDataOffset !== undefined
1050
- )
1051
- || (
1052
- Constants.USE_JPEG
1053
- && Constants.USE_JFIF
1054
- && jfifDataOffset !== undefined
1055
- )
1056
- || (
1057
- Constants.USE_EXIF
1058
- && tiffHeaderOffset !== undefined
1059
- )
1060
- || (
1061
- Constants.USE_JPEG
1062
- && Constants.USE_IPTC
1063
- && iptcDataOffset !== undefined
1064
- )
1065
- || (
1066
- Constants.USE_XMP
1067
- && hasXmpData(xmpChunks)
1068
- )
1069
- || (
1070
- Constants.USE_ICC
1071
- && hasIccData(iccChunks)
1072
- )
1073
- || (
1074
- Constants.USE_MPF
1075
- && mpfDataOffset !== undefined
1076
- )
1077
- || (
1078
- Constants.USE_PNG
1079
- && Constants.USE_PNG_FILE
1080
- && pngHeaderOffset !== undefined
1081
- )
1082
- || (
1083
- Constants.USE_PNG
1084
- && hasPngTextData(pngTextChunks)
1085
- )
1086
- || (
1087
- Constants.USE_PNG
1088
- && pngChunkOffsets !== undefined
1089
- )
1090
- || (
1091
- Constants.USE_WEBP
1092
- && vp8xChunkOffset !== undefined
1093
- )
1094
- || (
1095
- Constants.USE_GIF
1096
- && gifHeaderOffset !== undefined
1097
- )
1098
- || (
1099
- Constants.USE_JXL
1100
- && jxlCodestreamOffset !== undefined
1101
- )
1102
- || (
1103
- (Constants.USE_HEIC || Constants.USE_AVIF)
1104
- && (imageDimensionsOffset !== undefined || pixelInformationOffset !== undefined)
1105
- );
1106
- }
1107
-
1108
752
  function getGpsGroupFromExifTags(exifTags) {
1109
753
  let gps = undefined;
1110
754
 
@@ -1158,27 +802,31 @@ function isNumberArray(value) {
1158
802
  return Array.isArray(value) && typeof value[0] === 'number';
1159
803
  }
1160
804
 
1161
- function hasXmpData(xmpChunks) {
1162
- return Array.isArray(xmpChunks) && xmpChunks.length > 0;
805
+ // A brob block carries compressed XMP, not chunks.
806
+ function hasXmpData(xmpBlock) {
807
+ return xmpBlock !== undefined && xmpBlock.compression === undefined && xmpBlock.chunks.length > 0;
1163
808
  }
1164
809
 
1165
- function hasIccData(iccDataOffsets) {
1166
- return Array.isArray(iccDataOffsets) && iccDataOffsets.length > 0;
810
+ function hasIccData(iccBlock) {
811
+ return iccBlock !== undefined && iccBlock.chunks.length > 0;
1167
812
  }
1168
813
 
1169
- function hasCanonData(tags) {
1170
- return tags['Make'] && tags['Make'].value && Array.isArray(tags['Make'].value) && tags['Make'].value[0] === 'Canon'
1171
- && tags['MakerNote'] && tags['MakerNote'].__offset;
814
+ function hasPngTextData(pngTextBlocks) {
815
+ return Array.isArray(pngTextBlocks) && pngTextBlocks.length > 0;
1172
816
  }
1173
817
 
1174
- function hasPentaxType1Data(tags) {
1175
- const PENTAX_ID_STRING = 'PENTAX ';
1176
- return Array.isArray(tags['MakerNote'].value)
1177
- && tags['MakerNote'].value.length > PENTAX_ID_STRING.length
1178
- && getStringValueFromArray(tags['MakerNote'].value.slice(0, PENTAX_ID_STRING.length)) === PENTAX_ID_STRING
1179
- && tags['MakerNote'].__offset;
818
+ function isPngTextChunkBlock(block) {
819
+ return block.text !== undefined;
1180
820
  }
1181
821
 
1182
- function hasPngTextData(pngTextChunks) {
1183
- return Array.isArray(pngTextChunks) && pngTextChunks.length > 0;
822
+ // Decision 2026-10-21: sync mode keeps leaving PNG compressed-text chunks
823
+ // (TYPE_ZTXT, whatever their header says) and the iCCP chunk out of
824
+ // metadataRange, the potential-metadata check and the readers, as the PNG
825
+ // finder did while it took the async flag; the iCCP block is always
826
+ // compressed. A compressed iTXt and a brob box stay listed, and unread, in
827
+ // sync mode, as before. The USE_PNG gate keeps the PNG finder's constant out
828
+ // of a build without PNG.
829
+ function isHiddenInSyncMode(block) {
830
+ return (Constants.USE_PNG && isPngTextChunkBlock(block) && block.text.chunkType === TYPE_ZTXT)
831
+ || (block.kind === 'icc' && block.compression !== undefined);
1184
832
  }