Spaces:
Paused

File size: 8,190 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// Browser-side audio helpers for the STT tab (record / trim / save).
//
// Everything here is a pure function over the Web Audio API β€” no DOM, no
// external library. The two transformations that matter:
//
//  1. Recordings come out of MediaRecorder as webm/opus, which the Python
//     STT backends (soundfile, whisper-server) can NOT read. We decode the
//     blob and re-encode it as 16-bit PCM WAV β€” the one format every
//     consumer is guaranteed to read.
//  2. Trimming cuts an AudioBuffer between two timestamps and re-encodes
//     the slice to WAV, which doubles as the "preview" of the cut.

let _ctx = null;

/** The shared AudioContext β€” created lazily (browsers cap the number of
 * live contexts and it may only be created after a user gesture). */
function ctx() {
  if (!_ctx) _ctx = new (window.AudioContext || window.webkitAudioContext)();
  return _ctx;
}

/** Decode a File/Blob to a PCM AudioBuffer. Chrome decodes webm/opus,
 * wav, mp3, ogg and m4a here, so this works for uploads AND recordings. */
export async function decodeAudioFile(file) {
  const buf = await file.arrayBuffer();
  return ctx().decodeAudioData(buf);
}

/** Cut `buffer` between startSec and endSec (clamped to the buffer's
 * bounds; invalid ranges collapse to a 1-sample minimum). Returns a NEW
 * AudioBuffer at the same sample rate β€” the source is never mutated. */
export function sliceBuffer(buffer, startSec, endSec) {
  const sr = buffer.sampleRate;
  const start = Math.max(0, Math.min(buffer.duration, startSec));
  const end = Math.max(start, Math.min(buffer.duration, endSec));
  const length = Math.max(1, Math.round((end - start) * sr));
  const out = ctx().createBuffer(buffer.numberOfChannels, length, sr);
  const off = Math.round(start * sr);
  for (let ch = 0; ch < buffer.numberOfChannels; ch++) {
    const src = buffer.getChannelData(ch);
    const dst = out.getChannelData(ch);
    for (let i = 0; i < length; i++) dst[i] = src[off + i] || 0;
  }
  return out;
}

/** Encode an AudioBuffer as a 16-bit PCM mono/stereo WAV Blob (44-byte
 * RIFF header + interleaved samples). */
export function bufferToWav(buffer) {
  const numCh = buffer.numberOfChannels;
  const sr = buffer.sampleRate;
  const len = buffer.length;
  const blockAlign = numCh * 2;
  const dataSize = len * blockAlign;
  const ab = new ArrayBuffer(44 + dataSize);
  const view = new DataView(ab);

  writeStr(view, 0, "RIFF");
  view.setUint32(4, 36 + dataSize, true);
  writeStr(view, 8, "WAVE");
  writeStr(view, 12, "fmt ");
  view.setUint32(16, 16, true); // fmt chunk size
  view.setUint16(20, 1, true); // PCM
  view.setUint16(22, numCh, true);
  view.setUint32(24, sr, true);
  view.setUint32(28, sr * blockAlign, true); // byte rate
  view.setUint16(32, blockAlign, true);
  view.setUint16(34, 16, true); // bits per sample
  writeStr(view, 36, "data");
  view.setUint32(40, dataSize, true);

  const channels = [];
  for (let ch = 0; ch < numCh; ch++) channels.push(buffer.getChannelData(ch));
  let offset = 44;
  for (let i = 0; i < len; i++) {
    for (let ch = 0; ch < numCh; ch++) {
      let s = channels[ch][i];
      s = Math.max(-1, Math.min(1, s));
      // 16-bit PCM: negative β†’ 0x8000 range, positive β†’ 0x7FFF range.
      view.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
      offset += 2;
    }
  }
  return new Blob([ab], { type: "audio/wav" });
}

/** Seconds β†’ "m:ss" (or "0:00" for junk input). */
export function formatDuration(sec) {
  if (!isFinite(sec) || sec < 0) return "0:00";
  const m = Math.floor(sec / 60);
  const s = Math.round(sec % 60);
  return `${m}:${String(s).padStart(2, "0")}`;
}

/** Draw a peak-envelope waveform of `buffer` onto `canvas` β€” the
 * before/after comparison in the STT tab's noise-reduction preview AND the
 * STT trim bar's selection view. Uses channel 0, collapses every pixel
 * column to its min/max peak so quiet passages stay visible, and renders
 * crisp on HiDPI screens. `color` is a CSS color string; width follows the
 * canvas's current layout width.
 *
 * `selection` ({start, end} in seconds, e.g. the trim sliders' kept region)
 * colors that span in `selectColor` and draws thin handle lines at its
 * boundaries, so the exact cut points are visible on the audio shape.
 * `playhead` (seconds, e.g. the audio element's currentTime) draws a thin
 * line at the live playback position on top of everything.
 *
 * Returns the canvas for chaining. Never throws on a bad buffer β€” a null
 * buffer just clears the canvas. */
export function drawWaveform(
  canvas,
  buffer,
  {
    color = "#8a7a68",
    selection = null,
    selectColor = "#d97757",
    playhead = null,
    playheadColor = "#4e7a57",
  } = {}
) {
  // Canvas fillStyle does NOT resolve CSS custom properties (var(--x)) β€” the
  // color must be a concrete value. Resolve a var()/fallback string here so
  // callers can pass theme tokens and still get a real color (falls back to
  // the token's own fallback, then to a neutral grey).
  color = resolveColor(color);
  selectColor = resolveColor(selectColor);
  const g = canvas.getContext("2d");
  const dpr = window.devicePixelRatio || 1;
  const w = canvas.clientWidth || canvas.parentElement?.clientWidth || 300;
  const h = 64;
  canvas.width = Math.max(1, Math.round(w * dpr));
  canvas.height = Math.round(h * dpr);
  g.setTransform(dpr, 0, 0, dpr, 0, 0);
  g.clearRect(0, 0, w, h);
  if (!buffer) return canvas;

  const data = buffer.getChannelData(0);
  const cols = Math.max(1, Math.floor(w));
  const per = Math.max(1, Math.floor(data.length / cols));
  const mid = h / 2;

  // Map the selection span (seconds) onto the column range, clamped so a
  // sliver at the very edge can't draw outside the canvas.
  let selStartCol = -1;
  let selEndCol = -1;
  if (selection && buffer.duration > 0) {
    selStartCol = Math.max(0, Math.floor((selection.start / buffer.duration) * cols));
    selEndCol = Math.min(cols, Math.ceil((selection.end / buffer.duration) * cols));
  }

  for (let c = 0; c < cols; c++) {
    let mn = 1;
    let mx = -1;
    const start = c * per;
    const end = Math.min(data.length, start + per);
    for (let i = start; i < end; i++) {
      const v = data[i];
      if (v < mn) mn = v;
      if (v > mx) mx = v;
    }
    const top = Math.max(0, mid - mx * (mid - 2));
    const bot = Math.min(h, mid - mn * (mid - 2));
    if (bot > top) {
      // Columns inside the kept span render in the highlight color, the
      // trimmed-away parts stay in the dim base color.
      g.fillStyle = c >= selStartCol && c < selEndCol ? selectColor : color;
      g.fillRect(c, top, 1, bot - top);
    }
  }

  // Handle lines marking the exact trim start/end columns (drawn in the
  // theme's strong text color so they read on both light and dark).
  if (selection && selStartCol >= 0 && selEndCol > selStartCol) {
    g.fillStyle = resolveColor("var(--text-strong, #3f332b)");
    g.fillRect(selStartCol, 0, 2, h);
    g.fillRect(selEndCol - 2, 0, 2, h);
  }

  // Live playback position line (the audio player's currentTime), drawn on
  // top so the playhead stays visible over the selection highlight.
  if (playhead != null && buffer.duration > 0) {
    const col = Math.floor((playhead / buffer.duration) * cols);
    if (col >= 0 && col < cols) {
      g.fillStyle = resolveColor(playheadColor);
      g.fillRect(col, 0, 2, h);
    }
  }
  return canvas;
}

function writeStr(view, offset, str) {
  for (let i = 0; i < str.length; i++) view.setUint8(offset + i, str.charCodeAt(i));
}

/** Resolve a CSS color that may be a `var(--token, fallback)` custom-property
 * string to a concrete color value (canvas can't read CSS vars itself).
 * Unknown tokens fall back through: token fallback β†’ neutral grey. */
function resolveColor(color) {
  if (typeof color !== "string" || !color.startsWith("var(")) return color;
  const m = /var\(\s*(--[\w-]+)\s*(?:,\s*([^)]+))?\)/.exec(color);
  if (!m) return color;
  let resolved = "";
  try {
    resolved = getComputedStyle(document.documentElement)
      .getPropertyValue(m[1])
      .trim();
  } catch {
    resolved = "";
  }
  return resolved || (m[2] ? m[2].trim() : "#8a7a68");
}