-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodplayer.js
More file actions
405 lines (364 loc) · 14.6 KB
/
Copy pathmodplayer.js
File metadata and controls
405 lines (364 loc) · 14.6 KB
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
// Standalone Amiga ProTracker MOD Player
// Bündelt: Mod-Parser, Loader und ModPlayer in einem ES-Modul.
// Originalcode aus dem p_fraktal-Projekt extrahiert und entschlackt.
//
// Aufbau für Anfänger:
// - Instrument / Note / Row / Pattern / Mod = Klassen, die das .mod-Binärformat dekodieren.
// - loadMod() = lädt eine MOD-Datei per fetch() und gibt ein Mod-Objekt zurück.
// - ModPlayer = startet den AudioWorklet, schickt das Mod-Objekt rein und gibt Events raus.
//
// Das eigentliche Abspielen passiert im AudioWorklet (mod-player-worklet.js).
// Hier wird nur geparst und kommuniziert.
// ─── MOD-Parser ────────────────────────────────────────────────────────────────
// Ein Instrument (= Sample) im MOD-Header. Insgesamt 31 Stück, je 30 Bytes Header.
export class Instrument {
constructor(modfile, index, sampleStart) {
// Header liegt bei Offset 20 + index*30, ist 30 Bytes lang.
const data = new Uint8Array(modfile, 20 + index * 30, 30);
// Name: erste 22 Bytes, null-bytes ignorieren.
const nameBytes = data.slice(0, 22).filter(a => !!a);
this.index = index;
this.name = String.fromCodePoint(...Array.from(nameBytes)).trim();
// Länge ist Big-Endian Word in 16-bit Words, also *2 für Bytes.
this.length = 2 * (data[22] * 256 + data[23]);
// Finetune: signed nibble (-8..7), wird als 0..15 gespeichert.
this.finetune = data[24];
if (this.finetune > 7) this.finetune -= 16;
this.volume = data[25];
this.repeatOffset = 2 * (data[26] * 256 + data[27]);
this.repeatLength = 2 * (data[28] * 256 + data[29]);
// Sample-Daten als Int8Array; sicherheitshalber Grenzen prüfen.
const actualSampleStart = Math.min(sampleStart, modfile.byteLength);
const actualLength = Math.min(this.length, modfile.byteLength - actualSampleStart);
this.bytes = new Int8Array(modfile, actualSampleStart, actualLength);
// Loop genau dann, wenn die Loop-Laenge > 1 Word (> 2 Bytes) ist. repeatOffset
// allein markiert KEINEN Loop (sonst loopt ein One-Shot mit 2-Byte-Sentinel
// faelschlich eine winzige Region). Identisch zu ModParser.swift.
this.isLooped = this.repeatLength > 2;
}
}
// Eine einzelne Note in einer Pattern-Zeile (4 Bytes pro Note pro Kanal).
export class Note {
constructor(noteData) {
// Instrument-Nummer ist auf die oberen Nibbles von Byte 0 und 2 verteilt.
this.instrument = (noteData[0] & 0xf0) | (noteData[2] >> 4);
// Period (Tonhöhe) = unteres Nibble Byte 0 + Byte 1, 12-bit.
this.period = (noteData[0] & 0x0f) * 256 + noteData[1];
let effectId = noteData[2] & 0x0f;
let effectData = noteData[3];
// Erweiterter Effekt 0xE: ID liegt im oberen Nibble der Daten.
if (effectId === 0x0e) {
effectId = 0xe0 | (effectData >> 4);
effectData &= 0x0f;
}
this.rawEffect = ((noteData[2] & 0x0f) << 8) | noteData[3];
this.effectId = effectId;
this.effectData = effectData;
this.effectHigh = effectData >> 4;
this.effectLow = effectData & 0x0f;
this.hasEffect = effectId || effectData;
}
}
// Eine Zeile im Pattern (4 Kanäle = 16 Bytes).
export class Row {
constructor(rowData) {
this.notes = [];
for (let i = 0; i < 16; i += 4) {
this.notes.push(new Note(rowData.slice(i, i + 4)));
}
}
}
// Ein Pattern = 64 Zeilen á 16 Byte = 1024 Bytes.
export class Pattern {
constructor(modfile, index) {
// Bounds-Check: Kaputte/abgeschnittene MOD-Dateien deklarieren manchmal mehr
// Patterns als tatsächlich Bytes vorhanden sind. Ohne Prüfung würde der
// Uint8Array-Konstruktor eine RangeError werfen, die im async Drop-Handler
// unbehandelt bleibt (nur console.error). Der Swift-Parser (ModParser) ist
// hier defensiv und liefert leere Rows — die JS-Variante zieht nach:
// passt das komplette 1024-Byte-Pattern nicht mehr in die Datei, werden
// 64 leere (Null-)Rows erzeugt statt zu crashen.
const offset = 1084 + index * 1024;
const data = (offset + 1024 <= modfile.byteLength)
? new Uint8Array(modfile, offset, 1024)
: new Uint8Array(1024); // eigenständiger, nullgefüllter Puffer = 64 leere Rows
this.rows = [];
for (let i = 0; i < 64; ++i) {
this.rows.push(new Row(data.slice(i * 16, i * 16 + 16)));
}
}
}
// Das gesamte MOD-File.
export class Mod {
constructor(modfile) {
// Songname: erste 20 Bytes des Files.
const nameArray = new Uint8Array(modfile, 0, 20);
const nameBytes = nameArray.filter(a => !!a);
this.name = String.fromCodePoint(...Array.from(nameBytes)).trim();
// Anzahl der Pattern-Positionen + die Reihenfolge (PatternTable).
this.length = new Uint8Array(modfile, 950, 1)[0];
this.patternTable = new Uint8Array(modfile, 952, this.length);
// Höchste verwendete Pattern-Nummer bestimmt die Größe. Bei leerer
// Playlist (length === 0) liefert Math.max(...[]) -Infinity und wuerde
// alle Folgeoffsets vergiften — deshalb auf 0 absichern.
const maxPatternIndex = this.patternTable.length > 0
? Math.max(...Array.from(this.patternTable))
: 0;
// Index 0 ist leer (Instrumente werden ab 1 referenziert).
this.instruments = [null];
let sampleStart = 1084 + (maxPatternIndex + 1) * 1024;
for (let i = 0; i < 31; ++i) {
const instr = new Instrument(modfile, i, sampleStart);
this.instruments.push(instr);
sampleStart += instr.length;
}
this.patterns = [];
for (let i = 0; i <= maxPatternIndex; ++i) {
this.patterns.push(new Pattern(modfile, i));
}
}
}
// ─── Loader ────────────────────────────────────────────────────────────────────
// Lädt eine MOD-Datei per URL und prüft Signatur.
export async function loadMod(url) {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Fetch fehlgeschlagen: ${response.status} ${response.statusText} (${url})`);
}
const arrayBuffer = await response.arrayBuffer();
return parseModBuffer(arrayBuffer, url);
}
// Parst einen bereits geladenen ArrayBuffer (z.B. aus File-Upload).
export function parseModBuffer(arrayBuffer, label = 'buffer') {
if (arrayBuffer.byteLength < 1084) {
throw new Error(`MOD zu klein (${arrayBuffer.byteLength} Bytes): ${label}`);
}
const sig = new Uint8Array(arrayBuffer, 1080, 4);
const sigStr = String.fromCharCode(sig[0], sig[1], sig[2], sig[3]);
// Nur echte 4-Kanal-Signaturen. 6CHN/8CHN/FLT8 haben groessere Row-/Pattern-
// Strides; als 4ch geparst lesen sie Noten und Sampledaten aus falschen
// Offsets (Garbage). Bis echtes Multichannel-Parsing existiert: ablehnen.
const validSigs = ['M.K.', 'M!K!', 'FLT4', '4CHN'];
if (!validSigs.includes(sigStr)) {
throw new Error(`Ungültige MOD-Signatur "${sigStr}": ${label}`);
}
return new Mod(arrayBuffer);
}
// ─── ModPlayer ─────────────────────────────────────────────────────────────────
// Tabelle: aus Period -> MIDI-Noten-Index (0..47), wird vom Worklet-Event
// bei "watchNotes" gebraucht, damit Aufrufer die Notennummer bekommen.
// An PERIODS[0] = 856 (C-1) verankert, damit die an watchNotes() gemeldeten
// Indizes mit der Bildschirm-Notentabelle uebereinstimmen (vorher +12, eine
// Oktave zu hoch). 856->0, 428->12, 214->24, 56->47.
// codereview-ok: kein Crash, funktional harmlos — nur Speicherverschwendung, reine Micro-Optimierung, kein Bug (2026-07-01)
const notePerPeriod = new Array(65536);
for (let p = 0; p < 65536; p++) {
notePerPeriod[p] = p > 0 ? Math.round(12 * Math.log2(856 / p)) : null;
}
export class ModPlayer {
constructor() {
this.mod = null;
this.playing = false;
this.audio = null;
this.gain = null;
this.worklet = null;
this.setupPromise = null;
this.volume = 0.3;
this.workletUrl = 'mod-player-worklet.js';
this.rowCallbacks = [];
this.stopCallbacks = [];
this.noteCallbacks = [];
// levelCallbacks bekommen das echte Per-Channel-Peak-Array
// ([p0,p1,p2,p3] in 0..~0.5) aus dem Worklet, ~47x pro Sekunde.
// Damit zeigen die VU-Meter den tatsächlich gerade hörbaren Pegel,
// nicht nur den Note-Trigger.
this.levelCallbacks = [];
this.singleCallbacks = {};
}
// Lädt eine MOD-Datei von einer URL.
async load(url, workletUrl = 'mod-player-worklet.js') {
this.unload();
this.workletUrl = workletUrl;
this.mod = await loadMod(url);
}
// Setzt ein bereits geparstes Mod direkt (für File-Upload).
setMod(mod, workletUrl = 'mod-player-worklet.js') {
this.stop();
this.workletUrl = workletUrl;
this.mod = mod;
}
// Setup für AudioContext + Worklet. Wird beim ersten play() ausgeführt.
async setupAudio() {
if (this.worklet) return;
if (this.setupPromise) return this.setupPromise;
this.setupPromise = this.createAudioGraph();
try {
await this.setupPromise;
} finally {
this.setupPromise = null;
}
}
// Startet AudioContext + Worklet während der User-Geste. Das ist für
// Drag & Drop wichtig, weil Ordner-Traversal danach asynchron läuft.
prepareAudioForGesture(workletUrl = 'mod-player-worklet.js') {
this.workletUrl = workletUrl;
this.resumeContext();
return this.setupAudio();
}
async createAudioGraph() {
if (this.worklet) return;
if (!this.audio) {
const AC = window.AudioContext || window.webkitAudioContext;
this.audio = new AC();
}
const ctx = this.audio;
await this.tryResumeContext(250);
// Stumme Dummy-Source für iOS-Audio-Unlock.
try {
const buffer = ctx.createBuffer(1, 1, 22050);
const source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(ctx.destination);
source.start(0);
} catch (_) {}
this.gain = ctx.createGain();
this.gain.gain.value = this.volume;
const absoluteWorkletUrl = new URL(this.workletUrl, window.location.href).href;
if (!ctx.__workletAdded) {
await ctx.audioWorklet.addModule(absoluteWorkletUrl);
ctx.__workletAdded = true;
}
this.worklet = new AudioWorkletNode(ctx, 'mod-player-worklet', {
outputChannelCount: [2]
});
this.worklet.connect(this.gain).connect(ctx.destination);
this.worklet.port.onmessage = this.onMessage.bind(this);
if (this.rowCallbacks.length || Object.keys(this.singleCallbacks).length) {
this.worklet.port.postMessage({ type: 'enableRowSubscription' });
}
if (this.stopCallbacks.length) {
this.worklet.port.postMessage({ type: 'enableStopSubscription' });
}
if (this.noteCallbacks.length) {
this.worklet.port.postMessage({ type: 'enableNoteSubscription' });
}
if (this.levelCallbacks.length) {
this.worklet.port.postMessage({ type: 'enableLevelSubscription' });
}
}
// Empfängt Events vom Worklet (row, stop, note).
onMessage(event) {
const { data } = event;
if (data.type === 'row') {
for (const cb of this.rowCallbacks) cb(data.position, data.rowIndex, data.bpm, data.speed);
const key = data.position + ':' + data.rowIndex;
if (key in this.singleCallbacks) {
for (const cb of this.singleCallbacks[key]) cb();
}
} else if (data.type === 'stop') {
for (const cb of this.stopCallbacks) cb();
} else if (data.type === 'note') {
for (const cb of this.noteCallbacks) {
cb({
channel: data.channel,
sample: data.sample,
volume: data.volume,
note: notePerPeriod[data.period]
});
}
} else if (data.type === 'levels') {
// Realer Per-Channel-Peak. data.peaks ist [p0,p1,p2,p3].
// Wir reichen das Array 1:1 weiter — Aufrufer interpretieren die
// Skala (Maximum theoretisch 0.5, siehe Channel.nextOutput()).
for (const cb of this.levelCallbacks) cb(data.peaks);
}
}
watchRows(cb) {
if (this.worklet) this.worklet.port.postMessage({ type: 'enableRowSubscription' });
this.rowCallbacks.push(cb);
}
watchStop(cb) {
if (this.worklet) this.worklet.port.postMessage({ type: 'enableStopSubscription' });
this.stopCallbacks.push(cb);
}
watchNotes(cb) {
if (this.worklet) this.worklet.port.postMessage({ type: 'enableNoteSubscription' });
this.noteCallbacks.push(cb);
}
// Subscribed auf das echte Per-Channel-Peak-Array, das das Worklet
// ca. 47x pro Sekunde schickt. cb(peaks: number[4]).
watchLevels(cb) {
if (this.worklet) this.worklet.port.postMessage({ type: 'enableLevelSubscription' });
this.levelCallbacks.push(cb);
}
unload() {
this.stop();
if (this.worklet) {
try { this.worklet.disconnect(); } catch (_) {}
}
this.mod = null;
this.worklet = null;
this.setupPromise = null;
this.playing = false;
this.rowCallbacks = [];
this.stopCallbacks = [];
this.noteCallbacks = [];
this.levelCallbacks = [];
this.singleCallbacks = {};
}
resumeContext() {
if (!this.audio) {
const AC = window.AudioContext || window.webkitAudioContext;
this.audio = new AC();
}
if (this.audio.state === 'suspended') {
this.audio.resume().catch(() => {});
}
try {
const buffer = this.audio.createBuffer(1, 1, 22050);
const source = this.audio.createBufferSource();
source.buffer = buffer;
source.connect(this.audio.destination);
source.start(0);
} catch (_) {}
}
async tryResumeContext(timeoutMs = 1000) {
if (!this.audio || this.audio.state !== 'suspended') return;
try {
await Promise.race([
this.audio.resume(),
new Promise(resolve => setTimeout(resolve, timeoutMs))
]);
} catch (_) {}
}
async play() {
if (this.playing) return;
await this.setupAudio();
if (!this.worklet) return;
this.resumeContext();
await this.tryResumeContext(500);
this.worklet.port.postMessage({
type: 'play',
mod: this.mod,
sampleRate: this.audio.sampleRate
});
this.playing = true;
}
stop() {
if (this.worklet) {
this.worklet.port.postMessage({ type: 'stop' });
}
this.playing = false;
}
setVolume(v) {
this.volume = v;
// Psychoakustische (quadratische) Lautstärkeskalierung für besseres Hörempfinden
if (this.gain) this.gain.gain.value = v * v;
}
// Springt zu einer bestimmten Position (Pattern-Index) und Zeile (Row) im Song.
setPosition(position, row = 0) {
if (this.worklet) {
this.worklet.port.postMessage({ type: 'setRow', position, row });
}
}
}