taglib-wasm 2.4.1 → 2.5.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.
Files changed (92) hide show
  1. package/README.md +26 -22
  2. package/dist/bwf/bext.d.ts.map +1 -1
  3. package/dist/bwf/bext.js +25 -16
  4. package/dist/constants/complex-properties.d.ts.map +1 -1
  5. package/dist/constants/general-extended-properties.d.ts +2 -1
  6. package/dist/constants/general-extended-properties.d.ts.map +1 -1
  7. package/dist/constants/general-extended-properties.js +5 -2
  8. package/dist/constants/properties.d.ts.map +1 -1
  9. package/dist/constants/properties.js +2 -2
  10. package/dist/disc-folder.js +79 -45
  11. package/dist/folder-api/album-corroborate.d.ts.map +1 -1
  12. package/dist/folder-api/album-corroborate.js +25 -11
  13. package/dist/folder-api/album-discs.d.ts.map +1 -1
  14. package/dist/folder-api/album-discs.js +2 -5
  15. package/dist/folder-api/album-grouping.d.ts.map +1 -1
  16. package/dist/folder-api/album-grouping.js +27 -15
  17. package/dist/folder-api/album-identity.js +1 -1
  18. package/dist/folder-api/folder-disc.d.ts.map +1 -1
  19. package/dist/folder-api/folder-disc.js +24 -13
  20. package/dist/index.browser.d.ts +1 -1
  21. package/dist/index.browser.d.ts.map +1 -1
  22. package/dist/index.browser.js +2 -4477
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/msgpack/encoder.d.ts.map +1 -1
  26. package/dist/msgpack/encoder.js +3 -1
  27. package/dist/runtime/module-loader.d.ts.map +1 -1
  28. package/dist/runtime/module-loader.js +43 -33
  29. package/dist/runtime/platform-io.d.ts.map +1 -1
  30. package/dist/runtime/platform-io.js +4 -2
  31. package/dist/runtime/unified-loader/module-loading.d.ts.map +1 -1
  32. package/dist/runtime/unified-loader/module-loading.js +3 -2
  33. package/dist/runtime/wasi-adapter/audio-properties.d.ts.map +1 -1
  34. package/dist/runtime/wasi-adapter/audio-properties.js +8 -2
  35. package/dist/runtime/wasi-adapter/file-handle.d.ts +3 -1
  36. package/dist/runtime/wasi-adapter/file-handle.d.ts.map +1 -1
  37. package/dist/runtime/wasi-adapter/file-handle.js +16 -4
  38. package/dist/runtime/wasi-adapter/handle-state.d.ts.map +1 -1
  39. package/dist/runtime/wasi-adapter/handle-state.js +7 -1
  40. package/dist/runtime/wasi-adapter/mp4-items.d.ts +24 -0
  41. package/dist/runtime/wasi-adapter/mp4-items.d.ts.map +1 -1
  42. package/dist/runtime/wasi-adapter/mp4-items.js +119 -2
  43. package/dist/runtime/wasi-adapter/property-surface.d.ts.map +1 -1
  44. package/dist/runtime/wasi-adapter/property-surface.js +15 -6
  45. package/dist/runtime/wasi-adapter/structured-fields.js +1 -1
  46. package/dist/runtime/wasi-adapter/tag-keys.d.ts.map +1 -1
  47. package/dist/runtime/wasi-adapter/tag-keys.js +3 -1
  48. package/dist/runtime/wasi-adapter/wasm-io.d.ts.map +1 -1
  49. package/dist/simple/batch-operations.d.ts.map +1 -1
  50. package/dist/simple/batch-operations.js +5 -1
  51. package/dist/simple.browser.js +2 -3694
  52. package/dist/taglib/audio-file-base.d.ts +35 -1
  53. package/dist/taglib/audio-file-base.d.ts.map +1 -1
  54. package/dist/taglib/audio-file-base.js +90 -20
  55. package/dist/taglib/audio-file-checksum.d.ts.map +1 -1
  56. package/dist/taglib/audio-file-checksum.js +17 -13
  57. package/dist/taglib/audio-file-impl.d.ts.map +1 -1
  58. package/dist/taglib/audio-file-interface.d.ts +18 -1
  59. package/dist/taglib/audio-file-interface.d.ts.map +1 -1
  60. package/dist/taglib/embind-adapter.d.ts +3 -0
  61. package/dist/taglib/embind-adapter.d.ts.map +1 -1
  62. package/dist/taglib/embind-adapter.js +6 -0
  63. package/dist/taglib/extra-state-registry.d.ts.map +1 -1
  64. package/dist/taglib/extra-state-registry.js +15 -0
  65. package/dist/taglib/load-audio-data.d.ts +11 -8
  66. package/dist/taglib/load-audio-data.d.ts.map +1 -1
  67. package/dist/taglib/load-audio-data.js +39 -43
  68. package/dist/taglib/metadata-extent.d.ts.map +1 -1
  69. package/dist/taglib/metadata-extent.js +59 -32
  70. package/dist/taglib/mutable-tag-impl.d.ts.map +1 -1
  71. package/dist/taglib/mutable-tag-impl.js +72 -69
  72. package/dist/taglib/taglib-class.d.ts.map +1 -1
  73. package/dist/taglib/taglib-class.js +15 -5
  74. package/dist/taglib-wasi.wasm +0 -0
  75. package/dist/taglib-web.wasm +0 -0
  76. package/dist/taglib-wrapper.js +1 -1
  77. package/dist/types/tags.d.ts +44 -0
  78. package/dist/types/tags.d.ts.map +1 -1
  79. package/dist/utils/mp4-freeform.d.ts +20 -0
  80. package/dist/utils/mp4-freeform.d.ts.map +1 -0
  81. package/dist/utils/mp4-freeform.js +111 -0
  82. package/dist/utils/path.d.ts.map +1 -1
  83. package/dist/utils/path.js +3 -1
  84. package/dist/utils/tag-mapping.d.ts.map +1 -1
  85. package/dist/utils/tag-mapping.js +30 -18
  86. package/dist/version.d.ts +1 -1
  87. package/dist/version.js +1 -1
  88. package/dist/wasm.d.ts +3 -0
  89. package/dist/wasm.d.ts.map +1 -1
  90. package/dist/web-utils/data-url.js +1 -1
  91. package/dist/web.browser.js +2 -3412
  92. package/package.json +2 -1
@@ -1,3694 +1,2 @@
1
- //#region \0rolldown/runtime.js
2
- var __defProp = Object.defineProperty;
3
- var __esmMin = (fn, res, err) => () => {
4
- if (err) throw err[0];
5
- try {
6
- return fn && (res = fn(fn = 0)), res;
7
- } catch (e) {
8
- throw err = [e], e;
9
- }
10
- };
11
- var __exportAll = (all, no_symbols) => {
12
- let target = {};
13
- for (var name in all) __defProp(target, name, {
14
- get: all[name],
15
- enumerable: true
16
- });
17
- if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
18
- return target;
19
- };
20
- //#endregion
21
- //#region src/types/audio-formats.ts
22
- function isNamedAudioInput(input) {
23
- return typeof input === "object" && input !== null && "name" in input && "data" in input && !(input instanceof File) && !(input instanceof Uint8Array) && !(input instanceof ArrayBuffer);
24
- }
25
- var init_audio_formats = __esmMin((() => {}));
26
- //#endregion
27
- //#region src/types/tags.ts
28
- var init_tags = __esmMin((() => {}));
29
- //#endregion
30
- //#region src/types/metadata-mappings.ts
31
- var init_metadata_mappings = __esmMin((() => {}));
32
- //#endregion
33
- //#region src/types/pictures.ts
34
- var PICTURE_TYPE_VALUES, PICTURE_TYPE_NAMES;
35
- var init_pictures = __esmMin((() => {
36
- PICTURE_TYPE_VALUES = {
37
- Other: 0,
38
- FileIcon: 1,
39
- OtherFileIcon: 2,
40
- FrontCover: 3,
41
- BackCover: 4,
42
- LeafletPage: 5,
43
- Media: 6,
44
- LeadArtist: 7,
45
- Artist: 8,
46
- Conductor: 9,
47
- Band: 10,
48
- Composer: 11,
49
- Lyricist: 12,
50
- RecordingLocation: 13,
51
- DuringRecording: 14,
52
- DuringPerformance: 15,
53
- MovieScreenCapture: 16,
54
- ColouredFish: 17,
55
- Illustration: 18,
56
- BandLogo: 19,
57
- PublisherLogo: 20
58
- };
59
- PICTURE_TYPE_NAMES = {
60
- 0: "Other",
61
- 1: "FileIcon",
62
- 2: "OtherFileIcon",
63
- 3: "FrontCover",
64
- 4: "BackCover",
65
- 5: "LeafletPage",
66
- 6: "Media",
67
- 7: "LeadArtist",
68
- 8: "Artist",
69
- 9: "Conductor",
70
- 10: "Band",
71
- 11: "Composer",
72
- 12: "Lyricist",
73
- 13: "RecordingLocation",
74
- 14: "DuringRecording",
75
- 15: "DuringPerformance",
76
- 16: "MovieScreenCapture",
77
- 17: "ColouredFish",
78
- 18: "Illustration",
79
- 19: "BandLogo",
80
- 20: "PublisherLogo"
81
- };
82
- }));
83
- //#endregion
84
- //#region src/types/chapters.ts
85
- var init_chapters = __esmMin((() => {}));
86
- //#endregion
87
- //#region src/types/bwf.ts
88
- var init_bwf = __esmMin((() => {}));
89
- //#endregion
90
- //#region src/types/config.ts
91
- var init_config = __esmMin((() => {}));
92
- //#endregion
93
- //#region src/types/format-property-keys.ts
94
- var init_format_property_keys = __esmMin((() => {}));
95
- //#endregion
96
- //#region src/types/index.ts
97
- var init_types$1 = __esmMin((() => {
98
- init_audio_formats();
99
- init_tags();
100
- init_metadata_mappings();
101
- init_pictures();
102
- init_chapters();
103
- init_bwf();
104
- init_config();
105
- init_format_property_keys();
106
- }));
107
- //#endregion
108
- //#region src/types.ts
109
- var init_types = __esmMin((() => {
110
- init_types$1();
111
- }));
112
- //#endregion
113
- //#region src/bwf/bext.ts
114
- function readFixedString(bytes, offset, len) {
115
- let end = offset;
116
- const max = Math.min(offset + len, bytes.length);
117
- while (end < max && bytes[end] !== 0) end++;
118
- let s = "";
119
- for (let i = offset; i < end; i++) s += String.fromCharCode(bytes[i]);
120
- return s;
121
- }
122
- function writeFixedString(bytes, offset, len, value) {
123
- for (let i = 0; i < len; i++) bytes[offset + i] = i < value.length ? value.charCodeAt(i) & 255 : 0;
124
- }
125
- function clampInt16(n) {
126
- return Math.max(-32768, Math.min(32767, Math.round(n)));
127
- }
128
- function loudnessRaw(v) {
129
- return v === void 0 ? LOUDNESS_UNSET : clampInt16(v * 100);
130
- }
131
- function loudnessFromRaw(raw) {
132
- return raw === LOUDNESS_UNSET ? void 0 : raw / 100;
133
- }
134
- function bytesToHex(bytes) {
135
- let s = "";
136
- for (const b of bytes) s += b.toString(16).padStart(2, "0");
137
- return s;
138
- }
139
- function hexToBytes(hex, outLen) {
140
- const clean = hex.replace(/[^0-9a-fA-F]/g, "");
141
- const out = new Uint8Array(outLen);
142
- for (let i = 0; i + 1 < clean.length + 1 && i / 2 < outLen; i += 2) {
143
- const pair = clean.slice(i, i + 2);
144
- if (pair.length === 2) out[i / 2] = parseInt(pair, 16);
145
- }
146
- return out;
147
- }
148
- function decodeBext(bytes) {
149
- if (bytes.length < 348) return void 0;
150
- const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
151
- const timeRefLow = dv.getUint32(338, true);
152
- const timeRefHigh = dv.getUint32(342, true);
153
- const version = dv.getUint16(VERSION_OFFSET, true);
154
- const result = {
155
- description: readFixedString(bytes, 0, 256),
156
- originator: readFixedString(bytes, 256, 32),
157
- originatorReference: readFixedString(bytes, 288, 32),
158
- originationDate: readFixedString(bytes, 320, 10),
159
- originationTime: readFixedString(bytes, 330, 8),
160
- timeReferenceSamples: BigInt(timeRefHigh) << 32n | BigInt(timeRefLow),
161
- version,
162
- codingHistory: bytes.length > FIXED_PREFIX_LEN ? readFixedString(bytes, FIXED_PREFIX_LEN, bytes.length - FIXED_PREFIX_LEN) : ""
163
- };
164
- if (version >= 1 && bytes.length >= 412) result.umid = bytesToHex(bytes.subarray(UMID_OFFSET, 412));
165
- if (version >= 2 && bytes.length >= 422) {
166
- const lv = loudnessFromRaw(dv.getInt16(LOUDNESS_OFFSET, true));
167
- const lr = loudnessFromRaw(dv.getInt16(414, true));
168
- const mtp = loudnessFromRaw(dv.getInt16(416, true));
169
- const mml = loudnessFromRaw(dv.getInt16(418, true));
170
- const msl = loudnessFromRaw(dv.getInt16(420, true));
171
- if (lv !== void 0) result.loudnessValueDb = lv;
172
- if (lr !== void 0) result.loudnessRangeDb = lr;
173
- if (mtp !== void 0) result.maxTruePeakLevelDbtp = mtp;
174
- if (mml !== void 0) result.maxMomentaryLoudnessDb = mml;
175
- if (msl !== void 0) result.maxShortTermLoudnessDb = msl;
176
- }
177
- return result;
178
- }
179
- function encodeBext(b) {
180
- const codingHistory = b.codingHistory ?? "";
181
- const bytes = new Uint8Array(FIXED_PREFIX_LEN + codingHistory.length);
182
- const dv = new DataView(bytes.buffer);
183
- const hasLoudness = b.loudnessValueDb !== void 0 || b.loudnessRangeDb !== void 0 || b.maxTruePeakLevelDbtp !== void 0 || b.maxMomentaryLoudnessDb !== void 0 || b.maxShortTermLoudnessDb !== void 0;
184
- const version = Number.isInteger(b.version) ? b.version : hasLoudness ? 2 : b.umid ? 1 : 0;
185
- writeFixedString(bytes, 0, 256, b.description ?? "");
186
- writeFixedString(bytes, 256, 32, b.originator ?? "");
187
- writeFixedString(bytes, 288, 32, b.originatorReference ?? "");
188
- writeFixedString(bytes, 320, 10, b.originationDate ?? "");
189
- writeFixedString(bytes, 330, 8, b.originationTime ?? "");
190
- const tr = b.timeReferenceSamples ?? 0n;
191
- dv.setUint32(338, Number(tr & 4294967295n), true);
192
- dv.setUint32(342, Number(tr >> 32n & 4294967295n), true);
193
- dv.setUint16(VERSION_OFFSET, version, true);
194
- if (version >= 1 && b.umid) bytes.set(hexToBytes(b.umid, UMID_LEN), UMID_OFFSET);
195
- if (version >= 2) {
196
- dv.setInt16(LOUDNESS_OFFSET, loudnessRaw(b.loudnessValueDb), true);
197
- dv.setInt16(414, loudnessRaw(b.loudnessRangeDb), true);
198
- dv.setInt16(416, loudnessRaw(b.maxTruePeakLevelDbtp), true);
199
- dv.setInt16(418, loudnessRaw(b.maxMomentaryLoudnessDb), true);
200
- dv.setInt16(420, loudnessRaw(b.maxShortTermLoudnessDb), true);
201
- }
202
- writeFixedString(bytes, FIXED_PREFIX_LEN, codingHistory.length, codingHistory);
203
- return bytes;
204
- }
205
- var FIXED_PREFIX_LEN, VERSION_OFFSET, UMID_OFFSET, UMID_LEN, LOUDNESS_OFFSET, LOUDNESS_UNSET;
206
- var init_bext = __esmMin((() => {
207
- FIXED_PREFIX_LEN = 602;
208
- VERSION_OFFSET = 346;
209
- UMID_OFFSET = 348;
210
- UMID_LEN = 64;
211
- LOUDNESS_OFFSET = 412;
212
- LOUDNESS_UNSET = 32767;
213
- }));
214
- //#endregion
215
- //#region src/errors/base.ts
216
- var SUPPORTED_FORMATS, TagLibError;
217
- var init_base = __esmMin((() => {
218
- SUPPORTED_FORMATS = [
219
- "MP3",
220
- "AAC",
221
- "MP4",
222
- "M4A",
223
- "FLAC",
224
- "OGG",
225
- "OPUS",
226
- "OggFLAC",
227
- "SPEEX",
228
- "WAV",
229
- "AIFF",
230
- "ASF",
231
- "APE",
232
- "DSF",
233
- "DSDIFF",
234
- "WV",
235
- "MPC",
236
- "TTA",
237
- "SHN",
238
- "MOD",
239
- "S3M",
240
- "IT",
241
- "XM",
242
- "MATROSKA",
243
- "MKA"
244
- ];
245
- TagLibError = class TagLibError extends Error {
246
- constructor(code, message, details) {
247
- super(message);
248
- this.code = code;
249
- this.details = details;
250
- this.name = "TagLibError";
251
- Object.setPrototypeOf(this, TagLibError.prototype);
252
- }
253
- };
254
- }));
255
- //#endregion
256
- //#region src/errors/classes.ts
257
- function errorMessage(error) {
258
- return error instanceof Error ? error.message : String(error);
259
- }
260
- function createErrorMessage(prefix, details) {
261
- return `${prefix}: ${details}`;
262
- }
263
- function formatFileSize(bytes) {
264
- if (bytes < 1024) return `${bytes} bytes`;
265
- if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`;
266
- return `${(bytes / 1048576).toFixed(1)} MB`;
267
- }
268
- var TagLibInitializationError, InvalidFormatError, UnsupportedFormatError, FileOperationError, MetadataError, MemoryError, EnvironmentError;
269
- var init_classes = __esmMin((() => {
270
- init_base();
271
- TagLibInitializationError = class TagLibInitializationError extends TagLibError {
272
- constructor(message, details) {
273
- super("INITIALIZATION", createErrorMessage("Failed to initialize TagLib Wasm module", message), details);
274
- this.name = "TagLibInitializationError";
275
- Object.setPrototypeOf(this, TagLibInitializationError.prototype);
276
- }
277
- };
278
- InvalidFormatError = class InvalidFormatError extends TagLibError {
279
- constructor(message, bufferSize, details) {
280
- const errorDetails = [`Invalid audio file format: ${message}`];
281
- if (bufferSize !== void 0) {
282
- errorDetails.push(`Buffer size: ${formatFileSize(bufferSize)}`);
283
- if (bufferSize < 1024) errorDetails.push("Audio files must be at least 1KB to contain valid headers.");
284
- }
285
- super("INVALID_FORMAT", errorDetails.join(". "), {
286
- ...details,
287
- bufferSize
288
- });
289
- this.bufferSize = bufferSize;
290
- this.name = "InvalidFormatError";
291
- Object.setPrototypeOf(this, InvalidFormatError.prototype);
292
- }
293
- };
294
- UnsupportedFormatError = class UnsupportedFormatError extends TagLibError {
295
- constructor(format, supportedFormats = SUPPORTED_FORMATS, details) {
296
- super("UNSUPPORTED_FORMAT", `Unsupported audio format: ${format}. Supported formats: ${supportedFormats.join(", ")}`, {
297
- ...details,
298
- format,
299
- supportedFormats
300
- });
301
- this.format = format;
302
- this.supportedFormats = supportedFormats;
303
- this.name = "UnsupportedFormatError";
304
- Object.setPrototypeOf(this, UnsupportedFormatError.prototype);
305
- }
306
- };
307
- FileOperationError = class FileOperationError extends TagLibError {
308
- constructor(operation, message, path, details) {
309
- const errorDetails = [`Failed to ${operation} file`];
310
- if (path) errorDetails.push(`Path: ${path}`);
311
- errorDetails.push(message);
312
- super("FILE_OPERATION", errorDetails.join(". "), {
313
- ...details,
314
- operation,
315
- path
316
- });
317
- this.operation = operation;
318
- this.path = path;
319
- this.name = "FileOperationError";
320
- Object.setPrototypeOf(this, FileOperationError.prototype);
321
- }
322
- };
323
- MetadataError = class MetadataError extends TagLibError {
324
- constructor(operation, message, field, details) {
325
- const errorDetails = [`Failed to ${operation} metadata`];
326
- if (field) errorDetails.push(`Field: ${field}`);
327
- errorDetails.push(message);
328
- super("METADATA", errorDetails.join(". "), {
329
- ...details,
330
- operation,
331
- field
332
- });
333
- this.operation = operation;
334
- this.field = field;
335
- this.name = "MetadataError";
336
- Object.setPrototypeOf(this, MetadataError.prototype);
337
- }
338
- };
339
- MemoryError = class MemoryError extends TagLibError {
340
- constructor(message, details) {
341
- super("MEMORY", createErrorMessage("Memory allocation failed", message), details);
342
- this.name = "MemoryError";
343
- Object.setPrototypeOf(this, MemoryError.prototype);
344
- }
345
- };
346
- EnvironmentError = class EnvironmentError extends TagLibError {
347
- constructor(environment, reason, requiredFeature) {
348
- const message = requiredFeature ? `Environment '${environment}' ${reason}. Required feature: ${requiredFeature}.` : `Environment '${environment}' ${reason}.`;
349
- super("ENVIRONMENT", message);
350
- this.environment = environment;
351
- this.reason = reason;
352
- this.requiredFeature = requiredFeature;
353
- this.name = "EnvironmentError";
354
- Object.setPrototypeOf(this, EnvironmentError.prototype);
355
- }
356
- };
357
- }));
358
- //#endregion
359
- //#region src/errors/guards.ts
360
- function isTagLibError(error) {
361
- return error instanceof TagLibError;
362
- }
363
- function isInvalidFormatError(error) {
364
- return error instanceof InvalidFormatError;
365
- }
366
- function isUnsupportedFormatError(error) {
367
- return error instanceof UnsupportedFormatError;
368
- }
369
- function isFileOperationError(error) {
370
- return error instanceof FileOperationError;
371
- }
372
- function isMetadataError(error) {
373
- return error instanceof MetadataError;
374
- }
375
- function isMemoryError(error) {
376
- return error instanceof MemoryError;
377
- }
378
- function isEnvironmentError(error) {
379
- return error instanceof EnvironmentError;
380
- }
381
- var init_guards = __esmMin((() => {
382
- init_base();
383
- init_classes();
384
- }));
385
- //#endregion
386
- //#region src/errors/index.ts
387
- var init_errors$1 = __esmMin((() => {
388
- init_base();
389
- init_classes();
390
- init_guards();
391
- }));
392
- //#endregion
393
- //#region src/errors.ts
394
- var init_errors = __esmMin((() => {
395
- init_errors$1();
396
- }));
397
- //#endregion
398
- //#region src/taglib/audio-file-bwf.ts
399
- function requireBwf(format) {
400
- if (!BWF_FORMATS.has(format)) throw new UnsupportedFormatError(format, ["WAV", "FLAC"], { operation: "BWF metadata" });
401
- }
402
- function getBextData(handle) {
403
- const raw = handle.getBextData();
404
- return raw && raw.length > 0 ? raw : void 0;
405
- }
406
- function setBextData(handle, format, data) {
407
- requireBwf(format);
408
- handle.setBextData(data);
409
- }
410
- function getBext(handle) {
411
- const raw = handle.getBextData();
412
- return raw && raw.length > 0 ? decodeBext(raw) : void 0;
413
- }
414
- function setBext(handle, format, bext) {
415
- requireBwf(format);
416
- handle.setBextData(encodeBext(bext));
417
- }
418
- function getIxml(handle) {
419
- return handle.getIxml();
420
- }
421
- function setIxml(handle, format, data) {
422
- requireBwf(format);
423
- handle.setIxml(data);
424
- }
425
- var BWF_FORMATS;
426
- var init_audio_file_bwf = __esmMin((() => {
427
- init_bext();
428
- init_errors();
429
- BWF_FORMATS = /* @__PURE__ */ new Set(["WAV", "FLAC"]);
430
- }));
431
- //#endregion
432
- //#region src/taglib/id3v2-frames.ts
433
- function assertMp3(format) {
434
- if (format !== "MP3" && format !== "AAC") throw new UnsupportedFormatError(format, ["MP3", "AAC"], { operation: "id3v2Frames" });
435
- }
436
- function assertFrameId(id, operation) {
437
- if (!FRAME_ID_PATTERN.test(id)) throw new MetadataError(operation, `Invalid ID3v2 frame ID: "${id}". Frame IDs must match [A-Z0-9]{4}`, id);
438
- }
439
- function assertFrameBodies(id, data) {
440
- for (const body of data) if (body.length === 0) throw new MetadataError("write", "Frame data must not be empty: zero-size ID3v2 frames are invalid", id);
441
- }
442
- function toPublicFrame(frame) {
443
- return {
444
- id: frame.id,
445
- data: frame.data,
446
- ...frame.flags ? { flags: frame.flags } : {}
447
- };
448
- }
449
- var FRAME_ID_PATTERN;
450
- var init_id3v2_frames = __esmMin((() => {
451
- init_classes();
452
- FRAME_ID_PATTERN = /^[A-Z0-9]{4}$/;
453
- }));
454
- //#endregion
455
- //#region \0taglib:platform-io-stub
456
- function getPlatformIO() {
457
- throw new Error("Filesystem operations are not available in the browser.");
458
- }
459
- var init__taglib_platform_io_stub = __esmMin((() => {}));
460
- //#endregion
461
- //#region src/utils/write.ts
462
- async function writeFileData(path, data) {
463
- try {
464
- await getPlatformIO().writeFile(path, data);
465
- } catch (error) {
466
- if (error instanceof EnvironmentError) throw error;
467
- throw new FileOperationError("write", error.message, path);
468
- }
469
- }
470
- var init_write = __esmMin((() => {
471
- init_errors();
472
- init__taglib_platform_io_stub();
473
- }));
474
- //#endregion
475
- //#region \0taglib:node-fs-stub
476
- function getNodeFsSync() {
477
- return null;
478
- }
479
- var init__taglib_node_fs_stub = __esmMin((() => {}));
480
- //#endregion
481
- //#region src/utils/rating.ts
482
- function normalized(value) {
483
- return value;
484
- }
485
- var init_rating = __esmMin((() => {}));
486
- //#endregion
487
- //#region src/runtime/detector.ts
488
- function isDeno() {
489
- return g.Deno !== void 0;
490
- }
491
- var g;
492
- var init_detector = __esmMin((() => {
493
- g = globalThis;
494
- new Uint8Array([
495
- 0,
496
- 97,
497
- 115,
498
- 109,
499
- 1,
500
- 0,
501
- 0,
502
- 0,
503
- 6,
504
- 6,
505
- 1,
506
- 105,
507
- 0,
508
- 208,
509
- 105,
510
- 11
511
- ]);
512
- }));
513
- //#endregion
514
- //#region src/constants/additional-properties.ts
515
- var ADDITIONAL_PROPERTIES;
516
- var init_additional_properties = __esmMin((() => {
517
- ADDITIONAL_PROPERTIES = {
518
- albumArtistSort: {
519
- key: "ALBUMARTISTSORT",
520
- description: "Sort name for album artist (for alphabetization)",
521
- type: "string",
522
- supportedFormats: [
523
- "ID3v2",
524
- "MP4",
525
- "Vorbis"
526
- ],
527
- mappings: {
528
- id3v2: { frame: "TSO2" },
529
- vorbis: "ALBUMARTISTSORT",
530
- mp4: "soaa"
531
- }
532
- },
533
- composerSort: {
534
- key: "COMPOSERSORT",
535
- description: "Sort name for composer (for alphabetization)",
536
- type: "string",
537
- supportedFormats: [
538
- "ID3v2",
539
- "MP4",
540
- "Vorbis"
541
- ],
542
- mappings: {
543
- id3v2: { frame: "TSOC" },
544
- vorbis: "COMPOSERSORT",
545
- mp4: "soco"
546
- }
547
- },
548
- subtitle: {
549
- key: "SUBTITLE",
550
- description: "Subtitle or description refinement",
551
- type: "string",
552
- supportedFormats: [
553
- "ID3v2",
554
- "MP4",
555
- "Vorbis"
556
- ],
557
- mappings: {
558
- id3v2: { frame: "TIT3" },
559
- vorbis: "SUBTITLE",
560
- mp4: "----:com.apple.iTunes:SUBTITLE"
561
- }
562
- },
563
- label: {
564
- key: "LABEL",
565
- description: "Record label name",
566
- type: "string",
567
- supportedFormats: [
568
- "ID3v2",
569
- "MP4",
570
- "Vorbis",
571
- "WAV"
572
- ],
573
- mappings: {
574
- id3v2: { frame: "TPUB" },
575
- vorbis: "LABEL",
576
- mp4: "----:com.apple.iTunes:LABEL",
577
- wav: "IPUB"
578
- }
579
- },
580
- producer: {
581
- key: "PRODUCER",
582
- description: "Producer of the recording",
583
- type: "string",
584
- supportedFormats: [
585
- "ID3v2",
586
- "MP4",
587
- "Vorbis"
588
- ],
589
- mappings: {
590
- id3v2: {
591
- frame: "TXXX",
592
- description: "PRODUCER"
593
- },
594
- vorbis: "PRODUCER",
595
- mp4: "----:com.apple.iTunes:PRODUCER"
596
- }
597
- },
598
- radioStationOwner: {
599
- key: "RADIOSTATIONOWNER",
600
- description: "Owner of the radio station",
601
- type: "string",
602
- supportedFormats: ["ID3v2"],
603
- mappings: { id3v2: { frame: "TRSO" } }
604
- },
605
- asin: {
606
- key: "ASIN",
607
- description: "Amazon Standard Identification Number",
608
- type: "string",
609
- supportedFormats: [
610
- "ID3v2",
611
- "MP4",
612
- "Vorbis"
613
- ],
614
- mappings: {
615
- id3v2: {
616
- frame: "TXXX",
617
- description: "ASIN"
618
- },
619
- vorbis: "ASIN",
620
- mp4: "----:com.apple.iTunes:ASIN"
621
- }
622
- },
623
- musicbrainzReleaseArtistId: {
624
- key: "MUSICBRAINZ_ALBUMARTISTID",
625
- description: "MusicBrainz Release Artist ID (UUID)",
626
- type: "string",
627
- supportedFormats: [
628
- "ID3v2",
629
- "MP4",
630
- "Vorbis"
631
- ],
632
- mappings: {
633
- id3v2: {
634
- frame: "TXXX",
635
- description: "MusicBrainz Album Artist Id"
636
- },
637
- vorbis: "MUSICBRAINZ_ALBUMARTISTID",
638
- mp4: "----:com.apple.iTunes:MusicBrainz Album Artist Id"
639
- }
640
- },
641
- musicbrainzWorkId: {
642
- key: "MUSICBRAINZ_WORKID",
643
- description: "MusicBrainz Work ID (UUID)",
644
- type: "string",
645
- supportedFormats: [
646
- "ID3v2",
647
- "MP4",
648
- "Vorbis"
649
- ],
650
- mappings: {
651
- id3v2: {
652
- frame: "TXXX",
653
- description: "MusicBrainz Work Id"
654
- },
655
- vorbis: "MUSICBRAINZ_WORKID",
656
- mp4: "----:com.apple.iTunes:MusicBrainz Work Id"
657
- }
658
- },
659
- musicbrainzReleaseTrackId: {
660
- key: "MUSICBRAINZ_RELEASETRACKID",
661
- description: "MusicBrainz Release Track ID (UUID)",
662
- type: "string",
663
- supportedFormats: [
664
- "ID3v2",
665
- "MP4",
666
- "Vorbis"
667
- ],
668
- mappings: {
669
- id3v2: {
670
- frame: "TXXX",
671
- description: "MusicBrainz Release Track Id"
672
- },
673
- vorbis: "MUSICBRAINZ_RELEASETRACKID",
674
- mp4: "----:com.apple.iTunes:MusicBrainz Release Track Id"
675
- }
676
- },
677
- podcastId: {
678
- key: "PODCASTID",
679
- description: "Podcast episode identifier",
680
- type: "string",
681
- supportedFormats: [
682
- "ID3v2",
683
- "MP4",
684
- "Vorbis"
685
- ],
686
- mappings: {
687
- id3v2: { frame: "TGID" },
688
- vorbis: "PODCASTID",
689
- mp4: "egid"
690
- }
691
- },
692
- podcastUrl: {
693
- key: "PODCASTURL",
694
- description: "Podcast feed URL",
695
- type: "string",
696
- supportedFormats: [
697
- "ID3v2",
698
- "MP4",
699
- "Vorbis"
700
- ],
701
- mappings: {
702
- id3v2: { frame: "WFED" },
703
- vorbis: "PODCASTURL",
704
- mp4: "purl"
705
- }
706
- },
707
- originalArtist: {
708
- key: "ORIGINALARTIST",
709
- description: "Original artist of a cover or remix",
710
- type: "string",
711
- supportedFormats: ["ID3v2", "Vorbis"],
712
- mappings: {
713
- id3v2: { frame: "TOPE" },
714
- vorbis: "ORIGINALARTIST"
715
- }
716
- },
717
- originalAlbum: {
718
- key: "ORIGINALALBUM",
719
- description: "Original album of a cover or remix",
720
- type: "string",
721
- supportedFormats: ["ID3v2", "Vorbis"],
722
- mappings: {
723
- id3v2: { frame: "TOAL" },
724
- vorbis: "ORIGINALALBUM"
725
- }
726
- },
727
- originalDate: {
728
- key: "ORIGINALDATE",
729
- description: "Original release date",
730
- type: "string",
731
- supportedFormats: [
732
- "ID3v2",
733
- "MP4",
734
- "Vorbis"
735
- ],
736
- mappings: {
737
- id3v2: { frame: "TDOR" },
738
- vorbis: "ORIGINALDATE",
739
- mp4: "----:com.apple.iTunes:ORIGINALDATE"
740
- }
741
- },
742
- script: {
743
- key: "SCRIPT",
744
- description: "Writing script used for text (e.g., Latn, Jpan)",
745
- type: "string",
746
- supportedFormats: ["MP4", "Vorbis"],
747
- mappings: {
748
- vorbis: "SCRIPT",
749
- mp4: "----:com.apple.iTunes:SCRIPT"
750
- }
751
- },
752
- involvedPeople: {
753
- key: "INVOLVEDPEOPLE",
754
- description: "List of involved people and their roles",
755
- type: "string",
756
- supportedFormats: ["ID3v2"],
757
- mappings: { id3v2: { frame: "TIPL" } }
758
- },
759
- encoding: {
760
- key: "ENCODING",
761
- description: "Encoding software or settings",
762
- type: "string",
763
- supportedFormats: [
764
- "ID3v2",
765
- "MP4",
766
- "Vorbis",
767
- "WAV"
768
- ],
769
- mappings: {
770
- id3v2: { frame: "TSSE" },
771
- vorbis: "ENCODING",
772
- mp4: "©too",
773
- wav: "ISFT"
774
- }
775
- }
776
- };
777
- }));
778
- //#endregion
779
- //#region src/constants/basic-properties.ts
780
- var BASIC_PROPERTIES;
781
- var init_basic_properties = __esmMin((() => {
782
- BASIC_PROPERTIES = {
783
- title: {
784
- key: "TITLE",
785
- description: "The title of the track",
786
- type: "string",
787
- supportedFormats: [
788
- "ID3v2",
789
- "MP4",
790
- "Vorbis",
791
- "WAV"
792
- ],
793
- mappings: {
794
- id3v2: { frame: "TIT2" },
795
- vorbis: "TITLE",
796
- mp4: "©nam",
797
- wav: "INAM"
798
- }
799
- },
800
- artist: {
801
- key: "ARTIST",
802
- description: "The primary performer(s) of the track",
803
- type: "string",
804
- supportedFormats: [
805
- "ID3v2",
806
- "MP4",
807
- "Vorbis",
808
- "WAV"
809
- ],
810
- mappings: {
811
- id3v2: { frame: "TPE1" },
812
- vorbis: "ARTIST",
813
- mp4: "©ART",
814
- wav: "IART"
815
- }
816
- },
817
- album: {
818
- key: "ALBUM",
819
- description: "The album/collection name",
820
- type: "string",
821
- supportedFormats: [
822
- "ID3v2",
823
- "MP4",
824
- "Vorbis",
825
- "WAV"
826
- ],
827
- mappings: {
828
- id3v2: { frame: "TALB" },
829
- vorbis: "ALBUM",
830
- mp4: "©alb",
831
- wav: "IPRD"
832
- }
833
- },
834
- date: {
835
- key: "DATE",
836
- description: "The date of recording (typically year)",
837
- type: "string",
838
- supportedFormats: [
839
- "ID3v2",
840
- "MP4",
841
- "Vorbis",
842
- "WAV"
843
- ],
844
- mappings: {
845
- id3v2: { frame: "TDRC" },
846
- vorbis: "DATE",
847
- mp4: "©day",
848
- wav: "ICRD"
849
- }
850
- },
851
- trackNumber: {
852
- key: "TRACKNUMBER",
853
- description: "The track number within the album",
854
- type: "string",
855
- supportedFormats: [
856
- "ID3v2",
857
- "MP4",
858
- "Vorbis",
859
- "WAV"
860
- ],
861
- mappings: {
862
- id3v2: { frame: "TRCK" },
863
- vorbis: "TRACKNUMBER",
864
- mp4: "trkn",
865
- wav: "ITRK"
866
- }
867
- },
868
- genre: {
869
- key: "GENRE",
870
- description: "The musical genre",
871
- type: "string",
872
- supportedFormats: [
873
- "ID3v2",
874
- "MP4",
875
- "Vorbis",
876
- "WAV"
877
- ],
878
- mappings: {
879
- id3v2: { frame: "TCON" },
880
- vorbis: "GENRE",
881
- mp4: "©gen",
882
- wav: "IGNR"
883
- }
884
- },
885
- comment: {
886
- key: "COMMENT",
887
- description: "Comments or notes about the track",
888
- type: "string",
889
- supportedFormats: [
890
- "ID3v2",
891
- "MP4",
892
- "Vorbis",
893
- "WAV"
894
- ],
895
- mappings: {
896
- id3v2: { frame: "COMM" },
897
- vorbis: "COMMENT",
898
- mp4: "©cmt",
899
- wav: "ICMT"
900
- }
901
- }
902
- };
903
- }));
904
- //#endregion
905
- //#region src/constants/general-extended-properties.ts
906
- var GENERAL_EXTENDED_PROPERTIES;
907
- var init_general_extended_properties = __esmMin((() => {
908
- GENERAL_EXTENDED_PROPERTIES = {
909
- albumArtist: {
910
- key: "ALBUMARTIST",
911
- description: "The album artist (band/orchestra/ensemble)",
912
- type: "string",
913
- supportedFormats: [
914
- "ID3v2",
915
- "MP4",
916
- "Vorbis"
917
- ],
918
- mappings: {
919
- id3v2: { frame: "TPE2" },
920
- vorbis: "ALBUMARTIST",
921
- mp4: "aART"
922
- }
923
- },
924
- composer: {
925
- key: "COMPOSER",
926
- description: "The original composer(s) of the track",
927
- type: "string",
928
- supportedFormats: [
929
- "ID3v2",
930
- "MP4",
931
- "Vorbis"
932
- ],
933
- mappings: {
934
- id3v2: { frame: "TCOM" },
935
- vorbis: "COMPOSER",
936
- mp4: "©wrt"
937
- }
938
- },
939
- copyright: {
940
- key: "COPYRIGHT",
941
- description: "Copyright information",
942
- type: "string",
943
- supportedFormats: ["ID3v2", "Vorbis"],
944
- mappings: { vorbis: "COPYRIGHT" }
945
- },
946
- encodedBy: {
947
- key: "ENCODEDBY",
948
- description: "The encoding software or person",
949
- type: "string",
950
- supportedFormats: ["ID3v2", "Vorbis"],
951
- mappings: { vorbis: "ENCODEDBY" }
952
- },
953
- discNumber: {
954
- key: "DISCNUMBER",
955
- description: "The disc number for multi-disc sets",
956
- type: "string",
957
- supportedFormats: [
958
- "ID3v2",
959
- "MP4",
960
- "Vorbis"
961
- ],
962
- mappings: {
963
- id3v2: { frame: "TPOS" },
964
- vorbis: "DISCNUMBER",
965
- mp4: "disk"
966
- }
967
- },
968
- bpm: {
969
- key: "BPM",
970
- description: "Beats per minute",
971
- type: "string",
972
- supportedFormats: [
973
- "ID3v2",
974
- "MP4",
975
- "Vorbis"
976
- ],
977
- mappings: {
978
- id3v2: { frame: "TBPM" },
979
- vorbis: "BPM",
980
- mp4: "tmpo"
981
- }
982
- },
983
- totalTracks: {
984
- key: "TRACKTOTAL",
985
- description: "Total number of tracks on the album",
986
- type: "string",
987
- supportedFormats: [
988
- "ID3v2",
989
- "MP4",
990
- "Vorbis"
991
- ],
992
- mappings: {
993
- id3v2: { frame: "TRCK" },
994
- vorbis: "TRACKTOTAL",
995
- mp4: "trkn"
996
- }
997
- },
998
- totalDiscs: {
999
- key: "DISCTOTAL",
1000
- description: "Total number of discs in the set",
1001
- type: "string",
1002
- supportedFormats: [
1003
- "ID3v2",
1004
- "MP4",
1005
- "Vorbis"
1006
- ],
1007
- mappings: {
1008
- id3v2: { frame: "TPOS" },
1009
- vorbis: "DISCTOTAL",
1010
- mp4: "disk"
1011
- }
1012
- },
1013
- compilation: {
1014
- key: "COMPILATION",
1015
- description: "Whether the album is a compilation (various artists)",
1016
- type: "boolean",
1017
- supportedFormats: [
1018
- "ID3v2",
1019
- "MP4",
1020
- "Vorbis"
1021
- ],
1022
- mappings: {
1023
- id3v2: { frame: "TCMP" },
1024
- vorbis: "COMPILATION",
1025
- mp4: "cpil"
1026
- }
1027
- },
1028
- titleSort: {
1029
- key: "TITLESORT",
1030
- description: "Sort name for title (for alphabetization)",
1031
- type: "string",
1032
- supportedFormats: [
1033
- "ID3v2",
1034
- "MP4",
1035
- "Vorbis"
1036
- ],
1037
- mappings: {
1038
- id3v2: { frame: "TSOT" },
1039
- vorbis: "TITLESORT",
1040
- mp4: "sonm"
1041
- }
1042
- },
1043
- artistSort: {
1044
- key: "ARTISTSORT",
1045
- description: "Sort name for artist (for alphabetization)",
1046
- type: "string",
1047
- supportedFormats: [
1048
- "ID3v2",
1049
- "MP4",
1050
- "Vorbis"
1051
- ],
1052
- mappings: {
1053
- id3v2: { frame: "TSOP" },
1054
- vorbis: "ARTISTSORT",
1055
- mp4: "soar"
1056
- }
1057
- },
1058
- albumSort: {
1059
- key: "ALBUMSORT",
1060
- description: "Sort name for album (for alphabetization)",
1061
- type: "string",
1062
- supportedFormats: [
1063
- "ID3v2",
1064
- "MP4",
1065
- "Vorbis"
1066
- ],
1067
- mappings: {
1068
- id3v2: { frame: "TSOA" },
1069
- vorbis: "ALBUMSORT",
1070
- mp4: "soal"
1071
- }
1072
- },
1073
- lyricist: {
1074
- key: "LYRICIST",
1075
- description: "The lyrics/text writer(s)",
1076
- type: "string",
1077
- supportedFormats: ["Vorbis"],
1078
- mappings: { vorbis: "LYRICIST" }
1079
- },
1080
- conductor: {
1081
- key: "CONDUCTOR",
1082
- description: "The conductor",
1083
- type: "string",
1084
- supportedFormats: ["Vorbis"],
1085
- mappings: { vorbis: "CONDUCTOR" }
1086
- },
1087
- remixedBy: {
1088
- key: "REMIXER",
1089
- description: "Person who remixed the track",
1090
- type: "string",
1091
- supportedFormats: [
1092
- "ID3v2",
1093
- "MP4",
1094
- "Vorbis"
1095
- ],
1096
- mappings: {
1097
- id3v2: { frame: "TPE4" },
1098
- vorbis: "REMIXER",
1099
- mp4: "----:com.apple.iTunes:REMIXER"
1100
- }
1101
- },
1102
- language: {
1103
- key: "LANGUAGE",
1104
- description: "Language of vocals/lyrics",
1105
- type: "string",
1106
- supportedFormats: ["Vorbis"],
1107
- mappings: { vorbis: "LANGUAGE" }
1108
- },
1109
- publisher: {
1110
- key: "PUBLISHER",
1111
- description: "The publisher",
1112
- type: "string",
1113
- supportedFormats: ["Vorbis"],
1114
- mappings: { vorbis: "PUBLISHER" }
1115
- },
1116
- mood: {
1117
- key: "MOOD",
1118
- description: "The mood/atmosphere of the track",
1119
- type: "string",
1120
- supportedFormats: ["Vorbis"],
1121
- mappings: { vorbis: "MOOD" }
1122
- },
1123
- media: {
1124
- key: "MEDIA",
1125
- description: "Media type (CD, vinyl, etc.)",
1126
- type: "string",
1127
- supportedFormats: ["Vorbis"],
1128
- mappings: { vorbis: "MEDIA" }
1129
- },
1130
- grouping: {
1131
- key: "GROUPING",
1132
- description: "Content group/work",
1133
- type: "string",
1134
- supportedFormats: ["Vorbis"],
1135
- mappings: { vorbis: "GROUPING" }
1136
- },
1137
- work: {
1138
- key: "WORK",
1139
- description: "Work name",
1140
- type: "string",
1141
- supportedFormats: ["Vorbis"],
1142
- mappings: { vorbis: "WORK" }
1143
- },
1144
- lyrics: {
1145
- key: "LYRICS",
1146
- description: "Lyrics content",
1147
- type: "string",
1148
- supportedFormats: ["Vorbis"],
1149
- mappings: { vorbis: "LYRICS" }
1150
- },
1151
- isrc: {
1152
- key: "ISRC",
1153
- description: "International Standard Recording Code",
1154
- type: "string",
1155
- supportedFormats: ["Vorbis"],
1156
- mappings: { vorbis: "ISRC" }
1157
- },
1158
- catalogNumber: {
1159
- key: "CATALOGNUMBER",
1160
- description: "Catalog number",
1161
- type: "string",
1162
- supportedFormats: ["Vorbis"],
1163
- mappings: { vorbis: "CATALOGNUMBER" }
1164
- },
1165
- barcode: {
1166
- key: "BARCODE",
1167
- description: "Barcode (EAN/UPC)",
1168
- type: "string",
1169
- supportedFormats: ["Vorbis"],
1170
- mappings: { vorbis: "BARCODE" }
1171
- }
1172
- };
1173
- }));
1174
- //#endregion
1175
- //#region src/constants/specialized-properties.ts
1176
- var SPECIALIZED_PROPERTIES;
1177
- var init_specialized_properties = __esmMin((() => {
1178
- SPECIALIZED_PROPERTIES = {
1179
- musicbrainzArtistId: {
1180
- key: "MUSICBRAINZ_ARTISTID",
1181
- description: "MusicBrainz Artist ID (UUID)",
1182
- type: "string",
1183
- supportedFormats: [
1184
- "ID3v2",
1185
- "MP4",
1186
- "Vorbis"
1187
- ],
1188
- mappings: {
1189
- id3v2: {
1190
- frame: "TXXX",
1191
- description: "MusicBrainz Artist Id"
1192
- },
1193
- vorbis: "MUSICBRAINZ_ARTISTID",
1194
- mp4: "----:com.apple.iTunes:MusicBrainz Artist Id"
1195
- }
1196
- },
1197
- musicbrainzReleaseId: {
1198
- key: "MUSICBRAINZ_ALBUMID",
1199
- description: "MusicBrainz Release ID (UUID)",
1200
- type: "string",
1201
- supportedFormats: [
1202
- "ID3v2",
1203
- "MP4",
1204
- "Vorbis"
1205
- ],
1206
- mappings: {
1207
- id3v2: {
1208
- frame: "TXXX",
1209
- description: "MusicBrainz Album Id"
1210
- },
1211
- vorbis: "MUSICBRAINZ_ALBUMID",
1212
- mp4: "----:com.apple.iTunes:MusicBrainz Album Id"
1213
- }
1214
- },
1215
- musicbrainzTrackId: {
1216
- key: "MUSICBRAINZ_TRACKID",
1217
- description: "MusicBrainz Recording ID (UUID)",
1218
- type: "string",
1219
- supportedFormats: [
1220
- "ID3v2",
1221
- "MP4",
1222
- "Vorbis"
1223
- ],
1224
- mappings: {
1225
- id3v2: {
1226
- frame: "UFID",
1227
- description: "http://musicbrainz.org"
1228
- },
1229
- vorbis: "MUSICBRAINZ_TRACKID",
1230
- mp4: "----:com.apple.iTunes:MusicBrainz Track Id"
1231
- }
1232
- },
1233
- musicbrainzReleaseGroupId: {
1234
- key: "MUSICBRAINZ_RELEASEGROUPID",
1235
- description: "MusicBrainz Release Group ID (UUID)",
1236
- type: "string",
1237
- supportedFormats: [
1238
- "ID3v2",
1239
- "MP4",
1240
- "Vorbis"
1241
- ],
1242
- mappings: {
1243
- id3v2: {
1244
- frame: "TXXX",
1245
- description: "MusicBrainz Release Group Id"
1246
- },
1247
- vorbis: "MUSICBRAINZ_RELEASEGROUPID",
1248
- mp4: "----:com.apple.iTunes:MusicBrainz Release Group Id"
1249
- }
1250
- },
1251
- releaseType: {
1252
- key: "RELEASETYPE",
1253
- description: "Release type (album, single, EP, compilation, ...). Multi-value (e.g. 'album' + 'EP'). TagLib 2.3.2 translates the RELEASETYPE key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM TYPE' (TagLib's description casing), MP4 freeform atom, APEv2 MUSICBRAINZ_ALBUMTYPE, ASF 'MusicBrainz/Album Type', Vorbis/Matroska raw RELEASETYPE",
1254
- type: "string",
1255
- supportedFormats: [
1256
- "ID3v2",
1257
- "MP4",
1258
- "Vorbis",
1259
- "APE",
1260
- "ASF",
1261
- "Matroska"
1262
- ],
1263
- mappings: {
1264
- id3v2: {
1265
- frame: "TXXX",
1266
- description: "MusicBrainz Album Type"
1267
- },
1268
- vorbis: "RELEASETYPE",
1269
- mp4: "----:com.apple.iTunes:MusicBrainz Album Type"
1270
- }
1271
- },
1272
- releaseCountry: {
1273
- key: "RELEASECOUNTRY",
1274
- description: "Release country (ISO 3166-1 code, e.g. 'US'). TagLib 2.3.2 translates the RELEASECOUNTRY key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM RELEASE COUNTRY' (TagLib's description casing; an uppercase TXXX:RELEASECOUNTRY description also reads back), MP4 freeform atom 'MusicBrainz Album Release Country', APEv2 raw RELEASECOUNTRY, ASF 'MusicBrainz/Album Release Country', WAV ICNT, Vorbis/Matroska raw RELEASECOUNTRY",
1275
- type: "string",
1276
- supportedFormats: [
1277
- "ID3v2",
1278
- "MP4",
1279
- "Vorbis",
1280
- "APE",
1281
- "ASF",
1282
- "Matroska",
1283
- "WAV"
1284
- ],
1285
- mappings: {
1286
- id3v2: {
1287
- frame: "TXXX",
1288
- description: "MusicBrainz Album Release Country"
1289
- },
1290
- vorbis: "RELEASECOUNTRY",
1291
- mp4: "----:com.apple.iTunes:MusicBrainz Album Release Country"
1292
- }
1293
- },
1294
- releaseStatus: {
1295
- key: "RELEASESTATUS",
1296
- description: "Release status (official, promotion, bootleg, ...). TagLib 2.3.2 translates the RELEASESTATUS key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM STATUS' (TagLib's description casing), MP4 freeform atom 'MusicBrainz Album Status', APEv2 MUSICBRAINZ_ALBUMSTATUS, ASF 'MusicBrainz/Album Status', Vorbis/Matroska raw RELEASESTATUS",
1297
- type: "string",
1298
- supportedFormats: [
1299
- "ID3v2",
1300
- "MP4",
1301
- "Vorbis",
1302
- "APE",
1303
- "ASF",
1304
- "Matroska"
1305
- ],
1306
- mappings: {
1307
- id3v2: {
1308
- frame: "TXXX",
1309
- description: "MusicBrainz Album Status"
1310
- },
1311
- vorbis: "RELEASESTATUS",
1312
- mp4: "----:com.apple.iTunes:MusicBrainz Album Status"
1313
- }
1314
- },
1315
- itunesAdvisory: {
1316
- key: "ITUNESADVISORY",
1317
- description: "Content advisory in the ITUNESADVISORY convention ('1' = explicit, '2' = clean, '0' = unspecified). On MP4 the value is stored in the native rtng atom and surfaced here. The typed tri-state lives on ExtendedTag.advisory; aliases CONTENTADVISORY and EXPLICIT resolve here",
1318
- type: "string",
1319
- supportedFormats: [
1320
- "ID3v2",
1321
- "MP4",
1322
- "Vorbis",
1323
- "APE",
1324
- "ASF"
1325
- ],
1326
- mappings: {
1327
- id3v2: {
1328
- frame: "TXXX",
1329
- description: "ITUNESADVISORY"
1330
- },
1331
- vorbis: "ITUNESADVISORY",
1332
- mp4: "----:com.apple.iTunes:ITUNESADVISORY"
1333
- }
1334
- },
1335
- replayGainTrackGain: {
1336
- key: "REPLAYGAIN_TRACK_GAIN",
1337
- description: "ReplayGain track gain in dB (e.g., '-6.54 dB')",
1338
- type: "string",
1339
- supportedFormats: [
1340
- "ID3v2",
1341
- "MP4",
1342
- "Vorbis"
1343
- ],
1344
- mappings: {
1345
- id3v2: {
1346
- frame: "TXXX",
1347
- description: "ReplayGain_Track_Gain"
1348
- },
1349
- vorbis: "REPLAYGAIN_TRACK_GAIN",
1350
- mp4: "----:com.apple.iTunes:replaygain_track_gain"
1351
- }
1352
- },
1353
- replayGainTrackPeak: {
1354
- key: "REPLAYGAIN_TRACK_PEAK",
1355
- description: "ReplayGain track peak value (0.0-1.0)",
1356
- type: "string",
1357
- supportedFormats: [
1358
- "ID3v2",
1359
- "MP4",
1360
- "Vorbis"
1361
- ],
1362
- mappings: {
1363
- id3v2: {
1364
- frame: "TXXX",
1365
- description: "ReplayGain_Track_Peak"
1366
- },
1367
- vorbis: "REPLAYGAIN_TRACK_PEAK",
1368
- mp4: "----:com.apple.iTunes:replaygain_track_peak"
1369
- }
1370
- },
1371
- replayGainAlbumGain: {
1372
- key: "REPLAYGAIN_ALBUM_GAIN",
1373
- description: "ReplayGain album gain in dB",
1374
- type: "string",
1375
- supportedFormats: [
1376
- "ID3v2",
1377
- "MP4",
1378
- "Vorbis"
1379
- ],
1380
- mappings: {
1381
- id3v2: {
1382
- frame: "TXXX",
1383
- description: "ReplayGain_Album_Gain"
1384
- },
1385
- vorbis: "REPLAYGAIN_ALBUM_GAIN",
1386
- mp4: "----:com.apple.iTunes:replaygain_album_gain"
1387
- }
1388
- },
1389
- replayGainAlbumPeak: {
1390
- key: "REPLAYGAIN_ALBUM_PEAK",
1391
- description: "ReplayGain album peak value (0.0-1.0)",
1392
- type: "string",
1393
- supportedFormats: [
1394
- "ID3v2",
1395
- "MP4",
1396
- "Vorbis"
1397
- ],
1398
- mappings: {
1399
- id3v2: {
1400
- frame: "TXXX",
1401
- description: "ReplayGain_Album_Peak"
1402
- },
1403
- vorbis: "REPLAYGAIN_ALBUM_PEAK",
1404
- mp4: "----:com.apple.iTunes:replaygain_album_peak"
1405
- }
1406
- },
1407
- r128TrackGain: {
1408
- key: "R128_TRACK_GAIN",
1409
- description: "EBU R128 track loudness gain (RFC 7845), raw wire value: signed Q7.8 integer (dB x 256, e.g. '-573' = -2.23828125 dB). readTags() converts to a decibel number (see ExtendedTag.r128TrackGain)",
1410
- type: "string",
1411
- supportedFormats: [
1412
- "ID3v2",
1413
- "MP4",
1414
- "Vorbis",
1415
- "ASF"
1416
- ],
1417
- mappings: {
1418
- id3v2: {
1419
- frame: "TXXX",
1420
- description: "R128_TRACK_GAIN"
1421
- },
1422
- vorbis: "R128_TRACK_GAIN",
1423
- mp4: "----:com.apple.iTunes:R128_TRACK_GAIN"
1424
- }
1425
- },
1426
- r128AlbumGain: {
1427
- key: "R128_ALBUM_GAIN",
1428
- description: "EBU R128 album loudness gain (RFC 7845), raw wire value: signed Q7.8 integer (dB x 256). readTags() converts to a decibel number",
1429
- type: "string",
1430
- supportedFormats: [
1431
- "ID3v2",
1432
- "MP4",
1433
- "Vorbis",
1434
- "ASF"
1435
- ],
1436
- mappings: {
1437
- id3v2: {
1438
- frame: "TXXX",
1439
- description: "R128_ALBUM_GAIN"
1440
- },
1441
- vorbis: "R128_ALBUM_GAIN",
1442
- mp4: "----:com.apple.iTunes:R128_ALBUM_GAIN"
1443
- }
1444
- },
1445
- acoustidFingerprint: {
1446
- key: "ACOUSTID_FINGERPRINT",
1447
- description: "AcoustID fingerprint (Chromaprint)",
1448
- type: "string",
1449
- supportedFormats: [
1450
- "ID3v2",
1451
- "MP4",
1452
- "Vorbis"
1453
- ],
1454
- mappings: {
1455
- id3v2: {
1456
- frame: "TXXX",
1457
- description: "Acoustid Fingerprint"
1458
- },
1459
- vorbis: "ACOUSTID_FINGERPRINT",
1460
- mp4: "----:com.apple.iTunes:Acoustid Fingerprint"
1461
- }
1462
- },
1463
- acoustidId: {
1464
- key: "ACOUSTID_ID",
1465
- description: "AcoustID UUID",
1466
- type: "string",
1467
- supportedFormats: [
1468
- "ID3v2",
1469
- "MP4",
1470
- "Vorbis"
1471
- ],
1472
- mappings: {
1473
- id3v2: {
1474
- frame: "TXXX",
1475
- description: "Acoustid Id"
1476
- },
1477
- vorbis: "ACOUSTID_ID",
1478
- mp4: "----:com.apple.iTunes:Acoustid Id"
1479
- }
1480
- },
1481
- appleSoundCheck: {
1482
- key: "ITUNNORM",
1483
- description: "Apple Sound Check normalization data",
1484
- type: "string",
1485
- supportedFormats: [
1486
- "ID3v2",
1487
- "MP4",
1488
- "Vorbis"
1489
- ],
1490
- mappings: {
1491
- id3v2: {
1492
- frame: "TXXX",
1493
- description: "iTunNORM"
1494
- },
1495
- vorbis: "ITUNNORM",
1496
- mp4: "----:com.apple.iTunes:iTunNORM"
1497
- }
1498
- },
1499
- appleGaplessInfo: {
1500
- key: "ITUNSMPB",
1501
- description: "Apple gapless playback data (encoder delay and padding)",
1502
- type: "string",
1503
- supportedFormats: [
1504
- "ID3v2",
1505
- "MP4",
1506
- "Vorbis"
1507
- ],
1508
- mappings: {
1509
- id3v2: {
1510
- frame: "TXXX",
1511
- description: "iTunSMPB"
1512
- },
1513
- vorbis: "ITUNSMPB",
1514
- mp4: "----:com.apple.iTunes:iTunSMPB"
1515
- }
1516
- }
1517
- };
1518
- }));
1519
- //#endregion
1520
- //#region src/constants/properties.ts
1521
- function toTagLibKey(key) {
1522
- return _toTagLib[key] ?? key;
1523
- }
1524
- function mp4AtomWireKey(atom) {
1525
- return _mp4AtomToWireKey[atom];
1526
- }
1527
- function mp4FreeformAtomNames(wireKeys) {
1528
- const names = [];
1529
- for (const key of wireKeys) {
1530
- const atom = _mp4FreeformAtoms[key];
1531
- if (atom !== void 0) names.push(atom);
1532
- }
1533
- return names;
1534
- }
1535
- function fromTagLibKey(key) {
1536
- return _fromTagLib[key] ?? key;
1537
- }
1538
- function remapKeysFromTagLib(obj) {
1539
- const result = {};
1540
- for (const [key, value] of Object.entries(obj)) {
1541
- const canonical = READ_ALIASES[key];
1542
- if (canonical !== void 0 && canonical in obj) continue;
1543
- result[fromTagLibKey(key)] = value;
1544
- }
1545
- return result;
1546
- }
1547
- var PROPERTIES, _toTagLib, _fromTagLib, READ_ALIASES, _mp4FreeformAtoms, _mp4AtomToWireKey;
1548
- var init_properties = __esmMin((() => {
1549
- init_additional_properties();
1550
- init_basic_properties();
1551
- init_general_extended_properties();
1552
- init_specialized_properties();
1553
- PROPERTIES = {
1554
- ...BASIC_PROPERTIES,
1555
- ...GENERAL_EXTENDED_PROPERTIES,
1556
- ...SPECIALIZED_PROPERTIES,
1557
- ...ADDITIONAL_PROPERTIES
1558
- };
1559
- _toTagLib = {};
1560
- _fromTagLib = {};
1561
- for (const [camelKey, meta] of Object.entries(PROPERTIES)) {
1562
- const wireKey = meta.key;
1563
- _toTagLib[camelKey] = wireKey;
1564
- _fromTagLib[wireKey] = camelKey;
1565
- }
1566
- _toTagLib["year"] = "DATE";
1567
- _toTagLib["track"] = "TRACKNUMBER";
1568
- _fromTagLib["disc"] = "discNumber";
1569
- READ_ALIASES = {
1570
- "ALBUM ARTIST": "ALBUMARTIST",
1571
- ALBUM_ARTIST: "ALBUMARTIST",
1572
- ORGANIZATION: "LABEL",
1573
- PUBLISHER: "LABEL",
1574
- UPC: "BARCODE",
1575
- EAN: "BARCODE",
1576
- GTIN: "BARCODE",
1577
- TOTALTRACKS: "TRACKTOTAL",
1578
- TOTALDISCS: "DISCTOTAL",
1579
- MUSICBRAINZ_ALBUMTYPE: "RELEASETYPE",
1580
- "MusicBrainz Album Type": "RELEASETYPE",
1581
- MUSICBRAINZ_ALBUMSTATUS: "RELEASESTATUS",
1582
- "MusicBrainz Album Status": "RELEASESTATUS",
1583
- CONTENTADVISORY: "ITUNESADVISORY",
1584
- EXPLICIT: "ITUNESADVISORY"
1585
- };
1586
- for (const [alias, canonical] of Object.entries(READ_ALIASES)) if (_fromTagLib[alias] === void 0) _fromTagLib[alias] = _fromTagLib[canonical];
1587
- _mp4FreeformAtoms = {};
1588
- for (const meta of Object.values(PROPERTIES)) {
1589
- const { key, mappings } = meta;
1590
- const atom = mappings?.mp4;
1591
- if (typeof atom !== "string" || !atom.startsWith("----:")) continue;
1592
- const bare = atom.slice(atom.lastIndexOf(":") + 1);
1593
- if (bare === bare.toUpperCase()) continue;
1594
- _mp4FreeformAtoms[key] = atom;
1595
- const readKey = bare.toUpperCase();
1596
- const camel = _fromTagLib[key];
1597
- if (camel !== void 0 && _fromTagLib[readKey] === void 0) _fromTagLib[readKey] = camel;
1598
- }
1599
- _mp4AtomToWireKey = {};
1600
- for (const meta of Object.values(PROPERTIES)) {
1601
- const { key, mappings } = meta;
1602
- const atom = mappings?.mp4;
1603
- if (typeof atom !== "string" || atom.startsWith("----:")) continue;
1604
- if (_mp4AtomToWireKey[atom] === void 0) _mp4AtomToWireKey[atom] = key;
1605
- }
1606
- }));
1607
- //#endregion
1608
- //#region src/taglib/mp4-item-names.ts
1609
- var MP4_ITEM_NAMES_KEY;
1610
- var init_mp4_item_names = __esmMin((() => {
1611
- MP4_ITEM_NAMES_KEY = "_mp4ItemNames";
1612
- }));
1613
- //#endregion
1614
- //#region src/taglib/mutable-tag-impl.ts
1615
- function buildMutableTag(handle) {
1616
- let data = handle.getTagData();
1617
- const tag = {
1618
- get title() {
1619
- return data.title;
1620
- },
1621
- get artist() {
1622
- return data.artist;
1623
- },
1624
- get album() {
1625
- return data.album;
1626
- },
1627
- get comment() {
1628
- return data.comment;
1629
- },
1630
- get genre() {
1631
- return data.genre;
1632
- },
1633
- get year() {
1634
- return data.year;
1635
- },
1636
- get track() {
1637
- return data.track;
1638
- },
1639
- get date() {
1640
- return handle.getProperty("DATE") || void 0;
1641
- },
1642
- setTitle: (value) => {
1643
- handle.setTagData({ title: value });
1644
- data = handle.getTagData();
1645
- return tag;
1646
- },
1647
- setArtist: (value) => {
1648
- handle.setTagData({ artist: value });
1649
- data = handle.getTagData();
1650
- return tag;
1651
- },
1652
- setAlbum: (value) => {
1653
- handle.setTagData({ album: value });
1654
- data = handle.getTagData();
1655
- return tag;
1656
- },
1657
- setComment: (value) => {
1658
- handle.setTagData({ comment: value });
1659
- data = handle.getTagData();
1660
- return tag;
1661
- },
1662
- setGenre: (value) => {
1663
- handle.setTagData({ genre: value });
1664
- data = handle.getTagData();
1665
- return tag;
1666
- },
1667
- setYear: (value) => {
1668
- handle.setTagData({ year: value });
1669
- data = handle.getTagData();
1670
- return tag;
1671
- },
1672
- setTrack: (value) => {
1673
- const existing = value > 0 ? handle.getProperty(RAW_TRACK_WIRE_KEY) : "";
1674
- const slash = existing.indexOf("/");
1675
- if (slash !== -1) handle.setProperty(RAW_TRACK_WIRE_KEY, `${value}${existing.slice(slash)}`);
1676
- else handle.setTagData({ track: value });
1677
- data = handle.getTagData();
1678
- return tag;
1679
- },
1680
- setDate: (value) => {
1681
- if (value === "") handle.setTagData({ year: 0 });
1682
- else handle.setProperty("DATE", value);
1683
- data = handle.getTagData();
1684
- return tag;
1685
- }
1686
- };
1687
- return tag;
1688
- }
1689
- var RAW_TRACK_WIRE_KEY;
1690
- var init_mutable_tag_impl = __esmMin((() => {
1691
- init_properties();
1692
- RAW_TRACK_WIRE_KEY = toTagLibKey("trackNumber");
1693
- }));
1694
- //#endregion
1695
- //#region src/taglib/auto-dispose.ts
1696
- function registerAutoDispose(target, handle) {
1697
- registry.register(target, handle, target);
1698
- }
1699
- function unregisterAutoDispose(target) {
1700
- registry.unregister(target);
1701
- }
1702
- var registry;
1703
- var init_auto_dispose = __esmMin((() => {
1704
- registry = new FinalizationRegistry((handle) => {
1705
- handle.destroy();
1706
- });
1707
- }));
1708
- //#endregion
1709
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/typeof.js
1710
- function _typeof(o) {
1711
- "@babel/helpers - typeof";
1712
- return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o) {
1713
- return typeof o;
1714
- } : function(o) {
1715
- return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
1716
- }, _typeof(o);
1717
- }
1718
- var init_typeof = __esmMin((() => {}));
1719
- //#endregion
1720
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPrimitive.js
1721
- function toPrimitive(t, r) {
1722
- if ("object" != _typeof(t) || !t) return t;
1723
- var e = t[Symbol.toPrimitive];
1724
- if (void 0 !== e) {
1725
- var i = e.call(t, r || "default");
1726
- if ("object" != _typeof(i)) return i;
1727
- throw new TypeError("@@toPrimitive must return a primitive value.");
1728
- }
1729
- return ("string" === r ? String : Number)(t);
1730
- }
1731
- var init_toPrimitive = __esmMin((() => {
1732
- init_typeof();
1733
- }));
1734
- //#endregion
1735
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/toPropertyKey.js
1736
- function toPropertyKey(t) {
1737
- var i = toPrimitive(t, "string");
1738
- return "symbol" == _typeof(i) ? i : i + "";
1739
- }
1740
- var init_toPropertyKey = __esmMin((() => {
1741
- init_typeof();
1742
- init_toPrimitive();
1743
- }));
1744
- //#endregion
1745
- //#region \0@oxc-project+runtime@0.154.0/helpers/esm/defineProperty.js
1746
- function _defineProperty(e, r, t) {
1747
- return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
1748
- value: t,
1749
- enumerable: !0,
1750
- configurable: !0,
1751
- writable: !0
1752
- }) : e[r] = t, e;
1753
- }
1754
- var init_defineProperty = __esmMin((() => {
1755
- init_toPropertyKey();
1756
- }));
1757
- //#endregion
1758
- //#region src/taglib/audio-file-base.ts
1759
- var _Symbol$dispose, LYRICS_PROPERTY_KEY, LYRICS_WIRE_KEY, EMPTY_KEY_SET, BaseAudioFileImpl;
1760
- var init_audio_file_base = __esmMin((() => {
1761
- init_properties();
1762
- init_errors();
1763
- init_mp4_item_names();
1764
- init_mutable_tag_impl();
1765
- init_auto_dispose();
1766
- init_defineProperty();
1767
- LYRICS_PROPERTY_KEY = "lyrics";
1768
- LYRICS_WIRE_KEY = toTagLibKey(LYRICS_PROPERTY_KEY);
1769
- EMPTY_KEY_SET = /* @__PURE__ */ new Set();
1770
- _Symbol$dispose = Symbol.dispose;
1771
- BaseAudioFileImpl = class {
1772
- constructor(module, fileHandle, sourcePath, originalSource, isPartiallyLoaded = false, partialLoadOptions) {
1773
- this.module = module;
1774
- _defineProperty(this, "fileHandle", void 0);
1775
- _defineProperty(this, "cachedAudioProperties", null);
1776
- _defineProperty(this, "sourcePath", void 0);
1777
- _defineProperty(this, "originalSource", void 0);
1778
- _defineProperty(this, "isPartiallyLoaded", false);
1779
- _defineProperty(this, "partialLoadOptions", void 0);
1780
- _defineProperty(this, "partialKeysAtLoad", void 0);
1781
- this.fileHandle = fileHandle;
1782
- this.sourcePath = sourcePath;
1783
- this.originalSource = originalSource;
1784
- this.isPartiallyLoaded = isPartiallyLoaded;
1785
- this.partialLoadOptions = partialLoadOptions;
1786
- this.partialKeysAtLoad = isPartiallyLoaded ? new Set(Object.keys(fileHandle.getProperties())) : void 0;
1787
- registerAutoDispose(this, fileHandle);
1788
- }
1789
- partialDeletedPropertyKeys() {
1790
- if (!this.partialKeysAtLoad) return EMPTY_KEY_SET;
1791
- const current = new Set(Object.keys(this.handle.getProperties()));
1792
- const deleted = /* @__PURE__ */ new Set();
1793
- for (const key of this.partialKeysAtLoad) if (key !== LYRICS_WIRE_KEY && !current.has(key)) deleted.add(key);
1794
- return deleted;
1795
- }
1796
- get handle() {
1797
- if (!this.fileHandle) throw new MetadataError("read", "File handle has been disposed");
1798
- return this.fileHandle;
1799
- }
1800
- getFormat() {
1801
- return this.handle.getFormat();
1802
- }
1803
- isFormat(format) {
1804
- return this.getFormat() === format;
1805
- }
1806
- tag() {
1807
- return buildMutableTag(this.handle);
1808
- }
1809
- audioProperties() {
1810
- if (!this.cachedAudioProperties) this.cachedAudioProperties = this.handle.getAudioProperties() ?? null;
1811
- return this.cachedAudioProperties ?? void 0;
1812
- }
1813
- properties() {
1814
- const remapped = remapKeysFromTagLib(this.handle.getProperties());
1815
- delete remapped[LYRICS_PROPERTY_KEY];
1816
- return remapped;
1817
- }
1818
- setProperties(properties) {
1819
- const translated = {};
1820
- for (const [key, values] of Object.entries(properties)) if (values !== void 0) translated[toTagLibKey(fromTagLibKey(key))] = values;
1821
- if (!(LYRICS_WIRE_KEY in translated)) {
1822
- const existing = this.handle.getProperties()[LYRICS_WIRE_KEY];
1823
- if (existing !== void 0) translated[LYRICS_WIRE_KEY] = existing;
1824
- }
1825
- const atomNames = mp4FreeformAtomNames(Object.keys(translated));
1826
- if (atomNames.length > 0) translated[MP4_ITEM_NAMES_KEY] = atomNames;
1827
- this.handle.setProperties(translated);
1828
- }
1829
- getProperty(key) {
1830
- const wireKey = toTagLibKey(fromTagLibKey(key));
1831
- const values = this.handle.getProperties()[wireKey]?.filter((v) => v !== "");
1832
- if (values !== void 0 && values.length > 0) return values;
1833
- if (!this.isMP4()) return void 0;
1834
- const remapped = this.properties()[key]?.filter((v) => v !== "");
1835
- return remapped !== void 0 && remapped.length > 0 ? remapped : void 0;
1836
- }
1837
- setProperty(key, value) {
1838
- const wireKey = toTagLibKey(fromTagLibKey(key));
1839
- const atomNames = mp4FreeformAtomNames([wireKey]);
1840
- if (atomNames.length > 0 && this.isMP4()) {
1841
- if (value === "") {
1842
- const prior = this.handle.getMp4ItemRemovals?.() ?? [];
1843
- this.handle.setMp4ItemRemovals?.([.../* @__PURE__ */ new Set([...prior, ...atomNames])]);
1844
- if (this.module.isWasi) this.handle.setProperties({
1845
- ...this.handle.getProperties(),
1846
- [wireKey]: []
1847
- });
1848
- else {
1849
- const rest = { ...this.handle.getProperties() };
1850
- delete rest[wireKey];
1851
- this.handle.setProperties(rest);
1852
- }
1853
- return;
1854
- }
1855
- this.handle.setProperties({
1856
- ...this.handle.getProperties(),
1857
- [wireKey]: [value],
1858
- [MP4_ITEM_NAMES_KEY]: atomNames
1859
- });
1860
- return;
1861
- }
1862
- this.handle.setProperty(wireKey, value);
1863
- }
1864
- removeProperty(key) {
1865
- this.setProperty(key, "");
1866
- }
1867
- isMP4() {
1868
- return this.handle.isMP4();
1869
- }
1870
- getMP4Item(key) {
1871
- if (!this.isMP4()) throw new UnsupportedFormatError(this.getFormat(), ["MP4", "M4A"]);
1872
- const wireKey = mp4AtomWireKey(key);
1873
- const value = wireKey !== void 0 ? this.handle.getProperty(wireKey) : this.handle.getMP4Item(key);
1874
- return value === "" ? void 0 : value;
1875
- }
1876
- setMP4Item(key, value) {
1877
- if (!this.isMP4()) throw new UnsupportedFormatError(this.getFormat(), ["MP4", "M4A"]);
1878
- const wireKey = mp4AtomWireKey(key);
1879
- if (wireKey !== void 0) {
1880
- this.handle.setProperty(wireKey, value);
1881
- return;
1882
- }
1883
- this.handle.setMP4Item(key, value);
1884
- }
1885
- removeMP4Item(key) {
1886
- if (!this.isMP4()) throw new UnsupportedFormatError(this.getFormat(), ["MP4", "M4A"]);
1887
- this.handle.removeMP4Item(key);
1888
- }
1889
- isValid() {
1890
- return this.handle.isValid();
1891
- }
1892
- dispose() {
1893
- unregisterAutoDispose(this);
1894
- if (this.fileHandle) {
1895
- this.fileHandle.destroy();
1896
- this.fileHandle = null;
1897
- this.cachedAudioProperties = null;
1898
- }
1899
- }
1900
- [_Symbol$dispose]() {
1901
- this.dispose();
1902
- }
1903
- };
1904
- }));
1905
- //#endregion
1906
- //#region src/taglib/metadata-extent.ts
1907
- function be32(b, offset) {
1908
- return (b[offset] << 24 | b[offset + 1] << 16 | b[offset + 2] << 8 | b[offset + 3]) >>> 0;
1909
- }
1910
- function startsWith(bytes, magic, at = 0) {
1911
- if (bytes.length < at + magic.length) return false;
1912
- for (let i = 0; i < magic.length; i++) if (bytes[at + i] !== magic.charCodeAt(i)) return false;
1913
- return true;
1914
- }
1915
- function id3v2End(bytes) {
1916
- if (!startsWith(bytes, "ID3") || bytes.length < 10) return void 0;
1917
- const size = bytes[6] << 21 | bytes[7] << 14 | bytes[8] << 7 | bytes[9];
1918
- const hasFooter = (bytes[5] & 16) !== 0;
1919
- return 10 + size + (hasFooter ? 10 : 0);
1920
- }
1921
- function flacEnd(bytes, limit, start) {
1922
- let offset = start + 4;
1923
- for (;;) {
1924
- if (offset + 4 > bytes.length) return void 0;
1925
- const isLast = (bytes[offset] & 128) !== 0;
1926
- const length = bytes[offset + 1] << 16 | bytes[offset + 2] << 8 | bytes[offset + 3];
1927
- offset += 4 + length;
1928
- if (offset > limit) return offset;
1929
- if (isLast) return offset;
1930
- }
1931
- }
1932
- function flacMarkerOffset(bytes) {
1933
- const at = startsWith(bytes, "ID3") ? id3v2End(bytes) : 0;
1934
- if (at === void 0) return void 0;
1935
- return startsWith(bytes, "fLaC", at) ? at : void 0;
1936
- }
1937
- function flacAudioStart(bytes) {
1938
- const at = flacMarkerOffset(bytes);
1939
- if (at === void 0) return void 0;
1940
- return flacEnd(bytes, bytes.length, at);
1941
- }
1942
- function mp4MoovEnd(bytes, limit, start) {
1943
- let offset = start;
1944
- const readable = Math.min(bytes.length, limit);
1945
- while (offset + 8 <= readable) {
1946
- const size = be32(bytes, offset);
1947
- const type = String.fromCharCode(bytes[offset + 4], bytes[offset + 5], bytes[offset + 6], bytes[offset + 7]);
1948
- if (size < 8) return void 0;
1949
- if (type === "moov") return offset + size;
1950
- offset += size;
1951
- }
1952
- }
1953
- function oggMetadataEnd(bytes, limit, start) {
1954
- let offset = start;
1955
- let packetsCompleted = 0;
1956
- let first = true;
1957
- for (;;) {
1958
- if (offset + 27 > bytes.length || !startsWith(bytes, "OggS", offset)) return;
1959
- const segmentCount = bytes[offset + 26];
1960
- const tableStart = offset + 27;
1961
- if (tableStart + segmentCount > bytes.length) return void 0;
1962
- let payload = 0;
1963
- for (let i = 0; i < segmentCount; i++) {
1964
- const segment = bytes[tableStart + i];
1965
- payload += segment;
1966
- if (segment < 255) packetsCompleted++;
1967
- }
1968
- if (first) {
1969
- const payloadStart = tableStart + segmentCount;
1970
- if (payloadStart + 5 > bytes.length) return void 0;
1971
- if (bytes[payloadStart] === 127 && startsWith(bytes, "FLAC", payloadStart + 1)) return;
1972
- first = false;
1973
- }
1974
- offset = tableStart + segmentCount + payload;
1975
- if (packetsCompleted >= 2 || offset > limit) return offset;
1976
- }
1977
- }
1978
- function mpegFrameLength(bytes, at) {
1979
- if (bytes.length < at + 4) return 0;
1980
- if (bytes[at] !== 255 || (bytes[at + 1] & 224) !== 224) return 0;
1981
- const version = bytes[at + 1] >> 3 & 3;
1982
- const layer = bytes[at + 1] >> 1 & 3;
1983
- if (version === 1 || layer === 0) return 0;
1984
- const bitrateIndex = bytes[at + 2] >> 4 & 15;
1985
- const sampleRateIndex = bytes[at + 2] >> 2 & 3;
1986
- if (bitrateIndex === 0 || bitrateIndex === 15 || sampleRateIndex === 3) return 0;
1987
- const mpeg1 = version === 3;
1988
- const layerIndex = layer ^ 3;
1989
- const bitrate = MPEG_BITRATES[mpeg1 ? 0 : 1][layerIndex][bitrateIndex];
1990
- const sampleRate = MPEG_SAMPLE_RATES[mpeg1 ? 0 : version === 2 ? 1 : 2][sampleRateIndex];
1991
- let frameLength = Math.floor((layerIndex === 2 ? mpeg1 ? 1152 : 576 : layerIndex === 1 ? 1152 : 384) * bitrate * 125 / sampleRate);
1992
- if ((bytes[at + 2] & 2) !== 0) frameLength += layerIndex === 0 ? 4 : 1;
1993
- return frameLength === 0 ? 0 : frameLength;
1994
- }
1995
- function isMpegFrameSync(bytes, at = 0) {
1996
- const frameLength = mpegFrameLength(bytes, at);
1997
- if (frameLength === 0) return false;
1998
- const next = at + frameLength;
1999
- if (bytes.length < next + 4) return false;
2000
- const mask = 4294839296;
2001
- return ((bytes[at] << 24 | bytes[at + 1] << 16 | bytes[at + 2] << 8 | bytes[at + 3]) >>> 0 & mask) >>> 0 === ((bytes[next] << 24 | bytes[next + 1] << 16 | bytes[next + 2] << 8 | bytes[next + 3]) >>> 0 & mask) >>> 0;
2002
- }
2003
- function containerEnd(bytes, at, limit) {
2004
- if (at >= bytes.length) return bytes.length < limit ? null : void 0;
2005
- if (at + 8 > bytes.length) return void 0;
2006
- if (startsWith(bytes, "fLaC", at)) return flacEnd(bytes, limit, at);
2007
- if (startsWith(bytes, "ftyp", at + 4)) return mp4MoovEnd(bytes, limit, at);
2008
- if (startsWith(bytes, "OggS", at)) return oggMetadataEnd(bytes, limit, at);
2009
- return null;
2010
- }
2011
- function metadataFitsInHeader(header, limit) {
2012
- let end;
2013
- if (startsWith(header, "ID3")) {
2014
- const tagEnd = id3v2End(header);
2015
- if (tagEnd === void 0) return false;
2016
- end = tagEnd;
2017
- if (tagEnd <= limit) {
2018
- const behind = containerEnd(header, tagEnd, limit);
2019
- if (behind === void 0) return false;
2020
- if (behind !== null) end = behind;
2021
- }
2022
- } else {
2023
- const container = containerEnd(header, 0, limit);
2024
- if (container === null) end = isMpegFrameSync(header) ? 0 : void 0;
2025
- else end = container;
2026
- }
2027
- if (end === void 0 || end > header.length) return false;
2028
- return end <= limit;
2029
- }
2030
- function trailerFitsInFooter(tail, footerSize) {
2031
- if (tail.length < Math.min(footerSize, 32)) return false;
2032
- for (const offsetFromEnd of [32, 160]) {
2033
- const at = tail.length - offsetFromEnd;
2034
- if (at < 0 || !startsWith(tail, "APETAGEX", at)) continue;
2035
- const size = (tail[at + 12] | tail[at + 13] << 8 | tail[at + 14] << 16 | tail[at + 15] << 24) >>> 0;
2036
- const trailing = offsetFromEnd === 32 ? 0 : 128;
2037
- if (size + 32 + trailing > footerSize) return false;
2038
- }
2039
- return true;
2040
- }
2041
- var MPEG_BITRATES, MPEG_SAMPLE_RATES;
2042
- var init_metadata_extent = __esmMin((() => {
2043
- MPEG_BITRATES = [[
2044
- [
2045
- 0,
2046
- 32,
2047
- 64,
2048
- 96,
2049
- 128,
2050
- 160,
2051
- 192,
2052
- 224,
2053
- 256,
2054
- 288,
2055
- 320,
2056
- 352,
2057
- 384,
2058
- 416,
2059
- 448,
2060
- 0
2061
- ],
2062
- [
2063
- 0,
2064
- 32,
2065
- 48,
2066
- 56,
2067
- 64,
2068
- 80,
2069
- 96,
2070
- 112,
2071
- 128,
2072
- 160,
2073
- 192,
2074
- 224,
2075
- 256,
2076
- 320,
2077
- 384,
2078
- 0
2079
- ],
2080
- [
2081
- 0,
2082
- 32,
2083
- 40,
2084
- 48,
2085
- 56,
2086
- 64,
2087
- 80,
2088
- 96,
2089
- 112,
2090
- 128,
2091
- 160,
2092
- 192,
2093
- 224,
2094
- 256,
2095
- 320,
2096
- 0
2097
- ]
2098
- ], [
2099
- [
2100
- 0,
2101
- 32,
2102
- 48,
2103
- 56,
2104
- 64,
2105
- 80,
2106
- 96,
2107
- 112,
2108
- 128,
2109
- 144,
2110
- 160,
2111
- 176,
2112
- 192,
2113
- 224,
2114
- 256,
2115
- 0
2116
- ],
2117
- [
2118
- 0,
2119
- 8,
2120
- 16,
2121
- 24,
2122
- 32,
2123
- 40,
2124
- 48,
2125
- 56,
2126
- 64,
2127
- 80,
2128
- 96,
2129
- 112,
2130
- 128,
2131
- 144,
2132
- 160,
2133
- 0
2134
- ],
2135
- [
2136
- 0,
2137
- 8,
2138
- 16,
2139
- 24,
2140
- 32,
2141
- 40,
2142
- 48,
2143
- 56,
2144
- 64,
2145
- 80,
2146
- 96,
2147
- 112,
2148
- 128,
2149
- 144,
2150
- 160,
2151
- 0
2152
- ]
2153
- ]];
2154
- MPEG_SAMPLE_RATES = [
2155
- [
2156
- 44100,
2157
- 48e3,
2158
- 32e3
2159
- ],
2160
- [
2161
- 22050,
2162
- 24e3,
2163
- 16e3
2164
- ],
2165
- [
2166
- 11025,
2167
- 12e3,
2168
- 8e3
2169
- ]
2170
- ];
2171
- }));
2172
- //#endregion
2173
- //#region src/taglib/media-ranges.ts
2174
- function adtsFrameLength(bytes, at) {
2175
- if (bytes.length < at + 7) return 0;
2176
- if (bytes[at] !== 255 || (bytes[at + 1] & 246) !== 240) return 0;
2177
- const length = (bytes[at + 3] & 3) << 11 | bytes[at + 4] << 3 | bytes[at + 5] >> 5;
2178
- return length >= 7 ? length : 0;
2179
- }
2180
- function trailingTagStart(bytes, end = bytes.length) {
2181
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2182
- let at = Math.max(0, Math.min(end, bytes.length));
2183
- for (;;) {
2184
- if (at >= 128 && text(bytes, at - 128, 3) === "TAG") {
2185
- at -= 128;
2186
- continue;
2187
- }
2188
- if (at >= 32 && text(bytes, at - 32, 8) === "APETAGEX") {
2189
- const size = view.getUint32(at - 32 + 12, true);
2190
- const flags = view.getUint32(at - 32 + 20, true);
2191
- const start = at - size - ((flags & 2147483648) !== 0 ? 32 : 0);
2192
- if (start < 0 || start >= at) return at;
2193
- at = start;
2194
- continue;
2195
- }
2196
- return at;
2197
- }
2198
- }
2199
- function firstFrame(bytes) {
2200
- const from = id3v2End(bytes) ?? 0;
2201
- const limit = Math.min(bytes.length - 6, from + MPEG_SCAN_LIMIT);
2202
- for (let o = from; o < limit; o++) {
2203
- const len = frameLengthAt(bytes, o);
2204
- if (len > 0 && frameLengthAt(bytes, o + len) > 0) return o;
2205
- }
2206
- return -1;
2207
- }
2208
- function forwardLastFrame(bytes, from, end) {
2209
- let o = from;
2210
- let start = -1;
2211
- let length = 0;
2212
- let frames = 0;
2213
- while (o + 6 <= end) {
2214
- const len = frameLengthAt(bytes, o);
2215
- if (len === 0 || o + len > end) break;
2216
- start = o;
2217
- length = len;
2218
- frames++;
2219
- o += len;
2220
- }
2221
- return {
2222
- start,
2223
- length,
2224
- frames
2225
- };
2226
- }
2227
- function walkMpeg(bytes) {
2228
- const from = firstFrame(bytes);
2229
- if (from < 0) return fallback("no valid first frame");
2230
- const last = forwardLastFrame(bytes, from, trailingTagStart(bytes));
2231
- if (last.start < 0) return fallback("no valid frames");
2232
- return {
2233
- kind: "ranges",
2234
- ranges: [{
2235
- offset: from,
2236
- length: last.start + last.length - from
2237
- }],
2238
- detail: `first=${from} last=${last.start}+${last.length} frames=${last.frames}`
2239
- };
2240
- }
2241
- function flacStreamInfoMd5(bytes) {
2242
- const marker = flacMarkerOffset(bytes);
2243
- if (marker === void 0) return void 0;
2244
- const header = marker + 4;
2245
- if (header + 4 > bytes.length) return void 0;
2246
- if ((bytes[header] & 127) !== 0) return void 0;
2247
- if ((bytes[header + 1] << 16 | bytes[header + 2] << 8 | bytes[header + 3]) < 34) return void 0;
2248
- const payload = header + 4;
2249
- if (payload + 34 > bytes.length) return void 0;
2250
- let hex = "";
2251
- for (const byte of bytes.subarray(payload + 18, payload + 34)) hex += byte.toString(16).padStart(2, "0");
2252
- return hex;
2253
- }
2254
- function walkFlac(bytes) {
2255
- const start = flacAudioStart(bytes);
2256
- if (start === void 0) return fallback("no fLaC marker");
2257
- const end = trailingTagStart(bytes);
2258
- if (end <= start) return fallback("no audio bytes");
2259
- return {
2260
- kind: "ranges",
2261
- ranges: [{
2262
- offset: start,
2263
- length: end - start
2264
- }],
2265
- detail: `audioStart=${start} end=${end}`
2266
- };
2267
- }
2268
- function atomLength(bytes, view, o) {
2269
- const size = view.getUint32(o, false);
2270
- if (size === 0) return {
2271
- length: bytes.length - o,
2272
- headerSize: 8
2273
- };
2274
- if (size === 1) {
2275
- if (o + 16 > bytes.length) return void 0;
2276
- const big = view.getBigUint64(o + 8, false);
2277
- if (big > BigInt(Number.MAX_SAFE_INTEGER)) return void 0;
2278
- return {
2279
- length: Number(big),
2280
- headerSize: 16
2281
- };
2282
- }
2283
- return {
2284
- length: size,
2285
- headerSize: 8
2286
- };
2287
- }
2288
- function walkMp4(bytes) {
2289
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2290
- const ranges = [];
2291
- let o = 0;
2292
- while (o + 8 <= bytes.length) {
2293
- const type = text(bytes, o + 4, 4);
2294
- const atom = atomLength(bytes, view, o);
2295
- if (atom === void 0) return fallback(`malformed ${type} size`);
2296
- if (atom.length < atom.headerSize) return fallback(`malformed ${type} size`);
2297
- if (o + atom.length > bytes.length) return fallback(`oversized ${type}`);
2298
- if (type === "mdat" && atom.length > atom.headerSize) ranges.push({
2299
- offset: o + atom.headerSize,
2300
- length: atom.length - atom.headerSize
2301
- });
2302
- o += atom.length;
2303
- }
2304
- if (o !== bytes.length) return fallback("trailing bytes after the last atom");
2305
- if (ranges.length === 0) return fallback("no non-empty mdat");
2306
- return {
2307
- kind: "ranges",
2308
- ranges,
2309
- detail: `${ranges.length} mdat(s)`
2310
- };
2311
- }
2312
- function walkWav(bytes) {
2313
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
2314
- if (text(bytes, 0, 4) !== "RIFF") return fallback("not RIFF");
2315
- if (text(bytes, 8, 4) !== "WAVE") return fallback("not WAVE");
2316
- const ranges = [];
2317
- let o = 12;
2318
- while (o + 8 <= bytes.length) {
2319
- const id = text(bytes, o, 4);
2320
- const size = view.getUint32(o + 4, true);
2321
- const dataStart = o + 8;
2322
- if (dataStart + size > bytes.length) return fallback(`truncated ${id}`);
2323
- if (id === "data" && size > 0) ranges.push({
2324
- offset: dataStart,
2325
- length: size
2326
- });
2327
- o = dataStart + size + size % 2;
2328
- }
2329
- if (ranges.length === 0) return fallback("no data chunk");
2330
- return {
2331
- kind: "ranges",
2332
- ranges,
2333
- detail: `${ranges.length} data chunk(s)`
2334
- };
2335
- }
2336
- function mediaRanges(format, bytes) {
2337
- const walked = (() => {
2338
- switch (format.toUpperCase()) {
2339
- case "MP3":
2340
- case "AAC": return walkMpeg(bytes);
2341
- case "FLAC": return walkFlac(bytes);
2342
- case "MP4":
2343
- case "M4A": return walkMp4(bytes);
2344
- case "WAV": return walkWav(bytes);
2345
- default: return {
2346
- kind: "fallback",
2347
- ranges: [],
2348
- detail: "format not covered"
2349
- };
2350
- }
2351
- })();
2352
- if (walked.kind === "fallback") return {
2353
- kind: "fallback",
2354
- ranges: [{
2355
- offset: 0,
2356
- length: bytes.length
2357
- }],
2358
- detail: `${walked.detail} → whole file`
2359
- };
2360
- return walked;
2361
- }
2362
- var decoder, text, fallback, frameLengthAt, MPEG_SCAN_LIMIT;
2363
- var init_media_ranges = __esmMin((() => {
2364
- init_metadata_extent();
2365
- decoder = new TextDecoder();
2366
- text = (b, o, n) => decoder.decode(b.subarray(o, o + n));
2367
- fallback = (detail) => ({
2368
- kind: "fallback",
2369
- ranges: [],
2370
- detail
2371
- });
2372
- frameLengthAt = (bytes, at) => mpegFrameLength(bytes, at) || adtsFrameLength(bytes, at);
2373
- MPEG_SCAN_LIMIT = 65536;
2374
- }));
2375
- //#endregion
2376
- //#region src/taglib/audio-file-checksum.ts
2377
- async function fileBytes(source, io) {
2378
- if (source.path) return await io.readFile(source.path);
2379
- if (source.blob) return new Uint8Array(await source.blob.arrayBuffer());
2380
- if (!source.partiallyLoaded && source.bytes.length > 0) return source.bytes;
2381
- throw new MetadataError("read", "the handle holds no file bytes and has no readable source; a partial handle that has been saved drops its source — checksum the saved path instead");
2382
- }
2383
- function joinRanges(bytes, ranges) {
2384
- const total = ranges.reduce((n, r) => n + r.length, 0);
2385
- const overrun = ranges.find((r) => r.offset + r.length > bytes.length);
2386
- if (overrun || total > bytes.length) throw new MetadataError("read", `range walk overran the buffer (${overrun ? `range ${overrun.offset}+${overrun.length}` : `${total} bytes`} past the ${bytes.length}-byte buffer)`);
2387
- if (ranges.length === 1) {
2388
- const only = ranges[0];
2389
- const view = bytes.subarray(only.offset, only.offset + only.length);
2390
- return view.buffer instanceof ArrayBuffer ? view : new Uint8Array(view);
2391
- }
2392
- const out = new Uint8Array(total);
2393
- let at = 0;
2394
- for (const r of ranges) {
2395
- out.set(bytes.subarray(r.offset, r.offset + r.length), at);
2396
- at += r.length;
2397
- }
2398
- return out;
2399
- }
2400
- async function mediaChecksum(source, format, io, options = {}) {
2401
- if (options.basis === "pcm") {
2402
- if (format.toUpperCase() !== "FLAC") throw new UnsupportedFormatError(format, ["FLAC"], { operation: "media checksum (basis: pcm)" });
2403
- const windowed = source.bytes.length > 0 ? source.bytes : source.path && io.readPartial ? await io.readPartial(source.path, STREAMINFO_WINDOW, 0) : void 0;
2404
- let md5 = windowed === void 0 ? void 0 : flacStreamInfoMd5(windowed);
2405
- if (md5 === void 0 && windowed !== source.bytes) md5 = flacStreamInfoMd5(await fileBytes(source, io));
2406
- if (md5 === void 0) throw new MetadataError("read", "STREAMINFO digest unavailable");
2407
- return {
2408
- source: "flac-streaminfo-md5",
2409
- algorithm: "md5",
2410
- hex: md5,
2411
- bytesHashed: 16
2412
- };
2413
- }
2414
- const bytes = await fileBytes(source, io);
2415
- const walk = mediaRanges(format, bytes);
2416
- const payload = joinRanges(bytes, walk.ranges);
2417
- const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", payload));
2418
- let hex = "";
2419
- for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
2420
- return {
2421
- source: walk.kind === "ranges" ? "audio-payload" : "file",
2422
- algorithm: "sha256",
2423
- hex,
2424
- bytesHashed: payload.length
2425
- };
2426
- }
2427
- var STREAMINFO_WINDOW;
2428
- var init_audio_file_checksum = __esmMin((() => {
2429
- init_media_ranges();
2430
- init_errors();
2431
- STREAMINFO_WINDOW = 65536;
2432
- }));
2433
- //#endregion
2434
- //#region src/utils/file.ts
2435
- async function readFileData(file) {
2436
- if (file instanceof Uint8Array) return file;
2437
- if (file instanceof ArrayBuffer) return new Uint8Array(file);
2438
- if (typeof File !== "undefined" && file instanceof File) return new Uint8Array(await file.arrayBuffer());
2439
- if (typeof file === "string") try {
2440
- return await getPlatformIO().readFile(file);
2441
- } catch (error) {
2442
- if (error instanceof EnvironmentError) throw error;
2443
- throw new FileOperationError("read", error.message, file);
2444
- }
2445
- const inputType = Object.prototype.toString.call(file);
2446
- throw new FileOperationError("read", `Invalid file input type: ${inputType}. Expected string path, Uint8Array, ArrayBuffer, or File object.`);
2447
- }
2448
- async function getFileSize(path) {
2449
- try {
2450
- return (await getPlatformIO().stat(path)).size;
2451
- } catch (error) {
2452
- if (error instanceof EnvironmentError) throw error;
2453
- throw new FileOperationError("stat", error.message, path);
2454
- }
2455
- }
2456
- async function readPartialFileData(path, headerSize, footerSize) {
2457
- const io = getPlatformIO();
2458
- if (!io.readPartial) throw new EnvironmentError("current runtime", "does not support partial file reading", "filesystem access with seek support");
2459
- try {
2460
- return await io.readPartial(path, headerSize, footerSize);
2461
- } catch (error) {
2462
- if (error instanceof EnvironmentError) throw error;
2463
- throw new FileOperationError("read", error.message, path);
2464
- }
2465
- }
2466
- var init_file = __esmMin((() => {
2467
- init_errors();
2468
- init__taglib_platform_io_stub();
2469
- }));
2470
- //#endregion
2471
- //#region src/taglib/embind-adapter.ts
2472
- function isValidBitrateMode(value) {
2473
- return value === "CBR" || value === "VBR" || value === "ABR";
2474
- }
2475
- function wrapEmbindHandle(raw) {
2476
- const stagedId3v2Frames = {};
2477
- let destroyed = false;
2478
- const overrides = {
2479
- getTagData() {
2480
- const tw = raw.getTag();
2481
- return {
2482
- title: tw.title(),
2483
- artist: tw.artist(),
2484
- album: tw.album(),
2485
- comment: tw.comment(),
2486
- genre: tw.genre(),
2487
- year: tw.year(),
2488
- track: tw.track()
2489
- };
2490
- },
2491
- setTagData(data) {
2492
- const tw = raw.getTag();
2493
- if (data.title !== void 0) tw.setTitle(data.title);
2494
- if (data.artist !== void 0) tw.setArtist(data.artist);
2495
- if (data.album !== void 0) tw.setAlbum(data.album);
2496
- if (data.comment !== void 0) tw.setComment(data.comment);
2497
- if (data.genre !== void 0) tw.setGenre(data.genre);
2498
- if (data.year !== void 0) tw.setYear(data.year);
2499
- if (data.track !== void 0) tw.setTrack(data.track);
2500
- },
2501
- getBextData() {
2502
- const v = raw.getBextData();
2503
- if (v === void 0 || v === null) return void 0;
2504
- const u8 = v instanceof Uint8Array ? v : new Uint8Array(v);
2505
- return u8.length > 0 ? u8 : void 0;
2506
- },
2507
- setBextData(data) {
2508
- raw.setBextData(data ?? null);
2509
- },
2510
- getIxml() {
2511
- const v = raw.getIxml();
2512
- return typeof v === "string" && v.length > 0 ? v : void 0;
2513
- },
2514
- setIxml(data) {
2515
- raw.setIxml(data ?? null);
2516
- },
2517
- getLyrics() {
2518
- return (raw.getProperties()["LYRICS"] ?? []).map((text) => ({
2519
- text,
2520
- description: "",
2521
- language: ""
2522
- }));
2523
- },
2524
- setLyrics(lyrics) {
2525
- const handle = raw;
2526
- const props = handle.getProperties();
2527
- if (lyrics.length > 0) props["LYRICS"] = lyrics.map((l) => l.text);
2528
- else delete props["LYRICS"];
2529
- handle.setProperties(props);
2530
- },
2531
- setId3v2Frames(id, data) {
2532
- stagedId3v2Frames[id] = data.map((d) => new Uint8Array(d));
2533
- raw.setId3v2Frames(id, data);
2534
- },
2535
- removeId3v2Frames(id) {
2536
- stagedId3v2Frames[id] = [];
2537
- raw.removeId3v2Frames(id);
2538
- },
2539
- getStagedId3v2Frames() {
2540
- return Object.keys(stagedId3v2Frames).length > 0 ? { ...stagedId3v2Frames } : void 0;
2541
- },
2542
- hasId3Tags() {
2543
- const v = raw.hasId3Tags();
2544
- if (!v || typeof v !== "object") return {
2545
- v1: false,
2546
- v2: false
2547
- };
2548
- const o = v;
2549
- return {
2550
- v1: o.v1 === true,
2551
- v2: o.v2 === true
2552
- };
2553
- },
2554
- stripId3Tags(opts) {
2555
- raw.stripId3Tags(opts);
2556
- },
2557
- destroy() {
2558
- if (destroyed) return;
2559
- destroyed = true;
2560
- raw.destroy();
2561
- },
2562
- get destroyed() {
2563
- return destroyed;
2564
- },
2565
- setMp4ItemRemovals(removals) {
2566
- const handle = raw;
2567
- for (const name of removals) handle.removeMP4Item(name);
2568
- },
2569
- getAudioProperties() {
2570
- const pw = raw.getAudioProperties();
2571
- if (!pw) return null;
2572
- const containerFormat = pw.containerFormat() || "unknown";
2573
- const codec = pw.codec() || "unknown";
2574
- const mpegVersion = pw.mpegVersion();
2575
- const formatVersion = pw.formatVersion();
2576
- const bitrateMode = pw.bitrateMode();
2577
- const isEncrypted = pw.isEncrypted();
2578
- return {
2579
- duration: pw.lengthInSeconds(),
2580
- durationMs: pw.lengthInMilliseconds(),
2581
- bitrate: pw.bitrate(),
2582
- sampleRate: pw.sampleRate(),
2583
- channels: pw.channels(),
2584
- bitsPerSample: pw.bitsPerSample(),
2585
- codec,
2586
- containerFormat,
2587
- isLossless: pw.isLossless(),
2588
- ...mpegVersion > 0 ? {
2589
- mpegVersion,
2590
- mpegLayer: pw.mpegLayer()
2591
- } : {},
2592
- ...isEncrypted || containerFormat === "MP4" || containerFormat === "ASF" ? { isEncrypted } : {},
2593
- ...formatVersion > 0 ? { formatVersion } : {},
2594
- ...isValidBitrateMode(bitrateMode) ? { bitrateMode } : {},
2595
- ...containerFormat === "OGG" && codec === "Opus" ? { outputGainDb: pw.outputGainDb() } : {}
2596
- };
2597
- }
2598
- };
2599
- return new Proxy(raw, { get(target, prop, receiver) {
2600
- if (prop in overrides) return overrides[prop];
2601
- const value = Reflect.get(target, prop, receiver);
2602
- return typeof value === "function" ? value.bind(target) : value;
2603
- } });
2604
- }
2605
- var init_embind_adapter = __esmMin((() => {}));
2606
- //#endregion
2607
- //#region src/taglib/extra-state-registry.ts
2608
- function chapterStyle(chapters) {
2609
- const s = chapters[0]?.source;
2610
- return s === "nero" || s === "both" ? s : "quicktime";
2611
- }
2612
- function copyExtraState(target, source, sourceComplete) {
2613
- for (const field of EXTRA_FIELDS) field.copy(target, source, sourceComplete);
2614
- }
2615
- var EXTRA_FIELDS;
2616
- var init_extra_state_registry = __esmMin((() => {
2617
- EXTRA_FIELDS = [
2618
- {
2619
- name: "pictures",
2620
- copy(target, source, complete) {
2621
- const v = source.getPictures();
2622
- if (complete || v.length > 0) target.setPictures(v);
2623
- }
2624
- },
2625
- {
2626
- name: "ratings",
2627
- copy(target, source, complete) {
2628
- const v = source.getRatings();
2629
- if (complete || v.length > 0) target.setRatings(v);
2630
- }
2631
- },
2632
- {
2633
- name: "lyrics",
2634
- copy(target, source, complete) {
2635
- const v = source.getLyrics();
2636
- if (complete || v.length > 0) target.setLyrics(v);
2637
- }
2638
- },
2639
- {
2640
- name: "chapters",
2641
- copy(target, source, complete) {
2642
- const v = source.getChapters();
2643
- if (complete || v.length > 0) target.setChapters(v, chapterStyle(v));
2644
- }
2645
- },
2646
- {
2647
- name: "bextData",
2648
- copy(target, source, complete) {
2649
- const v = source.getBextData();
2650
- if (v !== void 0) target.setBextData(v);
2651
- else if (complete) target.setBextData(null);
2652
- }
2653
- },
2654
- {
2655
- name: "ixml",
2656
- copy(target, source, complete) {
2657
- const v = source.getIxml();
2658
- if (v !== void 0) target.setIxml(v);
2659
- else if (complete) target.setIxml(null);
2660
- }
2661
- },
2662
- {
2663
- name: "_mp4ItemRemovals",
2664
- copy(target, source, complete) {
2665
- const v = source.getMp4ItemRemovals?.();
2666
- if (complete || v !== void 0 && v.length > 0) target.setMp4ItemRemovals?.(v ?? []);
2667
- }
2668
- },
2669
- {
2670
- name: "id3v2Frames",
2671
- copy(target, source) {
2672
- const staged = source.getStagedId3v2Frames?.();
2673
- if (!staged) return;
2674
- for (const [id, bodies] of Object.entries(staged)) target.setId3v2Frames(id, bodies);
2675
- }
2676
- }
2677
- ];
2678
- }));
2679
- //#endregion
2680
- //#region src/taglib/save-reconstruct.ts
2681
- function copyEditedState(target, source, sourceComplete, deletedKeys) {
2682
- target.setTagData(source.getTagData());
2683
- const merged = sourceComplete ? source.getProperties() : {
2684
- ...target.getProperties(),
2685
- ...source.getProperties()
2686
- };
2687
- for (const key of deletedKeys) delete merged[key];
2688
- const atomNames = mp4FreeformAtomNames(Object.keys(merged));
2689
- if (atomNames.length > 0) merged[MP4_ITEM_NAMES_KEY] = atomNames;
2690
- target.setProperties(merged);
2691
- copyExtraState(target, source, sourceComplete);
2692
- }
2693
- async function saveViaFreshHandle(module, editing, source, targetPath, sourceComplete, deletedKeys = /* @__PURE__ */ new Set()) {
2694
- const rawFullHandle = module.createFileHandle();
2695
- const fullFileHandle = module.isWasi ? rawFullHandle : wrapEmbindHandle(rawFullHandle);
2696
- try {
2697
- {
2698
- const data = await readFileData(source);
2699
- if (!fullFileHandle.loadFromBuffer(data)) throw new InvalidFormatError("Failed to load full audio file for saving");
2700
- }
2701
- copyEditedState(fullFileHandle, editing, sourceComplete, deletedKeys);
2702
- if (!fullFileHandle.save()) throw new FileOperationError("save", "Failed to save changes to full file");
2703
- await writeFileData(targetPath, fullFileHandle.getBuffer());
2704
- } finally {
2705
- fullFileHandle.destroy();
2706
- }
2707
- }
2708
- var init_save_reconstruct = __esmMin((() => {
2709
- init_errors();
2710
- init_file();
2711
- init_write();
2712
- init_embind_adapter();
2713
- init_extra_state_registry();
2714
- init_properties();
2715
- init_mp4_item_names();
2716
- }));
2717
- //#endregion
2718
- //#region src/taglib/audio-file-impl.ts
2719
- function sortChapters(list) {
2720
- return [...list].sort((a, b) => a.startTimeMs - b.startTimeMs);
2721
- }
2722
- function inferEndTimeMs(sorted, index, trackEndMs) {
2723
- const own = sorted[index].endTimeMs;
2724
- if (own !== void 0) return own;
2725
- const next = sorted[index + 1];
2726
- return next ? next.startTimeMs : trackEndMs;
2727
- }
2728
- function readFileSync(path) {
2729
- if (isDeno()) return Deno.readFileSync(path);
2730
- const fs = getNodeFsSync();
2731
- if (fs) return new Uint8Array(fs.readFileSync(path));
2732
- throw new FileOperationError("read", "node:fs is unavailable in this runtime: cannot read file data from disk", path);
2733
- }
2734
- var AudioFileImpl;
2735
- var init_audio_file_impl = __esmMin((() => {
2736
- init_types();
2737
- init_audio_file_bwf();
2738
- init_id3v2_frames();
2739
- init_errors();
2740
- init_write();
2741
- init__taglib_node_fs_stub();
2742
- init_rating();
2743
- init_detector();
2744
- init_audio_file_base();
2745
- init_audio_file_checksum();
2746
- init__taglib_platform_io_stub();
2747
- init_save_reconstruct();
2748
- init_defineProperty();
2749
- AudioFileImpl = class extends BaseAudioFileImpl {
2750
- constructor(module, fileHandle, sourcePath, originalSource, isPartiallyLoaded = false, partialLoadOptions) {
2751
- super(module, fileHandle, sourcePath, originalSource, isPartiallyLoaded, partialLoadOptions);
2752
- _defineProperty(this, "pathModeBuffer", null);
2753
- _defineProperty(this, "partiallyLoadedAtConstruction", void 0);
2754
- this.partiallyLoadedAtConstruction = isPartiallyLoaded;
2755
- }
2756
- save() {
2757
- if (this.isPartiallyLoaded && this.originalSource) throw new FileOperationError("save", "Cannot save partially loaded file directly. Use saveToFile() instead");
2758
- this.cachedAudioProperties = null;
2759
- this.pathModeBuffer = null;
2760
- return this.handle.save();
2761
- }
2762
- getFileBuffer() {
2763
- const buffer = this.handle.getBuffer();
2764
- if (buffer.length > 0) return buffer;
2765
- if (this.pathModeBuffer) return this.pathModeBuffer;
2766
- if (this.sourcePath) try {
2767
- this.pathModeBuffer = readFileSync(this.sourcePath);
2768
- return this.pathModeBuffer;
2769
- } catch (error) {
2770
- if (error instanceof FileOperationError) throw error;
2771
- throw new FileOperationError("read", `Cannot return file data: ${errorMessage(error)}`, this.sourcePath, { cause: error });
2772
- }
2773
- throw new FileOperationError("read", "No file data available: in-memory buffer is empty and no source path is set");
2774
- }
2775
- mediaChecksum(options) {
2776
- return mediaChecksum({
2777
- bytes: this.handle.getBuffer(),
2778
- ...this.sourcePath !== void 0 ? { path: this.sourcePath } : {},
2779
- ...this.originalSource instanceof Blob ? { blob: this.originalSource } : {},
2780
- partiallyLoaded: this.partiallyLoadedAtConstruction
2781
- }, this.getFormat(), getPlatformIO(), options);
2782
- }
2783
- async saveToFile(path) {
2784
- const targetPath = path ?? this.sourcePath;
2785
- if (!targetPath) throw new FileOperationError("save", "No file path available. Provide a path or open the file from a path");
2786
- if (this.isPartiallyLoaded && this.originalSource) {
2787
- await saveViaFreshHandle(this.module, this.handle, this.originalSource, targetPath, false, this.partialDeletedPropertyKeys());
2788
- this.isPartiallyLoaded = false;
2789
- this.originalSource = void 0;
2790
- } else if (this.module.isWasi && this.sourcePath && targetPath !== this.sourcePath) await saveViaFreshHandle(this.module, this.handle, this.sourcePath, targetPath, true);
2791
- else {
2792
- if (!this.save()) throw new FileOperationError("save", "Failed to save changes to in-memory buffer");
2793
- const buffer = this.handle.getBuffer();
2794
- if (buffer.length > 0) await writeFileData(targetPath, buffer);
2795
- }
2796
- this.pathModeBuffer = null;
2797
- }
2798
- getPictures() {
2799
- return this.handle.getPictures().map((pic) => ({
2800
- mimeType: pic.mimeType,
2801
- data: pic.data,
2802
- type: PICTURE_TYPE_NAMES[pic.type] ?? "Other",
2803
- ...pic.description !== void 0 ? { description: pic.description } : {}
2804
- }));
2805
- }
2806
- setPictures(pictures) {
2807
- this.handle.setPictures(pictures.map((pic) => ({
2808
- mimeType: pic.mimeType,
2809
- data: pic.data,
2810
- type: PICTURE_TYPE_VALUES[pic.type] ?? 0,
2811
- description: pic.description ?? ""
2812
- })));
2813
- }
2814
- addPicture(picture) {
2815
- this.handle.addPicture({
2816
- mimeType: picture.mimeType,
2817
- data: picture.data,
2818
- type: PICTURE_TYPE_VALUES[picture.type] ?? 0,
2819
- description: picture.description ?? ""
2820
- });
2821
- }
2822
- removePictures() {
2823
- this.handle.removePictures();
2824
- }
2825
- getChapters() {
2826
- const sorted = sortChapters(this.handle.getChapters());
2827
- const trackEndMs = this.audioProperties()?.durationMs;
2828
- return sorted.map((c, i) => {
2829
- const endTimeMs = inferEndTimeMs(sorted, i, trackEndMs);
2830
- return {
2831
- startTimeMs: c.startTimeMs,
2832
- ...endTimeMs !== void 0 ? { endTimeMs } : {},
2833
- ...c.title ? { title: c.title } : {},
2834
- ...c.id ? { id: c.id } : {},
2835
- ...c.source !== void 0 ? { source: c.source } : {}
2836
- };
2837
- });
2838
- }
2839
- setChapters(chapters, options) {
2840
- const fmt = this.getFormat();
2841
- if (fmt !== "MP3" && fmt !== "AAC" && fmt !== "MP4") throw new UnsupportedFormatError(fmt, [
2842
- "MP3",
2843
- "AAC",
2844
- "MP4"
2845
- ], { operation: "setChapters" });
2846
- const sorted = sortChapters(chapters);
2847
- const trackEndMs = this.audioProperties()?.durationMs;
2848
- const style = options?.mp4ChapterStyle ?? "quicktime";
2849
- const source = fmt === "MP4" ? style : "id3";
2850
- const raw = sorted.map((c, i) => ({
2851
- ...c.id !== void 0 ? { id: c.id } : {},
2852
- startTimeMs: c.startTimeMs,
2853
- endTimeMs: inferEndTimeMs(sorted, i, trackEndMs) ?? c.startTimeMs,
2854
- ...c.title !== void 0 ? { title: c.title } : {},
2855
- source
2856
- }));
2857
- this.handle.setChapters(raw, style);
2858
- }
2859
- getBext() {
2860
- return getBext(this.handle);
2861
- }
2862
- setBext(bext) {
2863
- setBext(this.handle, this.getFormat(), bext);
2864
- }
2865
- getBextData() {
2866
- return getBextData(this.handle);
2867
- }
2868
- setBextData(data) {
2869
- setBextData(this.handle, this.getFormat(), data);
2870
- }
2871
- getIxml() {
2872
- return getIxml(this.handle);
2873
- }
2874
- setIxml(data) {
2875
- setIxml(this.handle, this.getFormat(), data);
2876
- }
2877
- getRatings() {
2878
- return this.handle.getRatings().map((r) => ({
2879
- rating: r.rating,
2880
- ...r.email !== void 0 && r.email !== "" ? { email: r.email } : {},
2881
- ...r.counter !== 0 ? { counter: r.counter } : {}
2882
- }));
2883
- }
2884
- setRatings(ratings) {
2885
- this.handle.setRatings(ratings.map((r) => ({
2886
- rating: r.rating,
2887
- email: r.email ?? "",
2888
- counter: r.counter ?? 0
2889
- })));
2890
- }
2891
- getLyrics() {
2892
- return this.handle.getLyrics().map((l) => {
2893
- const out = { text: l.text };
2894
- if (l.description) out.description = l.description;
2895
- if (l.language) out.language = l.language;
2896
- return out;
2897
- });
2898
- }
2899
- setLyrics(lyrics) {
2900
- this.handle.setLyrics(lyrics.map((l) => ({
2901
- text: l.text,
2902
- description: l.description ?? "",
2903
- language: l.language ?? ""
2904
- })));
2905
- }
2906
- getRating() {
2907
- const ratings = this.getRatings();
2908
- return ratings.length > 0 ? normalized(ratings[0].rating) : void 0;
2909
- }
2910
- setRating(rating, email) {
2911
- this.setRatings([{
2912
- rating,
2913
- ...email !== void 0 ? { email } : {},
2914
- counter: 0
2915
- }]);
2916
- }
2917
- getId3v2Frames(id) {
2918
- assertMp3(this.getFormat());
2919
- if (id !== void 0) assertFrameId(id, "read");
2920
- return this.handle.getId3v2Frames(id ?? "").map(toPublicFrame);
2921
- }
2922
- setId3v2Frames(id, data) {
2923
- assertMp3(this.getFormat());
2924
- assertFrameId(id, "write");
2925
- assertFrameBodies(id, data);
2926
- this.handle.setId3v2Frames(id, data);
2927
- }
2928
- removeId3v2Frames(id) {
2929
- assertMp3(this.getFormat());
2930
- assertFrameId(id, "write");
2931
- this.handle.removeId3v2Frames(id);
2932
- }
2933
- hasId3Tags() {
2934
- return this.handle.hasId3Tags();
2935
- }
2936
- stripId3Tags(opts) {
2937
- this.handle.stripId3Tags({
2938
- v1: opts?.v1 ?? true,
2939
- v2: opts?.v2 ?? true
2940
- });
2941
- }
2942
- };
2943
- }));
2944
- //#endregion
2945
- //#region src/taglib/load-audio-data.ts
2946
- async function loadAudioData(input, opts) {
2947
- if (opts.partial && typeof File !== "undefined" && input instanceof File) {
2948
- const headerSize = Math.min(opts.maxHeaderSize, input.size);
2949
- const footerSize = Math.min(opts.maxFooterSize, input.size);
2950
- if (input.size <= headerSize + footerSize) return {
2951
- data: await readFileData(input),
2952
- isPartiallyLoaded: false
2953
- };
2954
- const header = new Uint8Array(await input.slice(0, headerSize).arrayBuffer());
2955
- if (!metadataFitsInHeader(header, headerSize)) return {
2956
- data: await readFileData(input),
2957
- isPartiallyLoaded: false
2958
- };
2959
- const footerStart = Math.max(0, input.size - footerSize);
2960
- const footer = new Uint8Array(await input.slice(footerStart).arrayBuffer());
2961
- if (!trailerFitsInFooter(footer, footerSize)) return {
2962
- data: await readFileData(input),
2963
- isPartiallyLoaded: false
2964
- };
2965
- const combined = new Uint8Array(header.byteLength + footer.byteLength);
2966
- combined.set(header, 0);
2967
- combined.set(footer, header.byteLength);
2968
- return {
2969
- data: combined,
2970
- isPartiallyLoaded: true
2971
- };
2972
- }
2973
- if (opts.partial && typeof input === "string") {
2974
- if (await getFileSize(input) > opts.maxHeaderSize + opts.maxFooterSize) {
2975
- const data = await readPartialFileData(input, opts.maxHeaderSize, opts.maxFooterSize);
2976
- if (metadataFitsInHeader(data, opts.maxHeaderSize) && trailerFitsInFooter(data, opts.maxFooterSize)) return {
2977
- data,
2978
- isPartiallyLoaded: true
2979
- };
2980
- }
2981
- return {
2982
- data: await readFileData(input),
2983
- isPartiallyLoaded: false
2984
- };
2985
- }
2986
- return {
2987
- data: await readFileData(input),
2988
- isPartiallyLoaded: false
2989
- };
2990
- }
2991
- var init_load_audio_data = __esmMin((() => {
2992
- init_file();
2993
- init_metadata_extent();
2994
- }));
2995
- //#endregion
2996
- //#region src/utils/mirror-fields.ts
2997
- function parseLeadingInt(raw) {
2998
- const parsed = Number.parseInt(raw, 10);
2999
- return Number.isNaN(parsed) ? void 0 : parsed;
3000
- }
3001
- var MIRROR_FIELDS;
3002
- var init_mirror_fields = __esmMin((() => {
3003
- MIRROR_FIELDS = [{
3004
- raw: "date",
3005
- numeric: "year"
3006
- }, {
3007
- raw: "trackNumber",
3008
- numeric: "track"
3009
- }];
3010
- MIRROR_FIELDS[0];
3011
- MIRROR_FIELDS[1];
3012
- }));
3013
- //#endregion
3014
- //#region src/utils/tag-mapping.ts
3015
- function readExtendedTag(audioFile, includeProperties) {
3016
- const props = audioFile.properties();
3017
- const tag = mapPropertiesToExtendedTag(props);
3018
- const pictures = audioFile.getPictures();
3019
- if (pictures.length > 0) tag.pictures = pictures;
3020
- const ratings = audioFile.getRatings();
3021
- if (ratings.length > 0) tag.ratings = ratings;
3022
- const lyrics = audioFile.getLyrics();
3023
- if (lyrics.length > 0) tag.lyrics = lyrics;
3024
- const chapters = audioFile.getChapters();
3025
- if (chapters.length > 0) tag.chapters = chapters;
3026
- const bext = audioFile.getBext();
3027
- if (bext !== void 0) tag.bext = bext;
3028
- const bextData = audioFile.getBextData();
3029
- if (bextData !== void 0) tag.bextData = bextData;
3030
- const ixml = audioFile.getIxml();
3031
- if (ixml !== void 0) tag.ixml = ixml;
3032
- if (includeProperties !== void 0 && includeProperties.length > 0) {
3033
- const extraProperties = {};
3034
- for (const wireKey of includeProperties) {
3035
- const values = props[fromTagLibKey(wireKey)]?.filter((v) => v !== "");
3036
- if (values !== void 0 && values.length > 0) extraProperties[wireKey] = values;
3037
- }
3038
- if (Object.keys(extraProperties).length > 0) tag.extraProperties = extraProperties;
3039
- }
3040
- return tag;
3041
- }
3042
- function mapPropertiesToExtendedTag(props) {
3043
- const tag = {};
3044
- for (const [propKey, tagField] of Object.entries(BASIC_PROPERTY_KEYS)) {
3045
- const values = props[propKey];
3046
- if (!values || values.length === 0) continue;
3047
- if (tagField === "year" || tagField === "track") {
3048
- const num = parseLeadingInt(values[0]);
3049
- if (num !== void 0) tag[tagField] = num;
3050
- if (propKey === "date") tag.date = values.length === 1 ? values[0] : values;
3051
- if (propKey === "trackNumber") tag.trackNumber = values.length === 1 ? values[0] : values;
3052
- } else tag[tagField] = values;
3053
- }
3054
- for (const [propKey, totalField] of [["trackNumber", "totalTracks"], ["discNumber", "totalDiscs"]]) {
3055
- if (tag[totalField] !== void 0) continue;
3056
- const raw = props[propKey]?.[0];
3057
- const slash = raw?.indexOf("/") ?? -1;
3058
- if (raw === void 0 || slash === -1) continue;
3059
- const total = parseLeadingInt(raw.slice(slash + 1));
3060
- if (total !== void 0) tag[totalField] = total;
3061
- }
3062
- if (tag.date === void 0) {
3063
- const yearValues = props["YEAR"];
3064
- if (yearValues !== void 0 && yearValues.length > 0) {
3065
- const y = parseLeadingInt(yearValues[0]);
3066
- if (y !== void 0) tag.year = y;
3067
- tag.date = yearValues.length === 1 ? yearValues[0] : yearValues;
3068
- }
3069
- }
3070
- for (const [key, values] of Object.entries(props)) {
3071
- if (BASIC_PROPERTY_KEYS[key]) continue;
3072
- if (key === "YEAR") continue;
3073
- if (!values || values.length === 0) continue;
3074
- const camelKey = fromTagLibKey(key);
3075
- if (NUMERIC_FIELDS.has(camelKey)) {
3076
- const num = parseLeadingInt(values[0]);
3077
- if (num !== void 0) tag[camelKey] = num;
3078
- } else if (camelKey === "compilation") tag[camelKey] = values[0] === "1" || values[0] === "true";
3079
- else if (camelKey === "itunesAdvisory") {
3080
- tag[camelKey] = values;
3081
- if (values[0] === "1") tag.advisory = "explicit";
3082
- else if (values[0] === "2") tag.advisory = "clean";
3083
- else if (values[0] === "0") tag.advisory = "unspecified";
3084
- } else if (camelKey === "r128TrackGain" || camelKey === "r128AlbumGain") {
3085
- const raw = parseLeadingInt(values[0]);
3086
- if (raw !== void 0) tag[camelKey] = raw / 256;
3087
- } else tag[camelKey] = values;
3088
- }
3089
- return tag;
3090
- }
3091
- function mergeTagUpdatesInto(currentProps, tags) {
3092
- const newProps = normalizeTagInput(tags);
3093
- reconcilePairFields(currentProps, newProps, tags);
3094
- if (newProps.date !== void 0 || newProps.year !== void 0) currentProps.YEAR = [];
3095
- return {
3096
- ...currentProps,
3097
- ...newProps
3098
- };
3099
- }
3100
- function mergeTagUpdates(file, tags) {
3101
- file.setProperties(mergeTagUpdatesInto(file.properties(), tags));
3102
- }
3103
- function reconcilePairFields(currentProps, newProps, input) {
3104
- for (const [rawKey, totalKey, numericKey] of [[
3105
- "trackNumber",
3106
- "totalTracks",
3107
- "track"
3108
- ], [
3109
- "discNumber",
3110
- "totalDiscs",
3111
- "discNumber"
3112
- ]]) {
3113
- const incoming = newProps[rawKey]?.[0];
3114
- if (incoming?.includes("/")) {
3115
- newProps[totalKey] = [];
3116
- continue;
3117
- }
3118
- if (!(input[numericKey] !== void 0 && input[rawKey] === void 0) || incoming === void 0) continue;
3119
- const existing = currentProps[rawKey]?.[0];
3120
- const slash = existing?.indexOf("/") ?? -1;
3121
- if (existing !== void 0 && slash !== -1) newProps[rawKey] = [`${incoming}${existing.slice(slash)}`];
3122
- }
3123
- }
3124
- function normalizeTagInput(input) {
3125
- const props = {};
3126
- for (const field of [
3127
- "title",
3128
- "artist",
3129
- "album",
3130
- "comment",
3131
- "genre"
3132
- ]) {
3133
- const val = input[field];
3134
- if (val === void 0) continue;
3135
- props[field] = Array.isArray(val) ? val : [val];
3136
- }
3137
- if (input.year !== void 0) props.date = [String(input.year)];
3138
- if (input.date !== void 0) props.date = Array.isArray(input.date) ? input.date : [input.date];
3139
- if (input.track !== void 0) props.trackNumber = [String(input.track)];
3140
- if (input.trackNumber !== void 0) props.trackNumber = Array.isArray(input.trackNumber) ? input.trackNumber : [input.trackNumber];
3141
- for (const [field, val] of Object.entries(input)) {
3142
- if (BASIC_FIELDS.has(field) || val === void 0) continue;
3143
- if (field === "extraProperties") continue;
3144
- if (field === "compilation") props[field] = [val ? "1" : "0"];
3145
- else if (field === "advisory") {
3146
- if (val === "explicit") props.itunesAdvisory = ["1"];
3147
- else if (val === "clean") props.itunesAdvisory = ["2"];
3148
- else if (val === "unspecified") props.itunesAdvisory = [];
3149
- } else if (field === "bpm") props[field] = [String(Math.trunc(val))];
3150
- else if (NUMERIC_FIELDS.has(field)) props[field] = [String(val)];
3151
- else if (field === "r128TrackGain" || field === "r128AlbumGain") props[field] = Array.isArray(val) ? val : [String(Math.round(val * 256))];
3152
- else if (typeof val === "string") props[field] = [val];
3153
- else if (Array.isArray(val)) props[field] = val;
3154
- }
3155
- for (const [rawField, totalField] of [["trackNumber", "totalTracks"], ["discNumber", "totalDiscs"]]) if (props[rawField]?.[0]?.includes("/")) delete props[totalField];
3156
- return props;
3157
- }
3158
- var BASIC_PROPERTY_KEYS, BASIC_FIELDS, NUMERIC_FIELDS;
3159
- var init_tag_mapping = __esmMin((() => {
3160
- init_properties();
3161
- init_mirror_fields();
3162
- BASIC_PROPERTY_KEYS = {
3163
- title: "title",
3164
- artist: "artist",
3165
- album: "album",
3166
- comment: "comment",
3167
- genre: "genre",
3168
- date: "year",
3169
- trackNumber: "track"
3170
- };
3171
- BASIC_FIELDS = /* @__PURE__ */ new Set([
3172
- "title",
3173
- "artist",
3174
- "album",
3175
- "comment",
3176
- "genre",
3177
- "year",
3178
- "date",
3179
- "track",
3180
- "trackNumber"
3181
- ]);
3182
- NUMERIC_FIELDS = /* @__PURE__ */ new Set([
3183
- "year",
3184
- "track",
3185
- "discNumber",
3186
- "totalTracks",
3187
- "totalDiscs",
3188
- "bpm"
3189
- ]);
3190
- }));
3191
- //#endregion
3192
- //#region src/version.ts
3193
- var VERSION;
3194
- var init_version = __esmMin((() => {
3195
- VERSION = "2.4.1";
3196
- }));
3197
- //#endregion
3198
- //#region src/runtime/module-loader-browser.ts
3199
- var module_loader_browser_exports = /* @__PURE__ */ __exportAll({ loadTagLibModule: () => loadTagLibModule });
3200
- async function loadTagLibModule(options) {
3201
- let createTagLibModule;
3202
- try {
3203
- createTagLibModule = (await import("./taglib-wrapper.js")).default;
3204
- } catch {
3205
- try {
3206
- createTagLibModule = (await import("./taglib-wrapper.js")).default;
3207
- } catch {
3208
- throw new TagLibInitializationError("Could not load taglib-wrapper.js. Ensure it is co-located with the browser bundle.");
3209
- }
3210
- }
3211
- const moduleConfig = {};
3212
- if (options?.wasmBinary) moduleConfig.wasmBinary = options.wasmBinary;
3213
- if (options?.wasmUrl) moduleConfig.locateFile = (path) => {
3214
- if (path.endsWith(".wasm")) return options.wasmUrl;
3215
- return path;
3216
- };
3217
- else if (!options?.wasmBinary) {
3218
- const wasmUrl = new URL("./taglib-web.wasm", import.meta.url);
3219
- moduleConfig.locateFile = (path) => path.endsWith(".wasm") ? wasmUrl.href : path;
3220
- }
3221
- return await createTagLibModule(moduleConfig);
3222
- }
3223
- var init_module_loader_browser = __esmMin((() => {
3224
- init_classes();
3225
- }));
3226
- //#endregion
3227
- //#region src/taglib/taglib-class.ts
3228
- function toWasiPath(osPath) {
3229
- if (osPath.startsWith("\\\\") || osPath.startsWith("//")) throw new FileOperationError("read", `UNC paths are not supported. Path: ${osPath}`);
3230
- let p = osPath;
3231
- if (!p.startsWith("/") && !/^[A-Za-z]:/.test(p)) {
3232
- const g = globalThis;
3233
- const cwd = isDeno() ? Deno.cwd() : g.process?.cwd?.();
3234
- if (cwd) p = cwd.replace(/[/\\]+$/, "") + "/" + p;
3235
- }
3236
- p = p.replaceAll("\\", "/");
3237
- const driveMatch = p.match(/^([A-Za-z]):\//);
3238
- if (driveMatch) p = `/${driveMatch[1].toUpperCase()}${p.slice(2)}`;
3239
- p = p.replace(/\/\.\//g, "/").replace(/\/+/g, "/");
3240
- if (!p.startsWith("/")) p = "/" + p;
3241
- return p;
3242
- }
3243
- async function createTagLib(module) {
3244
- return new TagLib(module);
3245
- }
3246
- var TagLib;
3247
- var init_taglib_class = __esmMin((() => {
3248
- init_audio_formats();
3249
- init_errors();
3250
- init_detector();
3251
- init_audio_file_impl();
3252
- init_load_audio_data();
3253
- init_tag_mapping();
3254
- init_version();
3255
- init_embind_adapter();
3256
- init_defineProperty();
3257
- TagLib = class TagLib {
3258
- constructor(module) {
3259
- _defineProperty(this, "module", void 0);
3260
- this.module = module;
3261
- }
3262
- static async initialize(options) {
3263
- const { loadTagLibModule } = await Promise.resolve().then(() => (init_module_loader_browser(), module_loader_browser_exports));
3264
- const module = await loadTagLibModule(options);
3265
- return new TagLib(module);
3266
- }
3267
- async open(input, options) {
3268
- if (!this.module.createFileHandle) throw new TagLibInitializationError("TagLib module not properly initialized: createFileHandle not found. Make sure the module is fully loaded before calling open.");
3269
- const actualInput = isNamedAudioInput(input) ? input.data : input;
3270
- const sourcePath = typeof actualInput === "string" ? actualInput : void 0;
3271
- if (typeof actualInput === "string" && this.module.isWasi) {
3272
- const wasiPath = toWasiPath(actualInput);
3273
- if (this.module.loadAudioPath) {
3274
- const fileHandle = await this.module.loadAudioPath(wasiPath, actualInput);
3275
- return new AudioFileImpl(this.module, fileHandle, sourcePath, actualInput, false);
3276
- }
3277
- }
3278
- const opts = {
3279
- partial: true,
3280
- maxHeaderSize: 1048576,
3281
- maxFooterSize: 131072,
3282
- ...options
3283
- };
3284
- const { data: audioData, isPartiallyLoaded } = await loadAudioData(actualInput, opts);
3285
- const uint8Array = actualInput instanceof Uint8Array && audioData.buffer === actualInput.buffer ? new Uint8Array(audioData.buffer.slice(audioData.byteOffset, audioData.byteOffset + audioData.byteLength)) : audioData;
3286
- const rawHandle = this.module.createFileHandle();
3287
- const fileHandle = this.module.isWasi ? rawHandle : wrapEmbindHandle(rawHandle);
3288
- try {
3289
- if (!fileHandle.loadFromBuffer(uint8Array)) throw new InvalidFormatError("Failed to load audio file. File may be corrupted or in an unsupported format", uint8Array.byteLength);
3290
- return new AudioFileImpl(this.module, fileHandle, sourcePath, actualInput, isPartiallyLoaded, opts);
3291
- } catch (error) {
3292
- if (typeof fileHandle.destroy === "function") fileHandle.destroy();
3293
- throw error;
3294
- }
3295
- }
3296
- async edit(input, fn) {
3297
- const file = await this.open(input);
3298
- try {
3299
- await fn(file);
3300
- if (typeof input === "string") await file.saveToFile();
3301
- else {
3302
- file.save();
3303
- return file.getFileBuffer();
3304
- }
3305
- } finally {
3306
- file.dispose();
3307
- }
3308
- }
3309
- async updateFile(path, tags) {
3310
- const file = await this.open(path);
3311
- try {
3312
- mergeTagUpdates(file, tags);
3313
- await file.saveToFile();
3314
- } finally {
3315
- file.dispose();
3316
- }
3317
- }
3318
- async copyWithTags(sourcePath, destPath, tags) {
3319
- const file = await this.open(sourcePath);
3320
- try {
3321
- mergeTagUpdates(file, tags);
3322
- await file.saveToFile(destPath);
3323
- } finally {
3324
- file.dispose();
3325
- }
3326
- }
3327
- version() {
3328
- return `${VERSION} (TagLib ${this.taglibVersion()})`;
3329
- }
3330
- taglibVersion() {
3331
- if (this.module.getVersion) return this.module.getVersion();
3332
- if (this.module.version) return this.module.version();
3333
- return "unknown";
3334
- }
3335
- };
3336
- }));
3337
- //#endregion
3338
- //#region src/taglib/index.ts
3339
- var init_taglib$1 = __esmMin((() => {
3340
- init_audio_file_impl();
3341
- init_taglib_class();
3342
- init_errors();
3343
- }));
3344
- //#endregion
3345
- //#region src/taglib.ts
3346
- var taglib_exports = /* @__PURE__ */ __exportAll({
3347
- AudioFileImpl: () => AudioFileImpl,
3348
- EnvironmentError: () => EnvironmentError,
3349
- FileOperationError: () => FileOperationError,
3350
- InvalidFormatError: () => InvalidFormatError,
3351
- MemoryError: () => MemoryError,
3352
- MetadataError: () => MetadataError,
3353
- SUPPORTED_FORMATS: () => SUPPORTED_FORMATS,
3354
- TagLib: () => TagLib,
3355
- TagLibError: () => TagLibError,
3356
- TagLibInitializationError: () => TagLibInitializationError,
3357
- UnsupportedFormatError: () => UnsupportedFormatError,
3358
- createTagLib: () => createTagLib,
3359
- isEnvironmentError: () => isEnvironmentError,
3360
- isFileOperationError: () => isFileOperationError,
3361
- isInvalidFormatError: () => isInvalidFormatError,
3362
- isMemoryError: () => isMemoryError,
3363
- isMetadataError: () => isMetadataError,
3364
- isTagLibError: () => isTagLibError,
3365
- isUnsupportedFormatError: () => isUnsupportedFormatError
3366
- });
3367
- var init_taglib = __esmMin((() => {
3368
- init_taglib$1();
3369
- }));
3370
- //#endregion
3371
- //#region src/simple/config.ts
3372
- let cachedTagLib = null;
3373
- let bufferModeEnabled = false;
3374
- function setBufferMode(enabled) {
3375
- bufferModeEnabled = enabled;
3376
- cachedTagLib = null;
3377
- }
3378
- async function getTagLib() {
3379
- if (!cachedTagLib) {
3380
- const { TagLib } = await Promise.resolve().then(() => (init_taglib(), taglib_exports));
3381
- const initOptions = bufferModeEnabled ? { forceWasmType: "emscripten" } : void 0;
3382
- cachedTagLib = await TagLib.initialize(initOptions);
3383
- }
3384
- return cachedTagLib;
3385
- }
3386
- //#endregion
3387
- //#region src/simple/with-audio-file.ts
3388
- init_errors();
3389
- init_file();
3390
- async function withAudioFile(file, fn, options) {
3391
- const audioFile = await (await getTagLib()).open(file, options);
3392
- try {
3393
- if (!audioFile.isValid()) throw new InvalidFormatError("File may be corrupted or in an unsupported format");
3394
- return await fn(audioFile);
3395
- } finally {
3396
- audioFile.dispose();
3397
- }
3398
- }
3399
- async function withAudioFileSave(file, fn) {
3400
- return withAudioFile(typeof file === "string" ? await readFileData(file) : file, (audioFile) => {
3401
- fn(audioFile);
3402
- if (!audioFile.save()) throw new FileOperationError("save", "Failed to save metadata changes. The file may be read-only or corrupted.");
3403
- return audioFile.getFileBuffer();
3404
- }, { partial: false });
3405
- }
3406
- async function withAudioFileSaveToFile(file, fn) {
3407
- return withAudioFile(file, async (audioFile) => {
3408
- fn(audioFile);
3409
- await audioFile.saveToFile(file);
3410
- });
3411
- }
3412
- //#endregion
3413
- //#region src/simple/tag-operations.ts
3414
- init_errors();
3415
- init_tag_mapping();
3416
- async function readTags(file, options = {}) {
3417
- return withAudioFile(file, (audioFile) => readExtendedTag(audioFile, options.includeProperties));
3418
- }
3419
- async function applyTags(file, tags) {
3420
- return withAudioFileSave(file, (audioFile) => {
3421
- mergeTagUpdates(audioFile, tags);
3422
- });
3423
- }
3424
- async function applyTagsToFile(file, tags) {
3425
- if (typeof file !== "string") throw new FileOperationError("save", "applyTagsToFile requires a file path string to save changes");
3426
- await withAudioFileSaveToFile(file, (audioFile) => {
3427
- mergeTagUpdates(audioFile, tags);
3428
- });
3429
- }
3430
- async function readProperties(file) {
3431
- return withAudioFile(file, (audioFile) => {
3432
- const props = audioFile.audioProperties();
3433
- if (!props) throw new MetadataError("read", "File may not contain valid audio data", "audioProperties");
3434
- return props;
3435
- });
3436
- }
3437
- async function isValidAudioFile(file) {
3438
- try {
3439
- const audioFile = await (await getTagLib()).open(file);
3440
- try {
3441
- return audioFile.isValid();
3442
- } finally {
3443
- audioFile.dispose();
3444
- }
3445
- } catch {
3446
- return false;
3447
- }
3448
- }
3449
- async function readFormat(file) {
3450
- const audioFile = await (await getTagLib()).open(file);
3451
- try {
3452
- if (!audioFile.isValid()) return;
3453
- return audioFile.getFormat();
3454
- } finally {
3455
- audioFile.dispose();
3456
- }
3457
- }
3458
- async function clearTags(file) {
3459
- return withAudioFileSave(file, (audioFile) => {
3460
- const cleared = {};
3461
- for (const key of Object.keys(audioFile.properties())) cleared[key] = [];
3462
- audioFile.setProperties(cleared);
3463
- audioFile.removePictures();
3464
- audioFile.setLyrics([]);
3465
- audioFile.setRatings([]);
3466
- if (audioFile.getChapters().length > 0) audioFile.setChapters([]);
3467
- if (audioFile.getBextData() !== void 0) audioFile.setBextData(null);
3468
- if (audioFile.getIxml() !== void 0) audioFile.setIxml(null);
3469
- });
3470
- }
3471
- //#endregion
3472
- //#region src/simple/picture-operations.ts
3473
- async function readPictures(file) {
3474
- return withAudioFile(file, (audioFile) => audioFile.getPictures());
3475
- }
3476
- async function applyPictures(file, pictures) {
3477
- return withAudioFileSave(file, (audioFile) => {
3478
- audioFile.setPictures(pictures);
3479
- });
3480
- }
3481
- async function addPicture(file, picture) {
3482
- return withAudioFileSave(file, (audioFile) => {
3483
- audioFile.addPicture(picture);
3484
- });
3485
- }
3486
- async function clearPictures(file) {
3487
- return applyPictures(file, []);
3488
- }
3489
- async function readCoverArt(file) {
3490
- const pictures = await readPictures(file);
3491
- if (pictures.length === 0) return;
3492
- const frontCover = pictures.find((pic) => pic.type === "FrontCover");
3493
- if (frontCover) return frontCover.data;
3494
- return pictures[0].data;
3495
- }
3496
- async function applyCoverArt(file, imageData, mimeType) {
3497
- return applyPictures(file, [{
3498
- mimeType,
3499
- data: imageData,
3500
- type: "FrontCover",
3501
- description: "Front Cover"
3502
- }]);
3503
- }
3504
- function findPictureByType(pictures, type) {
3505
- return pictures.find((pic) => pic.type === type);
3506
- }
3507
- async function replacePictureByType(file, newPicture) {
3508
- const filteredPictures = (await readPictures(file)).filter((pic) => pic.type !== newPicture.type);
3509
- filteredPictures.push(newPicture);
3510
- return applyPictures(file, filteredPictures);
3511
- }
3512
- async function readPictureMetadata(file) {
3513
- return (await readPictures(file)).map((pic) => ({
3514
- type: pic.type,
3515
- mimeType: pic.mimeType,
3516
- ...pic.description !== void 0 ? { description: pic.description } : {},
3517
- size: pic.data.length
3518
- }));
3519
- }
3520
- //#endregion
3521
- //#region src/simple/batch-operations.ts
3522
- init_audio_formats();
3523
- init_errors();
3524
- init_properties();
3525
- init_tag_mapping();
3526
- async function executeBatch(files, options, processor) {
3527
- if (files.length === 0) return {
3528
- items: [],
3529
- duration: 0
3530
- };
3531
- const startTime = Date.now();
3532
- const { concurrency = 4, continueOnError = true, onProgress, signal } = options;
3533
- const items = new Array(files.length);
3534
- const taglib = await getTagLib();
3535
- let processed = 0;
3536
- const total = files.length;
3537
- for (let i = 0; i < files.length; i += concurrency) {
3538
- signal?.throwIfAborted();
3539
- const chunkPromises = files.slice(i, i + concurrency).map(async (file, idx) => {
3540
- const index = i + idx;
3541
- const fileName = typeof file === "string" ? file : file instanceof File ? file.name : isNamedAudioInput(file) ? file.name : `buffer-${index}`;
3542
- try {
3543
- const audioFile = await taglib.open(file);
3544
- try {
3545
- if (!audioFile.isValid()) throw new InvalidFormatError("File may be corrupted or in an unsupported format");
3546
- items[index] = {
3547
- status: "ok",
3548
- path: fileName,
3549
- data: processor(audioFile)
3550
- };
3551
- } finally {
3552
- audioFile.dispose();
3553
- }
3554
- } catch (error) {
3555
- const err = error instanceof Error ? error : new Error(String(error));
3556
- items[index] = {
3557
- status: "error",
3558
- path: fileName,
3559
- error: err
3560
- };
3561
- if (!continueOnError) throw err;
3562
- }
3563
- processed++;
3564
- onProgress?.(processed, total, fileName);
3565
- });
3566
- await Promise.all(chunkPromises);
3567
- }
3568
- return {
3569
- items,
3570
- duration: Date.now() - startTime
3571
- };
3572
- }
3573
- async function readTagsBatch(files, options = {}) {
3574
- return executeBatch(files, options, (audioFile) => readExtendedTag(audioFile, options.includeProperties));
3575
- }
3576
- async function readPropertiesBatch(files, options = {}) {
3577
- return executeBatch(files, options, (audioFile) => audioFile.audioProperties());
3578
- }
3579
- function extractDynamics(audioFile) {
3580
- const dynamics = {};
3581
- for (const field of [
3582
- "replayGainTrackGain",
3583
- "replayGainTrackPeak",
3584
- "replayGainAlbumGain",
3585
- "replayGainAlbumPeak"
3586
- ]) {
3587
- const val = audioFile.getProperty(field)?.[0];
3588
- if (val !== void 0) dynamics[field] = val;
3589
- }
3590
- let appleSoundCheck = audioFile.getProperty("appleSoundCheck")?.[0];
3591
- if (!appleSoundCheck && audioFile.isMP4()) appleSoundCheck = audioFile.getMP4Item("----:com.apple.iTunes:iTunNORM");
3592
- if (appleSoundCheck) dynamics.appleSoundCheck = appleSoundCheck;
3593
- return Object.keys(dynamics).length > 0 ? dynamics : void 0;
3594
- }
3595
- async function readMetadata(file, options = {}) {
3596
- const audioFile = await (await getTagLib()).open(file);
3597
- try {
3598
- if (!audioFile.isValid()) {
3599
- let name;
3600
- if (typeof file === "string") name = file;
3601
- else if (file instanceof File) name = file.name;
3602
- else if (isNamedAudioInput(file)) name = file.name;
3603
- else name = `buffer (${file.byteLength} bytes)`;
3604
- throw new InvalidFormatError(`File may be corrupted or in an unsupported format. File: ${name}`);
3605
- }
3606
- const dynamics = extractDynamics(audioFile);
3607
- return {
3608
- tags: readExtendedTag(audioFile, options.includeProperties),
3609
- properties: audioFile.audioProperties(),
3610
- hasCoverArt: audioFile.getPictures().length > 0,
3611
- ...dynamics !== void 0 ? { dynamics } : {}
3612
- };
3613
- } finally {
3614
- audioFile.dispose();
3615
- }
3616
- }
3617
- async function readMetadataBatch(files, options = {}) {
3618
- return executeBatch(files, options, (audioFile) => {
3619
- const dynamics = extractDynamics(audioFile);
3620
- return {
3621
- tags: readExtendedTag(audioFile, options.includeProperties),
3622
- properties: audioFile.audioProperties(),
3623
- hasCoverArt: audioFile.getPictures().length > 0,
3624
- ...dynamics !== void 0 ? { dynamics } : {}
3625
- };
3626
- });
3627
- }
3628
- function entryPath(entry) {
3629
- return typeof entry === "string" ? entry : entry.path;
3630
- }
3631
- async function executeWriteBatch(entries, options, writer) {
3632
- if (entries.length === 0) return {
3633
- items: [],
3634
- duration: 0
3635
- };
3636
- await getTagLib();
3637
- const startTime = Date.now();
3638
- const { concurrency = 4, continueOnError = true, onProgress, signal } = options;
3639
- const items = new Array(entries.length);
3640
- let processed = 0;
3641
- const total = entries.length;
3642
- for (let i = 0; i < entries.length; i += concurrency) {
3643
- signal?.throwIfAborted();
3644
- const chunkPromises = entries.slice(i, i + concurrency).map(async (entry, idx) => {
3645
- const index = i + idx;
3646
- const path = entryPath(entry);
3647
- try {
3648
- await writer(path);
3649
- items[index] = {
3650
- status: "ok",
3651
- path,
3652
- data: void 0
3653
- };
3654
- } catch (error) {
3655
- const err = error instanceof Error ? error : new Error(String(error));
3656
- items[index] = {
3657
- status: "error",
3658
- path,
3659
- error: err
3660
- };
3661
- if (!continueOnError) throw err;
3662
- }
3663
- processed++;
3664
- onProgress?.(processed, total, path);
3665
- });
3666
- await Promise.all(chunkPromises);
3667
- }
3668
- return {
3669
- items,
3670
- duration: Date.now() - startTime
3671
- };
3672
- }
3673
- async function writeTagsBatch(updates, options = {}) {
3674
- const byPath = new Map(updates.map((u) => [u.path, u]));
3675
- return executeWriteBatch(updates, options, (path) => withAudioFileSaveToFile(path, (audioFile) => {
3676
- const update = byPath.get(path);
3677
- const merged = update.tags !== void 0 ? mergeTagUpdatesInto(audioFile.properties(), update.tags) : audioFile.properties();
3678
- if (update.properties !== void 0) for (const [key, values] of Object.entries(update.properties)) merged[fromTagLibKey(key)] = values;
3679
- audioFile.setProperties(merged);
3680
- }));
3681
- }
3682
- async function editTagsBatch(files, mutator, options = {}) {
3683
- return executeWriteBatch(files, options, (path) => withAudioFileSaveToFile(path, (audioFile) => mutator(audioFile, path)));
3684
- }
3685
- //#endregion
3686
- //#region src/simple/checksum-operations.ts
3687
- async function readMediaChecksum(file, options) {
3688
- return withAudioFile(file, (audioFile) => audioFile.mediaChecksum(options));
3689
- }
3690
- //#endregion
3691
- //#region src/simple.browser.ts
3692
- init_pictures();
3693
- //#endregion
3694
- export { PICTURE_TYPE_NAMES, PICTURE_TYPE_VALUES, addPicture, applyCoverArt, applyPictures, applyTags, applyTagsToFile, clearPictures, clearTags, editTagsBatch, findPictureByType, getTagLib, isValidAudioFile, readCoverArt, readFormat, readMediaChecksum, readMetadata, readMetadataBatch, readPictureMetadata, readPictures, readProperties, readPropertiesBatch, readTags, readTagsBatch, replacePictureByType, setBufferMode, writeTagsBatch };
1
+ var __defProp=Object.defineProperty;var __esmMin=(fn,res,err)=>()=>{if(err)throw err[0];try{return fn&&(res=fn(fn=0)),res}catch(e){throw err=[e],e}};var __exportAll=(all,no_symbols)=>{let target={};for(var name in all){__defProp(target,name,{get:all[name],enumerable:true})}if(!no_symbols){__defProp(target,Symbol.toStringTag,{value:`Module`})}return target};function isNamedAudioInput(input){return typeof input===`object`&&input!==null&&`name`in input&&`data`in input&&!(input instanceof File)&&!(input instanceof Uint8Array)&&!(input instanceof ArrayBuffer)}var init_audio_formats=__esmMin((()=>{}));var init_tags=__esmMin((()=>{}));var init_metadata_mappings=__esmMin((()=>{}));var PICTURE_TYPE_VALUES,PICTURE_TYPE_NAMES;var init_pictures=__esmMin((()=>{PICTURE_TYPE_VALUES={Other:0,FileIcon:1,OtherFileIcon:2,FrontCover:3,BackCover:4,LeafletPage:5,Media:6,LeadArtist:7,Artist:8,Conductor:9,Band:10,Composer:11,Lyricist:12,RecordingLocation:13,DuringRecording:14,DuringPerformance:15,MovieScreenCapture:16,ColouredFish:17,Illustration:18,BandLogo:19,PublisherLogo:20};PICTURE_TYPE_NAMES={0:`Other`,1:`FileIcon`,2:`OtherFileIcon`,3:`FrontCover`,4:`BackCover`,5:`LeafletPage`,6:`Media`,7:`LeadArtist`,8:`Artist`,9:`Conductor`,10:`Band`,11:`Composer`,12:`Lyricist`,13:`RecordingLocation`,14:`DuringRecording`,15:`DuringPerformance`,16:`MovieScreenCapture`,17:`ColouredFish`,18:`Illustration`,19:`BandLogo`,20:`PublisherLogo`}}));var init_chapters=__esmMin((()=>{}));var init_bwf=__esmMin((()=>{}));var init_config=__esmMin((()=>{}));var init_format_property_keys=__esmMin((()=>{}));var init_types$1=__esmMin((()=>{init_audio_formats();init_tags();init_metadata_mappings();init_pictures();init_chapters();init_bwf();init_config();init_format_property_keys()}));var init_types=__esmMin((()=>{init_types$1()}));function readFixedString(bytes,offset,len){let end=offset;const max=Math.min(offset+len,bytes.length);while(end<max&&bytes[end]!==0)end++;let s=``;for(let i=offset;i<end;i++)s+=String.fromCodePoint(bytes[i]);return s}function writeFixedString(bytes,offset,len,value){for(let i=0;i<len;i++)bytes[offset+i]=i<value.length?(value.codePointAt(i)??0)&255:0}function clampInt16(n){return Math.max(-32768,Math.min(32767,Math.round(n)))}function loudnessRaw(v){return v===void 0?LOUDNESS_UNSET:clampInt16(v*100)}function loudnessFromRaw(raw){return raw===LOUDNESS_UNSET?void 0:raw/100}function bytesToHex(bytes){let s=``;for(const b of bytes)s+=b.toString(16).padStart(2,`0`);return s}function hexToBytes(hex,outLen){const clean=hex.replace(/[^0-9a-fA-F]/g,``);const out=new Uint8Array(outLen);for(let i=0;i+1<clean.length+1&&i/2<outLen;i+=2){const pair=clean.slice(i,i+2);if(pair.length===2)out[i/2]=Number.parseInt(pair,16)}return out}function decodeLoudnessFields(dv){const result={};for(const[field,offset]of LOUDNESS_FIELDS){const value=loudnessFromRaw(dv.getInt16(LOUDNESS_OFFSET+offset,true));if(value!==void 0)result[field]=value}return result}function decodeBext(bytes){if(bytes.length<348)return void 0;const dv=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);const timeRefLow=dv.getUint32(338,true);const timeRefHigh=dv.getUint32(342,true);const version=dv.getUint16(VERSION_OFFSET,true);const result={description:readFixedString(bytes,0,256),originator:readFixedString(bytes,256,32),originatorReference:readFixedString(bytes,288,32),originationDate:readFixedString(bytes,320,10),originationTime:readFixedString(bytes,330,8),timeReferenceSamples:BigInt(timeRefHigh)<<32n|BigInt(timeRefLow),version,codingHistory:bytes.length>FIXED_PREFIX_LEN?readFixedString(bytes,FIXED_PREFIX_LEN,bytes.length-FIXED_PREFIX_LEN):``};if(version>=1&&bytes.length>=412)result.umid=bytesToHex(bytes.subarray(UMID_OFFSET,412));if(version>=2&&bytes.length>=422)Object.assign(result,decodeLoudnessFields(dv));return result}function encodeBext(b){const codingHistory=b.codingHistory??``;const bytes=new Uint8Array(FIXED_PREFIX_LEN+codingHistory.length);const dv=new DataView(bytes.buffer);const hasLoudness=b.loudnessValueDb!==void 0||b.loudnessRangeDb!==void 0||b.maxTruePeakLevelDbtp!==void 0||b.maxMomentaryLoudnessDb!==void 0||b.maxShortTermLoudnessDb!==void 0;let version;if(Number.isInteger(b.version))version=b.version;else if(hasLoudness)version=2;else if(b.umid)version=1;else version=0;writeFixedString(bytes,0,256,b.description??``);writeFixedString(bytes,256,32,b.originator??``);writeFixedString(bytes,288,32,b.originatorReference??``);writeFixedString(bytes,320,10,b.originationDate??``);writeFixedString(bytes,330,8,b.originationTime??``);const tr=b.timeReferenceSamples??0n;dv.setUint32(338,Number(tr&4294967295n),true);dv.setUint32(342,Number(tr>>32n&4294967295n),true);dv.setUint16(VERSION_OFFSET,version,true);if(version>=1&&b.umid)bytes.set(hexToBytes(b.umid,UMID_LEN),UMID_OFFSET);if(version>=2){dv.setInt16(LOUDNESS_OFFSET,loudnessRaw(b.loudnessValueDb),true);dv.setInt16(414,loudnessRaw(b.loudnessRangeDb),true);dv.setInt16(416,loudnessRaw(b.maxTruePeakLevelDbtp),true);dv.setInt16(418,loudnessRaw(b.maxMomentaryLoudnessDb),true);dv.setInt16(420,loudnessRaw(b.maxShortTermLoudnessDb),true)}writeFixedString(bytes,FIXED_PREFIX_LEN,codingHistory.length,codingHistory);return bytes}var FIXED_PREFIX_LEN,VERSION_OFFSET,UMID_OFFSET,UMID_LEN,LOUDNESS_OFFSET,LOUDNESS_UNSET,LOUDNESS_FIELDS;var init_bext=__esmMin((()=>{FIXED_PREFIX_LEN=602;VERSION_OFFSET=346;UMID_OFFSET=348;UMID_LEN=64;LOUDNESS_OFFSET=412;LOUDNESS_UNSET=32767;LOUDNESS_FIELDS=[[`loudnessValueDb`,0],[`loudnessRangeDb`,2],[`maxTruePeakLevelDbtp`,4],[`maxMomentaryLoudnessDb`,6],[`maxShortTermLoudnessDb`,8]]}));var SUPPORTED_FORMATS,TagLibError;var init_base=__esmMin((()=>{SUPPORTED_FORMATS=[`MP3`,`AAC`,`MP4`,`M4A`,`FLAC`,`OGG`,`OPUS`,`OggFLAC`,`SPEEX`,`WAV`,`AIFF`,`ASF`,`APE`,`DSF`,`DSDIFF`,`WV`,`MPC`,`TTA`,`SHN`,`MOD`,`S3M`,`IT`,`XM`,`MATROSKA`,`MKA`];TagLibError=class TagLibError extends Error{constructor(code,message,details){super(message);this.code=code;this.details=details;this.name=`TagLibError`;Object.setPrototypeOf(this,TagLibError.prototype)}}}));function errorMessage(error){return error instanceof Error?error.message:String(error)}function createErrorMessage(prefix,details){return`${prefix}: ${details}`}function formatFileSize(bytes){if(bytes<1024)return`${bytes} bytes`;if(bytes<1048576)return`${(bytes/1024).toFixed(1)} KB`;return`${(bytes/1048576).toFixed(1)} MB`}var TagLibInitializationError,InvalidFormatError,UnsupportedFormatError,FileOperationError,MetadataError,MemoryError,EnvironmentError;var init_classes=__esmMin((()=>{init_base();TagLibInitializationError=class TagLibInitializationError extends TagLibError{constructor(message,details){super(`INITIALIZATION`,createErrorMessage(`Failed to initialize TagLib Wasm module`,message),details);this.name=`TagLibInitializationError`;Object.setPrototypeOf(this,TagLibInitializationError.prototype)}};InvalidFormatError=class InvalidFormatError extends TagLibError{constructor(message,bufferSize,details){const errorDetails=[`Invalid audio file format: ${message}`];if(bufferSize!==void 0){errorDetails.push(`Buffer size: ${formatFileSize(bufferSize)}`);if(bufferSize<1024)errorDetails.push(`Audio files must be at least 1KB to contain valid headers.`)}super(`INVALID_FORMAT`,errorDetails.join(`. `),{...details,bufferSize});this.bufferSize=bufferSize;this.name=`InvalidFormatError`;Object.setPrototypeOf(this,InvalidFormatError.prototype)}};UnsupportedFormatError=class UnsupportedFormatError extends TagLibError{constructor(format,supportedFormats=SUPPORTED_FORMATS,details){super(`UNSUPPORTED_FORMAT`,`Unsupported audio format: ${format}. Supported formats: ${supportedFormats.join(`, `)}`,{...details,format,supportedFormats});this.format=format;this.supportedFormats=supportedFormats;this.name=`UnsupportedFormatError`;Object.setPrototypeOf(this,UnsupportedFormatError.prototype)}};FileOperationError=class FileOperationError extends TagLibError{constructor(operation,message,path,details){const errorDetails=[`Failed to ${operation} file`];if(path)errorDetails.push(`Path: ${path}`);errorDetails.push(message);super(`FILE_OPERATION`,errorDetails.join(`. `),{...details,operation,path});this.operation=operation;this.path=path;this.name=`FileOperationError`;Object.setPrototypeOf(this,FileOperationError.prototype)}};MetadataError=class MetadataError extends TagLibError{constructor(operation,message,field,details){const errorDetails=[`Failed to ${operation} metadata`];if(field)errorDetails.push(`Field: ${field}`);errorDetails.push(message);super(`METADATA`,errorDetails.join(`. `),{...details,operation,field});this.operation=operation;this.field=field;this.name=`MetadataError`;Object.setPrototypeOf(this,MetadataError.prototype)}};MemoryError=class MemoryError extends TagLibError{constructor(message,details){super(`MEMORY`,createErrorMessage(`Memory allocation failed`,message),details);this.name=`MemoryError`;Object.setPrototypeOf(this,MemoryError.prototype)}};EnvironmentError=class EnvironmentError extends TagLibError{constructor(environment,reason,requiredFeature){const message=requiredFeature?`Environment '${environment}' ${reason}. Required feature: ${requiredFeature}.`:`Environment '${environment}' ${reason}.`;super(`ENVIRONMENT`,message);this.environment=environment;this.reason=reason;this.requiredFeature=requiredFeature;this.name=`EnvironmentError`;Object.setPrototypeOf(this,EnvironmentError.prototype)}}}));function isTagLibError(error){return error instanceof TagLibError}function isInvalidFormatError(error){return error instanceof InvalidFormatError}function isUnsupportedFormatError(error){return error instanceof UnsupportedFormatError}function isFileOperationError(error){return error instanceof FileOperationError}function isMetadataError(error){return error instanceof MetadataError}function isMemoryError(error){return error instanceof MemoryError}function isEnvironmentError(error){return error instanceof EnvironmentError}var init_guards=__esmMin((()=>{init_base();init_classes()}));var init_errors$1=__esmMin((()=>{init_base();init_classes();init_guards()}));var init_errors=__esmMin((()=>{init_errors$1()}));function requireBwf(format){if(!BWF_FORMATS.has(format))throw new UnsupportedFormatError(format,[`WAV`,`FLAC`],{operation:`BWF metadata`})}function getBextData(handle){const raw=handle.getBextData();return raw&&raw.length>0?raw:void 0}function setBextData(handle,format,data){requireBwf(format);handle.setBextData(data)}function getBext(handle){const raw=handle.getBextData();return raw&&raw.length>0?decodeBext(raw):void 0}function setBext(handle,format,bext){requireBwf(format);handle.setBextData(encodeBext(bext))}function getIxml(handle){return handle.getIxml()}function setIxml(handle,format,data){requireBwf(format);handle.setIxml(data)}var BWF_FORMATS;var init_audio_file_bwf=__esmMin((()=>{init_bext();init_errors();BWF_FORMATS=/* @__PURE__ */ new Set([`WAV`,`FLAC`])}));function assertMp3(format){if(format!==`MP3`&&format!==`AAC`)throw new UnsupportedFormatError(format,[`MP3`,`AAC`],{operation:`id3v2Frames`})}function assertFrameId(id,operation){if(!FRAME_ID_PATTERN.test(id))throw new MetadataError(operation,`Invalid ID3v2 frame ID: "${id}". Frame IDs must match [A-Z0-9]{4}`,id)}function assertFrameBodies(id,data){for(const body of data)if(body.length===0)throw new MetadataError(`write`,`Frame data must not be empty: zero-size ID3v2 frames are invalid`,id)}function toPublicFrame(frame){return{id:frame.id,data:frame.data,...frame.flags?{flags:frame.flags}:{}}}var FRAME_ID_PATTERN;var init_id3v2_frames=__esmMin((()=>{init_classes();FRAME_ID_PATTERN=/^[A-Z0-9]{4}$/}));function getPlatformIO(){throw new Error(`Filesystem operations are not available in the browser.`)}var init__taglib_platform_io_stub=__esmMin((()=>{}));async function writeFileData(path,data){try{await getPlatformIO().writeFile(path,data)}catch(error){if(error instanceof EnvironmentError)throw error;throw new FileOperationError(`write`,error.message,path)}}var init_write=__esmMin((()=>{init_errors();init__taglib_platform_io_stub()}));function getNodeFsSync(){return null}var init__taglib_node_fs_stub=__esmMin((()=>{}));function normalized(value){return value}var init_rating=__esmMin((()=>{}));function isDeno(){return g.Deno!==void 0}var g,EXNREF_PROBE;var init_detector=__esmMin((()=>{g=globalThis;EXNREF_PROBE=new Uint8Array([0,97,115,109,1,0,0,0,6,6,1,105,0,208,105,11])}));function freeformTypeFromCode(code){return CODE_TO_TYPE[code]??`other`}function freeformCode(type,typeCode){if(type===`other`){if(typeCode===void 0||!Number.isInteger(typeCode)||typeCode<0||typeCode>255)throw new MetadataError(`write`,`MP4 freeform type "other" requires typeCode 0..255`);return typeCode}return TYPE_TO_CODE[type]}function validateAtomPart(label,value){if(value.length===0)throw new MetadataError(`write`,`MP4 freeform ${label} must not be empty`);if(value.includes(`:`))throw new MetadataError(`write`,`MP4 freeform ${label} must not contain ":"`)}function encodeFreeformValue(type,value){if(type===`utf8`){if(typeof value!==`string`)throw new MetadataError(`write`,`MP4 freeform type "utf8" requires a string value`);return new TextEncoder().encode(value)}if(type===`integer`){if(typeof value!==`number`||!Number.isInteger(value)||value<INT32_MIN||value>INT32_MAX)throw new MetadataError(`write`,`MP4 freeform type "integer" requires an int32 value`);const bytes=/* @__PURE__ */ new Uint8Array(4);new DataView(bytes.buffer).setInt32(0,value,false);return bytes}if(!(value instanceof Uint8Array))throw new MetadataError(`write`,`MP4 freeform type "${type}" requires a Uint8Array value`);return new Uint8Array(value)}function decodeFreeformValue(type,bytes){if(type===`utf8`)return new TextDecoder().decode(bytes);if(type===`integer`&&bytes.byteLength===4)return new DataView(bytes.buffer,bytes.byteOffset,4).getInt32(0,false);return new Uint8Array(bytes)}function validateFreeformItems(items){const types=/* @__PURE__ */ new Map;for(const item of items){const atom=`${item.mean}\u0000${item.name}`;const signature=item.type===`other`?`other:${item.typeCode??`missing`}`:item.type;const previous=types.get(atom);if(previous!==void 0&&previous!==signature)throw new MetadataError(`write`,`MP4 freeform atom "${item.mean}:${item.name}" cannot mix types "${previous}" and "${signature}"`);types.set(atom,signature)}}function toRawFreeformItem(item){validateAtomPart(`mean`,item.mean);validateAtomPart(`name`,item.name);return{mean:item.mean,name:item.name,type:freeformCode(item.type,item.typeCode),value:encodeFreeformValue(item.type,item.value)}}function fromRawFreeformItem(raw){const type=freeformTypeFromCode(raw.type);if(type===`integer`&&raw.value.byteLength!==4)return{mean:raw.mean,name:raw.name,type:`other`,typeCode:raw.type,value:new Uint8Array(raw.value)};const value=decodeFreeformValue(type,raw.value);return type===`other`?{mean:raw.mean,name:raw.name,type,typeCode:raw.type,value}:{mean:raw.mean,name:raw.name,type,value}}var TYPE_TO_CODE,CODE_TO_TYPE,INT32_MIN,INT32_MAX;var init_mp4_freeform=__esmMin((()=>{init_errors();TYPE_TO_CODE={implicit:0,utf8:1,utf16:2,jpeg:13,png:14,integer:21,bmp:27,undefined:255};CODE_TO_TYPE={0:`implicit`,1:`utf8`,2:`utf16`,13:`jpeg`,14:`png`,21:`integer`,27:`bmp`,255:`undefined`};INT32_MIN=-2147483648;INT32_MAX=2147483647}));var ADDITIONAL_PROPERTIES;var init_additional_properties=__esmMin((()=>{ADDITIONAL_PROPERTIES={albumArtistSort:{key:`ALBUMARTISTSORT`,description:`Sort name for album artist (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSO2`},vorbis:`ALBUMARTISTSORT`,mp4:`soaa`}},composerSort:{key:`COMPOSERSORT`,description:`Sort name for composer (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSOC`},vorbis:`COMPOSERSORT`,mp4:`soco`}},subtitle:{key:`SUBTITLE`,description:`Subtitle or description refinement`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TIT3`},vorbis:`SUBTITLE`,mp4:`----:com.apple.iTunes:SUBTITLE`}},label:{key:`LABEL`,description:`Record label name`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TPUB`},vorbis:`LABEL`,mp4:`----:com.apple.iTunes:LABEL`,wav:`IPUB`}},producer:{key:`PRODUCER`,description:`Producer of the recording`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`PRODUCER`},vorbis:`PRODUCER`,mp4:`----:com.apple.iTunes:PRODUCER`}},radioStationOwner:{key:`RADIOSTATIONOWNER`,description:`Owner of the radio station`,type:`string`,supportedFormats:[`ID3v2`],mappings:{id3v2:{frame:`TRSO`}}},asin:{key:`ASIN`,description:`Amazon Standard Identification Number`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ASIN`},vorbis:`ASIN`,mp4:`----:com.apple.iTunes:ASIN`}},musicbrainzReleaseArtistId:{key:`MUSICBRAINZ_ALBUMARTISTID`,description:`MusicBrainz Release Artist ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Artist Id`},vorbis:`MUSICBRAINZ_ALBUMARTISTID`,mp4:`----:com.apple.iTunes:MusicBrainz Album Artist Id`}},musicbrainzWorkId:{key:`MUSICBRAINZ_WORKID`,description:`MusicBrainz Work ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Work Id`},vorbis:`MUSICBRAINZ_WORKID`,mp4:`----:com.apple.iTunes:MusicBrainz Work Id`}},musicbrainzReleaseTrackId:{key:`MUSICBRAINZ_RELEASETRACKID`,description:`MusicBrainz Release Track ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Release Track Id`},vorbis:`MUSICBRAINZ_RELEASETRACKID`,mp4:`----:com.apple.iTunes:MusicBrainz Release Track Id`}},podcastId:{key:`PODCASTID`,description:`Podcast episode identifier`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TGID`},vorbis:`PODCASTID`,mp4:`egid`}},podcastUrl:{key:`PODCASTURL`,description:`Podcast feed URL`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`WFED`},vorbis:`PODCASTURL`,mp4:`purl`}},originalArtist:{key:`ORIGINALARTIST`,description:`Original artist of a cover or remix`,type:`string`,supportedFormats:[`ID3v2`,`Vorbis`],mappings:{id3v2:{frame:`TOPE`},vorbis:`ORIGINALARTIST`}},originalAlbum:{key:`ORIGINALALBUM`,description:`Original album of a cover or remix`,type:`string`,supportedFormats:[`ID3v2`,`Vorbis`],mappings:{id3v2:{frame:`TOAL`},vorbis:`ORIGINALALBUM`}},originalDate:{key:`ORIGINALDATE`,description:`Original release date`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TDOR`},vorbis:`ORIGINALDATE`,mp4:`----:com.apple.iTunes:ORIGINALDATE`}},script:{key:`SCRIPT`,description:`Writing script used for text (e.g., Latn, Jpan)`,type:`string`,supportedFormats:[`MP4`,`Vorbis`],mappings:{vorbis:`SCRIPT`,mp4:`----:com.apple.iTunes:SCRIPT`}},involvedPeople:{key:`INVOLVEDPEOPLE`,description:`List of involved people and their roles`,type:`string`,supportedFormats:[`ID3v2`],mappings:{id3v2:{frame:`TIPL`}}},encoding:{key:`ENCODING`,description:`Encoding software or settings`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TSSE`},vorbis:`ENCODING`,mp4:`©too`,wav:`ISFT`}}}}));var BASIC_PROPERTIES;var init_basic_properties=__esmMin((()=>{BASIC_PROPERTIES={title:{key:`TITLE`,description:`The title of the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TIT2`},vorbis:`TITLE`,mp4:`©nam`,wav:`INAM`}},artist:{key:`ARTIST`,description:`The primary performer(s) of the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TPE1`},vorbis:`ARTIST`,mp4:`©ART`,wav:`IART`}},album:{key:`ALBUM`,description:`The album/collection name`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TALB`},vorbis:`ALBUM`,mp4:`©alb`,wav:`IPRD`}},date:{key:`DATE`,description:`The date of recording (typically year)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TDRC`},vorbis:`DATE`,mp4:`©day`,wav:`ICRD`}},trackNumber:{key:`TRACKNUMBER`,description:`The track number within the album`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TRCK`},vorbis:`TRACKNUMBER`,mp4:`trkn`,wav:`ITRK`}},genre:{key:`GENRE`,description:`The musical genre`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`TCON`},vorbis:`GENRE`,mp4:`©gen`,wav:`IGNR`}},comment:{key:`COMMENT`,description:`Comments or notes about the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`WAV`],mappings:{id3v2:{frame:`COMM`},vorbis:`COMMENT`,mp4:`©cmt`,wav:`ICMT`}}}}));var GENERAL_EXTENDED_PROPERTIES;var init_general_extended_properties=__esmMin((()=>{GENERAL_EXTENDED_PROPERTIES={albumArtist:{key:`ALBUMARTIST`,description:`The album artist (band/orchestra/ensemble)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TPE2`},vorbis:`ALBUMARTIST`,mp4:`aART`}},composer:{key:`COMPOSER`,description:`The original composer(s) of the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TCOM`},vorbis:`COMPOSER`,mp4:`©wrt`}},copyright:{key:`COPYRIGHT`,description:`Copyright information`,type:`string`,supportedFormats:[`ID3v2`,`Vorbis`],mappings:{vorbis:`COPYRIGHT`}},encodedBy:{key:`ENCODEDBY`,description:`The encoding software or person`,type:`string`,supportedFormats:[`ID3v2`,`Vorbis`],mappings:{vorbis:`ENCODEDBY`}},discNumber:{key:`DISCNUMBER`,description:`The disc number for multi-disc sets`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TPOS`},vorbis:`DISCNUMBER`,mp4:`disk`}},bpm:{key:`BPM`,description:`Beats per minute`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TBPM`},vorbis:`BPM`,mp4:`tmpo`}},totalTracks:{key:`TRACKTOTAL`,description:`Total number of tracks on the album`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TRCK`},vorbis:`TRACKTOTAL`,mp4:`trkn`}},totalDiscs:{key:`DISCTOTAL`,description:`Total number of discs in the set`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TPOS`},vorbis:`DISCTOTAL`,mp4:`disk`}},compilation:{key:`COMPILATION`,description:`Whether the album is a compilation (various artists)`,type:`boolean`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TCMP`},vorbis:`COMPILATION`,mp4:`cpil`}},titleSort:{key:`TITLESORT`,description:`Sort name for title (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSOT`},vorbis:`TITLESORT`,mp4:`sonm`}},artistSort:{key:`ARTISTSORT`,description:`Sort name for artist (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSOP`},vorbis:`ARTISTSORT`,mp4:`soar`}},albumSort:{key:`ALBUMSORT`,description:`Sort name for album (for alphabetization)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TSOA`},vorbis:`ALBUMSORT`,mp4:`soal`}},lyricist:{key:`LYRICIST`,description:`The lyrics/text writer(s)`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`LYRICIST`}},conductor:{key:`CONDUCTOR`,description:`The conductor`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`CONDUCTOR`}},remixedBy:{key:`REMIXER`,description:`Person who remixed the track`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TPE4`},vorbis:`REMIXER`,mp4:`----:com.apple.iTunes:REMIXER`}},language:{key:`LANGUAGE`,description:`Language of vocals/lyrics`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`LANGUAGE`}},publisher:{key:`PUBLISHER`,description:`The publisher`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`PUBLISHER`}},mood:{key:`MOOD`,description:`The mood/atmosphere of the track`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`MOOD`}},media:{key:`MEDIA`,description:`Media type (CD, vinyl, etc.)`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`MEDIA`}},grouping:{key:`GROUPING`,description:`Content group/work`,type:`string`,supportedFormats:[`MP4`,`Vorbis`],mappings:{vorbis:`GROUPING`,mp4:`©grp`}},work:{key:`WORK`,description:`Work name`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`WORK`}},lyrics:{key:`LYRICS`,description:`Lyrics content`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`LYRICS`}},isrc:{key:`ISRC`,description:`International Standard Recording Code`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`ISRC`}},catalogNumber:{key:`CATALOGNUMBER`,description:`Catalog number`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`CATALOGNUMBER`}},barcode:{key:`BARCODE`,description:`Barcode (EAN/UPC)`,type:`string`,supportedFormats:[`Vorbis`],mappings:{vorbis:`BARCODE`}}}}));var SPECIALIZED_PROPERTIES;var init_specialized_properties=__esmMin((()=>{SPECIALIZED_PROPERTIES={musicbrainzArtistId:{key:`MUSICBRAINZ_ARTISTID`,description:`MusicBrainz Artist ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Artist Id`},vorbis:`MUSICBRAINZ_ARTISTID`,mp4:`----:com.apple.iTunes:MusicBrainz Artist Id`}},musicbrainzReleaseId:{key:`MUSICBRAINZ_ALBUMID`,description:`MusicBrainz Release ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Id`},vorbis:`MUSICBRAINZ_ALBUMID`,mp4:`----:com.apple.iTunes:MusicBrainz Album Id`}},musicbrainzTrackId:{key:`MUSICBRAINZ_TRACKID`,description:`MusicBrainz Recording ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`UFID`,description:`http://musicbrainz.org`},vorbis:`MUSICBRAINZ_TRACKID`,mp4:`----:com.apple.iTunes:MusicBrainz Track Id`}},musicbrainzReleaseGroupId:{key:`MUSICBRAINZ_RELEASEGROUPID`,description:`MusicBrainz Release Group ID (UUID)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Release Group Id`},vorbis:`MUSICBRAINZ_RELEASEGROUPID`,mp4:`----:com.apple.iTunes:MusicBrainz Release Group Id`}},releaseType:{key:`RELEASETYPE`,description:`Release type (album, single, EP, compilation, ...). Multi-value (e.g. 'album' + 'EP'). TagLib 2.3.2 translates the RELEASETYPE key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM TYPE' (TagLib's description casing), MP4 freeform atom, APEv2 MUSICBRAINZ_ALBUMTYPE, ASF 'MusicBrainz/Album Type', Vorbis/Matroska raw RELEASETYPE`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`APE`,`ASF`,`Matroska`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Type`},vorbis:`RELEASETYPE`,mp4:`----:com.apple.iTunes:MusicBrainz Album Type`}},releaseCountry:{key:`RELEASECOUNTRY`,description:`Release country (ISO 3166-1 code, e.g. 'US'). TagLib 2.3.2 translates the RELEASECOUNTRY key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM RELEASE COUNTRY' (TagLib's description casing; an uppercase TXXX:RELEASECOUNTRY description also reads back), MP4 freeform atom 'MusicBrainz Album Release Country', APEv2 raw RELEASECOUNTRY, ASF 'MusicBrainz/Album Release Country', WAV ICNT, Vorbis/Matroska raw RELEASECOUNTRY`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`APE`,`ASF`,`Matroska`,`WAV`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Release Country`},vorbis:`RELEASECOUNTRY`,mp4:`----:com.apple.iTunes:MusicBrainz Album Release Country`}},releaseStatus:{key:`RELEASESTATUS`,description:`Release status (official, promotion, bootleg, ...). TagLib 2.3.2 translates the RELEASESTATUS key per format: ID3v2 TXXX 'MUSICBRAINZ ALBUM STATUS' (TagLib's description casing), MP4 freeform atom 'MusicBrainz Album Status', APEv2 MUSICBRAINZ_ALBUMSTATUS, ASF 'MusicBrainz/Album Status', Vorbis/Matroska raw RELEASESTATUS`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`APE`,`ASF`,`Matroska`],mappings:{id3v2:{frame:`TXXX`,description:`MusicBrainz Album Status`},vorbis:`RELEASESTATUS`,mp4:`----:com.apple.iTunes:MusicBrainz Album Status`}},itunesAdvisory:{key:`ITUNESADVISORY`,description:`Content advisory in the ITUNESADVISORY convention ('1' = explicit, '2' = clean, '0' = unspecified). On MP4 the value is stored in the native rtng atom and surfaced here. The typed tri-state lives on ExtendedTag.advisory; aliases CONTENTADVISORY and EXPLICIT resolve here`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`APE`,`ASF`],mappings:{id3v2:{frame:`TXXX`,description:`ITUNESADVISORY`},vorbis:`ITUNESADVISORY`,mp4:`----:com.apple.iTunes:ITUNESADVISORY`}},replayGainTrackGain:{key:`REPLAYGAIN_TRACK_GAIN`,description:`ReplayGain track gain in dB (e.g., '-6.54 dB')`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ReplayGain_Track_Gain`},vorbis:`REPLAYGAIN_TRACK_GAIN`,mp4:`----:com.apple.iTunes:replaygain_track_gain`}},replayGainTrackPeak:{key:`REPLAYGAIN_TRACK_PEAK`,description:`ReplayGain track peak value (0.0-1.0)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ReplayGain_Track_Peak`},vorbis:`REPLAYGAIN_TRACK_PEAK`,mp4:`----:com.apple.iTunes:replaygain_track_peak`}},replayGainAlbumGain:{key:`REPLAYGAIN_ALBUM_GAIN`,description:`ReplayGain album gain in dB`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ReplayGain_Album_Gain`},vorbis:`REPLAYGAIN_ALBUM_GAIN`,mp4:`----:com.apple.iTunes:replaygain_album_gain`}},replayGainAlbumPeak:{key:`REPLAYGAIN_ALBUM_PEAK`,description:`ReplayGain album peak value (0.0-1.0)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`ReplayGain_Album_Peak`},vorbis:`REPLAYGAIN_ALBUM_PEAK`,mp4:`----:com.apple.iTunes:replaygain_album_peak`}},r128TrackGain:{key:`R128_TRACK_GAIN`,description:`EBU R128 track loudness gain (RFC 7845), raw wire value: signed Q7.8 integer (dB x 256, e.g. '-573' = -2.23828125 dB). readTags() converts to a decibel number (see ExtendedTag.r128TrackGain)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`ASF`],mappings:{id3v2:{frame:`TXXX`,description:`R128_TRACK_GAIN`},vorbis:`R128_TRACK_GAIN`,mp4:`----:com.apple.iTunes:R128_TRACK_GAIN`}},r128AlbumGain:{key:`R128_ALBUM_GAIN`,description:`EBU R128 album loudness gain (RFC 7845), raw wire value: signed Q7.8 integer (dB x 256). readTags() converts to a decibel number`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`,`ASF`],mappings:{id3v2:{frame:`TXXX`,description:`R128_ALBUM_GAIN`},vorbis:`R128_ALBUM_GAIN`,mp4:`----:com.apple.iTunes:R128_ALBUM_GAIN`}},acoustidFingerprint:{key:`ACOUSTID_FINGERPRINT`,description:`AcoustID fingerprint (Chromaprint)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`Acoustid Fingerprint`},vorbis:`ACOUSTID_FINGERPRINT`,mp4:`----:com.apple.iTunes:Acoustid Fingerprint`}},acoustidId:{key:`ACOUSTID_ID`,description:`AcoustID UUID`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`Acoustid Id`},vorbis:`ACOUSTID_ID`,mp4:`----:com.apple.iTunes:Acoustid Id`}},appleSoundCheck:{key:`ITUNNORM`,description:`Apple Sound Check normalization data`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`iTunNORM`},vorbis:`ITUNNORM`,mp4:`----:com.apple.iTunes:iTunNORM`}},appleGaplessInfo:{key:`ITUNSMPB`,description:`Apple gapless playback data (encoder delay and padding)`,type:`string`,supportedFormats:[`ID3v2`,`MP4`,`Vorbis`],mappings:{id3v2:{frame:`TXXX`,description:`iTunSMPB`},vorbis:`ITUNSMPB`,mp4:`----:com.apple.iTunes:iTunSMPB`}}}}));function toTagLibKey(key){return _toTagLib[key]??key}function mp4AtomWireKey(atom){return _mp4AtomToWireKey[atom]}function mp4FreeformAtomNames(wireKeys){const names=[];for(const key of wireKeys){const atom=_mp4FreeformAtoms[key];if(atom!==void 0)names.push(atom)}return names}function fromTagLibKey(key){return _fromTagLib[key]??key}function remapKeysFromTagLib(obj){const result={};for(const[key,value]of Object.entries(obj)){const canonical=READ_ALIASES[key];if(canonical!==void 0&&canonical in obj)continue;result[fromTagLibKey(key)]=value}return result}var PROPERTIES,_toTagLib,_fromTagLib,READ_ALIASES,_mp4FreeformAtoms,_mp4AtomToWireKey;var init_properties=__esmMin((()=>{init_additional_properties();init_basic_properties();init_general_extended_properties();init_specialized_properties();PROPERTIES={...BASIC_PROPERTIES,...GENERAL_EXTENDED_PROPERTIES,...SPECIALIZED_PROPERTIES,...ADDITIONAL_PROPERTIES};_toTagLib={};_fromTagLib={};for(const[camelKey,meta]of Object.entries(PROPERTIES)){const wireKey=meta.key;_toTagLib[camelKey]=wireKey;_fromTagLib[wireKey]=camelKey}_toTagLib[`year`]=`DATE`;_toTagLib[`track`]=`TRACKNUMBER`;_fromTagLib[`disc`]=`discNumber`;READ_ALIASES={"ALBUM ARTIST":`ALBUMARTIST`,ALBUM_ARTIST:`ALBUMARTIST`,ORGANIZATION:`LABEL`,PUBLISHER:`LABEL`,UPC:`BARCODE`,EAN:`BARCODE`,GTIN:`BARCODE`,TOTALTRACKS:`TRACKTOTAL`,TOTALDISCS:`DISCTOTAL`,MUSICBRAINZ_ALBUMTYPE:`RELEASETYPE`,"MusicBrainz Album Type":`RELEASETYPE`,MUSICBRAINZ_ALBUMSTATUS:`RELEASESTATUS`,"MusicBrainz Album Status":`RELEASESTATUS`,CONTENTADVISORY:`ITUNESADVISORY`,EXPLICIT:`ITUNESADVISORY`};for(const[alias,canonical]of Object.entries(READ_ALIASES))_fromTagLib[alias]??(_fromTagLib[alias]=_fromTagLib[canonical]);_mp4FreeformAtoms={};for(const meta of Object.values(PROPERTIES)){const{key,mappings}=meta;const atom=mappings?.mp4;if(typeof atom!==`string`||!atom.startsWith(`----:`))continue;const bare=atom.slice(atom.lastIndexOf(`:`)+1);if(bare===bare.toUpperCase())continue;_mp4FreeformAtoms[key]=atom;const readKey=bare.toUpperCase();const camel=_fromTagLib[key];if(camel!==void 0&&_fromTagLib[readKey]===void 0)_fromTagLib[readKey]=camel}_mp4AtomToWireKey={};for(const meta of Object.values(PROPERTIES)){const{key,mappings}=meta;const atom=mappings?.mp4;if(typeof atom!==`string`||atom.startsWith(`----:`))continue;_mp4AtomToWireKey[atom]??(_mp4AtomToWireKey[atom]=key)}}));var MP4_ITEM_NAMES_KEY;var init_mp4_item_names=__esmMin((()=>{MP4_ITEM_NAMES_KEY=`_mp4ItemNames`}));function buildGetters(state,handle){const tag={};for(const field of TAG_GETTER_FIELDS)Object.defineProperty(tag,field,{enumerable:true,configurable:true,get:()=>state.data[field]});Object.defineProperties(tag,{year:{enumerable:true,configurable:true,get:()=>state.data.year},track:{enumerable:true,configurable:true,get:()=>state.data.track},date:{enumerable:true,configurable:true,get:()=>handle.getProperty(`DATE`)||void 0}});return tag}function stageTrackWrite(handle,value){const existing=value>0?handle.getProperty(RAW_TRACK_WIRE_KEY):``;const slash=existing.indexOf(`/`);if(slash!==-1)handle.setProperty(RAW_TRACK_WIRE_KEY,`${value}${existing.slice(slash)}`);else handle.setTagData({track:value})}function stageDateWrite(handle,value){if(value===``)handle.setTagData({year:0});else handle.setProperty(`DATE`,value)}function buildMutableTag(handle){const state={data:handle.getTagData()};const tag=buildGetters(state,handle);const refresh=()=>{state.data=handle.getTagData();return tag};const setBasic=(field,value)=>{handle.setTagData({[field]:value});return refresh()};tag.setTitle=value=>setBasic(`title`,value);tag.setArtist=value=>setBasic(`artist`,value);tag.setAlbum=value=>setBasic(`album`,value);tag.setComment=value=>setBasic(`comment`,value);tag.setGenre=value=>setBasic(`genre`,value);tag.setYear=value=>setBasic(`year`,value);tag.setTrack=value=>{stageTrackWrite(handle,value);return refresh()};tag.setDate=value=>{stageDateWrite(handle,value);return refresh()};return tag}var RAW_TRACK_WIRE_KEY,TAG_GETTER_FIELDS;var init_mutable_tag_impl=__esmMin((()=>{init_properties();RAW_TRACK_WIRE_KEY=toTagLibKey(`trackNumber`);TAG_GETTER_FIELDS=[`title`,`artist`,`album`,`comment`,`genre`]}));function registerAutoDispose(target,handle){registry.register(target,handle,target)}function unregisterAutoDispose(target){registry.unregister(target)}var registry;var init_auto_dispose=__esmMin((()=>{registry=new FinalizationRegistry(handle=>{handle.destroy()})}));function _typeof(o){"@babel/helpers - typeof";return _typeof=`function`==typeof Symbol&&`symbol`==typeof Symbol.iterator?function(o){return typeof o}:function(o){return o&&`function`==typeof Symbol&&o.constructor===Symbol&&o!==Symbol.prototype?`symbol`:typeof o},_typeof(o)}var init_typeof=__esmMin((()=>{}));function toPrimitive(t,r){if(`object`!=_typeof(t)||!t)return t;var e=t[Symbol.toPrimitive];if(void 0!==e){var i=e.call(t,r||`default`);if(`object`!=_typeof(i))return i;throw new TypeError(`@@toPrimitive must return a primitive value.`)}return(`string`===r?String:Number)(t)}var init_toPrimitive=__esmMin((()=>{init_typeof()}));function toPropertyKey(t){var i=toPrimitive(t,`string`);return`symbol`==_typeof(i)?i:i+``}var init_toPropertyKey=__esmMin((()=>{init_typeof();init_toPrimitive()}));function _defineProperty(e,r,t){return(r=toPropertyKey(r))in e?Object.defineProperty(e,r,{value:t,enumerable:!0,configurable:!0,writable:!0}):e[r]=t,e}var init_defineProperty=__esmMin((()=>{init_toPropertyKey()}));var _Symbol$dispose,LYRICS_PROPERTY_KEY,LYRICS_WIRE_KEY,EMPTY_KEY_SET,BaseAudioFileImpl;var init_audio_file_base=__esmMin((()=>{init_mp4_freeform();init_properties();init_errors();init_mp4_item_names();init_mutable_tag_impl();init_auto_dispose();init_defineProperty();;LYRICS_PROPERTY_KEY=`lyrics`;LYRICS_WIRE_KEY=toTagLibKey(LYRICS_PROPERTY_KEY);EMPTY_KEY_SET=/* @__PURE__ */ new Set;_Symbol$dispose=Symbol.dispose;BaseAudioFileImpl=class{constructor(module,fileHandle,sourcePath,originalSource,isPartiallyLoaded=false,partialLoadOptions){this.module=module;_defineProperty(this,`fileHandle`,void 0);_defineProperty(this,`cachedAudioProperties`,null);_defineProperty(this,`sourcePath`,void 0);_defineProperty(this,`originalSource`,void 0);_defineProperty(this,`isPartiallyLoaded`,false);_defineProperty(this,`partialLoadOptions`,void 0);_defineProperty(this,`partialKeysAtLoad`,void 0);this.fileHandle=fileHandle;this.sourcePath=sourcePath;this.originalSource=originalSource;this.isPartiallyLoaded=isPartiallyLoaded;this.partialLoadOptions=partialLoadOptions;this.partialKeysAtLoad=isPartiallyLoaded?new Set(Object.keys(fileHandle.getProperties())):void 0;registerAutoDispose(this,fileHandle)}partialDeletedPropertyKeys(){if(!this.partialKeysAtLoad)return EMPTY_KEY_SET;const current=new Set(Object.keys(this.handle.getProperties()));const deleted=/* @__PURE__ */ new Set;for(const key of this.partialKeysAtLoad)if(key!==LYRICS_WIRE_KEY&&!current.has(key))deleted.add(key);return deleted}get handle(){if(!this.fileHandle)throw new MetadataError(`read`,`File handle has been disposed`);return this.fileHandle}getFormat(){return this.handle.getFormat()}isFormat(format){return this.getFormat()===format}tag(){return buildMutableTag(this.handle)}audioProperties(){this.cachedAudioProperties??(this.cachedAudioProperties=this.handle.getAudioProperties()??null);return this.cachedAudioProperties??void 0}properties(){const remapped=remapKeysFromTagLib(this.handle.getProperties());delete remapped[LYRICS_PROPERTY_KEY];return remapped}setProperties(properties){const translated={};for(const[key,values]of Object.entries(properties))if(values!==void 0){const wireKey=toTagLibKey(fromTagLibKey(key));const emptyTotal=(wireKey===`TRACKTOTAL`||wireKey===`DISCTOTAL`)&&values.every(v=>v===``);if(emptyTotal&&!this.module.isWasi)continue;translated[wireKey]=emptyTotal?[]:values}if(!(LYRICS_WIRE_KEY in translated)){const existing=this.handle.getProperties()[LYRICS_WIRE_KEY];if(existing!==void 0)translated[LYRICS_WIRE_KEY]=existing}const atomNames=mp4FreeformAtomNames(Object.keys(translated));if(atomNames.length>0)translated[MP4_ITEM_NAMES_KEY]=atomNames;this.handle.setProperties(translated)}getProperty(key){const wireKey=toTagLibKey(fromTagLibKey(key));const values=this.handle.getProperties()[wireKey]?.filter(v=>v!==``);if(values!==void 0&&values.length>0)return values;if(!this.isMP4())return void 0;const remapped=this.properties()[key]?.filter(v=>v!==``);return remapped!==void 0&&remapped.length>0?remapped:void 0}setProperty(key,value){const wireKey=toTagLibKey(fromTagLibKey(key));if((wireKey===`TRACKTOTAL`||wireKey===`DISCTOTAL`)&&value===``){this.clearTotal(wireKey);return}const nextValue=this.preserveIntPairTotal(wireKey,value);const atomNames=mp4FreeformAtomNames([wireKey]);if(atomNames.length>0&&this.isMP4()){this.writeMp4FreeformProperty(wireKey,value,atomNames);return}this.handle.setProperty(wireKey,nextValue)}clearTotal(wireKey){const rest={...this.handle.getProperties()};if(this.module.isWasi)rest[wireKey]=[];else delete rest[wireKey];this.handle.setProperties(rest)}preserveIntPairTotal(wireKey,value){if(wireKey!==`TRACKNUMBER`&&wireKey!==`DISCNUMBER`||value===``||value.includes(`/`))return value;const existing=this.handle.getProperty(wireKey);const slash=existing.indexOf(`/`);return slash===-1?value:`${value}${existing.slice(slash)}`}writeMp4FreeformProperty(wireKey,value,atomNames){if(value===``){const prior=this.handle.getMp4ItemRemovals?.()??[];this.handle.setMp4ItemRemovals?.([.../* @__PURE__ */ new Set([...prior,...atomNames])]);if(this.module.isWasi)this.handle.setProperties({...this.handle.getProperties(),[wireKey]:[]});else{const rest={...this.handle.getProperties()};delete rest[wireKey];this.handle.setProperties(rest)}return}this.handle.setProperties({...this.handle.getProperties(),[wireKey]:[value],[MP4_ITEM_NAMES_KEY]:[...atomNames]})}removeProperty(key){this.setProperty(key,``)}isMP4(){return this.handle.isMP4()}getMP4Item(key){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);const wireKey=mp4AtomWireKey(key);const value=wireKey!==void 0?this.handle.getProperty(wireKey):this.handle.getMP4Item(key);return value===``?void 0:value}setMP4Item(key,value){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);const wireKey=mp4AtomWireKey(key);if(wireKey!==void 0){this.handle.setProperty(wireKey,value);return}if(value===``){this.handle.removeMP4Item(key);return}this.handle.setMP4Item(key,value)}removeMP4Item(key){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);this.handle.removeMP4Item(key)}getMP4FreeformItems(){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);if(!this.handle.getMP4FreeformItems)throw new MetadataError(`read`,`MP4 freeform items are unavailable on this backend`);return this.handle.getMP4FreeformItems().map(fromRawFreeformItem)}setMP4FreeformItems(items){if(!this.isMP4())throw new UnsupportedFormatError(this.getFormat(),[`MP4`,`M4A`]);if(!this.handle.setMP4FreeformItems)throw new MetadataError(`write`,`MP4 freeform items are unavailable on this backend`);validateFreeformItems(items);this.handle.setMP4FreeformItems(items.map(toRawFreeformItem))}isValid(){return this.handle.isValid()}dispose(){unregisterAutoDispose(this);if(this.fileHandle){this.fileHandle.destroy();this.fileHandle=null;this.cachedAudioProperties=null}}[_Symbol$dispose](){this.dispose()}}}));function be32(b,offset){return(b[offset]<<24|b[offset+1]<<16|b[offset+2]<<8|b[offset+3])>>>0}function startsWith(bytes,magic,at=0){if(bytes.length<at+magic.length)return false;for(let i=0;i<magic.length;i++)if(bytes[at+i]!==magic.codePointAt(i))return false;return true}function id3v2End(bytes){if(!startsWith(bytes,`ID3`)||bytes.length<10)return void 0;const size=bytes[6]<<21|bytes[7]<<14|bytes[8]<<7|bytes[9];const hasFooter=(bytes[5]&16)!==0;return 10+size+(hasFooter?10:0)}function flacEnd(bytes,limit,start){let offset=start+4;for(;;){if(offset+4>bytes.length)return void 0;const isLast=(bytes[offset]&128)!==0;const length=bytes[offset+1]<<16|bytes[offset+2]<<8|bytes[offset+3];offset+=4+length;if(offset>limit)return offset;if(isLast)return offset}}function flacMarkerOffset(bytes){const at=startsWith(bytes,`ID3`)?id3v2End(bytes):0;if(at===void 0)return void 0;return startsWith(bytes,`fLaC`,at)?at:void 0}function flacAudioStart(bytes){const at=flacMarkerOffset(bytes);if(at===void 0)return void 0;return flacEnd(bytes,bytes.length,at)}function mp4MoovEnd(bytes,limit,start){let offset=start;const readable=Math.min(bytes.length,limit);while(offset+8<=readable){const size=be32(bytes,offset);const type=String.fromCodePoint(bytes[offset+4],bytes[offset+5],bytes[offset+6],bytes[offset+7]);if(size<8)return void 0;if(type===`moov`)return offset+size;offset+=size}}function oggMetadataEnd(bytes,limit,start){let offset=start;let packetsCompleted=0;let first=true;for(;;){if(offset+27>bytes.length||!startsWith(bytes,`OggS`,offset))return;const segmentCount=bytes[offset+26];const tableStart=offset+27;if(tableStart+segmentCount>bytes.length)return void 0;let payload=0;for(let i=0;i<segmentCount;i++){const segment=bytes[tableStart+i];payload+=segment;if(segment<255)packetsCompleted++}if(first){const payloadStart=tableStart+segmentCount;if(payloadStart+5>bytes.length)return void 0;if(bytes[payloadStart]===127&&startsWith(bytes,`FLAC`,payloadStart+1))return;first=false}offset=tableStart+segmentCount+payload;if(packetsCompleted>=2||offset>limit)return offset}}function parseMpegFrameHeader(bytes,at){if(bytes.length<at+4)return void 0;if(bytes[at]!==255||(bytes[at+1]&224)!==224)return void 0;const version=bytes[at+1]>>3&3;const layer=bytes[at+1]>>1&3;if(version===1||layer===0)return void 0;const bitrateIndex=bytes[at+2]>>4&15;const sampleRateIndex=bytes[at+2]>>2&3;if(bitrateIndex===0||bitrateIndex===15||sampleRateIndex===3)return;let sampleRateTable=2;if(version===3)sampleRateTable=0;else if(version===2)sampleRateTable=1;return{mpeg1:version===3,layerIndex:layer^3,bitrateIndex,sampleRateIndex,sampleRateTable}}function mpegFrameLength(bytes,at){const header=parseMpegFrameHeader(bytes,at);if(!header)return 0;const{mpeg1,layerIndex,bitrateIndex,sampleRateIndex,sampleRateTable}=header;const bitrate=MPEG_BITRATES[mpeg1?0:1][layerIndex][bitrateIndex];const sampleRate=MPEG_SAMPLE_RATES[sampleRateTable][sampleRateIndex];let samplesPerFrame;if(layerIndex===2)samplesPerFrame=mpeg1?1152:576;else if(layerIndex===1)samplesPerFrame=1152;else samplesPerFrame=384;let frameLength=Math.floor(samplesPerFrame*bitrate*125/sampleRate);if((bytes[at+2]&2)!==0)frameLength+=layerIndex===0?4:1;return frameLength===0?0:frameLength}function isMpegFrameSync(bytes,at=0){const frameLength=mpegFrameLength(bytes,at);if(frameLength===0)return false;const next=at+frameLength;if(bytes.length<next+4)return false;const mask=4294839296;return((bytes[at]<<24|bytes[at+1]<<16|bytes[at+2]<<8|bytes[at+3])>>>0&mask)>>>0===((bytes[next]<<24|bytes[next+1]<<16|bytes[next+2]<<8|bytes[next+3])>>>0&mask)>>>0}function containerEnd(bytes,at,limit){if(at>=bytes.length)return bytes.length<limit?null:void 0;if(at+8>bytes.length)return void 0;if(startsWith(bytes,`fLaC`,at))return flacEnd(bytes,limit,at);if(startsWith(bytes,`ftyp`,at+4))return mp4MoovEnd(bytes,limit,at);if(startsWith(bytes,`OggS`,at))return oggMetadataEnd(bytes,limit,at);return null}function id3MetadataEnd(header,limit){const tagEnd=id3v2End(header);if(tagEnd===void 0)return void 0;if(tagEnd>limit)return tagEnd;const behind=containerEnd(header,tagEnd,limit);if(behind===void 0)return void 0;return behind??tagEnd}function headerMetadataEnd(header,limit){if(startsWith(header,`ID3`))return id3MetadataEnd(header,limit);const container=containerEnd(header,0,limit);if(container!==null)return container;return isMpegFrameSync(header)?0:void 0}function metadataFitsInHeader(header,limit){const end=headerMetadataEnd(header,limit);if(end===void 0||end>header.length)return false;return end<=limit}function apeFooterSize(tail,at){if(at<0||!startsWith(tail,`APETAGEX`,at))return void 0;return(tail[at+12]|tail[at+13]<<8|tail[at+14]<<16|tail[at+15]<<24)>>>0}function trailerFitsInFooter(tail,footerSize){if(tail.length<Math.min(footerSize,32))return false;for(const offsetFromEnd of[32,160]){const size=apeFooterSize(tail,tail.length-offsetFromEnd);if(size===void 0)continue;const trailing=offsetFromEnd===32?0:128;if(size+32+trailing>footerSize)return false}return true}var MPEG_BITRATES,MPEG_SAMPLE_RATES;var init_metadata_extent=__esmMin((()=>{MPEG_BITRATES=[[[0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,0],[0,32,48,56,64,80,96,112,128,160,192,224,256,320,384,0],[0,32,40,48,56,64,80,96,112,128,160,192,224,256,320,0]],[[0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,0],[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0],[0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,0]]];MPEG_SAMPLE_RATES=[[44100,48e3,32e3],[22050,24e3,16e3],[11025,12e3,8e3]]}));function adtsFrameLength(bytes,at){if(bytes.length<at+7)return 0;if(bytes[at]!==255||(bytes[at+1]&246)!==240)return 0;const length=(bytes[at+3]&3)<<11|bytes[at+4]<<3|bytes[at+5]>>5;return length>=7?length:0}function trailingTagStart(bytes,end=bytes.length){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);let at=Math.max(0,Math.min(end,bytes.length));for(;;){if(at>=128&&text(bytes,at-128,3)===`TAG`){at-=128;continue}if(at>=32&&text(bytes,at-32,8)===`APETAGEX`){const size=view.getUint32(at-32+12,true);const flags=view.getUint32(at-32+20,true);const start=at-size-((flags&2147483648)!==0?32:0);if(start<0||start>=at)return at;at=start;continue}return at}}function firstFrame(bytes){const from=id3v2End(bytes)??0;const limit=Math.min(bytes.length-6,from+MPEG_SCAN_LIMIT);for(let o=from;o<limit;o++){const len=frameLengthAt(bytes,o);if(len>0&&frameLengthAt(bytes,o+len)>0)return o}return-1}function forwardLastFrame(bytes,from,end){let o=from;let start=-1;let length=0;let frames=0;while(o+6<=end){const len=frameLengthAt(bytes,o);if(len===0||o+len>end)break;start=o;length=len;frames++;o+=len}return{start,length,frames}}function walkMpeg(bytes){const from=firstFrame(bytes);if(from<0)return fallback(`no valid first frame`);const last=forwardLastFrame(bytes,from,trailingTagStart(bytes));if(last.start<0)return fallback(`no valid frames`);return{kind:`ranges`,ranges:[{offset:from,length:last.start+last.length-from}],detail:`first=${from} last=${last.start}+${last.length} frames=${last.frames}`}}function flacStreamInfoMd5(bytes){const marker=flacMarkerOffset(bytes);if(marker===void 0)return void 0;const header=marker+4;if(header+4>bytes.length)return void 0;if((bytes[header]&127)!==0)return void 0;if((bytes[header+1]<<16|bytes[header+2]<<8|bytes[header+3])<34)return void 0;const payload=header+4;if(payload+34>bytes.length)return void 0;let hex=``;for(const byte of bytes.subarray(payload+18,payload+34))hex+=byte.toString(16).padStart(2,`0`);return hex}function walkFlac(bytes){const start=flacAudioStart(bytes);if(start===void 0)return fallback(`no fLaC marker`);const end=trailingTagStart(bytes);if(end<=start)return fallback(`no audio bytes`);return{kind:`ranges`,ranges:[{offset:start,length:end-start}],detail:`audioStart=${start} end=${end}`}}function atomLength(bytes,view,o){const size=view.getUint32(o,false);if(size===0)return{length:bytes.length-o,headerSize:8};if(size===1){if(o+16>bytes.length)return void 0;const big=view.getBigUint64(o+8,false);if(big>BigInt(Number.MAX_SAFE_INTEGER))return void 0;return{length:Number(big),headerSize:16}}return{length:size,headerSize:8}}function walkMp4(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);const ranges=[];let o=0;while(o+8<=bytes.length){const type=text(bytes,o+4,4);const atom=atomLength(bytes,view,o);if(atom===void 0)return fallback(`malformed ${type} size`);if(atom.length<atom.headerSize)return fallback(`malformed ${type} size`);if(o+atom.length>bytes.length)return fallback(`oversized ${type}`);if(type===`mdat`&&atom.length>atom.headerSize)ranges.push({offset:o+atom.headerSize,length:atom.length-atom.headerSize});o+=atom.length}if(o!==bytes.length)return fallback(`trailing bytes after the last atom`);if(ranges.length===0)return fallback(`no non-empty mdat`);return{kind:`ranges`,ranges,detail:`${ranges.length} mdat(s)`}}function walkWav(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);if(text(bytes,0,4)!==`RIFF`)return fallback(`not RIFF`);if(text(bytes,8,4)!==`WAVE`)return fallback(`not WAVE`);const ranges=[];let o=12;while(o+8<=bytes.length){const id=text(bytes,o,4);const size=view.getUint32(o+4,true);const dataStart=o+8;if(dataStart+size>bytes.length)return fallback(`truncated ${id}`);if(id===`data`&&size>0)ranges.push({offset:dataStart,length:size});o=dataStart+size+size%2}if(ranges.length===0)return fallback(`no data chunk`);return{kind:`ranges`,ranges,detail:`${ranges.length} data chunk(s)`}}function mediaRanges(format,bytes){const walked=(()=>{switch(format.toUpperCase()){case`MP3`:case`AAC`:return walkMpeg(bytes);case`FLAC`:return walkFlac(bytes);case`MP4`:case`M4A`:return walkMp4(bytes);case`WAV`:return walkWav(bytes);default:return{kind:`fallback`,ranges:[],detail:`format not covered`}}})();if(walked.kind===`fallback`)return{kind:`fallback`,ranges:[{offset:0,length:bytes.length}],detail:`${walked.detail} → whole file`};return walked}var decoder,text,fallback,frameLengthAt,MPEG_SCAN_LIMIT;var init_media_ranges=__esmMin((()=>{init_metadata_extent();decoder=new TextDecoder;text=(b,o,n)=>decoder.decode(b.subarray(o,o+n));fallback=detail=>({kind:`fallback`,ranges:[],detail});frameLengthAt=(bytes,at)=>mpegFrameLength(bytes,at)||adtsFrameLength(bytes,at);MPEG_SCAN_LIMIT=65536}));async function fileBytes(source,io){if(source.path)return await io.readFile(source.path);if(source.blob)return new Uint8Array(await source.blob.arrayBuffer());if(!source.partiallyLoaded&&source.bytes.length>0)return source.bytes;throw new MetadataError(`read`,`the handle holds no file bytes and has no readable source; a partial handle that has been saved drops its source — checksum the saved path instead`)}function joinRanges(bytes,ranges){const total=ranges.reduce((n,r)=>n+r.length,0);const overrun=ranges.find(r=>r.offset+r.length>bytes.length);if(overrun||total>bytes.length)throw new MetadataError(`read`,`range walk overran the buffer (${overrun?`range ${overrun.offset}+${overrun.length}`:`${total} bytes`} past the ${bytes.length}-byte buffer)`);if(ranges.length===1){const only=ranges[0];const view=bytes.subarray(only.offset,only.offset+only.length);return view.buffer instanceof ArrayBuffer?view:new Uint8Array(view)}const out=new Uint8Array(total);let at=0;for(const r of ranges){out.set(bytes.subarray(r.offset,r.offset+r.length),at);at+=r.length}return out}async function pcmChecksum(source,format,io){if(format.toUpperCase()!==`FLAC`)throw new UnsupportedFormatError(format,[`FLAC`],{operation:`media checksum (basis: pcm)`});let windowed;if(source.bytes.length>0)windowed=source.bytes;else if(source.path&&io.readPartial)windowed=await io.readPartial(source.path,STREAMINFO_WINDOW,0);let md5=windowed===void 0?void 0:flacStreamInfoMd5(windowed);if(md5===void 0&&windowed!==source.bytes)md5=flacStreamInfoMd5(await fileBytes(source,io));if(md5===void 0)throw new MetadataError(`read`,`STREAMINFO digest unavailable`);return{source:`flac-streaminfo-md5`,algorithm:`md5`,hex:md5,bytesHashed:16}}async function mediaChecksum(source,format,io,options={}){if(options.basis===`pcm`)return pcmChecksum(source,format,io);const bytes=await fileBytes(source,io);const walk=mediaRanges(format,bytes);const payload=joinRanges(bytes,walk.ranges);const digest=new Uint8Array(await crypto.subtle.digest(`SHA-256`,payload));let hex=``;for(const byte of digest)hex+=byte.toString(16).padStart(2,`0`);return{source:walk.kind===`ranges`?`audio-payload`:`file`,algorithm:`sha256`,hex,bytesHashed:payload.length}}var STREAMINFO_WINDOW;var init_audio_file_checksum=__esmMin((()=>{init_media_ranges();init_errors();STREAMINFO_WINDOW=65536}));async function readFileData(file){if(file instanceof Uint8Array)return file;if(file instanceof ArrayBuffer)return new Uint8Array(file);if(typeof File!==`undefined`&&file instanceof File)return new Uint8Array(await file.arrayBuffer());if(typeof file===`string`)try{return await getPlatformIO().readFile(file)}catch(error){if(error instanceof EnvironmentError)throw error;throw new FileOperationError(`read`,error.message,file)}const inputType=Object.prototype.toString.call(file);throw new FileOperationError(`read`,`Invalid file input type: ${inputType}. Expected string path, Uint8Array, ArrayBuffer, or File object.`)}async function getFileSize(path){try{return(await getPlatformIO().stat(path)).size}catch(error){if(error instanceof EnvironmentError)throw error;throw new FileOperationError(`stat`,error.message,path)}}async function readPartialFileData(path,headerSize,footerSize){const io=getPlatformIO();if(!io.readPartial)throw new EnvironmentError(`current runtime`,`does not support partial file reading`,`filesystem access with seek support`);try{return await io.readPartial(path,headerSize,footerSize)}catch(error){if(error instanceof EnvironmentError)throw error;throw new FileOperationError(`read`,error.message,path)}}var init_file=__esmMin((()=>{init_errors();init__taglib_platform_io_stub()}));function isValidBitrateMode(value){return value===`CBR`||value===`VBR`||value===`ABR`}function wrapEmbindHandle(raw){const stagedId3v2Frames={};let destroyed=false;const overrides={getTagData(){const tw=raw.getTag();return{title:tw.title(),artist:tw.artist(),album:tw.album(),comment:tw.comment(),genre:tw.genre(),year:tw.year(),track:tw.track()}},setTagData(data){const tw=raw.getTag();if(data.title!==void 0)tw.setTitle(data.title);if(data.artist!==void 0)tw.setArtist(data.artist);if(data.album!==void 0)tw.setAlbum(data.album);if(data.comment!==void 0)tw.setComment(data.comment);if(data.genre!==void 0)tw.setGenre(data.genre);if(data.year!==void 0)tw.setYear(data.year);if(data.track!==void 0)tw.setTrack(data.track)},getBextData(){const v=raw.getBextData();if(v===void 0||v===null)return void 0;const u8=v instanceof Uint8Array?v:new Uint8Array(v);return u8.length>0?u8:void 0},setBextData(data){raw.setBextData(data??null)},getIxml(){const v=raw.getIxml();return typeof v===`string`&&v.length>0?v:void 0},setIxml(data){raw.setIxml(data??null)},getLyrics(){return(raw.getProperties()[`LYRICS`]??[]).map(text=>({text,description:``,language:``}))},setLyrics(lyrics){const handle=raw;const props=handle.getProperties();if(lyrics.length>0)props[`LYRICS`]=lyrics.map(l=>l.text);else delete props[`LYRICS`];handle.setProperties(props)},setId3v2Frames(id,data){stagedId3v2Frames[id]=data.map(d=>new Uint8Array(d));raw.setId3v2Frames(id,data)},removeId3v2Frames(id){stagedId3v2Frames[id]=[];raw.removeId3v2Frames(id)},getStagedId3v2Frames(){return Object.keys(stagedId3v2Frames).length>0?{...stagedId3v2Frames}:void 0},hasId3Tags(){const v=raw.hasId3Tags();if(!v||typeof v!==`object`)return{v1:false,v2:false};const o=v;return{v1:o.v1===true,v2:o.v2===true}},stripId3Tags(opts){raw.stripId3Tags(opts)},destroy(){if(destroyed)return;destroyed=true;raw.destroy()},get destroyed(){return destroyed},setMp4ItemRemovals(removals){const handle=raw;for(const name of removals)handle.removeMP4Item(name)},getMP4FreeformItems(){return raw.getMP4FreeformItems()},setMP4FreeformItems(items){raw.setMP4FreeformItems(items)},getAudioProperties(){const pw=raw.getAudioProperties();if(!pw)return null;const containerFormat=pw.containerFormat()||`unknown`;const codec=pw.codec()||`unknown`;const mpegVersion=pw.mpegVersion();const formatVersion=pw.formatVersion();const bitrateMode=pw.bitrateMode();const isEncrypted=pw.isEncrypted();return{duration:pw.lengthInSeconds(),durationMs:pw.lengthInMilliseconds(),bitrate:pw.bitrate(),sampleRate:pw.sampleRate(),channels:pw.channels(),bitsPerSample:pw.bitsPerSample(),codec,containerFormat,isLossless:pw.isLossless(),...mpegVersion>0?{mpegVersion,mpegLayer:pw.mpegLayer()}:{},...isEncrypted||containerFormat===`MP4`||containerFormat===`ASF`?{isEncrypted}:{},...formatVersion>0?{formatVersion}:{},...isValidBitrateMode(bitrateMode)?{bitrateMode}:{},...containerFormat===`OGG`&&codec===`Opus`?{outputGainDb:pw.outputGainDb()}:{}}}};return new Proxy(raw,{get(target,prop,receiver){if(prop in overrides)return overrides[prop];const value=Reflect.get(target,prop,receiver);return typeof value===`function`?value.bind(target):value}})}var init_embind_adapter=__esmMin((()=>{}));function chapterStyle(chapters){const s=chapters[0]?.source;return s===`nero`||s===`both`?s:`quicktime`}function freeformSignature(items){return items.map(item=>`${item.mean}\u0000${item.name}\u0000${item.type}\u0000`+Array.from(item.value).join(`,`)).sort((a,b)=>a.localeCompare(b)).join(`
2
+ `)}function copyExtraState(target,source,sourceComplete){for(const field of EXTRA_FIELDS)field.copy(target,source,sourceComplete)}var EXTRA_FIELDS;var init_extra_state_registry=__esmMin((()=>{EXTRA_FIELDS=[{name:`pictures`,copy(target,source,complete){const v=source.getPictures();if(complete||v.length>0)target.setPictures(v)}},{name:`ratings`,copy(target,source,complete){const v=source.getRatings();if(complete||v.length>0)target.setRatings(v)}},{name:`lyrics`,copy(target,source,complete){const v=source.getLyrics();if(complete||v.length>0)target.setLyrics(v)}},{name:`chapters`,copy(target,source,complete){const v=source.getChapters();if(complete||v.length>0)target.setChapters(v,chapterStyle(v))}},{name:`bextData`,copy(target,source,complete){const v=source.getBextData();if(v!==void 0)target.setBextData(v);else if(complete)target.setBextData(null)}},{name:`ixml`,copy(target,source,complete){const v=source.getIxml();if(v!==void 0)target.setIxml(v);else if(complete)target.setIxml(null)}},{name:`_mp4Freeform`,copy(target,source,complete){const items=source.getMP4FreeformItems?.();if(items===void 0)return;if(!complete&&items.length===0)return;const targetItems=target.getMP4FreeformItems?.()??[];if(freeformSignature(items)===freeformSignature(targetItems))return;target.setMP4FreeformItems?.(items)}},{name:`_mp4ItemRemovals`,copy(target,source,complete){const v=source.getMp4ItemRemovals?.();if(complete||v!==void 0&&v.length>0)target.setMp4ItemRemovals?.(v??[])}},{name:`id3v2Frames`,copy(target,source){const staged=source.getStagedId3v2Frames?.();if(!staged)return;for(const[id,bodies]of Object.entries(staged))target.setId3v2Frames(id,bodies)}}]}));function copyEditedState(target,source,sourceComplete,deletedKeys){target.setTagData(source.getTagData());const merged=sourceComplete?source.getProperties():{...target.getProperties(),...source.getProperties()};for(const key of deletedKeys)delete merged[key];const atomNames=mp4FreeformAtomNames(Object.keys(merged));if(atomNames.length>0)merged[MP4_ITEM_NAMES_KEY]=atomNames;target.setProperties(merged);copyExtraState(target,source,sourceComplete)}async function saveViaFreshHandle(module,editing,source,targetPath,sourceComplete,deletedKeys=/* @__PURE__ */ new Set){const rawFullHandle=module.createFileHandle();const fullFileHandle=module.isWasi?rawFullHandle:wrapEmbindHandle(rawFullHandle);try{{const data=await readFileData(source);if(!fullFileHandle.loadFromBuffer(data))throw new InvalidFormatError(`Failed to load full audio file for saving`)}copyEditedState(fullFileHandle,editing,sourceComplete,deletedKeys);if(!fullFileHandle.save())throw new FileOperationError(`save`,`Failed to save changes to full file`);await writeFileData(targetPath,fullFileHandle.getBuffer())}finally{fullFileHandle.destroy()}}var init_save_reconstruct=__esmMin((()=>{init_errors();init_file();init_write();init_embind_adapter();init_extra_state_registry();init_properties();init_mp4_item_names()}));function sortChapters(list){return[...list].sort((a,b)=>a.startTimeMs-b.startTimeMs)}function inferEndTimeMs(sorted,index,trackEndMs){const own=sorted[index].endTimeMs;if(own!==void 0)return own;const next=sorted[index+1];return next?next.startTimeMs:trackEndMs}function readFileSync(path){if(isDeno())return Deno.readFileSync(path);const fs=getNodeFsSync();if(fs)return new Uint8Array(fs.readFileSync(path));throw new FileOperationError(`read`,`node:fs is unavailable in this runtime: cannot read file data from disk`,path)}var AudioFileImpl;var init_audio_file_impl=__esmMin((()=>{init_types();init_audio_file_bwf();init_id3v2_frames();init_errors();init_write();init__taglib_node_fs_stub();init_rating();init_detector();init_audio_file_base();init_audio_file_checksum();init__taglib_platform_io_stub();init_save_reconstruct();init_defineProperty();AudioFileImpl=class extends BaseAudioFileImpl{constructor(module,fileHandle,sourcePath,originalSource,isPartiallyLoaded=false,partialLoadOptions){super(module,fileHandle,sourcePath,originalSource,isPartiallyLoaded,partialLoadOptions);_defineProperty(this,`pathModeBuffer`,null);_defineProperty(this,`partiallyLoadedAtConstruction`,void 0);this.partiallyLoadedAtConstruction=isPartiallyLoaded}save(){if(this.isPartiallyLoaded&&this.originalSource)throw new FileOperationError(`save`,`Cannot save partially loaded file directly. Use saveToFile() instead`);this.cachedAudioProperties=null;this.pathModeBuffer=null;return this.handle.save()}getFileBuffer(){const buffer=this.handle.getBuffer();if(buffer.length>0)return buffer;if(this.pathModeBuffer)return this.pathModeBuffer;if(this.sourcePath)try{this.pathModeBuffer=readFileSync(this.sourcePath);return this.pathModeBuffer}catch(error){if(error instanceof FileOperationError)throw error;throw new FileOperationError(`read`,`Cannot return file data: ${errorMessage(error)}`,this.sourcePath,{cause:error})}throw new FileOperationError(`read`,`No file data available: in-memory buffer is empty and no source path is set`)}mediaChecksum(options){return mediaChecksum({bytes:this.handle.getBuffer(),...this.sourcePath!==void 0?{path:this.sourcePath}:{},...this.originalSource instanceof Blob?{blob:this.originalSource}:{},partiallyLoaded:this.partiallyLoadedAtConstruction},this.getFormat(),getPlatformIO(),options)}async saveToFile(path){const targetPath=path??this.sourcePath;if(!targetPath)throw new FileOperationError(`save`,`No file path available. Provide a path or open the file from a path`);if(this.isPartiallyLoaded&&this.originalSource){await saveViaFreshHandle(this.module,this.handle,this.originalSource,targetPath,false,this.partialDeletedPropertyKeys());this.isPartiallyLoaded=false;this.originalSource=void 0}else if(this.module.isWasi&&this.sourcePath&&targetPath!==this.sourcePath)await saveViaFreshHandle(this.module,this.handle,this.sourcePath,targetPath,true);else{if(!this.save())throw new FileOperationError(`save`,`Failed to save changes to in-memory buffer`);const buffer=this.handle.getBuffer();if(buffer.length>0)await writeFileData(targetPath,buffer)}this.pathModeBuffer=null}getPictures(){return this.handle.getPictures().map(pic=>({mimeType:pic.mimeType,data:pic.data,type:PICTURE_TYPE_NAMES[pic.type]??`Other`,...pic.description!==void 0?{description:pic.description}:{}}))}setPictures(pictures){this.handle.setPictures(pictures.map(pic=>({mimeType:pic.mimeType,data:pic.data,type:PICTURE_TYPE_VALUES[pic.type]??0,description:pic.description??``})))}addPicture(picture){this.handle.addPicture({mimeType:picture.mimeType,data:picture.data,type:PICTURE_TYPE_VALUES[picture.type]??0,description:picture.description??``})}removePictures(){this.handle.removePictures()}getChapters(){const sorted=sortChapters(this.handle.getChapters());const trackEndMs=this.audioProperties()?.durationMs;return sorted.map((c,i)=>{const endTimeMs=inferEndTimeMs(sorted,i,trackEndMs);return{startTimeMs:c.startTimeMs,...endTimeMs!==void 0?{endTimeMs}:{},...c.title?{title:c.title}:{},...c.id?{id:c.id}:{},...c.source!==void 0?{source:c.source}:{}}})}setChapters(chapters,options){const fmt=this.getFormat();if(fmt!==`MP3`&&fmt!==`AAC`&&fmt!==`MP4`)throw new UnsupportedFormatError(fmt,[`MP3`,`AAC`,`MP4`],{operation:`setChapters`});const sorted=sortChapters(chapters);const trackEndMs=this.audioProperties()?.durationMs;const style=options?.mp4ChapterStyle??`quicktime`;const source=fmt===`MP4`?style:`id3`;const raw=sorted.map((c,i)=>({...c.id!==void 0?{id:c.id}:{},startTimeMs:c.startTimeMs,endTimeMs:inferEndTimeMs(sorted,i,trackEndMs)??c.startTimeMs,...c.title!==void 0?{title:c.title}:{},source}));this.handle.setChapters(raw,style)}getBext(){return getBext(this.handle)}setBext(bext){setBext(this.handle,this.getFormat(),bext)}getBextData(){return getBextData(this.handle)}setBextData(data){setBextData(this.handle,this.getFormat(),data)}getIxml(){return getIxml(this.handle)}setIxml(data){setIxml(this.handle,this.getFormat(),data)}getRatings(){return this.handle.getRatings().map(r=>({rating:r.rating,...r.email!==void 0&&r.email!==``?{email:r.email}:{},...r.counter!==0?{counter:r.counter}:{}}))}setRatings(ratings){this.handle.setRatings(ratings.map(r=>({rating:r.rating,email:r.email??``,counter:r.counter??0})))}getLyrics(){return this.handle.getLyrics().map(l=>{const out={text:l.text};if(l.description)out.description=l.description;if(l.language)out.language=l.language;return out})}setLyrics(lyrics){this.handle.setLyrics(lyrics.map(l=>({text:l.text,description:l.description??``,language:l.language??``})))}getRating(){const ratings=this.getRatings();return ratings.length>0?normalized(ratings[0].rating):void 0}setRating(rating,email){this.setRatings([{rating,...email!==void 0?{email}:{},counter:0}])}getId3v2Frames(id){assertMp3(this.getFormat());if(id!==void 0)assertFrameId(id,`read`);return this.handle.getId3v2Frames(id??``).map(toPublicFrame)}setId3v2Frames(id,data){assertMp3(this.getFormat());assertFrameId(id,`write`);assertFrameBodies(id,data);this.handle.setId3v2Frames(id,data)}removeId3v2Frames(id){assertMp3(this.getFormat());assertFrameId(id,`write`);this.handle.removeId3v2Frames(id)}hasId3Tags(){return this.handle.hasId3Tags()}stripId3Tags(opts){this.handle.stripId3Tags({v1:opts?.v1??true,v2:opts?.v2??true})}}}));async function loadFull(input){return{data:await readFileData(input),isPartiallyLoaded:false}}async function loadPartialFile(input,opts){const headerSize=Math.min(opts.maxHeaderSize,input.size);const footerSize=Math.min(opts.maxFooterSize,input.size);if(input.size<=headerSize+footerSize)return loadFull(input);const header=new Uint8Array(await input.slice(0,headerSize).arrayBuffer());if(!metadataFitsInHeader(header,headerSize))return loadFull(input);const footerStart=Math.max(0,input.size-footerSize);const footer=new Uint8Array(await input.slice(footerStart).arrayBuffer());if(!trailerFitsInFooter(footer,footerSize))return loadFull(input);const combined=new Uint8Array(header.byteLength+footer.byteLength);combined.set(header,0);combined.set(footer,header.byteLength);return{data:combined,isPartiallyLoaded:true}}async function loadPartialPath(input,opts){if(await getFileSize(input)>opts.maxHeaderSize+opts.maxFooterSize){const data=await readPartialFileData(input,opts.maxHeaderSize,opts.maxFooterSize);if(metadataFitsInHeader(data,opts.maxHeaderSize)&&trailerFitsInFooter(data,opts.maxFooterSize))return{data,isPartiallyLoaded:true}}return loadFull(input)}async function loadAudioData(input,opts){if(!opts.partial)return loadFull(input);if(typeof File!==`undefined`&&input instanceof File)return loadPartialFile(input,opts);if(typeof input===`string`)return loadPartialPath(input,opts);return loadFull(input)}var init_load_audio_data=__esmMin((()=>{init_file();init_metadata_extent()}));function parseLeadingInt(raw){const parsed=Number.parseInt(raw,10);return Number.isNaN(parsed)?void 0:parsed}var MIRROR_FIELDS,DATE_MIRROR,TRACK_MIRROR;var init_mirror_fields=__esmMin((()=>{MIRROR_FIELDS=[{raw:`date`,numeric:`year`},{raw:`trackNumber`,numeric:`track`}];DATE_MIRROR=MIRROR_FIELDS[0];TRACK_MIRROR=MIRROR_FIELDS[1]}));function attachStructuredFields(audioFile,tag){const pictures=audioFile.getPictures();if(pictures.length>0)tag.pictures=pictures;const ratings=audioFile.getRatings();if(ratings.length>0)tag.ratings=ratings;const lyrics=audioFile.getLyrics();if(lyrics.length>0)tag.lyrics=lyrics;const chapters=audioFile.getChapters();if(chapters.length>0)tag.chapters=chapters;const bext=audioFile.getBext();if(bext!==void 0)tag.bext=bext;const bextData=audioFile.getBextData();if(bextData!==void 0)tag.bextData=bextData;const ixml=audioFile.getIxml();if(ixml!==void 0)tag.ixml=ixml}function attachExtraProperties(props,tag,includeProperties){if(includeProperties===void 0||includeProperties.length===0)return;const extraProperties={};for(const wireKey of includeProperties){const values=props[fromTagLibKey(wireKey)]?.filter(v=>v!==``);if(values!==void 0&&values.length>0)extraProperties[wireKey]=values}if(Object.keys(extraProperties).length>0)tag.extraProperties=extraProperties}function readExtendedTag(audioFile,includeProperties){const props=audioFile.properties();const tag=mapPropertiesToExtendedTag(props);attachStructuredFields(audioFile,tag);attachExtraProperties(props,tag,includeProperties);return tag}function mapPropertiesToExtendedTag(props){const tag={};for(const[propKey,tagField]of Object.entries(BASIC_PROPERTY_KEYS)){const values=props[propKey];if(!values||values.length===0)continue;if(tagField===`year`||tagField===`track`){const num=parseLeadingInt(values[0]);if(num!==void 0)tag[tagField]=num;if(propKey===`date`)tag.date=values.length===1?values[0]:values;if(propKey===`trackNumber`)tag.trackNumber=values.length===1?values[0]:values}else tag[tagField]=values}for(const[propKey,totalField]of[[`trackNumber`,`totalTracks`],[`discNumber`,`totalDiscs`]]){if(tag[totalField]!==void 0)continue;const raw=props[propKey]?.[0];const slash=raw?.indexOf(`/`)??-1;if(raw===void 0||slash===-1)continue;const total=parseLeadingInt(raw.slice(slash+1));if(total!==void 0)tag[totalField]=total}if(tag.date===void 0){const yearValues=props[`YEAR`];if(yearValues!==void 0&&yearValues.length>0){const y=parseLeadingInt(yearValues[0]);if(y!==void 0)tag.year=y;tag.date=yearValues.length===1?yearValues[0]:yearValues}}for(const[key,values]of Object.entries(props)){if(BASIC_PROPERTY_KEYS[key])continue;if(key===`YEAR`)continue;if(!values||values.length===0)continue;const camelKey=fromTagLibKey(key);if(NUMERIC_FIELDS.has(camelKey)){const num=parseLeadingInt(values[0]);if(num!==void 0)tag[camelKey]=num}else if(camelKey===`compilation`)tag[camelKey]=values[0]===`1`||values[0]===`true`;else if(camelKey===`itunesAdvisory`){tag[camelKey]=values;if(values[0]===`1`)tag.advisory=`explicit`;else if(values[0]===`2`)tag.advisory=`clean`;else if(values[0]===`0`)tag.advisory=`unspecified`}else if(camelKey===`r128TrackGain`||camelKey===`r128AlbumGain`){const raw=parseLeadingInt(values[0]);if(raw!==void 0)tag[camelKey]=raw/256}else tag[camelKey]=values}return tag}function mergeTagUpdatesInto(currentProps,tags){const newProps=normalizeTagInput(tags);reconcilePairFields(currentProps,newProps,tags);if(newProps.date!==void 0||newProps.year!==void 0)currentProps.YEAR=[];return{...currentProps,...newProps}}function mergeTagUpdates(file,tags){file.setProperties(mergeTagUpdatesInto(file.properties(),tags))}function reconcilePairFields(currentProps,newProps,input){for(const[rawKey,totalKey,numericKey]of[[`trackNumber`,`totalTracks`,`track`],[`discNumber`,`totalDiscs`,`discNumber`]]){const incoming=newProps[rawKey]?.[0];if(incoming?.includes(`/`)){newProps[totalKey]=[];continue}if(!(input[numericKey]!==void 0&&input[rawKey]===void 0)||incoming===void 0)continue;const existing=currentProps[rawKey]?.[0];const slash=existing?.indexOf(`/`)??-1;if(existing!==void 0&&slash!==-1)newProps[rawKey]=[`${incoming}${existing.slice(slash)}`]}}function normalizeTagInput(input){const props={};for(const field of[`title`,`artist`,`album`,`comment`,`genre`]){const val=input[field];if(val===void 0)continue;props[field]=Array.isArray(val)?val:[val]}if(input.year!==void 0)props.date=[String(input.year)];if(input.date!==void 0)props.date=Array.isArray(input.date)?input.date:[input.date];if(input.track!==void 0)props.trackNumber=[String(input.track)];if(input.trackNumber!==void 0)props.trackNumber=Array.isArray(input.trackNumber)?input.trackNumber:[input.trackNumber];for(const[field,val]of Object.entries(input)){if(BASIC_FIELDS.has(field)||val===void 0)continue;if(field===`extraProperties`)continue;if(field===`compilation`)props[field]=[val?`1`:`0`];else if(field===`advisory`){if(val===`explicit`)props.itunesAdvisory=[`1`];else if(val===`clean`)props.itunesAdvisory=[`2`];else if(val===`unspecified`)props.itunesAdvisory=[]}else if(field===`bpm`)props[field]=[String(Math.trunc(val))];else if(NUMERIC_FIELDS.has(field))props[field]=[String(val)];else if(field===`r128TrackGain`||field===`r128AlbumGain`)props[field]=Array.isArray(val)?val:[String(Math.round(val*256))];else if(typeof val===`string`)props[field]=[val];else if(Array.isArray(val))props[field]=val}for(const[rawField,totalField]of[[`trackNumber`,`totalTracks`],[`discNumber`,`totalDiscs`]])if(props[rawField]?.[0]?.includes(`/`))delete props[totalField];return props}var BASIC_PROPERTY_KEYS,BASIC_FIELDS,NUMERIC_FIELDS;var init_tag_mapping=__esmMin((()=>{init_properties();init_mirror_fields();BASIC_PROPERTY_KEYS={title:`title`,artist:`artist`,album:`album`,comment:`comment`,genre:`genre`,date:`year`,trackNumber:`track`};BASIC_FIELDS=/* @__PURE__ */ new Set([`title`,`artist`,`album`,`comment`,`genre`,`year`,`date`,`track`,`trackNumber`]);NUMERIC_FIELDS=/* @__PURE__ */ new Set([`year`,`track`,`discNumber`,`totalTracks`,`totalDiscs`,`bpm`])}));var VERSION;var init_version=__esmMin((()=>{VERSION=`2.5.0`}));var module_loader_browser_exports=/* @__PURE__ */ __exportAll({loadTagLibModule:()=>loadTagLibModule});async function loadTagLibModule(options){let createTagLibModule;try{createTagLibModule=(await import(`./taglib-wrapper.js`)).default}catch{try{createTagLibModule=(await import(`./taglib-wrapper.js`)).default}catch{throw new TagLibInitializationError(`Could not load taglib-wrapper.js. Ensure it is co-located with the browser bundle.`)}}const moduleConfig={};if(options?.wasmBinary)moduleConfig.wasmBinary=options.wasmBinary;if(options?.wasmUrl)moduleConfig.locateFile=path=>{if(path.endsWith(`.wasm`))return options.wasmUrl;return path};else if(!options?.wasmBinary){const wasmUrl=new URL(`./taglib-web.wasm`,import.meta.url);moduleConfig.locateFile=path=>path.endsWith(`.wasm`)?wasmUrl.href:path}return await createTagLibModule(moduleConfig)}var init_module_loader_browser=__esmMin((()=>{init_classes()}));function trimTrailingSeparators(p){let end=p.length;while(end>0){const c=p.charAt(end-1);if(c!==`/`&&c!==`\\`)break;end--}return p.slice(0,end)}function toWasiPath(osPath){if(osPath.startsWith(`\\\\`)||osPath.startsWith(`//`))throw new FileOperationError(`read`,`UNC paths are not supported. Path: ${osPath}`);let p=osPath;if(!p.startsWith(`/`)&&!/^[A-Za-z]:/.test(p)){const g=globalThis;const cwd=isDeno()?Deno.cwd():g.process?.cwd?.();if(cwd)p=trimTrailingSeparators(cwd)+`/`+p}p=p.replaceAll(`\\`,`/`);const driveMatch=/^([A-Za-z]):\//.exec(p);if(driveMatch)p=`/${driveMatch[1].toUpperCase()}${p.slice(2)}`;p=p.replaceAll(`/./`,`/`).replace(/\/+/g,`/`);if(!p.startsWith(`/`))p=`/`+p;return p}function createTagLib(module){return Promise.resolve(new TagLib(module))}var TagLib;var init_taglib_class=__esmMin((()=>{init_audio_formats();init_errors();init_detector();init_audio_file_impl();init_load_audio_data();init_tag_mapping();init_version();init_embind_adapter();init_defineProperty();TagLib=class TagLib{constructor(module){_defineProperty(this,`module`,void 0);this.module=module}static async initialize(options){const{loadTagLibModule}=await Promise.resolve().then(()=>(init_module_loader_browser(),module_loader_browser_exports));const module=await loadTagLibModule(options);return new TagLib(module)}async open(input,options){if(!this.module.createFileHandle)throw new TagLibInitializationError(`TagLib module not properly initialized: createFileHandle not found. Make sure the module is fully loaded before calling open.`);const actualInput=isNamedAudioInput(input)?input.data:input;const sourcePath=typeof actualInput===`string`?actualInput:void 0;if(typeof actualInput===`string`&&this.module.isWasi){const wasiPath=toWasiPath(actualInput);if(this.module.loadAudioPath){const fileHandle=await this.module.loadAudioPath(wasiPath,actualInput);return new AudioFileImpl(this.module,fileHandle,sourcePath,actualInput,false)}}const opts={partial:true,maxHeaderSize:1048576,maxFooterSize:131072,...options};const{data:audioData,isPartiallyLoaded}=await loadAudioData(actualInput,opts);const uint8Array=actualInput instanceof Uint8Array&&audioData.buffer===actualInput.buffer?new Uint8Array(audioData.buffer.slice(audioData.byteOffset,audioData.byteOffset+audioData.byteLength)):audioData;const rawHandle=this.module.createFileHandle();const fileHandle=this.module.isWasi?rawHandle:wrapEmbindHandle(rawHandle);try{if(!fileHandle.loadFromBuffer(uint8Array))throw new InvalidFormatError(`Failed to load audio file. File may be corrupted or in an unsupported format`,uint8Array.byteLength);return new AudioFileImpl(this.module,fileHandle,sourcePath,actualInput,isPartiallyLoaded,opts)}catch(error){if(typeof fileHandle.destroy===`function`)fileHandle.destroy();throw error}}async edit(input,fn){const file=await this.open(input);try{await fn(file);if(typeof input===`string`)await file.saveToFile();else{file.save();return file.getFileBuffer()}}finally{file.dispose()}}async updateFile(path,tags){const file=await this.open(path);try{mergeTagUpdates(file,tags);await file.saveToFile()}finally{file.dispose()}}async copyWithTags(sourcePath,destPath,tags){const file=await this.open(sourcePath);try{mergeTagUpdates(file,tags);await file.saveToFile(destPath)}finally{file.dispose()}}version(){return`${VERSION} (TagLib ${this.taglibVersion()})`}taglibVersion(){if(this.module.getVersion)return this.module.getVersion();if(this.module.version)return this.module.version();return`unknown`}}}));var init_taglib$1=__esmMin((()=>{init_audio_file_impl();init_taglib_class();init_errors()}));var taglib_exports=/* @__PURE__ */ __exportAll({AudioFileImpl:()=>AudioFileImpl,EnvironmentError:()=>EnvironmentError,FileOperationError:()=>FileOperationError,InvalidFormatError:()=>InvalidFormatError,MemoryError:()=>MemoryError,MetadataError:()=>MetadataError,SUPPORTED_FORMATS:()=>SUPPORTED_FORMATS,TagLib:()=>TagLib,TagLibError:()=>TagLibError,TagLibInitializationError:()=>TagLibInitializationError,UnsupportedFormatError:()=>UnsupportedFormatError,createTagLib:()=>createTagLib,isEnvironmentError:()=>isEnvironmentError,isFileOperationError:()=>isFileOperationError,isInvalidFormatError:()=>isInvalidFormatError,isMemoryError:()=>isMemoryError,isMetadataError:()=>isMetadataError,isTagLibError:()=>isTagLibError,isUnsupportedFormatError:()=>isUnsupportedFormatError});var init_taglib=__esmMin((()=>{init_taglib$1()}));let cachedTagLib=null;let bufferModeEnabled=false;function setBufferMode(enabled){bufferModeEnabled=enabled;cachedTagLib=null}async function getTagLib(){if(!cachedTagLib){const{TagLib}=await Promise.resolve().then(()=>(init_taglib(),taglib_exports));const initOptions=bufferModeEnabled?{forceWasmType:`emscripten`}:void 0;cachedTagLib=await TagLib.initialize(initOptions)}return cachedTagLib}init_errors();init_file();async function withAudioFile(file,fn,options){const audioFile=await(await getTagLib()).open(file,options);try{if(!audioFile.isValid())throw new InvalidFormatError(`File may be corrupted or in an unsupported format`);return await fn(audioFile)}finally{audioFile.dispose()}}async function withAudioFileSave(file,fn){return withAudioFile(typeof file===`string`?await readFileData(file):file,audioFile=>{fn(audioFile);if(!audioFile.save())throw new FileOperationError(`save`,`Failed to save metadata changes. The file may be read-only or corrupted.`);return audioFile.getFileBuffer()},{partial:false})}async function withAudioFileSaveToFile(file,fn){return withAudioFile(file,async audioFile=>{fn(audioFile);await audioFile.saveToFile(file)})}init_errors();init_tag_mapping();async function readTags(file,options={}){return withAudioFile(file,audioFile=>readExtendedTag(audioFile,options.includeProperties))}async function applyTags(file,tags){return withAudioFileSave(file,audioFile=>{mergeTagUpdates(audioFile,tags)})}async function applyTagsToFile(file,tags){if(typeof file!==`string`)throw new FileOperationError(`save`,`applyTagsToFile requires a file path string to save changes`);await withAudioFileSaveToFile(file,audioFile=>{mergeTagUpdates(audioFile,tags)})}async function readProperties(file){return withAudioFile(file,audioFile=>{const props=audioFile.audioProperties();if(!props)throw new MetadataError(`read`,`File may not contain valid audio data`,`audioProperties`);return props})}async function isValidAudioFile(file){try{const audioFile=await(await getTagLib()).open(file);try{return audioFile.isValid()}finally{audioFile.dispose()}}catch{return false}}async function readFormat(file){const audioFile=await(await getTagLib()).open(file);try{if(!audioFile.isValid())return;return audioFile.getFormat()}finally{audioFile.dispose()}}async function clearTags(file){return withAudioFileSave(file,audioFile=>{const cleared={};for(const key of Object.keys(audioFile.properties()))cleared[key]=[];audioFile.setProperties(cleared);audioFile.removePictures();audioFile.setLyrics([]);audioFile.setRatings([]);if(audioFile.getChapters().length>0)audioFile.setChapters([]);if(audioFile.getBextData()!==void 0)audioFile.setBextData(null);if(audioFile.getIxml()!==void 0)audioFile.setIxml(null)})}async function readPictures(file){return withAudioFile(file,audioFile=>audioFile.getPictures())}async function applyPictures(file,pictures){return withAudioFileSave(file,audioFile=>{audioFile.setPictures(pictures)})}async function addPicture(file,picture){return withAudioFileSave(file,audioFile=>{audioFile.addPicture(picture)})}async function clearPictures(file){return applyPictures(file,[])}async function readCoverArt(file){const pictures=await readPictures(file);if(pictures.length===0)return;const frontCover=pictures.find(pic=>pic.type===`FrontCover`);if(frontCover)return frontCover.data;return pictures[0].data}async function applyCoverArt(file,imageData,mimeType){return applyPictures(file,[{mimeType,data:imageData,type:`FrontCover`,description:`Front Cover`}])}function findPictureByType(pictures,type){return pictures.find(pic=>pic.type===type)}async function replacePictureByType(file,newPicture){const filteredPictures=(await readPictures(file)).filter(pic=>pic.type!==newPicture.type);filteredPictures.push(newPicture);return applyPictures(file,filteredPictures)}async function readPictureMetadata(file){return(await readPictures(file)).map(pic=>({type:pic.type,mimeType:pic.mimeType,...pic.description!==void 0?{description:pic.description}:{},size:pic.data.length}))}init_audio_formats();init_errors();init_properties();init_tag_mapping();async function executeBatch(files,options,processor){if(files.length===0)return{items:[],duration:0};const startTime=Date.now();const{concurrency=4,continueOnError=true,onProgress,signal}=options;const items=new Array(files.length);const taglib=await getTagLib();let processed=0;const total=files.length;for(let i=0;i<files.length;i+=concurrency){signal?.throwIfAborted();const chunkPromises=files.slice(i,i+concurrency).map(async(file,idx)=>{const index=i+idx;let fileName;if(typeof file===`string`)fileName=file;else if(file instanceof File)fileName=file.name;else if(isNamedAudioInput(file))fileName=file.name;else fileName=`buffer-${index}`;try{const audioFile=await taglib.open(file);try{if(!audioFile.isValid())throw new InvalidFormatError(`File may be corrupted or in an unsupported format`);items[index]={status:`ok`,path:fileName,data:processor(audioFile)}}finally{audioFile.dispose()}}catch(error){const err=error instanceof Error?error:new Error(String(error));items[index]={status:`error`,path:fileName,error:err};if(!continueOnError)throw err}processed++;onProgress?.(processed,total,fileName)});await Promise.all(chunkPromises)}return{items,duration:Date.now()-startTime}}async function readTagsBatch(files,options={}){return executeBatch(files,options,audioFile=>readExtendedTag(audioFile,options.includeProperties))}async function readPropertiesBatch(files,options={}){return executeBatch(files,options,audioFile=>audioFile.audioProperties())}function extractDynamics(audioFile){const dynamics={};for(const field of[`replayGainTrackGain`,`replayGainTrackPeak`,`replayGainAlbumGain`,`replayGainAlbumPeak`]){const val=audioFile.getProperty(field)?.[0];if(val!==void 0)dynamics[field]=val}let appleSoundCheck=audioFile.getProperty(`appleSoundCheck`)?.[0];if(!appleSoundCheck&&audioFile.isMP4())appleSoundCheck=audioFile.getMP4Item(`----:com.apple.iTunes:iTunNORM`);if(appleSoundCheck)dynamics.appleSoundCheck=appleSoundCheck;return Object.keys(dynamics).length>0?dynamics:void 0}async function readMetadata(file,options={}){const audioFile=await(await getTagLib()).open(file);try{if(!audioFile.isValid()){let name;if(typeof file===`string`)name=file;else if(file instanceof File)name=file.name;else if(isNamedAudioInput(file))name=file.name;else name=`buffer (${file.byteLength} bytes)`;throw new InvalidFormatError(`File may be corrupted or in an unsupported format. File: ${name}`)}const dynamics=extractDynamics(audioFile);return{tags:readExtendedTag(audioFile,options.includeProperties),properties:audioFile.audioProperties(),hasCoverArt:audioFile.getPictures().length>0,...dynamics!==void 0?{dynamics}:{}}}finally{audioFile.dispose()}}async function readMetadataBatch(files,options={}){return executeBatch(files,options,audioFile=>{const dynamics=extractDynamics(audioFile);return{tags:readExtendedTag(audioFile,options.includeProperties),properties:audioFile.audioProperties(),hasCoverArt:audioFile.getPictures().length>0,...dynamics!==void 0?{dynamics}:{}}})}function entryPath(entry){return typeof entry===`string`?entry:entry.path}async function executeWriteBatch(entries,options,writer){if(entries.length===0)return{items:[],duration:0};await getTagLib();const startTime=Date.now();const{concurrency=4,continueOnError=true,onProgress,signal}=options;const items=new Array(entries.length);let processed=0;const total=entries.length;for(let i=0;i<entries.length;i+=concurrency){signal?.throwIfAborted();const chunkPromises=entries.slice(i,i+concurrency).map(async(entry,idx)=>{const index=i+idx;const path=entryPath(entry);try{await writer(path);items[index]={status:`ok`,path,data:void 0}}catch(error){const err=error instanceof Error?error:new Error(String(error));items[index]={status:`error`,path,error:err};if(!continueOnError)throw err}processed++;onProgress?.(processed,total,path)});await Promise.all(chunkPromises)}return{items,duration:Date.now()-startTime}}async function writeTagsBatch(updates,options={}){const byPath=new Map(updates.map(u=>[u.path,u]));return executeWriteBatch(updates,options,path=>withAudioFileSaveToFile(path,audioFile=>{const update=byPath.get(path);const merged=update.tags!==void 0?mergeTagUpdatesInto(audioFile.properties(),update.tags):audioFile.properties();if(update.properties!==void 0)for(const[key,values]of Object.entries(update.properties))merged[fromTagLibKey(key)]=values;audioFile.setProperties(merged)}))}async function editTagsBatch(files,mutator,options={}){return executeWriteBatch(files,options,path=>withAudioFileSaveToFile(path,audioFile=>mutator(audioFile,path)))}async function readMediaChecksum(file,options){return withAudioFile(file,audioFile=>audioFile.mediaChecksum(options))}init_pictures();export{PICTURE_TYPE_NAMES,PICTURE_TYPE_VALUES,addPicture,applyCoverArt,applyPictures,applyTags,applyTagsToFile,clearPictures,clearTags,editTagsBatch,findPictureByType,getTagLib,isValidAudioFile,readCoverArt,readFormat,readMediaChecksum,readMetadata,readMetadataBatch,readPictureMetadata,readPictures,readProperties,readPropertiesBatch,readTags,readTagsBatch,replacePictureByType,setBufferMode,writeTagsBatch};