File size: 4,938 Bytes
804f155
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// The dataset's ACN/SN3D channels are W,Y,Z,X; +X front, +Y left, +Z up.
export const radians = degrees => degrees * Math.PI / 180;
export const clamp = (value, low, high) => Math.max(low, Math.min(high, value));
export const wrapYaw = yaw => ((yaw + 180) % 360 + 360) % 360 - 180;

export function viewBasis(yaw, pitch) {
  const a = radians(yaw), e = radians(pitch);
  const ca = Math.cos(a), sa = Math.sin(a), ce = Math.cos(e), se = Math.sin(e);
  return {forward: [ce * ca, ce * sa, se], left: [-sa, ca, 0], up: [-se * ca, -se * sa, ce]};
}

export function directionToUV([x, y, z]) {
  return [((0.5 - Math.atan2(y, x) / (2 * Math.PI)) % 1 + 1) % 1,
    0.5 - Math.asin(clamp(z, -1, 1)) / Math.PI];
}

export function omnitoneRotation(yaw, pitch) {
  const {forward: f, left: l, up: u} = viewBasis(yaw, pitch);
  // Desired local coefficients: X'=f路D, Y'=l路D, Z'=u路D.
  // Omnitone internally maps WYZX to graphics axes [-Y,Z,-X] on both sides.
  // Supply S A S (S=diag(-1,+1,-1), A in YZX order), column-major.
  return [l[1], -u[1], f[1], -l[2], u[2], -f[2], l[0], -u[0], f[0]];
}

export function parseFOAWav(arrayBuffer) {
  const view = new DataView(arrayBuffer);
  const text = (offset, count) => String.fromCharCode(...new Uint8Array(arrayBuffer, offset, count));
  if (view.byteLength < 12 || text(0, 4) !== 'RIFF' || text(8, 4) !== 'WAVE') {
    throw new Error('Expected a RIFF/WAVE audio file.');
  }
  let format, data;
  for (let pos = 12; pos + 8 <= view.byteLength;) {
    const id = text(pos, 4), size = view.getUint32(pos + 4, true), start = pos + 8;
    if (start + size > view.byteLength) throw new Error('Truncated WAV file.');
    if (id === 'fmt ') {
      if (size < 16) throw new Error('Invalid WAV format chunk.');
      let encoding = view.getUint16(start, true);
      if (encoding === 0xfffe && size >= 40) encoding = view.getUint16(start + 24, true);
      format = {encoding, channels: view.getUint16(start + 2, true),
        sampleRate: view.getUint32(start + 4, true), block: view.getUint16(start + 12, true),
        bits: view.getUint16(start + 14, true)};
    }
    if (id === 'data') data = {start, size};
    pos = start + size + (size % 2);
  }
  if (!format || !data || format.channels !== 4) throw new Error('Expected four FOA channels in W,Y,Z,X order.');
  const floating = format.encoding === 3 && format.bits === 32;
  const pcm16 = format.encoding === 1 && format.bits === 16;
  if (!floating && !pcm16) throw new Error('Supported WAV formats: float32 and PCM16.');
  if (format.block !== 4 * format.bits / 8 || data.size % format.block) throw new Error('Invalid WAV block alignment.');
  const length = data.size / format.block;
  const channels = Array.from({length: 4}, () => new Float32Array(length));
  for (let frame = 0; frame < length; frame++) {
    for (let channel = 0; channel < 4; channel++) {
      const pos = data.start + frame * format.block + channel * format.bits / 8;
      const value = floating ? view.getFloat32(pos, true) : view.getInt16(pos, true) / 32768;
      if (!Number.isFinite(value)) throw new Error('WAV contains a non-finite sample.');
      channels[channel][frame] = value;
    }
  }
  return {channels, length, sampleRate: format.sampleRate, duration: length / format.sampleRate};
}

export class SpatialAudio {
  async initialize() {
    if (!this.initializing) {
      this.context = new AudioContext({latencyHint: 'interactive'});
      this.renderer = Omnitone.createFOARenderer(this.context, {channelMap: [0, 1, 2, 3]});
      this.gain = this.context.createGain();
      this.gain.channelCount = 4;
      this.gain.channelCountMode = 'explicit';
      this.gain.channelInterpretation = 'discrete';
      this.gain.gain.value = 10 ** (-24 / 20);
      this.gain.connect(this.renderer.input);
      this.renderer.output.connect(this.context.destination);
      this.initializing = this.renderer.initialize();
    }
    await this.initializing;
  }

  setBuffer(wav) {
    this.stop();
    this.buffer = this.context.createBuffer(4, wav.length, wav.sampleRate);
    wav.channels.forEach((samples, channel) => this.buffer.copyToChannel(samples, channel));
  }

  setPose(yaw, pitch) { this.renderer?.setRotationMatrix3(omnitoneRotation(yaw, pitch)); }
  setGain(db) { this.gain?.gain.setTargetAtTime(10 ** (db / 20), this.context.currentTime, 0.015); }

  start(offset) {
    this.stop();
    if (!this.buffer || offset >= this.buffer.duration) return;
    this.source = this.context.createBufferSource();
    this.source.buffer = this.buffer;
    this.source.connect(this.gain);
    this.startedAt = this.context.currentTime;
    this.offset = offset;
    this.source.start(this.startedAt, offset);
  }

  stop() {
    if (this.source) {
      this.source.stop();
      this.source.disconnect();
      this.source = null;
    }
  }

  get position() { return this.source ? this.offset + this.context.currentTime - this.startedAt : null; }
}