Repository navigation
Expand file tree
/
Copy pathbeat-map-grid.html
More file actions
516 lines (468 loc) · 21.2 KB
/
Copy pathbeat-map-grid.html
File metadata and controls
516 lines (468 loc) · 21.2 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
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>dawcore — beat map grid</title>
<style>
body {
font-family: system-ui, sans-serif;
background: #0f0f1a;
color: #e0d4c8;
padding: 24px;
}
h1 { font-size: 1.2rem; margin-bottom: 8px; }
p.desc { font-size: 0.85rem; color: #888; margin-bottom: 16px; line-height: 1.5; }
p.desc a { color: #63C75F; }
p.desc code { background: #1a1a2e; padding: 1px 5px; border-radius: 3px; font-size: 0.8rem; }
daw-editor {
--daw-wave-color: #c49a6c;
--daw-playhead-color: #d08070;
--daw-background: #1a1a2e;
--daw-track-background: #16213e;
--daw-ruler-color: #c49a6c;
--daw-ruler-background: #0f0f1a;
--daw-selection-color: rgba(99, 199, 95, 0.3);
--daw-grid-odd: rgba(255, 255, 255, 0.03);
--daw-grid-even: rgba(255, 255, 255, 0.06);
--daw-grid-line-color: rgba(255, 255, 255, 0.1);
margin-bottom: 12px;
}
.toolbar {
display: flex; gap: 8px; align-items: stretch;
margin-bottom: 12px; height: 28px;
}
.toolbar button, .toolbar select {
cursor: pointer; background: #1a1a2e; color: #e0d4c8;
border: 1px solid currentColor; padding: 0 10px; font: inherit; line-height: 1;
}
.toolbar select { padding: 0 6px; }
.toolbar .separator { width: 1px; background: rgba(255, 255, 255, 0.15); }
.toolbar .label {
font-family: 'Courier New', monospace; font-size: 0.75rem;
color: #888; display: flex; align-items: center;
}
.drop-zone {
border: 2px dashed #444; border-radius: 8px; padding: 24px;
text-align: center; margin-bottom: 16px;
transition: border-color 0.15s, background 0.15s;
}
.drop-zone.drag-over { border-color: #63C75F; background: rgba(99, 199, 95, 0.05); }
.drop-zone.loaded { border-color: #63C75F; border-style: solid; }
.drop-zone p { margin: 4px 0; font-size: 0.85rem; color: #888; }
.drop-zone .filename { color: #c49a6c; font-family: 'Courier New', monospace; font-size: 0.8rem; }
.drop-zone .or { color: #555; font-size: 0.8rem; margin: 8px 0; }
.file-input { display: none; }
.file-label { display: inline-block; cursor: pointer; color: #63C75F; font-size: 0.85rem; text-decoration: underline; }
.drop-zones { display: flex; gap: 16px; }
.drop-zones .drop-zone { flex: 1; }
.hidden { display: none; }
.tempo-display {
font-family: 'Courier New', monospace; font-size: 1.4rem;
color: #c49a6c; display: inline-block;
}
.tempo-display span { font-size: 0.75rem; color: #888; }
.info {
font-family: 'Courier New', monospace; font-size: 0.8rem;
color: #888; margin: 4px 0;
}
#log {
margin-top: 12px; font-family: monospace; font-size: 0.75rem;
color: #888; max-height: 120px; overflow-y: auto;
}
input[type="range"] { width: 120px; accent-color: #63C75F; }
.status-bar {
display: flex; gap: 16px; align-items: center; margin-bottom: 12px;
}
</style>
</head>
<body>
<h1>beat map grid</h1>
<p class="desc">
Drop an audio file and its <a href="https://github.com/CPJKU/beat_this">Beat This!</a> beat map
into a full dawcore editor with variable tempo grid. Generate beat maps with:<br>
<code>pipx install git+https://github.com/CPJKU/beat_this.git</code><br>
<code>pipx inject beat_this torchcodec</code> (for non-wav formats)<br>
<code>beat_this your_song.mp3</code>
</p>
<div class="drop-zones">
<div class="drop-zone" id="audio-drop">
<p>Drop audio file here</p>
<p class="or">or</p>
<label class="file-label" for="audio-input">choose file</label>
<input class="file-input" type="file" id="audio-input" accept="audio/*" />
<p class="filename" id="audio-name"></p>
</div>
<div class="drop-zone" id="beats-drop">
<p>Drop <code>.beats</code> file here</p>
<p class="or">or</p>
<label class="file-label" for="beats-input">choose file</label>
<input class="file-input" type="file" id="beats-input" accept=".beats,.txt" />
<p class="filename" id="beats-name"></p>
</div>
</div>
<script type="module">import '@dawcore/components';</script>
<daw-editor id="editor" scale-mode="beats" ticks-per-pixel="24" bpm="120" snap-to="beat"
samples-per-pixel="1024" wave-height="80" timescale file-drop clip-headers interactive-clips>
<daw-grid></daw-grid>
<daw-keyboard-shortcuts playback splitting undo></daw-keyboard-shortcuts>
</daw-editor>
<div class="toolbar">
<daw-transport for="editor" style="display:contents;">
<daw-play-button></daw-play-button>
<daw-pause-button></daw-pause-button>
<daw-stop-button></daw-stop-button>
</daw-transport>
<span class="separator"></span>
<button id="zoom-in">+</button>
<button id="zoom-out">−</button>
<span id="zoom-level" class="label">24 tpp</span>
<span class="separator"></span>
<label class="label" for="snap-select">Snap</label>
<select id="snap-select">
<option value="off">Off</option>
<option value="bar">Bar</option>
<option value="beat" selected>Beat</option>
<option value="1/2">1/2</option>
<option value="1/4">1/4</option>
<option value="1/8">1/8</option>
<option value="1/16">1/16</option>
<option value="1/32">1/32</option>
<option value="1/4T">1/4T</option>
<option value="1/8T">1/8T</option>
<option value="1/16T">1/16T</option>
</select>
<span class="separator"></span>
<label class="label">Metro</label>
<input type="range" id="metro-vol" min="0" max="100" value="50" />
</div>
<div id="status-section" class="hidden">
<div class="status-bar">
<div class="tempo-display" id="tempo-display">-- <span>BPM</span></div>
<div class="info" id="position"></div>
</div>
<div class="info" id="stats"></div>
</div>
<div id="log"></div>
<script type="module">
import { detectMeterChanges } from '@waveform-playlist/core';
import { NativePlayoutAdapter } from '@dawcore/transport';
const editor = document.getElementById('editor');
const audioCtx = new AudioContext({ sampleRate: 48000, latencyHint: 0 });
const adapter = new NativePlayoutAdapter(audioCtx);
editor.adapter = adapter;
// Build engine eagerly so adapter.transport is available before tracks load.
// This gives us a single transport for metronome, tempo, and clip scheduling.
await editor.ready();
const transport = adapter.transport;
transport.setMetronomeEnabled(true);
// Click buffer helper for metronome volume control
function createClickBuffer(frequency, duration, gain) {
const length = Math.floor(audioCtx.sampleRate * duration);
const buffer = audioCtx.createBuffer(1, length, audioCtx.sampleRate);
const data = buffer.getChannelData(0);
for (let i = 0; i < length; i++) {
const t = i / audioCtx.sampleRate;
const envelope = Math.exp(-t * 40);
data[i] = Math.sin(2 * Math.PI * frequency * t) * envelope * gain;
}
return buffer;
}
// State
let pendingAudioFile = null;
let pendingBeatsText = null;
let isPlaying = false;
// UI elements
const tempoDisplay = document.getElementById('tempo-display');
const positionEl = document.getElementById('position');
const statsEl = document.getElementById('stats');
const statusSection = document.getElementById('status-section');
const logEl = document.getElementById('log');
function addLog(msg) {
const line = document.createElement('div');
line.textContent = new Date().toLocaleTimeString() + ' ' + msg;
logEl.prepend(line);
while (logEl.children.length > 20) logEl.lastChild.remove();
}
// --- Drop zones ---
function setupDropZone(zoneId, onFile) {
const zone = document.getElementById(zoneId);
zone.addEventListener('dragover', (e) => { e.preventDefault(); zone.classList.add('drag-over'); });
zone.addEventListener('dragleave', () => zone.classList.remove('drag-over'));
zone.addEventListener('drop', (e) => {
e.preventDefault();
zone.classList.remove('drag-over');
const file = e.dataTransfer.files[0];
if (file) onFile(file);
});
}
function handleAudioFile(file) {
pendingAudioFile = file;
document.getElementById('audio-name').textContent = file.name;
document.getElementById('audio-drop').classList.add('loaded');
addLog('audio: ' + file.name + ' (' + (file.size / 1024 / 1024).toFixed(1) + ' MB)');
tryLoad();
}
function handleBeatsFile(file) {
const reader = new FileReader();
reader.onload = () => {
pendingBeatsText = reader.result;
document.getElementById('beats-name').textContent = file.name;
document.getElementById('beats-drop').classList.add('loaded');
addLog('beats: ' + file.name);
tryLoad();
};
reader.readAsText(file);
}
setupDropZone('audio-drop', handleAudioFile);
setupDropZone('beats-drop', handleBeatsFile);
document.getElementById('audio-input').addEventListener('change', (e) => {
if (e.target.files[0]) handleAudioFile(e.target.files[0]);
});
document.getElementById('beats-input').addEventListener('change', (e) => {
if (e.target.files[0]) handleBeatsFile(e.target.files[0]);
});
// --- Parse beats ---
function parseBeats(text) {
const parsed = text.trim().split('\n').map(line => {
const parts = line.trim().split(/\s+/);
return { time: parseFloat(parts[0]), beat: parseInt(parts[1]) };
}).filter(b => !isNaN(b.time) && !isNaN(b.beat));
parsed.sort((a, b) => a.time - b.time);
// Drop near-duplicate detections: a zero interval means an infinite
// per-beat BPM, which TempoMap rejects. 50ms = 1200 BPM ceiling.
const MIN_BEAT_INTERVAL = 0.05;
const beats = [];
for (const b of parsed) {
if (beats.length === 0 || b.time - beats[beats.length - 1].time >= MIN_BEAT_INTERVAL) {
beats.push(b);
}
}
return beats;
}
// --- Build tempo curve ---
// Single-clock: tick 0 = audio time 0 (start of file).
// First downbeat (beat === 1) lands on the first bar boundary with room
// for the intro audio and any pickup beats before it (e.g. bar 2 beat 1
// for a 4/4 song with a short intro). Empty lead-in bars run at the
// first segment's tempo so ticksToSeconds maps to correct audio times.
function buildTempoCurve(beats) {
const ppqn = 960;
const ticksPerBeat = ppqn;
const firstDownbeatIdx = beats.findIndex(b => b.beat === 1);
if (firstDownbeatIdx < 0) throw new Error('No downbeat (beat 1) found in beat map');
const pickupBeats = firstDownbeatIdx;
// Lead-in bar length follows the FIRST declared bar's meter (the
// distance between the first two downbeats), falling back to 4/4 —
// the warp-markers gridPlanFromBeats convention. Hardcoding 4/4 here
// while the grid uses the detected meter pushed a 2/4 song's first
// downbeat to bar 3 (two 2/4 bars fit in one 4/4 lead-in bar).
const secondDownbeatIdx = beats.findIndex(
(b, i) => i > firstDownbeatIdx && b.beat === 1
);
const leadMeter =
secondDownbeatIdx > firstDownbeatIdx ? secondDownbeatIdx - firstDownbeatIdx : 4;
const ticksPerBar = leadMeter * ticksPerBeat;
// BPM from first full beat interval (at the downbeat)
let beatBpm = 120;
if (firstDownbeatIdx < beats.length - 1) {
const interval = beats[firstDownbeatIdx + 1].time - beats[firstDownbeatIdx].time;
if (interval > 0.1) beatBpm = 60 / interval;
}
// Use beatBpm uniformly from tick 0 — no gap BPM needed.
// Compute where beat 1 naturally falls at beatBpm, then round up
// to the next bar boundary for the downbeat.
const naturalFirstBeatTick = Math.round(
(beats[0].time * ppqn * beatBpm) / 60
);
const firstDownbeatBar = Math.max(1, Math.ceil(
(naturalFirstBeatTick + pickupBeats * ticksPerBeat) / ticksPerBar
));
const firstDownbeatTick = firstDownbeatBar * ticksPerBar;
// Clip starts at the tick where the audio begins — shifted so that
// beat 1 in the audio lines up with the bar boundary.
const firstBeatTick = firstDownbeatTick - pickupBeats * ticksPerBeat;
const clipStartTick = Math.max(0, firstBeatTick - naturalFirstBeatTick);
// Build tempo events — beatBpm from tick 0, per-beat BPMs from first beat
const tempoEvents = [{ tick: 0, bpm: beatBpm }];
let currentTick = firstBeatTick;
for (let i = 0; i < beats.length - 1; i++) {
const interval = beats[i + 1].time - beats[i].time;
// Defensive: parseBeats dedupes, but a non-positive interval would
// make TempoMap.setTempo throw. Carry the previous tempo instead.
if (interval > 0) {
tempoEvents.push({ tick: currentTick, bpm: 60 / interval });
}
currentTick += ticksPerBeat;
}
const bpms = tempoEvents.map(e => e.bpm).filter(b => b > 30 && b < 300);
bpms.sort((a, b) => a - b);
const medianBpm = bpms.length > 0 ? bpms[Math.floor(bpms.length / 2)] : beatBpm;
const meterChanges = detectMeterChanges(beats, firstBeatTick, ppqn);
return { medianBpm, tempoEvents, totalBeats: beats.length, firstBeatTick, clipStartTick, meterChanges };
}
// --- Apply tempo curve ---
// Single transport: editor.transport handles metronome, tempo, and clips.
let lastCurve = null;
function applyTempoCurve(curve) {
lastCurve = curve;
transport.stop();
// Display BPM for the readout. First run: the callbacks aren't assigned
// yet, so this forwards and writes tick 0 — harmless, the clearTempos()
// + explicit tick-0 event below overwrite it. Repeat runs: the callbacks
// (assigned below) make editor.bpm display-only, and the transport's
// #407 guard refuses defaulted tick-0 writes on multi-entry maps anyway.
// No ordering of these statements can corrupt the final tick-0 entry.
editor.bpm = Math.round(curve.medianBpm);
transport.clearTempos();
transport.clearMeters();
transport.setMeter(4, 4);
for (const event of curve.tempoEvents) {
transport.setTempo(event.bpm, event.tick);
}
for (const meter of curve.meterChanges) {
transport.setMeter(meter.numerator, meter.denominator, meter.tick);
}
editor.secondsToTicks = (s) => transport.timeToTick(s);
editor.ticksToSeconds = (t) => transport.tickToTime(t);
editor.meterEntries = curve.meterChanges;
}
// --- Handle loading independently or together ---
let beatsApplied = false;
// Reposition every loaded clip so beat 1 in the audio lands on the
// curve's bar boundary. Needed in BOTH drop orders: beats-then-audio
// (after loadFiles) and audio-then-beats (clip sits at tick 0 until
// the curve arrives).
function repositionClips(curve) {
if (!editor.engine) return false;
const state = editor.engine.getState();
if (state.tracks.length === 0) return false;
const sr = editor.effectiveSampleRate;
const clipStartSec = transport.tickToTime(curve.clipStartTick);
const clipStartSample = Math.round(clipStartSec * sr);
const tracks = state.tracks.map(t => ({
...t,
clips: t.clips.map(c => ({
...c,
startTick: curve.clipStartTick,
startSample: clipStartSample,
})),
}));
editor.engine.setTracks(tracks);
return true;
}
async function tryLoad() {
// Beats only (no pending audio): apply the tempo curve. If a track is
// already loaded (audio was dropped first), realign its clips too.
if (pendingBeatsText && !pendingAudioFile) {
addLog('applying beat map...');
const beats = parseBeats(pendingBeatsText);
const curve = buildTempoCurve(beats);
applyTempoCurve(curve);
beatsApplied = true;
pendingBeatsText = null;
statsEl.textContent = beats.length + ' beats · median ~' +
Math.round(curve.medianBpm) + ' BPM';
statusSection.classList.remove('hidden');
const repositioned = repositionClips(curve);
addLog('ready: ' + curve.tempoEvents.length + ' tempo events' +
(repositioned ? ' (clips realigned)' : ' (drop audio to add track)'));
return;
}
// Audio dropped (with or without beats already applied)
if (pendingAudioFile) {
// Apply beats if not yet applied
if (pendingBeatsText && !beatsApplied) {
addLog('processing beats + audio...');
const beats = parseBeats(pendingBeatsText);
const curve = buildTempoCurve(beats);
applyTempoCurve(curve);
beatsApplied = true;
statsEl.textContent = beats.length + ' beats · median ~' +
Math.round(curve.medianBpm) + ' BPM';
statusSection.classList.remove('hidden');
}
// Load audio
const result = await editor.loadFiles([pendingAudioFile]);
if (result.loaded.length > 0) addLog('track: ' + result.loaded[0]);
if (beatsApplied && lastCurve) {
repositionClips(lastCurve);
addLog('meters: ' + lastCurve.meterChanges.map(m => m.numerator + '/' + m.denominator + ' @tick ' + m.tick).join(', '));
} else {
addLog('audio loaded — single BPM (drop .beats to add variable tempo)');
}
pendingAudioFile = null;
pendingBeatsText = null;
return;
}
}
// --- Zoom controls ---
const tppLevels = [8, 12, 16, 24, 32, 48, 64, 96, 128];
const zoomLabel = document.getElementById('zoom-level');
function updateZoomLabel() { zoomLabel.textContent = editor.ticksPerPixel + ' tpp'; }
document.getElementById('zoom-in').addEventListener('click', () => {
const idx = tppLevels.indexOf(editor.ticksPerPixel);
if (idx > 0) { editor.ticksPerPixel = tppLevels[idx - 1]; updateZoomLabel(); }
});
document.getElementById('zoom-out').addEventListener('click', () => {
const idx = tppLevels.indexOf(editor.ticksPerPixel);
if (idx < tppLevels.length - 1) { editor.ticksPerPixel = tppLevels[idx + 1]; updateZoomLabel(); }
});
// Snap control
document.getElementById('snap-select').addEventListener('change', (e) => {
editor.snapTo = e.target.value;
addLog('snap: ' + e.target.value);
});
// Metronome volume
const metroVolEl = document.getElementById('metro-vol');
function applyMetroVolume(vol) {
const accent = createClickBuffer(1200, 0.05, 0.8 * vol);
const normal = createClickBuffer(800, 0.04, 0.5 * vol);
transport.setMetronomeClickSounds(accent, normal);
}
metroVolEl.addEventListener('input', (e) => applyMetroVolume(e.target.value / 100));
applyMetroVolume(metroVolEl.value / 100);
// --- Track playback state for the tempo/position display ---
// No custom playhead wiring: daw-editor animates the playhead itself
// through the secondsToTicks/ticksToSeconds callbacks set above, with
// output-latency compensation (engine.getAudibleTime). Re-driving it
// from raw transport.getCurrentTime() would undo that compensation.
editor.addEventListener('daw-play', () => {
isPlaying = true;
});
editor.addEventListener('daw-pause', () => {
isPlaying = false;
});
editor.addEventListener('daw-stop', () => {
isPlaying = false;
});
// --- Editor events ---
editor.addEventListener('daw-seek', (e) => addLog('seek: ' + e.detail.time.toFixed(3) + 's'));
editor.addEventListener('daw-track-select', (e) => addLog('track-select: ' + e.detail.trackId));
editor.addEventListener('daw-selection', (e) => addLog('selection: ' + e.detail.start.toFixed(3) + ' - ' + e.detail.end.toFixed(3)));
editor.addEventListener('daw-clip-move', (e) => addLog('clip-move: ' + e.detail.clipId + ' delta=' + e.detail.deltaSamples));
editor.addEventListener('daw-clip-trim', (e) => addLog('clip-trim: ' + e.detail.clipId + ' ' + e.detail.boundary + ' delta=' + e.detail.deltaSamples));
editor.addEventListener('daw-clip-split', (e) => addLog('clip-split: ' + e.detail.originalClipId + ' → ' + e.detail.leftClipId + ' + ' + e.detail.rightClipId));
// --- Animation loop for tempo/position display ---
function tick() {
if (isPlaying && beatsApplied) {
const time = transport.getCurrentTime();
const currentTick = transport.timeToTick(time);
const bar = transport.tickToBar(currentTick);
const barStartTick = transport.barToTick(bar);
const tickIntoBar = currentTick - barStartTick;
const currentBeat = Math.floor(tickIntoBar / 960);
const bpm = transport.getTempo(currentTick);
positionEl.textContent = 'Bar ' + bar + ' · Beat ' + (currentBeat + 1);
tempoDisplay.textContent = '';
tempoDisplay.appendChild(document.createTextNode(Math.round(bpm) + ' '));
const span = document.createElement('span');
span.textContent = 'BPM';
tempoDisplay.appendChild(span);
}
requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
</script>
</body>
</html>