-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathID3Writer.mjs
655 lines (586 loc) · 19.1 KB
/
ID3Writer.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import { encodeWindows1252, encodeUtf16le } from './encoder.mjs';
import { getMimeType, isId3v2 } from './signatures.mjs';
import {
uint7ArrayToUint28,
uint28ToUint7Array,
uint32ToUint8Array,
} from './transform.mjs';
import {
getNumericFrameSize,
getStringFrameSize,
getPictureFrameSize,
getLyricsFrameSize,
getCommentFrameSize,
getUserStringFrameSize,
getUrlLinkFrameSize,
getPrivateFrameSize,
getPairedTextFrameSize,
getSynchronisedLyricsFrameSize,
} from './sizes.mjs';
export class ID3Writer {
_setIntegerFrame(name, value) {
const integer = parseInt(value, 10);
this.frames.push({
name,
value: integer,
size: getNumericFrameSize(integer.toString().length),
});
}
_setStringFrame(name, value) {
const stringValue = value.toString();
let size = getStringFrameSize(stringValue.length);
if (name === 'TDAT') {
size = getNumericFrameSize(stringValue.length);
}
this.frames.push({
name,
value: stringValue,
size,
});
}
_setPictureFrame(pictureType, data, description, useUnicodeEncoding) {
const mimeType = getMimeType(new Uint8Array(data));
const descriptionString = description.toString();
if (!mimeType) {
throw new Error('Unknown picture MIME type');
}
if (!description) {
useUnicodeEncoding = false;
}
this.frames.push({
name: 'APIC',
value: data,
pictureType,
mimeType,
useUnicodeEncoding,
description: descriptionString,
size: getPictureFrameSize(
data.byteLength,
mimeType.length,
descriptionString.length,
useUnicodeEncoding,
),
});
}
_setLyricsFrame(language, description, lyrics) {
const languageCode = language.split('').map((c) => c.charCodeAt(0));
const descriptionString = description.toString();
const lyricsString = lyrics.toString();
this.frames.push({
name: 'USLT',
value: lyricsString,
language: languageCode,
description: descriptionString,
size: getLyricsFrameSize(descriptionString.length, lyricsString.length),
});
}
_setCommentFrame(language, description, text) {
const languageCode = language.split('').map((c) => c.charCodeAt(0));
const descriptionString = description.toString();
const textString = text.toString();
this.frames.push({
name: 'COMM',
value: textString,
language: languageCode,
description: descriptionString,
size: getCommentFrameSize(descriptionString.length, textString.length),
});
}
_setPrivateFrame(id, data) {
const identifier = id.toString();
this.frames.push({
name: 'PRIV',
value: data,
id: identifier,
size: getPrivateFrameSize(identifier.length, data.byteLength),
});
}
_setUserStringFrame(description, value) {
const descriptionString = description.toString();
const valueString = value.toString();
this.frames.push({
name: 'TXXX',
description: descriptionString,
value: valueString,
size: getUserStringFrameSize(
descriptionString.length,
valueString.length,
),
});
}
_setUrlLinkFrame(name, url) {
const urlString = url.toString();
this.frames.push({
name,
value: urlString,
size: getUrlLinkFrameSize(urlString.length),
});
}
_setPairedTextFrame(name, list) {
this.frames.push({
name,
value: list,
size: getPairedTextFrameSize(list),
});
}
_setSynchronisedLyricsFrame(
type,
text,
timestampFormat,
language,
description,
) {
const descriptionString = description.toString();
const languageCode = language.split('').map((c) => c.charCodeAt(0));
this.frames.push({
name: 'SYLT',
value: text,
language: languageCode,
description: descriptionString,
type,
timestampFormat,
size: getSynchronisedLyricsFrameSize(text, descriptionString.length),
});
}
constructor(buffer) {
if (!buffer || typeof buffer !== 'object' || !('byteLength' in buffer)) {
throw new Error(
'First argument should be an instance of ArrayBuffer or Buffer',
);
}
this.arrayBuffer = buffer;
this.padding = 4096;
this.frames = [];
this.url = '';
}
setFrame(frameName, frameValue) {
switch (frameName) {
case 'TPE1': // song artists
case 'TCOM': // song composers
case 'TCON': {
// song genres
if (!Array.isArray(frameValue)) {
throw new Error(
`${frameName} frame value should be an array of strings`,
);
}
const delemiter = frameName === 'TCON' ? ';' : '/';
const value = frameValue.join(delemiter);
this._setStringFrame(frameName, value);
break;
}
case 'TLAN': // language
case 'TIT1': // content group description
case 'TIT2': // song title
case 'TIT3': // song subtitle
case 'TALB': // album title
case 'TPE2': // album artist // spec doesn't say anything about separator, so it is a string, not array
case 'TPE3': // conductor/performer refinement
case 'TPE4': // interpreted, remixed, or otherwise modified by
case 'TRCK': // song number in album: 5 or 5/10
case 'TPOS': // album disc number: 1 or 1/3
case 'TMED': // media type
case 'TPUB': // label name
case 'TCOP': // copyright
case 'TKEY': // musical key in which the sound starts
case 'TEXT': // lyricist / text writer
case 'TDAT': // album release date expressed as DDMM
case 'TCMP': // compilation flag ("1" stored as a string)
case 'TSRC': {
// isrc
this._setStringFrame(frameName, frameValue);
break;
}
case 'TBPM': // beats per minute
case 'TLEN': // song duration
case 'TYER': {
// album release year
this._setIntegerFrame(frameName, frameValue);
break;
}
case 'USLT': {
// unsychronised lyrics
frameValue.language = frameValue.language || 'eng';
if (
typeof frameValue !== 'object' ||
!('description' in frameValue) ||
!('lyrics' in frameValue)
) {
throw new Error(
'USLT frame value should be an object with keys description and lyrics',
);
}
if (frameValue.language && !frameValue.language.match(/[a-z]{3}/i)) {
throw new Error(
'Language must be coded following the ISO 639-2 standards',
);
}
this._setLyricsFrame(
frameValue.language,
frameValue.description,
frameValue.lyrics,
);
break;
}
case 'APIC': {
// song cover
if (
typeof frameValue !== 'object' ||
!('type' in frameValue) ||
!('data' in frameValue) ||
!('description' in frameValue)
) {
throw new Error(
'APIC frame value should be an object with keys type, data and description',
);
}
if (frameValue.type < 0 || frameValue.type > 20) {
throw new Error('Incorrect APIC frame picture type');
}
this._setPictureFrame(
frameValue.type,
frameValue.data,
frameValue.description,
!!frameValue.useUnicodeEncoding,
);
break;
}
case 'TXXX': {
// user defined text information
if (
typeof frameValue !== 'object' ||
!('description' in frameValue) ||
!('value' in frameValue)
) {
throw new Error(
'TXXX frame value should be an object with keys description and value',
);
}
this._setUserStringFrame(frameValue.description, frameValue.value);
break;
}
case 'WCOM': // Commercial information
case 'WCOP': // Copyright/Legal information
case 'WOAF': // Official audio file webpage
case 'WOAR': // Official artist/performer webpage
case 'WOAS': // Official audio source webpage
case 'WORS': // Official internet radio station homepage
case 'WPAY': // Payment
case 'WPUB': {
// Publishers official webpage
this._setUrlLinkFrame(frameName, frameValue);
break;
}
case 'COMM': {
// Comments
frameValue.language = frameValue.language || 'eng';
if (
typeof frameValue !== 'object' ||
!('description' in frameValue) ||
!('text' in frameValue)
) {
throw new Error(
'COMM frame value should be an object with keys description and text',
);
}
if (frameValue.language && !frameValue.language.match(/[a-z]{3}/i)) {
throw new Error(
'Language must be coded following the ISO 639-2 standards',
);
}
this._setCommentFrame(
frameValue.language,
frameValue.description,
frameValue.text,
);
break;
}
case 'PRIV': {
// Private frame
if (
typeof frameValue !== 'object' ||
!('id' in frameValue) ||
!('data' in frameValue)
) {
throw new Error(
'PRIV frame value should be an object with keys id and data',
);
}
this._setPrivateFrame(frameValue.id, frameValue.data);
break;
}
case 'IPLS': {
// Involved people
if (!Array.isArray(frameValue) || !Array.isArray(frameValue[0])) {
throw new Error('IPLS frame value should be an array of pairs');
}
this._setPairedTextFrame(frameName, frameValue);
break;
}
case 'SYLT': {
// Synchronised Lyrics
if (
typeof frameValue !== 'object' ||
!('type' in frameValue) ||
!('text' in frameValue) ||
!('timestampFormat' in frameValue)
) {
throw new Error(
'SYLT frame value should be an object with keys type, text and timestampFormat',
);
}
if (
!Array.isArray(frameValue.text) ||
!Array.isArray(frameValue.text[0])
) {
throw new Error('SYLT frame text value should be an array of pairs');
}
if (frameValue.type < 0 || frameValue.type > 6) {
throw new Error('Incorrect SYLT frame content type');
}
if (frameValue.timestampFormat < 1 || frameValue.timestampFormat > 2) {
throw new Error('Incorrect SYLT frame time stamp format');
}
frameValue.language = frameValue.language || 'eng';
frameValue.description = frameValue.description || '';
this._setSynchronisedLyricsFrame(
frameValue.type,
frameValue.text,
frameValue.timestampFormat,
frameValue.language,
frameValue.description,
);
break;
}
default: {
throw new Error(`Unsupported frame ${frameName}`);
}
}
return this;
}
removeTag() {
const headerLength = 10;
if (this.arrayBuffer.byteLength < headerLength) {
return;
}
const bytes = new Uint8Array(this.arrayBuffer);
const version = bytes[3];
const tagSize =
uint7ArrayToUint28([bytes[6], bytes[7], bytes[8], bytes[9]]) +
headerLength;
if (!isId3v2(bytes) || version < 2 || version > 4) {
return;
}
this.arrayBuffer = new Uint8Array(bytes.subarray(tagSize)).buffer;
}
addTag() {
this.removeTag();
const BOM = [0xff, 0xfe];
const headerSize = 10;
const totalFrameSize = this.frames.reduce(
(sum, frame) => sum + frame.size,
0,
);
const totalTagSize = headerSize + totalFrameSize + this.padding;
const buffer = new ArrayBuffer(this.arrayBuffer.byteLength + totalTagSize);
const bufferWriter = new Uint8Array(buffer);
let offset = 0;
let writeBytes = [];
writeBytes = [0x49, 0x44, 0x33, 3]; // ID3 tag and version
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
offset++; // version revision
offset++; // flags
writeBytes = uint28ToUint7Array(totalTagSize - headerSize); // tag size (without header)
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
this.frames.forEach((frame) => {
writeBytes = encodeWindows1252(frame.name); // frame name
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = uint32ToUint8Array(frame.size - headerSize); // frame size (without header)
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
offset += 2; // flags
switch (frame.name) {
case 'WCOM':
case 'WCOP':
case 'WOAF':
case 'WOAR':
case 'WOAS':
case 'WORS':
case 'WPAY':
case 'WPUB': {
writeBytes = encodeWindows1252(frame.value); // URL
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
break;
}
case 'TPE1':
case 'TCOM':
case 'TCON':
case 'TLAN':
case 'TIT1':
case 'TIT2':
case 'TIT3':
case 'TALB':
case 'TPE2':
case 'TPE3':
case 'TPE4':
case 'TRCK':
case 'TPOS':
case 'TKEY':
case 'TMED':
case 'TPUB':
case 'TCOP':
case 'TEXT':
case 'TSRC': {
writeBytes = [1].concat(BOM); // encoding, BOM
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeUtf16le(frame.value); // frame value
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
break;
}
case 'TXXX':
case 'USLT':
case 'COMM': {
writeBytes = [1]; // encoding
if (frame.name === 'USLT' || frame.name === 'COMM') {
writeBytes = writeBytes.concat(frame.language); // language
}
writeBytes = writeBytes.concat(BOM); // BOM for content descriptor
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeUtf16le(frame.description); // content descriptor
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = [0, 0].concat(BOM); // separator, BOM for frame value
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeUtf16le(frame.value); // frame value
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
break;
}
case 'TBPM':
case 'TLEN':
case 'TDAT':
case 'TYER': {
offset++; // encoding
writeBytes = encodeWindows1252(frame.value); // frame value
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
break;
}
case 'PRIV': {
writeBytes = encodeWindows1252(frame.id); // identifier
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
offset++; // separator
bufferWriter.set(new Uint8Array(frame.value), offset); // frame data
offset += frame.value.byteLength;
break;
}
case 'APIC': {
writeBytes = [frame.useUnicodeEncoding ? 1 : 0]; // encoding
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeWindows1252(frame.mimeType); // MIME type
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = [0, frame.pictureType]; // separator, pic type
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
if (frame.useUnicodeEncoding) {
writeBytes = [].concat(BOM); // BOM
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeUtf16le(frame.description); // description
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
offset += 2; // separator
} else {
writeBytes = encodeWindows1252(frame.description); // description
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
offset++; // separator
}
bufferWriter.set(new Uint8Array(frame.value), offset); // picture content
offset += frame.value.byteLength;
break;
}
case 'IPLS': {
writeBytes = [1]; // encoding
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
frame.value.forEach((pair) => {
writeBytes = [].concat(BOM); // BOM
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeUtf16le(pair[0].toString()); // role
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = [0, 0].concat(BOM); // separator + BOM
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeUtf16le(pair[1].toString()); // name
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = [0, 0]; // separator
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
});
break;
}
case 'SYLT': {
writeBytes = [1] // encoding
.concat(frame.language) // language
.concat(frame.timestampFormat) // time stamp format
.concat(frame.type); // content type
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = [].concat(BOM); // BOM
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeUtf16le(frame.description); // description
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
offset += 2; // separator
frame.value.forEach((line) => {
writeBytes = [].concat(BOM); // BOM
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = encodeUtf16le(line[0].toString()); // lyric line
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = [0, 0]; // separator
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
writeBytes = uint32ToUint8Array(line[1]); // timestamp
bufferWriter.set(writeBytes, offset);
offset += writeBytes.length;
});
break;
}
}
});
offset += this.padding; // free space for rewriting
bufferWriter.set(new Uint8Array(this.arrayBuffer), offset);
this.arrayBuffer = buffer;
return buffer;
}
getBlob() {
return new Blob([this.arrayBuffer], { type: 'audio/mpeg' });
}
getURL() {
if (!this.url) {
this.url = URL.createObjectURL(this.getBlob());
}
return this.url;
}
revokeURL() {
URL.revokeObjectURL(this.url);
}
}