// SPDX-License-Identifier: GPL-3.0-only // Copyright (C) 2026 Juan Ignacio Antonucci (Juan Jiant) // JIANT Studio's audio editor: takes and audio files as clips on tracks, edited in the browser and mixed down. A clip is // a window on a buffer (start on the timeline, offset into its buffer, length), with its gain, fades and direction; the // buffers are never changed, so every edit can be undone. Moves and trims snap to a grid (a sixteenth at the BPM, or // off). Playback: one AudioBufferSource per clip, its gain ramped for the fades; the mix and each track rendered offline // to WAV. No DOM outside the element it is given; studio.js feeds it takes and files and gives it its words. // const ed = new AudioEditor(root, words, { wav, zip }); // ed.addTake({ name, rate, planes, lanes: [{ name, color, pan }] }); ed.addFile(file) const DB = (g) => Math.pow(10, g / 20); export class AudioEditor { constructor(root, L, lib) { this.root = root; this.L = L; this.lib = lib; this.tracks = []; this.sel = null; this.pps = 60; this.bpm = 120; this.snap = true; this.ph = 0; this.loop = { on: false, a: 0, b: 0 }; this.auto = false; this.mixOpen = false; this.undoS = []; this.redoS = []; this.ac = null; this.srcs = []; this.playing = false; this.t0 = 0; this.raf = 0; this.peaks = new Map(); this.build(); } /* ---- the model */ get dur() { let d = 4; for (const t of this.tracks) for (const c of t.clips) d = Math.max(d, c.start + c.len); return d; } snapT(x) { if (!this.snap) return Math.max(0, x); const g = 60 / this.bpm / 4; return Math.max(0, Math.round(x / g) * g); } snapshot() { return JSON.stringify(this.tracks.map((t) => ({ ...t, clips: t.clips.map((c) => ({ ...c, buf: c.buf ? c.buf.id : null })) }))); } bufs() { const m = new Map(); for (const t of this.tracks) for (const c of t.clips) if (c.buf) m.set(c.buf.id, c.buf); return m; } push() { this.undoS.push({ s: this.snapshot(), b: this.bufs() }); if (this.undoS.length > 80) this.undoS.shift(); this.redoS = []; } restore(x) { const b = x.b; this.tracks = JSON.parse(x.s).map((t) => ({ ...t, clips: t.clips.map((c) => ({ ...c, buf: c.buf ? b.get(c.buf) : null })) })); this.sel = null; this.draw(); } undo() { if (!this.undoS.length) return; this.redoS.push({ s: this.snapshot(), b: this.bufs() }); this.restore(this.undoS.pop()); this.say(this.L.undone); } redo() { if (!this.redoS.length) return; this.undoS.push({ s: this.snapshot(), b: this.bufs() }); this.restore(this.redoS.pop()); } buffer(planes, rate, name) { return { id: Math.random().toString(36).slice(2), planes, rate, name, secs: planes[0].length / rate }; } addTake(tk, start = 0) { this.push(); const lanes = tk.lanes && tk.lanes.length === tk.planes.length ? tk.lanes : null; if (!lanes || tk.planes.length <= 2) { const b = this.buffer(tk.planes.slice(0, 2), tk.rate, tk.name); this.tracks.push({ name: tk.name.replace(/^JIANT-/, "").slice(0, 22), color: "#a77bff", vol: 0, pan: 0, mute: false, solo: false, clips: [this.clip(b, start)] }); } else tk.planes.forEach((p, i) => { if (!p.some((v) => Math.abs(v) > 1e-4)) return; // a silent stem: no track const b = this.buffer([p], tk.rate, `${tk.name} ${lanes[i].name}`); this.tracks.push({ name: lanes[i].name, color: lanes[i].color || "#a77bff", vol: 0, pan: lanes[i].pan || 0, mute: false, solo: false, clips: [this.clip(b, start)] }); }); this.fitZoom(); this.draw(); this.say(this.L.added.replace("%s", tk.name)); } async addFile(f) { const ac = this.ctx(), ab = await ac.decodeAudioData(await f.arrayBuffer()); const planes = Array.from({ length: Math.min(2, ab.numberOfChannels) }, (_, k) => ab.getChannelData(k).slice()); this.push(); this.tracks.push({ name: f.name.replace(/\.[^.]+$/, "").slice(0, 22), color: "#ff8a1f", vol: 0, pan: 0, mute: false, solo: false, clips: [this.clip(this.buffer(planes, ab.sampleRate, f.name), this.ph)] }); this.fitZoom(); this.draw(); this.say(this.L.added.replace("%s", f.name)); } /* a take's MIDI (events: {t ms, data}) as a MIDI track: its notes paired on and off, heard with a small synth */ addMidi(name, events, start = 0) { const on = new Map(), notes = []; for (const e of [...events].sort((a, b) => a.t - b.t)) { const st = e.data[0] & 0xF0, k = (e.data[0] & 15) * 128 + e.data[1]; if (st === 0x90 && e.data[2]) on.set(k, { t: e.t / 1000, n: e.data[1], v: e.data[2], ch: e.data[0] & 15 }); else if ((st === 0x80 || st === 0x90) && on.has(k)) { const o = on.get(k); on.delete(k); notes.push({ ...o, d: Math.max(0.02, e.t / 1000 - o.t) }); } } for (const o of on.values()) notes.push({ ...o, d: 0.25 }); if (!notes.length) return; const len = Math.max(...notes.map((x) => x.t + x.d)) + 0.05; this.push(); this.tracks.push({ name: "MIDI", color: "#5ee6a0", vol: -6, pan: 0, mute: false, solo: false, midi: true, clips: [{ midi: true, notes, start, off: 0, len, gain: 0, fin: 0, fout: 0, rev: false, name: "MIDI" }] }); this.fitZoom(); this.draw(); this.say(this.L.added.replace("%s", `MIDI (${notes.length})`)); } clip(buf, start) { return { buf, start, off: 0, len: buf.secs, gain: 0, fin: 0, fout: 0, rev: false }; } selClip() { const s = this.sel; return s ? this.tracks[s.t] && this.tracks[s.t].clips[s.c] : null; } /* ---- the edits (each one undoable) */ edit(f, audioOnly) { const c = this.selClip(); if (!c) { this.say(this.L.pick); return; } if (audioOnly && c.midi) { this.say(this.L.midiNo); return; } this.push(); f(c, this.tracks[this.sel.t]); this.draw(); } split() { this.edit((c, t) => { const at = this.ph - c.start; if (at <= 0.01 || at >= c.len - 0.01) { this.undoS.pop(); this.say(this.L.splitHere); return; } const b = { ...c, start: this.ph, off: c.rev ? c.off : c.off + at, len: c.len - at, fin: 0 }; if (c.rev) c.off = c.off + (c.len - at); if (c.midi) { b.notes = c.notes.filter((n) => n.t >= c.off + at).map((n) => ({ ...n })); b.off = c.off + at; c.notes = c.notes.filter((n) => n.t < c.off + at); } c.len = at; c.fout = 0; t.clips.splice(this.sel.c + 1, 0, b); }); } del() { this.edit((c, t) => { t.clips.splice(this.sel.c, 1); this.sel = null; }); } dup() { this.edit((c, t) => { t.clips.push({ ...c, notes: c.notes ? c.notes.map((n) => ({ ...n })) : undefined, start: this.snapT(c.start + c.len) }); this.sel = { t: this.sel.t, c: t.clips.length - 1 }; }); } reverse() { this.edit((c) => { c.rev = !c.rev; }, true); } normalize() { this.edit((c) => { let pk = 0; const r = c.buf.rate, a = Math.floor(c.off * r), n = Math.floor(c.len * r); for (const p of c.buf.planes) for (let i = a; i < a + n && i < p.length; i++) pk = Math.max(pk, Math.abs(p[i])); if (pk > 1e-6) c.gain = Math.round(20 * Math.log10(0.966 / pk) * 10) / 10; }, true); } set(k, v) { this.edit((c) => { c[k] = v; }); } /* ---- the view */ build() { const h = (tag, cls, txt) => { const e = document.createElement(tag); if (cls) e.className = cls; if (txt != null) e.textContent = txt; return e; }; this.h = h; this.root.replaceChildren(); this.root.classList.add("aed"); const tools = h("div", "aedtools"), L = this.L; const B = (txt, f, k) => { const b = h("button", "aedbtn", txt); b.type = "button"; b.onclick = f; if (k) b.title = k; tools.append(b); return b; }; this.recB = B("●", () => this.lib.record && this.lib.record(this), "R"); this.recB.classList.add("aedrec"); this.playB = B("▶", () => (this.playing ? this.stop() : this.play()), "Espacio"); B("■", () => { this.stop(); this.ph = 0; this.draw(); }); B("✂ " + L.split, () => this.split(), "S"); B(L.dup, () => this.dup(), "D"); B(L.rev, () => this.reverse()); B(L.norm, () => this.normalize()); B("⌫ " + L.del, () => this.del(), "Supr"); B("↶", () => this.undo(), "Ctrl+Z"); B("↷", () => this.redo(), "Ctrl+Shift+Z"); B("−", () => { this.pps = Math.max(8, this.pps / 1.5); this.draw(); }); B("+", () => { this.pps = Math.min(600, this.pps * 1.5); this.draw(); }); const loopB = B(L.loop, () => { const l = this.loop; if (!(l.b > l.a)) { const c = this.selClip(); const bar = 240 / this.bpm; Object.assign(l, c ? { a: c.start, b: c.start + c.len } : { a: 0, b: bar * 4 }); } l.on = !l.on; loopB.setAttribute("aria-pressed", String(l.on)); this.draw(); }, "L"); loopB.setAttribute("aria-pressed", "false"); this.loopB = loopB; const autoB = B(L.auto, () => { this.auto = !this.auto; autoB.setAttribute("aria-pressed", String(this.auto)); this.root.classList.toggle("automode", this.auto); this.draw(); this.say(this.auto ? L.autoHelp : ""); }); autoB.setAttribute("aria-pressed", "false"); const mixB = B(L.mixer, () => { this.mixOpen = !this.mixOpen; mixB.setAttribute("aria-pressed", String(this.mixOpen)); this.drawMixer(); }); mixB.setAttribute("aria-pressed", "false"); this.met = false; const met = B(L.met, () => { this.met = !this.met; met.setAttribute("aria-pressed", String(this.met)); }); met.setAttribute("aria-pressed", "false"); const snap = B(L.snap + ": 1/16", () => { this.snap = !this.snap; snap.textContent = `${L.snap}: ${this.snap ? "1/16" : "—"}`; }); const bpm = h("input"); bpm.type = "number"; bpm.min = 40; bpm.max = 240; bpm.value = this.bpm; bpm.className = "aedbpm"; bpm.setAttribute("aria-label", "BPM"); bpm.onchange = () => { this.bpm = Math.max(40, Math.min(240, +bpm.value || 120)); this.draw(); }; tools.append(bpm, h("span", "aeddim", "BPM")); this.scroll = h("div", "aedscroll"); this.grid = h("div", "aedgrid"); this.scroll.append(this.grid); this.mixer = h("div", "aedmixer"); this.mixer.hidden = true; this.insp = h("div", "aedinsp"); this.status = h("p", "aedstat"); this.foot = h("div", "aedfoot"); this.clock = h("b", "aedclock", "00:00.0"); this.bars = h("span", "aedbars", "1.1.1"); const ex = (txt, f) => { const b = h("button", "btn", txt); b.type = "button"; b.onclick = f; return b; }; const clk = h("div", "aedclk"); clk.append(this.bars, this.clock); this.foot.append(clk, ex(L.expMix, () => this.exportMix()), ex(L.expTracks, () => this.exportTracks()), ex(L.expMidi, () => this.exportMidi())); this.empty = h("p", "aeddim aedempty", L.empty); this.root.append(tools, this.empty, this.scroll, this.mixer, this.insp, this.foot, this.status); this.root.tabIndex = 0; this.root.addEventListener("keydown", (e) => { if (e.target.tagName === "INPUT") return; const k = e.key.toLowerCase(); if (k === " ") { e.preventDefault(); this.playing ? this.stop() : this.play(); } else if (k === "r") this.lib.record && this.lib.record(this); else if (k === "l") this.loopB.click(); else if (k === "s") this.split(); else if (k === "d") this.dup(); else if (k === "delete" || k === "backspace") { e.preventDefault(); this.del(); } else if (k === "z" && (e.ctrlKey || e.metaKey)) { e.preventDefault(); e.shiftKey ? this.redo() : this.undo(); } }); new ResizeObserver(() => this.draw()).observe(this.scroll); this.draw(); } fitZoom() { const w = (this.scroll.clientWidth || 600) - 120; this.pps = Math.max(8, Math.min(200, w / (this.dur + 1))); } say(s) { this.status.textContent = s; } peaksOf(buf) { if (this.peaks.has(buf.id)) return this.peaks.get(buf.id); const p = buf.planes[0], q = buf.planes[1] || p, step = Math.max(1, Math.floor(buf.rate / 400)), n = Math.ceil(p.length / step), out = new Float32Array(n); for (let i = 0; i < n; i++) { let m = 0; for (let j = i * step, e = Math.min(p.length, j + step); j < e; j++) m = Math.max(m, Math.abs(p[j]), Math.abs(q[j])); out[i] = m; } this.peaks.set(buf.id, { out, per: step / buf.rate }); return this.peaks.get(buf.id); } draw() { if (!this.grid) return; const h = this.h, HEAD = 110, W = Math.max(this.scroll.clientWidth - HEAD, (this.dur + 2) * this.pps), beat = 60 / this.bpm; this.empty.hidden = !!this.tracks.length; this.scroll.hidden = !this.tracks.length; this.insp.hidden = this.foot.hidden = !this.tracks.length; this.grid.style.width = `${HEAD + W}px`; this.grid.replaceChildren(); const ruler = h("div", "aedruler"); ruler.style.width = `${W}px`; ruler.style.marginLeft = `${HEAD}px`; const barW = beat * 4 * this.pps, every = barW < 40 ? Math.ceil(40 / barW) : 1; for (let b = 0; b * beat * 4 < this.dur + 2; b += every) { const m = h("span", null, String(b + 1)); m.style.left = `${b * beat * 4 * this.pps}px`; ruler.append(m); } ruler.onpointerdown = (e) => { // a click: the position; a drag: the loop's region const r = ruler.getBoundingClientRect(), x0 = e.clientX, at = (x) => this.snapT((x - r.left) / this.pps); let moved = false; const mv = (ev) => { if (Math.abs(ev.clientX - x0) < 5) return; moved = true; const a = at(x0), b = at(ev.clientX); Object.assign(this.loop, { a: Math.min(a, b), b: Math.max(a, b), on: true }); this.loopB.setAttribute("aria-pressed", "true"); this.drawLoop(); }; const up = (ev) => { removeEventListener("pointermove", mv); removeEventListener("pointerup", up); if (!moved) { this.ph = at(ev.clientX); if (this.playing) { this.stop(); this.play(); } } this.draw(); }; addEventListener("pointermove", mv); addEventListener("pointerup", up); }; this.grid.append(ruler); const solo = this.tracks.some((t) => t.solo); this.tracks.forEach((t, ti) => { const row = h("div", "aedrow"), head = h("div", "aedhead"), lane = h("div", "aedlane"); head.style.setProperty("--c", t.color); const nm = h("b", null, t.name), ms = h("div", "aedms"), M = h("button", null, "M"), S = h("button", null, "S"), vol = h("input"); M.type = S.type = "button"; M.setAttribute("aria-pressed", String(t.mute)); S.setAttribute("aria-pressed", String(t.solo)); M.onclick = () => { t.mute = !t.mute; this.draw(); this.remix(); }; S.onclick = () => { t.solo = !t.solo; this.draw(); this.remix(); }; vol.type = "range"; vol.min = -30; vol.max = 6; vol.step = 0.5; vol.value = t.vol; vol.setAttribute("aria-label", `${t.name} dB`); vol.oninput = () => { t.vol = +vol.value; this.remix(); }; ms.append(M, S); head.append(nm, ms, vol); lane.style.width = `${W}px`; if (t.mute || (solo && !t.solo)) row.classList.add("off"); for (let b = 0; b * beat < this.dur + 2; b++) { const g = h("i", b % 4 ? "beat" : "bar"); g.style.left = `${b * beat * this.pps}px`; lane.append(g); } t.clips.forEach((c, ci) => lane.append(this.clipEl(t, ti, c, ci))); lane.onpointerdown = (e) => { const r = lane.getBoundingClientRect(); if (this.auto) { this.autoAdd(t, (e.clientX - r.left) / this.pps, (e.clientY - r.top) / r.height); return; } if (e.target !== lane) return; this.sel = null; this.ph = this.snapT((e.clientX - r.left) / this.pps); this.draw(); }; if (t.auto && t.auto.length || this.auto) lane.append(this.autoSvg(t, W)); row.append(head, lane); this.grid.append(row); }); this.loopEl = h("div", "aedloop"); this.grid.append(this.loopEl); this.drawLoop(); this.phEl = h("div", "aedph"); this.phEl.style.left = `${HEAD + this.ph * this.pps}px`; this.grid.append(this.phEl); this.clockSet(this.ph); this.drawInsp(); if (this.mixOpen) this.drawMixer(); } drawLoop() { const l = this.loop, e = this.loopEl; if (!e) return; e.hidden = !(l.on && l.b > l.a); e.style.left = `${110 + l.a * this.pps}px`; e.style.width = `${(l.b - l.a) * this.pps}px`; } /* ---- volume automation: points {t, db} on a track, a line over its lane; in AUTO a tap adds one, a drag moves it, a double tap removes it; played as a ramp under the track's level */ autoY(db, H) { return (1 - (db + 30) / 36) * H; } autoAt(t, x) { const a = t.auto; if (!a || !a.length) return 0; if (x <= a[0].t) return a[0].db; for (let i = 1; i < a.length; i++) if (x <= a[i].t) { const p = a[i - 1], q = a[i]; return p.db + (q.db - p.db) * (x - p.t) / (q.t - p.t || 1); } return a[a.length - 1].db; } autoAdd(t, x, fy) { this.push(); t.auto = (t.auto || []).concat({ t: Math.max(0, x), db: Math.round((6 - fy * 36) * 2) / 2 }).sort((a, b) => a.t - b.t); t.auto.forEach((p) => { p.db = Math.max(-30, Math.min(6, p.db)); }); this.draw(); } autoSvg(t, W) { const NS = "http://www.w3.org/2000/svg", H = 72, svg = document.createElementNS(NS, "svg"), a = t.auto || []; svg.setAttribute("class", "aedauto"); svg.setAttribute("width", W); svg.setAttribute("height", H); const pts = a.length ? [{ t: 0, db: a[0].db }, ...a, { t: this.dur + 2, db: a[a.length - 1].db }] : [{ t: 0, db: 0 }, { t: this.dur + 2, db: 0 }]; const pl = document.createElementNS(NS, "polyline"); pl.setAttribute("points", pts.map((p) => `${p.t * this.pps},${this.autoY(p.db, H)}`).join(" ")); svg.append(pl); a.forEach((p, i) => { const c = document.createElementNS(NS, "circle"); c.setAttribute("cx", p.t * this.pps); c.setAttribute("cy", this.autoY(p.db, H)); c.setAttribute("r", 5); const ti = document.createElementNS(NS, "title"); ti.textContent = `${p.db} dB`; c.append(ti); c.addEventListener("pointerdown", (e) => { e.stopPropagation(); e.preventDefault(); if (e.detail >= 2) { this.push(); a.splice(i, 1); this.draw(); return; } this.push(); const r = svg.getBoundingClientRect(); const mv = (ev) => { p.t = Math.max(0, (ev.clientX - r.left) / this.pps); p.db = Math.round(Math.max(-30, Math.min(6, 6 - (ev.clientY - r.top) / H * 36)) * 2) / 2; a.sort((x, y) => x.t - y.t); c.setAttribute("cx", p.t * this.pps); c.setAttribute("cy", this.autoY(p.db, H)); }; const up = () => { removeEventListener("pointermove", mv); removeEventListener("pointerup", up); this.draw(); }; addEventListener("pointermove", mv); addEventListener("pointerup", up); }); svg.append(c); }); return svg; } /* ---- the mixer: a strip a track (its meter, level, pan, mute, solo) and the master's meter */ drawMixer() { const h = this.h; this.mixer.hidden = !this.mixOpen || !this.tracks.length; if (this.mixer.hidden) return; this.mixer.replaceChildren(); this.meterEls = []; const strip = (name, color, t) => { const s = h("div", "aedstrip"), m = h("div", "aedmeter"), f = h("i"); m.append(f); s.style.setProperty("--c", color); s.append(h("b", null, name), m); this.meterEls.push({ t, f }); if (t) { const vol = h("input"), pan = h("input"), ms = h("div", "aedms"), M = h("button", null, "M"), S = h("button", null, "S"), vv = h("span", null, `${t.vol} dB`); vol.type = "range"; vol.min = -30; vol.max = 6; vol.step = 0.5; vol.value = t.vol; vol.className = "aedfader"; vol.setAttribute("aria-label", `${t.name} dB`); vol.oninput = () => { t.vol = +vol.value; vv.textContent = `${t.vol} dB`; this.remix(); }; pan.type = "range"; pan.min = -1; pan.max = 1; pan.step = 0.05; pan.value = t.pan || 0; pan.setAttribute("aria-label", `${t.name} pan`); pan.oninput = () => { t.pan = +pan.value; this.remix(); }; M.type = S.type = "button"; M.setAttribute("aria-pressed", String(t.mute)); S.setAttribute("aria-pressed", String(t.solo)); M.onclick = () => { t.mute = !t.mute; this.draw(); this.remix(); }; S.onclick = () => { t.solo = !t.solo; this.draw(); this.remix(); }; ms.append(M, S); s.append(vol, vv, h("span", "aeddim", "PAN"), pan, ms); } else s.classList.add("master"); this.mixer.append(s); }; this.tracks.forEach((t) => strip(t.name, t.color, t)); strip("MASTER", "#ffe14d", null); } meters() { if (!this.meterEls || !this.mixers) return; const lv = (an) => { if (!an) return 0; const d = this.mbuf || (this.mbuf = new Float32Array(1024)); an.getFloatTimeDomainData(d); let m = 0; for (let i = 0; i < d.length; i += 4) m = Math.max(m, Math.abs(d[i])); return m; }; for (const e of this.meterEls) { const v = e.t ? lv((this.mixers.find((m) => m.t === e.t) || {}).an) : lv(this.masterAn); const db = v > 1e-5 ? 20 * Math.log10(v) : -60; e.f.style.height = `${Math.max(0, Math.min(100, (db + 60) / 60 * 100))}%`; e.f.classList.toggle("clip", v >= 0.99); } } clipEl(t, ti, c, ci) { const h = this.h, el = h("div", "aedclip" + (c.midi ? " midi" : "")), cv = h("canvas"), lb = h("span", null, c.midi ? `MIDI · ${c.notes.length}` : c.buf.name.split(" ").pop()); const sel = this.sel && this.sel.t === ti && this.sel.c === ci; el.style.cssText = `left:${c.start * this.pps}px;width:${Math.max(4, c.len * this.pps)}px;--c:${t.color}`; if (sel) el.classList.add("sel"); const wpx = Math.max(4, Math.round(c.len * this.pps)); cv.width = Math.min(4000, wpx); cv.height = 56; const g = cv.getContext("2d"); g.fillStyle = t.color; if (c.midi) { // the notes, their pitch across the clip's height const ns = c.notes.filter((n) => n.t + n.d > c.off && n.t < c.off + c.len), lo = Math.min(...ns.map((n) => n.n), 60) - 1, hi = Math.max(...ns.map((n) => n.n), 72) + 1; for (const n of ns) { const x = (n.t - c.off) / c.len * cv.width, w = Math.max(2, n.d / c.len * cv.width), y = (1 - (n.n - lo) / (hi - lo)) * (cv.height - 6) + 1; g.globalAlpha = 0.4 + n.v / 210; g.fillRect(x, y, w, 4); } g.globalAlpha = 1; } else { const P = this.peaksOf(c.buf), gain = DB(c.gain); for (let x = 0; x < cv.width; x++) { const tt = (x / cv.width) * c.len, src = c.rev ? c.off + c.len - tt : c.off + tt, i = Math.floor(src / P.per); let env = 1; if (c.fin && tt < c.fin) env = tt / c.fin; if (c.fout && tt > c.len - c.fout) env = (c.len - tt) / c.fout; const a = Math.min(1, (P.out[i] || 0) * gain * env) * 26; g.fillRect(x, 28 - a, 1, a * 2 || 1); } } if (c.fin) { const f = h("i", "fin"); f.style.width = `${c.fin * this.pps}px`; el.append(f); } if (c.fout) { const f = h("i", "fout"); f.style.width = `${c.fout * this.pps}px`; el.append(f); } const tl = h("i", "trim l"), tr = h("i", "trim r"); el.append(cv, lb, tl, tr); const drag = (e, mode) => { e.stopPropagation(); e.preventDefault(); this.sel = { t: ti, c: ci }; const x0 = e.clientX, s0 = { ...c }; let moved = false; const mv = (ev) => { const dt = (ev.clientX - x0) / this.pps; if (!moved && Math.abs(ev.clientX - x0) < 3) return; if (!moved) { this.push(); moved = true; } if (mode === "move") c.start = this.snapT(s0.start + dt); else if (mode === "l") { const ns = Math.min(s0.start + s0.len - 0.02, this.snapT(s0.start + dt)), d = ns - s0.start; const lim = c.rev ? 0 : -s0.off; const dd = Math.max(d, lim, -s0.start); c.start = s0.start + dd; c.len = s0.len - dd; if (!c.rev) c.off = s0.off + dd; } else { const end = this.snapT(s0.start + s0.len + dt), max = c.midi ? 1e6 : c.rev ? s0.off + s0.len : c.buf.secs - s0.off; c.len = Math.max(0.02, Math.min(end - s0.start, c.rev ? s0.len + s0.off : max)); if (c.rev) c.off = Math.max(0, s0.off + s0.len - c.len); } el.style.left = `${c.start * this.pps}px`; el.style.width = `${c.len * this.pps}px`; }; const up = () => { removeEventListener("pointermove", mv); removeEventListener("pointerup", up); this.draw(); }; addEventListener("pointermove", mv); addEventListener("pointerup", up); }; el.onpointerdown = (e) => drag(e, "move"); tl.onpointerdown = (e) => drag(e, "l"); tr.onpointerdown = (e) => drag(e, "r"); return el; } drawInsp() { const h = this.h, c = this.selClip(), L = this.L; this.insp.replaceChildren(); if (!c) { this.insp.append(h("p", "aeddim", L.pickHelp)); return; } const k = (lab, key, min, max, step, unit) => { const w = h("label", "aedk"), i = h("input"), o = h("b", null, `${c[key]}${unit}`); i.type = "range"; i.min = min; i.max = max; i.step = step; i.value = c[key]; i.onpointerdown = () => this.push(); i.oninput = () => { c[key] = +i.value; o.textContent = `${c[key]}${unit}`; this.drawLane(); }; w.append(h("span", null, lab), o, i); return w; }; const t = this.tracks[this.sel.t]; this.insp.append(h("p", "aedclipn", `${t.name} · ${c.midi ? "MIDI" : c.buf.name.split(" ").pop()} · ${c.start.toFixed(2)} s → ${(c.start + c.len).toFixed(2)} s${c.rev ? " · ⇆" : ""}`), k(L.gain, "gain", -24, 12, 0.5, " dB"), k(L.fin, "fin", 0, Math.min(4, c.len / 2), 0.01, " s"), k(L.fout, "fout", 0, Math.min(4, c.len / 2), 0.01, " s")); } drawLane() { clearTimeout(this.dl); this.dl = setTimeout(() => { const keep = this.insp; this.draw(); }, 60); } clockSet(s) { const m = Math.floor(s / 60), r = s - m * 60; this.clock.textContent = `${String(m).padStart(2, "0")}:${r.toFixed(1).padStart(4, "0")}`; const beat = 60 / this.bpm, b = Math.floor(s / beat); this.bars.textContent = `${Math.floor(b / 4) + 1}.${(b % 4) + 1}.${Math.floor((s / beat - b) * 4) + 1}`; } recording(on) { this.recB.classList.toggle("on", on); this.recB.textContent = on ? "■ REC" : "●"; } /* ---- sound */ ctx() { return this.ac || (this.ac = new AudioContext()); } abuf(ac, c) { // the clip's window as an AudioBuffer (reversed if so) const r = c.buf.rate, a = Math.floor(c.off * r), n = Math.max(1, Math.floor(c.len * r)), b = ac.createBuffer(c.buf.planes.length, n, r); c.buf.planes.forEach((p, k) => { const d = b.getChannelData(k); d.set(p.subarray(a, a + n)); if (c.rev) d.reverse(); }); return b; } schedule(ac, dest, from, when) { const solo = this.tracks.some((t) => t.solo), out = [], live = dest === ac.destination; let bus = dest; if (live) { bus = ac.createGain(); this.masterAn = ac.createAnalyser(); this.masterAn.fftSize = 1024; bus.connect(this.masterAn); bus.connect(dest); } for (const t of this.tracks) { const tg = ac.createGain(), ag = ac.createGain(), pan = ac.createStereoPanner(); tg.gain.value = t.mute || (solo && !t.solo) ? 0 : DB(t.vol); pan.pan.value = t.pan || 0; if (t.auto && t.auto.length) { // the automation: the value now, then a ramp to each point ahead ag.gain.setValueAtTime(DB(this.autoAt(t, from)), when); for (const p of t.auto) if (p.t > from) ag.gain.linearRampToValueAtTime(DB(p.db), when + p.t - from); } tg.connect(ag).connect(pan).connect(bus); const o = { t, tg, pan }; out.push(o); if (live) { o.an = ac.createAnalyser(); o.an.fftSize = 1024; pan.connect(o.an); } for (const c of t.clips) { const end = c.start + c.len; if (end <= from) continue; if (c.midi) { // a small synth: a triangle with a short envelope per note for (const n of c.notes) { const ts = c.start + (n.t - c.off); if (n.t < c.off || n.t >= c.off + c.len || ts + n.d < from) continue; const at = when + Math.max(0, ts - from), d = Math.min(n.d, c.off + c.len - n.t), o = ac.createOscillator(), g = ac.createGain(); o.type = "triangle"; o.frequency.value = 440 * Math.pow(2, (n.n - 69) / 12); const v = 0.25 * (n.v / 127) * DB(c.gain); g.gain.setValueAtTime(0, at); g.gain.linearRampToValueAtTime(v, at + 0.005); g.gain.setTargetAtTime(0, at + Math.max(0.01, d), 0.04); o.connect(g).connect(tg); o.start(at); o.stop(at + d + 0.3); this.srcs.push(o); } continue; } const s = ac.createBufferSource(), g = ac.createGain(), into = Math.max(0, from - c.start), at = when + Math.max(0, c.start - from), v = DB(c.gain); s.buffer = this.abuf(ac, c); s.connect(g).connect(tg); g.gain.setValueAtTime(c.fin && into < c.fin ? v * into / c.fin : v, at); if (c.fin && into < c.fin) g.gain.linearRampToValueAtTime(v, at + (c.fin - into)); if (c.fout) { const fs = Math.max(at, at + (c.len - c.fout - into)); g.gain.setValueAtTime(v, fs); g.gain.linearRampToValueAtTime(0, at + (c.len - into)); } s.start(at, into); this.srcs.push(s); } } if (this.met && live) { // the metronome: a click each beat, louder on the bar const beat = 60 / this.bpm, first = Math.ceil(from / beat - 1e-6); for (let b = first; b * beat < this.dur + 8; b++) { const at = when + (b * beat - from), o = ac.createOscillator(), g = ac.createGain(); o.frequency.value = b % 4 ? 1000 : 1600; g.gain.setValueAtTime(0.3, at); g.gain.exponentialRampToValueAtTime(0.001, at + 0.05); o.connect(g).connect(dest); o.start(at); o.stop(at + 0.06); this.srcs.push(o); } } return out; } play() { const ac = this.ctx(), l = this.loop, looping = () => l.on && l.b - l.a > 0.05; ac.resume(); if (looping() && (this.ph < l.a || this.ph >= l.b)) this.ph = l.a; const go = (from) => { this.srcs = []; this.mixers = this.schedule(ac, ac.destination, from, ac.currentTime + 0.03); this.t0 = ac.currentTime + 0.03 - from; }; go(this.ph); this.playing = true; this.playB.textContent = "❚❚"; const tick = () => { if (!this.playing) return; let p = ac.currentTime - this.t0; if (looping() && p >= l.b) { for (const s of this.srcs) { try { s.stop(); } catch (_) {} } go(l.a); p = l.a; } // the loop: back to its start this.phEl.style.left = `${110 + p * this.pps}px`; this.clockSet(p); this.meters(); if (!looping() && p > this.dur + 0.2) { this.stop(); return; } this.raf = requestAnimationFrame(tick); }; tick(); } stop() { if (!this.playing) return; this.ph = Math.max(0, this.ctx().currentTime - this.t0); for (const s of this.srcs) { try { s.stop(); } catch (_) {} } this.srcs = []; this.playing = false; this.playB.textContent = "▶"; cancelAnimationFrame(this.raf); this.draw(); } remix() { if (!this.mixers) return; const solo = this.tracks.some((t) => t.solo); for (const m of this.mixers) { m.tg.gain.value = m.t.mute || (solo && !m.t.solo) ? 0 : DB(m.t.vol); if (m.pan) m.pan.pan.value = m.t.pan || 0; } } async render(only) { const rate = 44100, n = Math.ceil(this.dur * rate) + 1, oc = new OfflineAudioContext(2, n, rate), keep = this.tracks; if (only) this.tracks = [{ ...only, mute: false, solo: false }]; try { this.schedule(oc, oc.destination, 0, 0); } finally { this.tracks = keep; } const b = await oc.startRendering(); return [b.getChannelData(0), b.getChannelData(1)]; } save(blob, name) { const a = document.createElement("a"); a.href = URL.createObjectURL(blob); a.download = name; document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(a.href), 4000); } async exportMix() { if (!this.tracks.length) return; this.say(this.L.rendering); const p = await this.render(); this.save(new Blob([this.lib.wav(p, 44100)], { type: "audio/wav" }), "jiant-mix.wav"); this.say(this.L.exported); } exportMidi() { const ev = []; for (const t of this.tracks) for (const c of t.clips) if (c.midi && !t.mute) for (const n of c.notes) { if (n.t < c.off || n.t >= c.off + c.len) continue; const ts = (c.start + n.t - c.off) * 1000, d = Math.min(n.d, c.off + c.len - n.t) * 1000; ev.push({ t: ts, data: [0x90 | n.ch, n.n, n.v] }, { t: ts + d, data: [0x80 | n.ch, n.n, 0] }); } if (!ev.length) { this.say(this.L.noMidi); return; } this.save(new Blob([this.lib.midi(ev, this.bpm)], { type: "audio/midi" }), "jiant-midi.mid"); this.say(this.L.exported); } async exportTracks() { if (!this.tracks.length) return; this.say(this.L.rendering); const files = []; for (const [i, t] of this.tracks.entries()) files.push({ name: `jiant-tracks/${String(i + 1).padStart(2, "0")}-${t.name.replace(/[^\w-]+/g, "_")}.wav`, data: this.lib.wav(await this.render(t), 44100) }); files.push({ name: "jiant-tracks/MIX.wav", data: this.lib.wav(await this.render(), 44100) }); this.save(new Blob([this.lib.zip(files)], { type: "application/zip" }), "jiant-tracks.zip"); this.say(this.L.exported); } }