use it elsewhere

ADC → DAC round trip

Put it on your own page with two lines, or fork it and make it yours. It is CC-BY-4.0.

Embed

The script finds its own origin, so nothing else is needed; the widget runs in a sandboxed frame and cannot touch your page. Set the controls and the two lines update; the preview beneath shows what your readers get.

<script src="https://learn.mimmsy.com/learn-widget.js"></script> <learn-widget name="adc-dac-round-trip"></learn-widget>

It is CC-BY-4.0: keep the credit line the frame shows.

Preview

Fork

A fork is a copy whose manifest names its parent and the parent's version; lineage is kept forever, and the copy is yours to change. The library is its own repository: clone it, copy adc-dac-round-trip/ to a new name (one DNS label), set forkedFrom to { "name": "adc-dac-round-trip", "version": 1 }, change what you want, run npm run check, and open a pull request. Passing the check is the whole gate. Without a checkout, submit the same files to POST /api/widgets and it is served instantly as an unreviewed draft.

Source

The whole widget is these files; the repository has their history.

widget.json

{
  "name": "adc-dac-round-trip",
  "title": "ADC → DAC round trip",
  "version": 1,
  "claim": "For content below fₛ/2, sampling, holding and sinc-filtering returns the input waveform exactly, and the only permanent loss is the quantization error, which every added bit pushes about 6 dB lower.",
  "summary": "Four animated panels run a two-component wave through the whole pipeline: analog in, the ADC's samples, the quantized and held staircase, and the reconstruction-filtered output. Lower the sample rate below twice the top component and the output aliases; lower the bit depth and quantization noise appears. Two buttons play the same pipeline 100× faster (220 + 470 Hz) so both failures are audible.",
  "topics": ["audio/digital", "signals/sampling"],
  "aliases": ["ADC", "DAC", "reconstruction filter", "sample and hold", "zero-order hold", "pipeline", "converter"],
  "params": {
    "rate": { "type": "integer", "default": 32, "min": 6, "max": 48, "label": "samples per window" },
    "bits": { "type": "integer", "default": 5, "min": 2, "max": 8, "label": "bits per sample" }
  },
  "check": [
    {
      "q": "The “staircase” a DAC produces is smoothed into a wave by…",
      "options": ["a low-pass reconstruction filter", "the mechanical inertia of the speaker cone", "adding extra bits after the fact", "raising the sample rate after the fact"],
      "answer": 0,
      "why": "The reconstruction filter removes everything above Nyquist, leaving the one smooth wave that passes through the samples; this is the sinc interpolation."
    },
    {
      "q": "Doubling the sample rate primarily provides…",
      "options": ["a higher frequency ceiling", "a lower noise floor", "twice the loudness", "better stereo separation"],
      "answer": 0,
      "why": "Sample rate sets the bandwidth through the Nyquist limit and bit depth sets the noise floor; the two sliders here fail independently."
    },
    {
      "q": "A DAC's job is to…",
      "options": ["turn the stored numbers back into a continuous voltage", "compress audio for streaming", "measure the wave and produce numbers", "remove frequencies above Nyquist before sampling"],
      "answer": 0,
      "why": "A digital-to-analog converter performs the reconstruction step; measuring the wave into numbers is the ADC's job, and filtering before sampling is the anti-aliasing stage."
    },
    {
      "q": "With the sample rate well above twice the top component, the round trip's output differs from the input only by…",
      "options": ["the quantization error set by the bit depth", "a small loss of high frequencies", "a slight change of pitch", "nothing, even at 2 bits"],
      "answer": 0,
      "why": "Below Nyquist the sinc reconstruction is exact, so the panels match apart from the rounding noise, which shrinks by about 6 dB per added bit."
    }
  ],
  "capabilities": [],
  "height": 500,
  "requires": ["nyquist-fold", "bit-depth-buckets", "sinc-interpolation"],
  "forkedFrom": null,
  "authors": []
}

index.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ADC → DAC round trip</title>
<style>
  :root {
    color-scheme: light dark;
    --bg: #f7f3ea;
    --bg-card: #efe9da;
    --border: #d8cfba;
    --text: #211d14;
    --text-dim: #6e6553;
    --accent: #31597f;
    --accent2: #b04e1b;
    --hot: #a82433;
    --ok: #3d6b4f;
    --ink-rgb: 33, 29, 20;
    --serif: "Iowan Old Style", "Palatino Linotype", Palatino, "Book Antiqua", Georgia, serif;
    --mono: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
  }
  @media (prefers-color-scheme: dark) {
    :root {
      --bg: #161410;
      --bg-card: #1e1b15;
      --border: #383225;
      --text: #e9e3d3;
      --text-dim: #9c917c;
      --accent: #8fb8e0;
      --accent2: #dd9355;
      --hot: #df7a88;
      --ok: #82bd97;
      --ink-rgb: 233, 227, 211;
    }
  }

  * { box-sizing: border-box; }
  html, body { margin: 0; }
  body { background: transparent; color: var(--text); font-family: var(--serif); }

  .widget {
    background: var(--bg-card);
    border: 1px solid var(--border);
    border-radius: 4px;
    padding: 22px;
  }

  .control-row { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-bottom: 14px; }
  .control-row.sym.single {
    display: grid; grid-template-columns: 88px 1fr; gap: 12px 16px;
    align-items: center; margin-bottom: 14px;
  }
  .control-row label { font-size: 14px; color: var(--text-dim); white-space: nowrap; }
  .ctl { display: flex; align-items: center; gap: 10px; min-width: 0; }
  .ctl input[type="range"] { flex: 1; min-width: 0; }
  .ctl .val { flex: none; width: 72px; text-align: right; font-size: 13px; }
  input[type="range"] { accent-color: var(--accent); }
  @media (max-width: 600px) { .control-row.sym.single { grid-template-columns: 64px 1fr; } }

  .toggle { display: inline-flex; align-items: baseline; gap: 7px; font-size: 13.5px; color: var(--text-dim); cursor: pointer; white-space: normal; }
  .toggle input { accent-color: var(--accent2); }

  .mono { font-family: var(--mono); font-variant-numeric: tabular-nums; }
  .dim { color: var(--text-dim); font-size: 12.5px; }

  .chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 8px; }
  .btn, .chip {
    font-family: var(--mono); font-size: 12.5px; color: var(--text);
    background: transparent; border: 1px solid var(--border); border-radius: 3px;
    padding: 6px 13px; cursor: pointer; transition: border-color 0.15s, color 0.15s;
  }
  .btn:hover, .chip:hover { border-color: var(--accent); color: var(--accent); }
  .btn.primary { border-color: var(--accent); color: var(--accent); }
  .btn.playing, .btn.playing:hover { border-color: var(--hot); color: var(--hot); }
  .btn.off { border-color: var(--hot); color: var(--hot); opacity: 0.85; }

  .plot { display: block; width: 100%; height: 220px; margin-top: 8px; }
  .plot.tall { height: 280px; }

  .readout-row { display: flex; gap: 28px; flex-wrap: wrap; margin: 14px 0 0; }
  .readout { text-align: left; }
  .readout .big {
    display: block; font-size: 28px; font-weight: 600; color: var(--accent);
    line-height: 1.1; min-width: 5ch; font-variant-numeric: tabular-nums;
  }
  .readout.accent .big { color: var(--accent2); }
  .readout .big.hot { color: var(--hot); }
  .readout small { color: var(--text-dim); font-size: 12.5px; }
  @media (max-width: 560px) {
    .widget { padding: 16px; }
    .readout-row { gap: 12px 18px; }
    .readout .big { font-size: 22px; }
    .plot { height: 180px; }
    .plot.tall { height: 220px; }
    .plot.pipe { height: 200px; }
    .narrow-hide { display: none; }
  }
  .plot.pipe { height: 250px; }
</style>
</head>
<body>
  <div class="widget" id="root">
    <div class="control-row sym single">
      <label for="pipe-fs">sample rate</label>
      <span class="ctl wide"><input type="range" id="pipe-fs" min="6" max="48" value="32" step="2"><span class="mono val" id="pipe-fs-label">32 /s</span></span>
    </div>
    <div class="control-row sym single">
      <label for="pipe-bits">bit depth</label>
      <span class="ctl wide"><input type="range" id="pipe-bits" min="2" max="8" value="5"><span class="mono val" id="pipe-bits-label">5 bits</span></span>
    </div>
    <div class="control-row">
      <button class="btn primary" id="pipe-play-in">&#9654; analog in</button>
      <button class="btn primary" id="pipe-play-out">&#9654; after the round trip</button>
      <span class="dim mono narrow-hide" id="pipe-audio-note">audio runs the same pipeline 100&times; faster: 220 + 470 Hz sampled at 3,200/s</span>
    </div>
    <canvas id="pipe-canvas" class="plot pipe"></canvas>
    <div class="readout-row">
      <div class="readout">
        <span class="big mono" id="pipe-nyq">16.0</span>
        <small>Nyquist &middot; cycles per window (signal tops out at 4.7)</small>
      </div>
      <div class="readout accent">
        <span class="big mono" id="pipe-snr">31.9</span>
        <small>SNR &middot; dB</small>
      </div>
    </div>
  </div>
  <script src="/w/_sdk/host.js?v=1"></script>
  <script src="/w/_lib/audio.js?v=1"></script>
  <script src="widget.js?v=1"></script>
</body>
</html>

widget.js

/* ADC → DAC round trip: analog in, sampled, quantized + held, sinc-filtered out; audible at 100× speed. */
(() => {
  'use strict';
  const K = window.AudioKit;
  const $ = (id) => document.getElementById(id);
  const F1 = 2.2, A1 = 0.62, F2 = 4.7, A2 = 0.30, PH2 = 1.3;
  const AUDIO_SCALE = 100;
  const TAPS = 40;
  let rate = 32, bits = 5, host = null;
  let dims = null, tau = 0, last = performance.now();

  const sig = (u) => A1 * Math.sin(2 * Math.PI * F1 * (u + tau)) + A2 * Math.sin(2 * Math.PI * F2 * (u + tau) + PH2);

  function labels() {
    $('pipe-fs-label').textContent = rate + ' /s';
    $('pipe-bits-label').textContent = bits + ' bits';
    const ny = $('pipe-nyq');
    ny.textContent = (rate / 2).toFixed(1);
    ny.classList.toggle('hot', rate / 2 < F2);
    $('pipe-snr').textContent = K.snrDb(bits).toFixed(1);
    $('pipe-audio-note').textContent = 'audio runs the same pipeline ' + AUDIO_SCALE + '× faster: ' +
      Math.round(F1 * AUDIO_SCALE) + ' + ' + Math.round(F2 * AUDIO_SCALE) + ' Hz sampled at ' + K.fmtInt(rate * AUDIO_SCALE) + '/s';
  }

  function frame(now) {
    const dt = Math.min(now - last, 50) / 1000;
    last = now;
    tau += dt * 0.10;
    const { ctx, w, h } = dims;
    const mOut = 10, gap = 26;
    const pw = (w - 2 * mOut - 3 * gap) / 4;
    const top = 12;
    const bandH = h - 46;
    const mid = top + bandH / 2;
    const amp = bandH * 0.42;
    const titles = ['analog in', 'sampled', 'quantized + held', 'filtered out'];

    const samples = [];
    for (let k = -8; k <= rate + 8; k++) samples.push({ k, t: k / rate, v: K.quantize(sig(k / rate), bits) });
    const held = (u) => samples[K.clamp(Math.floor(u * rate) + 8, 0, samples.length - 1)].v;
    const recon = (u) => {
      let y = 0;
      for (const s of samples) y += s.v * K.sinc((u - s.t) * rate);
      return y;
    };

    ctx.clearRect(0, 0, w, h);
    ctx.font = '10px ui-monospace, Menlo, monospace';
    ctx.textAlign = 'center';

    for (let p = 0; p < 4; p++) {
      const x0 = mOut + p * (pw + gap);
      ctx.strokeStyle = K.T.GRID;
      ctx.lineWidth = 1;
      ctx.strokeRect(x0, top, pw, bandH);
      K.hline(ctx, x0, x0 + pw, mid, K.T.GRID);
      ctx.fillStyle = K.T.DIM;
      ctx.textAlign = 'center';
      ctx.fillText(titles[p], x0 + pw / 2, h - 14);
      if (p < 3) {
        ctx.font = '15px ui-monospace, Menlo, monospace';
        ctx.fillText('→', x0 + pw + gap / 2, mid + 5);
        ctx.font = '10px ui-monospace, Menlo, monospace';
      }
      if (p === 0 || p === 2 || p === 3) {
        const fn = p === 0 ? sig : p === 2 ? held : recon;
        const color = p === 0 ? K.T.ACCENT : p === 2 ? K.T.ACCENT2 : K.T.OK;
        K.trace(ctx, x0, x0 + pw, (u) => mid - K.clamp(fn(u), -1.1, 1.1) * amp, color, p === 2 ? 1.8 : 2);
      }
      if (p === 1) {
        for (const s of samples) {
          if (s.t < 0 || s.t > 1) continue;
          K.lollipop(ctx, x0 + s.t * pw, mid, mid - sig(s.t) * amp, 2.2);
        }
      }
    }
    requestAnimationFrame(frame);
  }

  function renderAudio(sr, roundTrip) {
    const len = sr;
    const out = new Float32Array(len);
    const f1 = F1 * AUDIO_SCALE, f2 = F2 * AUDIO_SCALE;
    const analog = (t) => A1 * Math.sin(2 * Math.PI * f1 * t) + A2 * Math.sin(2 * Math.PI * f2 * t + PH2);
    if (!roundTrip) {
      for (let i = 0; i < len; i++) out[i] = analog(i / sr);
      return out;
    }
    const fs = rate * AUDIO_SCALE;
    const q = new Float32Array(fs);
    for (let n = 0; n < fs; n++) q[n] = K.quantize(analog(n / fs), bits);
    const sampleAt = (n) => q[((n % fs) + fs) % fs];
    for (let i = 0; i < len; i++) out[i] = K.sincReconstruct(sampleAt, fs, i / sr, TAPS);
    return out;
  }

  const ping = (data) => { if (host && host.signal) host.signal('interaction', data); };
  function setRate(r) { rate = K.clamp(Math.round(r / 2) * 2, 6, 48); $('pipe-fs').value = rate; labels(); }
  function setBits(b) { bits = K.clamp(Math.round(b), 2, 8); $('pipe-bits').value = bits; labels(); }

  $('pipe-fs').addEventListener('input', () => { setRate(+$('pipe-fs').value); ping({ rate, bits }); });
  $('pipe-bits').addEventListener('input', () => { setBits(+$('pipe-bits').value); ping({ rate, bits }); });

  const playBuffer = (btn, roundTrip) => K.bindPlay(btn, (ctx) => {
    const loop = K.loopBuffer(ctx, renderAudio(ctx.sampleRate, roundTrip), 0.28);
    loop.start();
    return () => loop.stop();
  }, () => ping({ play: roundTrip ? 'round-trip' : 'analog', rate, bits }));
  playBuffer($('pipe-play-in'), false);
  playBuffer($('pipe-play-out'), true);
  K.stopWhenHidden($('root'));

  function layout() { dims = K.setupCanvas($('pipe-canvas')); }
  K.debounceResize(layout);
  layout();
  labels();
  requestAnimationFrame(frame);

  LearnWidget.connect().then((h) => {
    host = h;
    K.fitFrame(h, $('root'));
    const apply = (p) => {
      if (typeof p.rate === 'number') setRate(p.rate);
      if (typeof p.bits === 'number') setBits(p.bits);
    };
    apply(h.params || {});
    h.on('theme.changed', K.readTheme);
    h.on('params.changed', apply);
    K.readTheme();
  });
})();