@hussmartinez/audio-sdk 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -18,8 +18,8 @@ function audioWorkerSource(assetsUrl) {
18
18
  loadWorker: selfHosted ? async () => () => new Worker(selfHosted, {
19
19
  type: "module",
20
20
  name: "hm-audio"
21
- }) : async () => (await import("./lazy/inline-worker-C5z229iw.js")).createInlineWorker,
22
- version: "0.3.1",
21
+ }) : async () => (await import("./lazy/inline-worker-CR5UIkzK.js")).createInlineWorker,
22
+ version: "0.5.0",
23
23
  ...selfHosted ? { asset: selfHosted } : {}
24
24
  };
25
25
  }
@@ -336,6 +336,253 @@ function assertClip(clip, sourceFrames) {
336
336
  const problem = clipProblem(clip, sourceFrames);
337
337
  if (problem) throw new RangeError(`Clip ${clip.key} isn't valid: ${problem}.`);
338
338
  }
339
+ // src/core/model/envelope.ts
340
+ function dbToGain(db) {
341
+ return 10 ** (db / 20);
342
+ }
343
+ function fadeShape(curve, position) {
344
+ return curve === "equalPower" ? Math.sin(position * Math.PI / 2) : position;
345
+ }
346
+ function gainAt(clip, frame) {
347
+ const length = clip.end - clip.start;
348
+ let gain = dbToGain(clip.gainDb);
349
+ const { fadeIn, fadeOut } = clip;
350
+ if (fadeIn.frames > 0 && frame < fadeIn.frames) gain *= fadeShape(fadeIn.curve, frame / fadeIn.frames);
351
+ const fromEnd = length - 1 - frame;
352
+ if (fadeOut.frames > 0 && fromEnd < fadeOut.frames) gain *= fadeShape(fadeOut.curve, Math.max(0, fromEnd) / fadeOut.frames);
353
+ return gain;
354
+ }
355
+ // src/adapters/web-audio/gain-automation.ts
356
+ var MAX_CURVE_POINTS = 1024;
357
+ function curve(clip, from, to) {
358
+ const points = Math.min(MAX_CURVE_POINTS, to - from + 1);
359
+ const values = new Float32Array(points);
360
+ for (let i = 0; i < points; i += 1) {
361
+ const frame = points === 1 ? from : from + (to - from) * i / (points - 1);
362
+ values[i] = gainAt(clip, Math.round(frame));
363
+ }
364
+ return values;
365
+ }
366
+ function gainEvents(clip, from, sampleRate) {
367
+ const length = clipLength(clip);
368
+ const fadeInEnd = clip.fadeIn.frames;
369
+ const fadeOutStart = length - clip.fadeOut.frames;
370
+ const at = (frame) => (frame - from) / sampleRate;
371
+ const events = [];
372
+ let cursor = from;
373
+ if (from < fadeInEnd) {
374
+ events.push({
375
+ kind: "curve",
376
+ time: 0,
377
+ duration: at(fadeInEnd),
378
+ values: curve(clip, from, fadeInEnd)
379
+ });
380
+ cursor = fadeInEnd;
381
+ }
382
+ const outFrom = Math.max(cursor, fadeOutStart);
383
+ const fadingOut = clip.fadeOut.frames > 0 && outFrom < length - 1;
384
+ if (events.length === 0 && !(fadingOut && outFrom === from)) events.push({
385
+ kind: "set",
386
+ time: 0,
387
+ value: gainAt(clip, from)
388
+ });
389
+ if (fadingOut) events.push({
390
+ kind: "curve",
391
+ time: at(outFrom),
392
+ duration: at(length - 1) - at(outFrom),
393
+ values: curve(clip, outFrom, length - 1)
394
+ });
395
+ else if (clip.fadeOut.frames > 0 && outFrom > cursor) events.push({
396
+ kind: "set",
397
+ time: at(outFrom),
398
+ value: gainAt(clip, outFrom)
399
+ });
400
+ return events;
401
+ }
402
+ // src/adapters/web-audio/play-graph.ts
403
+ function schedulePlan(context, destination, plan, buffer, from, at) {
404
+ const rate = plan.sampleRate;
405
+ const bus = context.createGain();
406
+ bus.channelCount = plan.channels;
407
+ bus.channelCountMode = "explicit";
408
+ bus.channelInterpretation = "speakers";
409
+ bus.connect(destination);
410
+ const nodes = [];
411
+ const offsets = clipOffsets(plan);
412
+ const end = planLength(plan);
413
+ for (const [index, clip] of plan.clips.entries()) {
414
+ const offset = offsets[index];
415
+ const length = clipLength(clip);
416
+ if (offset + length <= from || offset >= end) continue;
417
+ const within = Math.max(0, from - offset);
418
+ const when = at + Math.max(0, offset - from) / rate;
419
+ const source = context.createBufferSource();
420
+ source.buffer = buffer(clip.source);
421
+ const gain = context.createGain();
422
+ for (const event of gainEvents(clip, within, rate)) if (event.kind === "set") gain.gain.setValueAtTime(event.value, when + event.time);
423
+ else gain.gain.setValueCurveAtTime(event.values, when + event.time, event.duration);
424
+ source.connect(gain).connect(bus);
425
+ source.start(when, (clip.start + within) / rate, (length - within) / rate);
426
+ nodes.push({
427
+ source,
428
+ gain
429
+ });
430
+ }
431
+ return { stop() {
432
+ for (const { source, gain } of nodes) {
433
+ try {
434
+ source.stop();
435
+ } catch {}
436
+ source.disconnect();
437
+ gain.disconnect();
438
+ }
439
+ bus.disconnect();
440
+ } };
441
+ }
442
+ // src/adapters/audio-output.ts
443
+ var START_LEAD = .03;
444
+ var RESUME_TIMEOUT = 2e3;
445
+ function createAudioOutput() {
446
+ return createOutput({ createContext: () => new AudioContext() });
447
+ }
448
+ function createOutput(environment) {
449
+ const store = createStore(Object.freeze({ state: "stopped" }));
450
+ const copies = /* @__PURE__ */ new WeakMap();
451
+ let context;
452
+ let plan;
453
+ let sources = /* @__PURE__ */ new Map();
454
+ let playhead = 0;
455
+ let playing;
456
+ let endTimer;
457
+ let destroyed = false;
458
+ const length = () => plan ? planLength(plan) : 0;
459
+ const assertAlive = () => {
460
+ if (destroyed) throw new Error("The audio output has been destroyed.");
461
+ };
462
+ const setState = (state) => {
463
+ if (store.getSnapshot().state !== state) store.set(Object.freeze({ state }));
464
+ };
465
+ function buffer(id) {
466
+ const audio = sources.get(id);
467
+ if (!audio) throw new TypeError(`The plan's source ${id} isn't loaded.`);
468
+ if (audio instanceof AudioBuffer) return audio;
469
+ let copy = copies.get(audio);
470
+ if (!copy) {
471
+ copy = new AudioBuffer({
472
+ length: audio.length,
473
+ numberOfChannels: audio.numberOfChannels,
474
+ sampleRate: audio.sampleRate
475
+ });
476
+ for (let channel = 0; channel < audio.numberOfChannels; channel += 1) copy.copyToChannel(Float32Array.from(audio.getChannelData(channel)), channel);
477
+ copies.set(audio, copy);
478
+ }
479
+ return copy;
480
+ }
481
+ function position() {
482
+ if (!playing || !context || !plan) return playhead;
483
+ const elapsed = Math.max(0, context.currentTime - playing.time);
484
+ return Math.min(length(), Math.floor(playing.frame + elapsed * plan.sampleRate));
485
+ }
486
+ function unschedule() {
487
+ if (!playing) return;
488
+ playhead = position();
489
+ playing.scheduled.stop();
490
+ playing = void 0;
491
+ clearTimeout(endTimer);
492
+ endTimer = void 0;
493
+ }
494
+ function watchEnd() {
495
+ clearTimeout(endTimer);
496
+ if (!playing || !context || !plan) return;
497
+ const remaining = playing.time - context.currentTime + (length() - playing.frame) / plan.sampleRate;
498
+ endTimer = setTimeout(() => {
499
+ if (position() >= length()) {
500
+ unschedule();
501
+ playhead = length();
502
+ setState("stopped");
503
+ } else watchEnd();
504
+ }, Math.max(0, remaining * 1e3) + 5);
505
+ }
506
+ function schedule() {
507
+ if (!context || !plan) return;
508
+ const time = context.currentTime + START_LEAD;
509
+ playing = {
510
+ scheduled: schedulePlan(context, context.destination, plan, buffer, playhead, time),
511
+ frame: playhead,
512
+ time
513
+ };
514
+ watchEnd();
515
+ }
516
+ async function running(audio) {
517
+ if (audio.state === "running") return true;
518
+ let timer;
519
+ const timedOut = new Promise((resolve) => {
520
+ timer = setTimeout(() => resolve(false), RESUME_TIMEOUT);
521
+ });
522
+ try {
523
+ await Promise.race([audio.resume().then(() => true), timedOut]);
524
+ } finally {
525
+ clearTimeout(timer);
526
+ }
527
+ return audio.state === "running";
528
+ }
529
+ return {
530
+ getSnapshot: store.getSnapshot,
531
+ subscribe: store.subscribe,
532
+ position,
533
+ load(next, nextSources) {
534
+ assertAlive();
535
+ const wasPlaying = playing !== void 0;
536
+ unschedule();
537
+ plan = next;
538
+ sources = nextSources;
539
+ playhead = Math.min(playhead, length());
540
+ if (!wasPlaying) return;
541
+ if (playhead >= length()) {
542
+ playhead = length();
543
+ setState("stopped");
544
+ } else schedule();
545
+ },
546
+ async play() {
547
+ assertAlive();
548
+ if (length() === 0 || playing) return;
549
+ context ??= environment.createContext();
550
+ if (!await running(context)) throw new AudioError("UNSUPPORTED_ENVIRONMENT", "The browser didn't start audio output. Play from a click or a key press.", { details: { feature: "audio-output" } });
551
+ if (destroyed || playing || length() === 0) return;
552
+ if (playhead >= length()) playhead = 0;
553
+ schedule();
554
+ setState("playing");
555
+ },
556
+ pause() {
557
+ assertAlive();
558
+ if (!playing) return;
559
+ unschedule();
560
+ setState("paused");
561
+ },
562
+ stop() {
563
+ assertAlive();
564
+ unschedule();
565
+ playhead = 0;
566
+ setState("stopped");
567
+ },
568
+ seek(frame) {
569
+ assertAlive();
570
+ const wasPlaying = playing !== void 0;
571
+ unschedule();
572
+ playhead = Math.max(0, Math.min(Math.round(frame), length()));
573
+ if (wasPlaying && playhead < length()) schedule();
574
+ else if (wasPlaying) setState("stopped");
575
+ },
576
+ async destroy() {
577
+ if (destroyed) return;
578
+ destroyed = true;
579
+ unschedule();
580
+ setState("stopped");
581
+ await context?.close().catch(() => {});
582
+ context = void 0;
583
+ }
584
+ };
585
+ }
339
586
  // src/adapters/wav/wav-writer.ts
340
587
  var BYTES = {
341
588
  pcm16: 2,
@@ -1130,22 +1377,6 @@ function toAudioPlanDocument(plan, sources) {
1130
1377
  metadata: { ...plan.metadata }
1131
1378
  };
1132
1379
  }
1133
- // src/core/model/envelope.ts
1134
- function dbToGain(db) {
1135
- return 10 ** (db / 20);
1136
- }
1137
- function fadeShape(curve, position) {
1138
- return curve === "equalPower" ? Math.sin(position * Math.PI / 2) : position;
1139
- }
1140
- function gainAt(clip, frame) {
1141
- const length = clip.end - clip.start;
1142
- let gain = dbToGain(clip.gainDb);
1143
- const { fadeIn, fadeOut } = clip;
1144
- if (fadeIn.frames > 0 && frame < fadeIn.frames) gain *= fadeShape(fadeIn.curve, frame / fadeIn.frames);
1145
- const fromEnd = length - 1 - frame;
1146
- if (fadeOut.frames > 0 && fromEnd < fadeOut.frames) gain *= fadeShape(fadeOut.curve, Math.max(0, fromEnd) / fadeOut.frames);
1147
- return gain;
1148
- }
1149
1380
  // src/core/model/time.ts
1150
1381
  function framesToSeconds(frames, sampleRate) {
1151
1382
  return frames / sampleRate;
@@ -1153,6 +1384,32 @@ function framesToSeconds(frames, sampleRate) {
1153
1384
  function secondsToFrames(seconds, sampleRate) {
1154
1385
  return Math.round(seconds * sampleRate);
1155
1386
  }
1387
+ // src/core/session/connect-output.ts
1388
+ function connectOutput(session, output) {
1389
+ let plan;
1390
+ let held = /* @__PURE__ */ new Set();
1391
+ function sync() {
1392
+ const snapshot = session.getSnapshot();
1393
+ const next = snapshot.plan;
1394
+ const ids = new Set(snapshot.sources.map((source) => source.id));
1395
+ if (next === plan) {
1396
+ held = ids;
1397
+ return;
1398
+ }
1399
+ if ((next === void 0 || plan !== void 0 && !next.clips.some((clip) => held.has(clip.source))) && plan !== void 0) output.stop();
1400
+ plan = next;
1401
+ held = ids;
1402
+ if (!next) return;
1403
+ const sources = /* @__PURE__ */ new Map();
1404
+ for (const { source } of next.clips) {
1405
+ const audio = session.getAudio(source);
1406
+ if (audio) sources.set(source, audio);
1407
+ }
1408
+ output.load(next, sources);
1409
+ }
1410
+ sync();
1411
+ return session.subscribe(sync);
1412
+ }
1156
1413
  // src/core/session/session.ts
1157
1414
  var BYTES_PER_SAMPLE = 4;
1158
1415
  function clipsOf(command) {
@@ -1558,6 +1815,7 @@ function createAudioSession(options) {
1558
1815
  changed();
1559
1816
  },
1560
1817
  getPeaks: (id) => sources.get(id)?.peaks,
1818
+ getAudio: (id) => sources.get(id)?.audio,
1561
1819
  async export(exportOptions = {}) {
1562
1820
  const current = plan;
1563
1821
  const format = exportOptions.format ?? { container: "wav" };
@@ -1646,6 +1904,6 @@ var audioMessages = /* @__PURE__ */ defineMessages({
1646
1904
  }),
1647
1905
  "warnings.truncated": "This recording looks incomplete, perhaps from an interrupted recording or download. It opened with the audio it holds."
1648
1906
  });
1649
- export { AUDIO_PLAN_FORMAT, AUDIO_PLAN_VERSION, AudioError, EMPTY_METADATA, MAX_GAIN_DB, MAX_METADATA_LENGTH, MIN_GAIN_DB, NO_FADE, audioLimitDefinitions, audioLimits, audioMessages, clipLength, clipOffsets, createAudioEngine, createAudioProcessor, createAudioSession, dbToGain, framesToSeconds, gainAt, isAudioError, planLength, readAudioPlanDocument, secondsToFrames, toAudioPlanDocument };
1907
+ export { AUDIO_PLAN_FORMAT, AUDIO_PLAN_VERSION, AudioError, EMPTY_METADATA, MAX_GAIN_DB, MAX_METADATA_LENGTH, MIN_GAIN_DB, NO_FADE, audioLimitDefinitions, audioLimits, audioMessages, clipLength, clipOffsets, connectOutput, createAudioEngine, createAudioOutput, createAudioProcessor, createAudioSession, dbToGain, framesToSeconds, gainAt, isAudioError, planLength, readAudioPlanDocument, secondsToFrames, toAudioPlanDocument };
1650
1908
 
1651
1909
  //# sourceMappingURL=index.js.map