Back to The Bathyal Post
SOURCE / PINNED RELEASE

Made of little things.

The Bathyal Post

Release
fa6ce530b9f3…
Author-recorded commit
b255b3c9fd49…
License
LICENSE
Author’s source reference
nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-55c50b9a042

Archive hash verified: 03cf62191e7476c5…. The source-to-build association is the author’s claim; it has not been independently rebuilt.

src/sound.ts
import { identity, media, type MediaAction, type Subscription } from '@napplet/sdk';
import { runtimeHasDomain } from './domain-availability.js';

export type SoundStatus = 'off' | 'starting' | 'on' | 'unavailable';
export type SoundCue = 'select' | 'drift' | 'drive' | 'deliver' | 'service' | 'danger' | 'dock' | 'lose' | 'win';

const bounded = (n: number) => Number.isFinite(n) ? Math.max(0, Math.min(1, n)) : 0;

// Each hydrophone has one mix bus. Pulling that bus silences scheduled echoes,
// machinery and the water bed together, even between two audio render quanta.
class Hydrophone {
  private readonly bus: GainNode;
  private readonly sea: BiquadFilterNode;
  private readonly water: AudioBuffer;
  private readonly voices = new Set<AudioScheduledSourceNode>();
  private readonly hum: OscillatorNode;
  private readonly humLevel: GainNode;
  private readonly breath: OscillatorNode;
  private timer = 0;
  private depth = 0;
  private wake = 0;
  private phrases = 0;

  constructor(private ctx: AudioContext, output: GainNode) {
    this.bus = ctx.createGain();
    this.bus.connect(output);
    this.water = ctx.createBuffer(1, ctx.sampleRate * 2, ctx.sampleRate);
    const samples = this.water.getChannelData(0);
    let brown = 0;
    for (let i = 0; i < samples.length; i++) {
      brown = brown * 0.94 + (Math.random() * 2 - 1) * 0.17;
      const edge = Math.min(1, i / 320, (samples.length - i - 1) / 320);
      samples[i] = brown * edge;
    }
    const surf = ctx.createBufferSource();
    surf.buffer = this.water;
    surf.loop = true;
    this.sea = ctx.createBiquadFilter();
    this.sea.type = 'lowpass';
    this.sea.Q.value = 0.4;
    const surfLevel = ctx.createGain();
    surfLevel.gain.value = 0.075;
    surf.connect(this.sea).connect(surfLevel).connect(this.bus);
    this.track(surf);
    surf.start();

    this.hum = ctx.createOscillator();
    this.humLevel = ctx.createGain();
    this.hum.frequency.value = 73.42;
    this.humLevel.gain.value = 0.019;
    this.hum.connect(this.humLevel).connect(this.bus);
    this.breath = ctx.createOscillator();
    this.breath.frequency.value = 0.105;
    const flutter = ctx.createGain();
    flutter.gain.value = 0.003;
    this.breath.connect(flutter).connect(this.humLevel.gain);
    this.track(this.breath);
    this.track(this.hum);
    this.breath.start();
    this.hum.start();
    this.environment(0, 0);
    this.timer = window.setTimeout(() => this.call(), 4600);
  }

  private track(source: AudioScheduledSourceNode): void {
    this.voices.add(source);
    source.onended = () => {
      this.voices.delete(source);
      source.disconnect();
    };
  }

  environment(depth: number, wake: number): void {
    this.depth = bounded(depth);
    this.wake = bounded(wake);
    const t = this.ctx.currentTime;
    this.sea.frequency.setTargetAtTime(540 - 370 * this.depth, t, 0.45);
    this.hum.frequency.setTargetAtTime(73.42 - 18.42 * this.depth, t, 0.7);
    this.humLevel.gain.setTargetAtTime(0.019 + 0.012 * this.wake, t, 0.6);
  }

  private note(frequency: number, end: number, wait: number, duration: number, level: number, attack = 0.008, wave: OscillatorType = 'sine', bearing = 0): void {
    const t = this.ctx.currentTime + 0.005 + wait;
    const voice = this.ctx.createOscillator();
    const gain = this.ctx.createGain();
    voice.type = wave;
    voice.frequency.setValueAtTime(frequency, t);
    voice.frequency.exponentialRampToValueAtTime(end, t + duration);
    gain.gain.setValueAtTime(0.00002, t);
    gain.gain.linearRampToValueAtTime(level, t + attack);
    gain.gain.exponentialRampToValueAtTime(0.00002, t + duration);
    voice.connect(gain);
    if (bearing && typeof this.ctx.createStereoPanner === 'function') {
      const pan = this.ctx.createStereoPanner();
      pan.pan.value = bearing;
      gain.connect(pan).connect(this.bus);
    } else {
      gain.connect(this.bus);
    }
    this.track(voice);
    voice.start(t);
    voice.stop(t + duration + 0.01);
  }

  private scrape(wait: number, frequency: number, duration: number, level: number): void {
    const src = this.ctx.createBufferSource();
    src.buffer = this.water;
    const band = this.ctx.createBiquadFilter();
    band.type = 'bandpass';
    band.frequency.value = frequency;
    band.Q.value = 1.8;
    const gain = this.ctx.createGain();
    const t = this.ctx.currentTime + 0.005 + wait;
    gain.gain.setValueAtTime(0.00002, t);
    gain.gain.linearRampToValueAtTime(level, t + Math.min(0.025, duration / 3));
    gain.gain.exponentialRampToValueAtTime(0.00002, t + duration);
    src.connect(band).connect(gain).connect(this.bus);
    this.track(src);
    src.start(t, Math.random() * 0.75);
    src.stop(t + duration);
  }

  private bell(pitch: number, wait: number, level: number): void {
    this.note(pitch, pitch * 0.997, wait, 1.15, level);
    this.note(pitch * 2.72, pitch * 2.69, wait, 0.43, level * 0.31);
    this.note(pitch * 4.1, pitch * 4.04, wait, 0.18, level * 0.12);
    this.note(pitch, pitch * 0.995, wait + 0.32, 1.3, level * 0.14, 0.06, 'sine', -0.36);
  }

  private call(): void {
    const chord = [73.42, 98, 82.41, 110];
    const root = chord[this.phrases++ % chord.length];
    const pitch = root * (this.depth > 0.55 ? 1 : 2);
    const bearing = Math.sin(this.phrases * 2.3) * 0.62;
    this.note(pitch * 0.95, pitch * 1.08, 0, 3.3, 0.023, 0.85, 'sine', bearing);
    this.note(pitch * 1.48, pitch * 1.55, 0.65, 3.8, 0.012, 1.15, 'triangle', -bearing * 0.45);
    if (this.wake >= 0.55) {
      this.note(68, 62, 2.2, 0.6, 0.043, 0.02);
      this.note(61, 56, 2.56, 0.67, 0.03, 0.03);
    }
    this.timer = window.setTimeout(() => this.call(), 9600 + Math.random() * 3500 - this.wake * 2900);
  }

  cue(cue: SoundCue, recipient?: string): void {
    switch (cue) {
      case 'select':
        this.scrape(0, 1230, 0.068, 0.32);
        this.note(590, 550, 0, 0.065, 0.04);
        break;
      case 'drift':
        this.scrape(0, 620, 0.82, 0.34);
        this.note(196, 110, 0, 0.62, 0.045, 0.055, 'triangle');
        this.note(392, 294, 0.22, 0.85, 0.026, 0.15);
        break;
      case 'drive':
        for (let j = 0; j < 5; j++) {
          this.note(76 + j * 6, 48, j * 0.084, 0.23, 0.09, 0.008, 'triangle');
          this.scrape(j * 0.084, 380 + j * 65, 0.08, 0.31);
        }
        break;
      case 'deliver':
        this.scrape(0, 850, 0.095, 0.58);
        this.note(121, 62, 0, 0.18, 0.14, 0.004, 'triangle');
        // The address and its answering postmark are one call-and-response.
        this.bell(293.66, 0.10, 0.10);
        if (recipient === 'whale') {
          this.note(105, 151, 0.32, 1.9, 0.092, 0.38, 'sine', -0.5);
          this.note(163, 221, 0.62, 2.4, 0.055, 0.58, 'triangle', 0.24);
        } else if (recipient === 'garden') {
          [440, 554.37, 659.25, 880].forEach((pitch, i) =>
            this.note(pitch * 0.74, pitch, 0.29 + i * 0.13, 0.26, 0.065, 0.027, 'sine', 0.4 - i * 0.26));
        } else if (recipient === 'trench') {
          this.note(155.56, 73.42, 0.35, 1.9, 0.10, 0.24, 'triangle');
          this.bell(146.83, 0.86, 0.079);
        } else {
          this.bell(440, 0.31, 0.08);
          this.bell(587.33, 0.62, 0.06);
        }
        break;
      case 'service':
        this.scrape(0, 570, 0.52, 0.55);
        this.note(221, 293.66, 0.19, 0.6, 0.05, 0.075);
        this.bell(369.99, 0.46, 0.055);
        break;
      case 'danger':
        this.note(116.5, 47, 0, 1.10, 0.145, 0.018, 'triangle');
        this.scrape(0.02, 1650, 0.29, 0.66);
        this.note(156, 73, 0.12, 0.8, 0.06, 0.045);
        this.scrape(0.17, 230, 1.05, 0.44);
        break;
      case 'dock':
        this.bell(220, 0, 0.105);
        this.bell(329.63, 0.33, 0.09);
        break;
      case 'lose':
        this.scrape(0, 280, 1.2, 0.47);
        this.note(146.83, 65.4, 0, 1.9, 0.095, 0.10);
        this.note(220, 98, 0.28, 1.8, 0.05, 0.18);
        break;
      case 'win':
        [220, 293.66, 369.99, 440, 587.33].forEach((pitch, index) => this.bell(pitch, index * 0.24, 0.075));
        break;
    }
  }

  close(): void {
    window.clearTimeout(this.timer);
    this.bus.disconnect();
    for (const voice of this.voices) {
      voice.stop();
      voice.disconnect();
    }
    this.voices.clear();
  }
}

export function createSound(onChange: (status: SoundStatus) => void) {
  const available = () => runtimeHasDomain('media') && typeof AudioContext !== 'undefined';
  let status: SoundStatus = available() ? 'off' : 'unavailable';
  let ctx: AudioContext | undefined;
  let output: GainNode | undefined;
  let scene: Hydrophone | undefined;
  let session = '';
  let requesting = false;
  let desired = false;
  let stopped = false;
  let disposed = false;
  let trial = 0;
  let registrationTimer = 0;
  let commands: Subscription | undefined;
  let identityChanges: Subscription | undefined;
  let depth = 0;
  let wake = 0;
  let volume = 0.8;

  function change(next: SoundStatus): void {
    if (status === next) return;
    status = next;
    onChange(next);
  }

  function retire(next: SoundStatus): void {
    trial++;
    window.clearTimeout(registrationTimer);
    requesting = desired = stopped = false;
    scene?.close();
    scene = undefined;
    if (output) output.gain.value = 0;
    if (ctx) {
      ctx.onstatechange = null;
      void ctx.close().catch(() => {});
    }
    ctx = output = undefined;
    try { commands?.close(); } catch { /* A retired host port can already be closed. */ }
    commands = undefined;
    if (session) {
      try { media.destroySession(session); } catch { /* The host retired the session first. */ }
      session = '';
    }
    change(next);
  }

  function sync(): void {
    if (!ctx || !output || disposed) return;
    const playing = Boolean(session) && desired && ctx.state === 'running';
    output.gain.value = playing ? volume : 0;
    if (playing && !scene) {
      scene = new Hydrophone(ctx, output);
      scene.environment(depth, wake);
    } else if (!playing && scene) {
      scene.close();
      scene = undefined;
    }
    change(playing ? 'on' : requesting ? 'starting' : 'off');
    if (!session) return;
    try {
      media.reportState(session, { status: playing ? 'playing' : stopped ? 'stopped' : 'paused', volume });
    } catch {
      retire('unavailable');
    }
  }

  function command(action: MediaAction, value?: number): void {
    if (!ctx || disposed) return;
    if (action === 'pause' || action === 'stop') {
      desired = false;
      stopped = action === 'stop';
      sync();
      void ctx?.suspend().catch(() => {});
    } else if (action === 'play') {
      stopped = false;
      desired = true;
      if (ctx.state !== 'running') void ctx.resume().then(sync, sync);
      sync();
    } else if (action === 'volume' && typeof value === 'number' && Number.isFinite(value)) {
      volume = bounded(value);
      sync();
    }
  }

  async function register(sequence: number): Promise<void> {
    try {
      const result = await media.createSession({
        owner: 'napplet',
        capabilities: ['play', 'pause', 'stop', 'volume'],
        metadata: { title: 'The Bathyal Post · Hydrophone', mediaType: 'audio' },
      });
      if (sequence !== trial || disposed) {
        if (result.sessionId) media.destroySession(result.sessionId);
        return;
      }
      window.clearTimeout(registrationTimer);
      session = result.sessionId ?? '';
      if (result.error || !session || result.owner !== 'napplet') {
        retire('unavailable');
        return;
      }
      commands = media.onCommand(session, command);
      requesting = false;
      sync();
    } catch {
      if (sequence === trial) retire('unavailable');
    }
  }

  function toggle(): void {
    if (disposed || status === 'unavailable' || requesting) return;
    if (ctx && session) {
      command(status === 'on' ? 'pause' : 'play');
      return;
    }
    try {
      if (!available()) { change('unavailable'); return; }
      ctx = new AudioContext();
      output = ctx.createGain();
      output.gain.value = 0;
      output.connect(ctx.destination);
      ctx.onstatechange = sync;
      desired = requesting = true;
      change('starting');
      // Ask during the click. This graph stays muted until the host grants ownership.
      if (ctx.state !== 'running') void ctx.resume().then(sync, sync);
      registrationTimer = window.setTimeout(() => retire('unavailable'), 8000);
      void register(++trial);
    } catch {
      retire('unavailable');
    }
  }

  if (runtimeHasDomain('identity')) {
    try { identityChanges = identity.onChanged(() => retire(available() ? 'off' : 'unavailable')); }
    catch { /* Some hosts expose an empty optional domain. */ }
  }

  function background(): void {
    if (document.hidden && ctx) command('pause');
  }
  document.addEventListener('visibilitychange', background);

  return {
    get status(): SoundStatus { return status; },
    toggle,
    cue(cue: SoundCue, recipient?: string): void { scene?.cue(cue, recipient); },
    environment(nextDepth: number, nextWake: number): void {
      depth = bounded(nextDepth);
      wake = bounded(nextWake);
      scene?.environment(depth, wake);
    },
    dispose(): void {
      disposed = true;
      document.removeEventListener('visibilitychange', background);
      try { identityChanges?.close(); } catch { /* An iframe can be removed before its port closes. */ }
      retire('off');
    },
  };
}