-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.js
More file actions
279 lines (245 loc) · 10.3 KB
/
Copy pathmain.js
File metadata and controls
279 lines (245 loc) · 10.3 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
import { dotnet } from './_framework/dotnet.js';
import { initPatternsView, renderPatternsView, resetPatternsView } from './view-patterns.js';
import { initSamplesView, renderSamplesView, resetSamplesView } from './view-samples.js';
import { initTrackPicker, setTrackPickerEntries, setTrackPickerUnavailable, resetTrackPicker, isTrackPickerBusy } from './track-picker.js';
const $ = (id) => document.getElementById(id);
const status = (msg) => { $('status').textContent = msg; };
const SUPPORTED_EXTENSIONS = new Set(['.mod', '.s3m', '.xm', '.stm', '.669']);
const DEMO_TRACKS_API = 'https://api.github.com/repos/morphx666/SharpMod/contents/Release/mods?ref=master';
status('Loading .NET runtime…');
const { getAssemblyExports, getConfig, runMain } = await dotnet.create();
const config = getConfig();
const exports = await getAssemblyExports(config.mainAssemblyName);
const sm = exports.SharpModInterop;
runMain();
let audioCtx = null;
let workletNode = null;
let pumpTimer = 0;
let pumping = false;
let activeBytesPerFrame = 0;
let activeChannels = 1;
let activeIs16Bit = true;
let queuedFrames = 0;
let queueStartTime = 0;
const TARGET_LEAD_SEC = 0.25;
let view = 'patterns';
let rafId = 0;
let loadedToken = 0; // bumped on every successful Load() so views can drop caches
initPatternsView({ root: $('channels-row'), patterns: $('patterns') });
initSamplesView({ summary: { length: $('s-length'), bpm: $('s-bpm'), filename: $('s-filename') }, list: $('samples-list') });
$('file').disabled = false;
status('Ready. Load a file or pick a demo track.');
initTrackPicker({
els: {
root: $('trackPick'),
button: $('trackPickButton'),
caption: $('trackPickCaption'),
panel: $('trackPickPanel'),
filter: $('trackPickFilter'),
list: $('trackPickList'),
empty: $('trackPickEmpty'),
},
probe: (bytes) => sm.ProbeMetadata(bytes),
onSelect: (bytes, name) => {
// Clear the file input so re-picking the same local file later still fires 'change'.
$('file').value = '';
loadModuleFromBytes(bytes, name, 'the demo tracks');
},
onStatus: status,
});
initializeDemoTracks();
$('file').addEventListener('change', async (e) => {
const f = e.target.files && e.target.files[0];
if(!f) return;
// Either way the engine has dropped whatever the picker was pointing at, so clear its
// selection — the two sources are alternatives, not a combined playlist.
resetTrackPicker();
try {
const buf = new Uint8Array(await f.arrayBuffer());
loadModuleFromBytes(buf, f.name, 'local drive');
} catch(err) {
status('Local load failed: ' + formatError(err));
}
});
$('playPause').addEventListener('click', () => togglePlayback());
$('pos').addEventListener('input', (e) => sm.SetPosition(parseInt(e.target.value, 10)));
document.querySelectorAll('.tab').forEach(btn => {
btn.addEventListener('click', () => setView(btn.dataset.view));
});
window.addEventListener('keydown', (e) => {
if(e.target instanceof HTMLInputElement || e.target instanceof HTMLSelectElement) return;
// The demo-track picker is a button + popup, not a form control, so it would otherwise
// fall through to Space = play/pause and the digit mute keys.
if(isTrackPickerBusy()) return;
if(e.code === 'Space') {
e.preventDefault();
togglePlayback();
} else if(e.code === 'Tab') {
e.preventDefault();
setView(view === 'patterns' ? 'samples' : 'patterns');
} else if(sm.IsLoaded() && /^Digit[1-9]$/.test(e.code)) {
const n = parseInt(e.code.slice(5), 10) - 1;
const bank = e.ctrlKey ? 2 : e.shiftKey ? 1 : 0;
sm.ToggleChannelMute(bank * 9 + n);
resetPatternsView();
}
});
function setView(v) {
view = v;
$('view-patterns').classList.toggle('hidden', v !== 'patterns');
$('view-samples').classList.toggle('hidden', v !== 'samples');
document.querySelectorAll('.tab').forEach(b => b.classList.toggle('active', b.dataset.view === v));
}
function togglePlayback() {
if(audioCtx) { stopPlayback(); status('Paused'); }
else if(sm.IsLoaded()) startPlayback();
}
async function startPlayback() {
stopPlayback();
if(!sm.IsLoaded()) return;
setPlayPauseUi(true);
const rate = sm.GetSampleRate();
activeIs16Bit = sm.GetIs16Bit();
activeChannels = sm.GetIsStereo() ? 2 : 1;
activeBytesPerFrame = activeChannels * (activeIs16Bit ? 2 : 1);
audioCtx = new AudioContext({ sampleRate: rate });
await audioCtx.audioWorklet.addModule('mod-processor.js');
workletNode = new AudioWorkletNode(audioCtx, 'mod-processor', {
numberOfInputs: 0,
numberOfOutputs: 1,
outputChannelCount: [activeChannels],
processorOptions: { channels: activeChannels, capacityFrames: Math.round(rate * 0.75) }
});
workletNode.connect(audioCtx.destination);
queuedFrames = 0;
queueStartTime = audioCtx.currentTime;
pumpChunk(Math.round(rate * TARGET_LEAD_SEC));
pumpTimer = setInterval(pump, 20);
status('Playing');
ensureRenderLoop();
}
function stopPlayback() {
if(pumpTimer) { clearInterval(pumpTimer); pumpTimer = 0; }
if(workletNode) { try { workletNode.port.postMessage({ type: 'stop' }); workletNode.disconnect(); } catch { } workletNode = null; }
if(audioCtx) { audioCtx.close().catch(() => { }); audioCtx = null; }
setPlayPauseUi(false);
}
function setPlayPauseUi(playing) {
const btn = $('playPause');
btn.querySelector('.icon').className = `icon fa-solid ${playing ? 'fa-pause' : 'fa-play'}`;
btn.querySelector('.label').textContent = playing ? 'Pause' : 'Play';
}
// Feed decoded module bytes to the runtime and sync the UI. Shared by the
// local file picker and the demo-track dropdown.
function loadModuleFromBytes(buf, displayName, sourceLabel) {
stopPlayback();
const err = sm.Load(buf, 44100, true, true, false);
if(err) {
status('Load failed: ' + err);
return false;
}
loadedToken++;
resetPatternsView();
resetSamplesView();
$('playPause').disabled = false;
$('pos').disabled = false;
$('pos').max = String(sm.GetPositionCount());
$('s-filename').textContent = displayName;
ensureRenderLoop();
status(`Loaded ${displayName} from ${sourceLabel} (${buf.length.toLocaleString()} bytes)`);
return true;
}
// List the demo tracks straight from the repo's Release/mods folder via the
// GitHub contents API, so the picker stays in sync without bundling anything.
// The file input keeps working if this fails (offline, rate-limited, etc.).
async function initializeDemoTracks() {
try {
setTrackPickerEntries(await fetchDemoTracks());
} catch(err) {
setTrackPickerUnavailable(formatError(err));
status(`Demo tracks unavailable: ${formatError(err)}. Local file loading is still ready.`);
}
}
async function fetchDemoTracks() {
const response = await fetch(DEMO_TRACKS_API, {
headers: {
Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2022-11-28'
}
});
if(!response.ok) throw new Error(`GitHub API responded with ${response.status}`);
const listing = await response.json();
if(!Array.isArray(listing)) return [];
return listing
.filter((item) => item && item.type === 'file' && trackerExtension(item.name))
.map((item) => ({
name: item.name,
ext: trackerExtension(item.name),
size: item.size || 0,
// Prefer GitHub's canonical raw URL from the API for browser fetch compatibility.
url: item.download_url || `https://raw.githubusercontent.com/morphx666/SharpMod/master/Release/mods/${encodeURIComponent(item.name)}`
}))
.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
}
// Returns the lower-cased extension when the name is a supported module, else ''.
function trackerExtension(name) {
if(typeof name !== 'string') return '';
const dot = name.lastIndexOf('.');
if(dot < 0) return '';
const ext = name.slice(dot).toLowerCase();
return SUPPORTED_EXTENSIONS.has(ext) ? ext : '';
}
function formatError(err) {
return err instanceof Error ? err.message : String(err);
}
function pump() {
if(pumping || !workletNode || !audioCtx) return;
const elapsedFrames = (audioCtx.currentTime - queueStartTime) * audioCtx.sampleRate;
const pendingFrames = queuedFrames - elapsedFrames;
const targetFrames = audioCtx.sampleRate * TARGET_LEAD_SEC;
if(pendingFrames >= targetFrames) return;
pumping = true;
try { pumpChunk(Math.ceil(targetFrames - pendingFrames)); }
finally { pumping = false; }
}
function pumpChunk(frames) {
if(!workletNode || frames <= 0) return;
const bytes = frames * activeBytesPerFrame;
const raw = sm.Read(bytes);
if(!raw || raw.length === 0) return;
const float = convertToFloat32(raw, activeIs16Bit);
queuedFrames += float.length / activeChannels;
workletNode.port.postMessage({ type: 'samples', data: float }, [float.buffer]);
}
function convertToFloat32(bytes, is16Bit) {
if(is16Bit) {
const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const n = bytes.byteLength >> 1;
const out = new Float32Array(n);
for(let i = 0; i < n; i++) out[i] = dv.getInt16(i * 2, true) / 32768;
return out;
}
const n = bytes.byteLength;
const out = new Float32Array(n);
for(let i = 0; i < n; i++) out[i] = (bytes[i] - 128) / 128;
return out;
}
function ensureRenderLoop() {
if(rafId) return;
const tick = () => {
rafId = requestAnimationFrame(tick);
if(!sm.IsLoaded()) return;
const pos = sm.GetPosition();
const total = sm.GetPositionCount();
$('m-title').textContent = sm.GetTitle() || '(untitled)';
$('m-type').textContent = sm.GetTypeName();
$('m-channels').textContent = sm.GetActiveChannels();
$('m-pattern').textContent = `${sm.GetCurrentPattern()} / ${total > 0 ? Math.max(0, Math.floor(total / 64) - 1) : 0}`;
$('m-row').textContent = sm.GetRow();
$('m-tempo').textContent = `${sm.GetMusicTempo()} / ${sm.GetMusicSpeed()}`;
$('pos').value = String(pos);
if(view === 'patterns') renderPatternsView(sm, loadedToken);
else renderSamplesView(sm, loadedToken);
};
rafId = requestAnimationFrame(tick);
}