@waveform-playlist/browser 16.0.1 → 17.0.0-next.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/tone.mjs CHANGED
@@ -38,213 +38,11 @@ var __async = (__this, __arguments, generator) => {
38
38
  });
39
39
  };
40
40
 
41
- // src/hooks/useAudioTracks.ts
42
- import { useState, useEffect, useRef, useMemo } from "react";
43
- import * as Tone from "tone";
44
-
45
- // src/hooks/buildTrackFromConfig.ts
46
- import { createTrack, createClipFromSeconds } from "@waveform-playlist/core";
47
- function buildTrackFromConfig(config, index, audioBuffer, stableIds, contextSampleRate = 48e3, options = {}) {
48
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p;
49
- const buffer = audioBuffer != null ? audioBuffer : config.audioBuffer;
50
- const sampleRate = (_c = (_b = buffer == null ? void 0 : buffer.sampleRate) != null ? _b : (_a = config.waveformData) == null ? void 0 : _a.sample_rate) != null ? _c : contextSampleRate;
51
- const sourceDuration = (_g = (_e = buffer == null ? void 0 : buffer.duration) != null ? _e : (_d = config.waveformData) == null ? void 0 : _d.duration) != null ? _g : config.duration != null ? config.duration + ((_f = config.offset) != null ? _f : 0) : void 0;
52
- if (sourceDuration === void 0) {
53
- if (!options.suppressMissingDurationWarning) {
54
- console.warn(
55
- `[waveform-playlist] Track ${index + 1} ("${(_h = config.name) != null ? _h : "unnamed"}"): Cannot create track \u2014 provide duration, audioBuffer, or waveformData with duration.`
56
- );
57
- }
58
- return null;
59
- }
60
- const clip = createClipFromSeconds({
61
- audioBuffer: buffer,
62
- sampleRate,
63
- sourceDuration,
64
- startTime: (_i = config.startTime) != null ? _i : 0,
65
- duration: (_j = config.duration) != null ? _j : sourceDuration,
66
- offset: (_k = config.offset) != null ? _k : 0,
67
- name: config.name || `Track ${index + 1}`,
68
- fadeIn: config.fadeIn,
69
- fadeOut: config.fadeOut,
70
- waveformData: config.waveformData
71
- });
72
- if (isNaN(clip.startSample) || isNaN(clip.durationSamples) || isNaN(clip.offsetSamples)) {
73
- console.error(
74
- `[waveform-playlist] Invalid clip values for track ${index + 1} ("${(_l = config.name) != null ? _l : "unnamed"}"): startSample=${clip.startSample}, durationSamples=${clip.durationSamples}, offsetSamples=${clip.offsetSamples}`
75
- );
76
- return null;
77
- }
78
- const track = __spreadProps(__spreadValues({}, createTrack({
79
- name: config.name || `Track ${index + 1}`,
80
- clips: [clip],
81
- muted: (_m = config.muted) != null ? _m : false,
82
- soloed: (_n = config.soloed) != null ? _n : false,
83
- volume: (_o = config.volume) != null ? _o : 1,
84
- pan: (_p = config.pan) != null ? _p : 0,
85
- color: config.color
86
- })), {
87
- effects: config.effects,
88
- renderMode: config.renderMode,
89
- spectrogramConfig: config.spectrogramConfig,
90
- spectrogramColorMap: config.spectrogramColorMap
91
- });
92
- const existingIds = stableIds.get(index);
93
- if (existingIds) {
94
- track.id = existingIds.trackId;
95
- track.clips[0] = __spreadProps(__spreadValues({}, track.clips[0]), { id: existingIds.clipId });
96
- } else {
97
- stableIds.set(index, { trackId: track.id, clipId: track.clips[0].id });
98
- }
99
- return track;
100
- }
101
-
102
- // src/hooks/useAudioTracks.ts
103
- function useAudioTracks(configs, options = {}) {
104
- const { immediate = false, progressive = false } = options;
105
- const isImmediate = immediate || progressive;
106
- const [loading, setLoading] = useState(true);
107
- const [error, setError] = useState(null);
108
- const [loadedCount, setLoadedCount] = useState(0);
109
- const totalCount = configs.length;
110
- const [loadedBuffers, setLoadedBuffers] = useState(/* @__PURE__ */ new Map());
111
- const stableIdsRef = useRef(/* @__PURE__ */ new Map());
112
- const contextSampleRateRef = useRef(48e3);
113
- const derivedTracks = useMemo(() => {
114
- if (!isImmediate) return null;
115
- const result = [];
116
- for (let i = 0; i < configs.length; i++) {
117
- const pendingDecode = !loadedBuffers.has(i) && !configs[i].audioBuffer && configs[i].src != null;
118
- const track = buildTrackFromConfig(
119
- configs[i],
120
- i,
121
- loadedBuffers.get(i),
122
- stableIdsRef.current,
123
- contextSampleRateRef.current,
124
- { suppressMissingDurationWarning: pendingDecode }
125
- );
126
- if (track) result.push(track);
127
- }
128
- return result;
129
- }, [isImmediate, configs, loadedBuffers]);
130
- const [tracks, setTracks] = useState(derivedTracks != null ? derivedTracks : []);
131
- const prevDerivedRef = useRef(derivedTracks);
132
- if (derivedTracks !== prevDerivedRef.current) {
133
- prevDerivedRef.current = derivedTracks;
134
- if (derivedTracks) setTracks(derivedTracks);
135
- }
136
- useEffect(() => {
137
- if (configs.length === 0) {
138
- setTracks([]);
139
- setLoading(false);
140
- setLoadedCount(0);
141
- return;
142
- }
143
- let cancelled = false;
144
- const abortController = new AbortController();
145
- const loadTracks = () => __async(null, null, function* () {
146
- try {
147
- setLoading(true);
148
- setError(null);
149
- setLoadedCount(0);
150
- if (isImmediate) {
151
- setLoadedBuffers(/* @__PURE__ */ new Map());
152
- }
153
- const audioContext = Tone.getContext().rawContext;
154
- contextSampleRateRef.current = audioContext.sampleRate;
155
- const loadPromises = configs.map((config, index) => __async(null, null, function* () {
156
- if (config.audioBuffer) {
157
- if (isImmediate && !cancelled) {
158
- setLoadedBuffers((prev) => {
159
- const next = new Map(prev);
160
- next.set(index, config.audioBuffer);
161
- return next;
162
- });
163
- setLoadedCount((prev) => prev + 1);
164
- return;
165
- }
166
- return buildTrackFromConfig(
167
- config,
168
- index,
169
- config.audioBuffer,
170
- stableIdsRef.current,
171
- audioContext.sampleRate
172
- );
173
- }
174
- if (!config.src && config.waveformData) {
175
- if (isImmediate && !cancelled) {
176
- setLoadedCount((prev) => prev + 1);
177
- return;
178
- }
179
- return buildTrackFromConfig(
180
- config,
181
- index,
182
- void 0,
183
- stableIdsRef.current,
184
- audioContext.sampleRate
185
- );
186
- }
187
- if (!config.src) {
188
- throw new Error(`Track ${index + 1}: Must provide src, audioBuffer, or waveformData`);
189
- }
190
- const response = yield fetch(config.src, { signal: abortController.signal });
191
- if (!response.ok) {
192
- throw new Error(`Failed to fetch ${config.src}: ${response.statusText}`);
193
- }
194
- const arrayBuffer = yield response.arrayBuffer();
195
- const audioBuffer = yield audioContext.decodeAudioData(arrayBuffer);
196
- if (!audioBuffer || !audioBuffer.sampleRate || !audioBuffer.duration) {
197
- throw new Error(`Invalid audio buffer for ${config.src}`);
198
- }
199
- if (isImmediate && !cancelled) {
200
- setLoadedBuffers((prev) => {
201
- const next = new Map(prev);
202
- next.set(index, audioBuffer);
203
- return next;
204
- });
205
- setLoadedCount((prev) => prev + 1);
206
- return;
207
- }
208
- return buildTrackFromConfig(
209
- config,
210
- index,
211
- audioBuffer,
212
- stableIdsRef.current,
213
- audioContext.sampleRate
214
- );
215
- }));
216
- const loadedTracks = yield Promise.all(loadPromises);
217
- if (!cancelled) {
218
- if (!isImmediate) {
219
- const validTracks = loadedTracks.filter((t) => t != null);
220
- setTracks(validTracks);
221
- setLoadedCount(validTracks.length);
222
- }
223
- setLoading(false);
224
- }
225
- } catch (err) {
226
- if (!cancelled) {
227
- const errorMessage = err instanceof Error ? err.message : "Unknown error loading audio";
228
- setError(errorMessage);
229
- setLoading(false);
230
- console.error(`[waveform-playlist] Error loading audio tracks: ${errorMessage}`);
231
- }
232
- }
233
- });
234
- loadTracks();
235
- return () => {
236
- cancelled = true;
237
- abortController.abort();
238
- };
239
- }, [configs, isImmediate]);
240
- return { tracks, loading, error, loadedCount, totalCount };
241
- }
242
-
243
41
  // src/hooks/useAudioEffects.ts
244
- import { useRef as useRef2, useCallback } from "react";
42
+ import { useRef, useCallback } from "react";
245
43
  import { Analyser } from "tone";
246
44
  var useMasterAnalyser = (fftSize = 256) => {
247
- const analyserRef = useRef2(null);
45
+ const analyserRef = useRef(null);
248
46
  const masterEffects = useCallback(
249
47
  (masterGainNode, destination, _isOffline) => {
250
48
  const analyserNode = new Analyser("fft", fftSize);
@@ -262,11 +60,16 @@ var useMasterAnalyser = (fftSize = 256) => {
262
60
  };
263
61
 
264
62
  // src/hooks/useDynamicEffects.ts
265
- import { useState as useState2, useCallback as useCallback2, useRef as useRef3, useEffect as useEffect2 } from "react";
63
+ import { useCallback as useCallback2, useMemo, useRef as useRef2, useState } from "react";
64
+ import { Analyser as Analyser2 } from "tone";
65
+
66
+ // src/effects/customEffectFactory.ts
67
+ import { connect, disconnect } from "tone";
68
+ import { isNativeGlobalContext } from "@waveform-playlist/playout";
266
69
  import {
267
- isNativeGlobalContext,
268
- getGlobalAudioContext
269
- } from "@waveform-playlist/playout";
70
+ createEffectInstance as createRegisteredEffect,
71
+ getEffectDefinitions
72
+ } from "@waveform-playlist/core";
270
73
 
271
74
  // src/effects/effectDefinitions.ts
272
75
  var effectDefinitions = [
@@ -814,6 +617,113 @@ var effectCategories = [
814
617
  { id: "spatial", name: "Spatial" }
815
618
  ];
816
619
 
620
+ // src/effects/customEffectFactory.ts
621
+ var converted = /* @__PURE__ */ new WeakMap();
622
+ function toEffectDefinition(type, definition) {
623
+ var _a;
624
+ const byType = (_a = converted.get(definition)) != null ? _a : /* @__PURE__ */ new Map();
625
+ converted.set(definition, byType);
626
+ const existing = byType.get(type);
627
+ if (existing) return existing;
628
+ const parameters = Object.entries(definition.params).map(([name, param]) => {
629
+ var _a2, _b;
630
+ return __spreadProps(__spreadValues(__spreadValues({
631
+ name,
632
+ label: (_a2 = param.label) != null ? _a2 : name,
633
+ type: "number",
634
+ min: param.min,
635
+ max: param.max
636
+ }, param.step !== void 0 ? { step: param.step } : {}), param.unit !== void 0 ? { unit: param.unit } : {}), {
637
+ default: (_b = definition.defaults[name]) != null ? _b : param.min
638
+ });
639
+ });
640
+ const result = {
641
+ id: type,
642
+ name: definition.label,
643
+ category: definition.category,
644
+ description: "",
645
+ parameters
646
+ };
647
+ byType.set(type, result);
648
+ return result;
649
+ }
650
+ var availableCache = null;
651
+ function getAvailableEffects() {
652
+ if (!isNativeGlobalContext()) return effectDefinitions;
653
+ const custom = [];
654
+ getEffectDefinitions().forEach((definition, type) => {
655
+ if (definition.builtIn || getEffectDefinition(type)) return;
656
+ custom.push(toEffectDefinition(type, definition));
657
+ });
658
+ if (custom.length === 0) return effectDefinitions;
659
+ const cached = availableCache;
660
+ if (cached && cached.custom.length === custom.length && cached.custom.every((definition, i) => definition === custom[i])) {
661
+ return cached.list;
662
+ }
663
+ const list = [...effectDefinitions, ...custom];
664
+ availableCache = { custom, list };
665
+ return list;
666
+ }
667
+ function numericParams(params) {
668
+ const result = {};
669
+ for (const [name, value] of Object.entries(params)) {
670
+ if (typeof value === "number") result[name] = value;
671
+ }
672
+ return result;
673
+ }
674
+ var customInstanceCounter = 0;
675
+ function createCustomEffectInstance(type, audioContext, params = {}) {
676
+ const created = createRegisteredEffect(type, audioContext, numericParams(params));
677
+ const native = created.instance;
678
+ const current = __spreadValues({}, created.params);
679
+ const instanceId = "custom_" + ++customInstanceCounter;
680
+ const disconnectOutput = () => {
681
+ try {
682
+ disconnect(native.output);
683
+ } catch (err) {
684
+ console.warn(
685
+ '[waveform-playlist] Error disconnecting effect "' + type + '" (' + instanceId + "): " + (err instanceof Error ? err.message : String(err))
686
+ );
687
+ }
688
+ };
689
+ return {
690
+ kind: "custom",
691
+ native,
692
+ input: native.input,
693
+ output: native.output,
694
+ id: type,
695
+ instanceId,
696
+ dispose: () => {
697
+ var _a;
698
+ disconnectOutput();
699
+ try {
700
+ (_a = native.dispose) == null ? void 0 : _a.call(native);
701
+ } catch (err) {
702
+ console.warn(
703
+ '[waveform-playlist] Error disposing effect "' + type + '" (' + instanceId + "): " + (err instanceof Error ? err.message : String(err))
704
+ );
705
+ }
706
+ },
707
+ setParameter: (name, value) => {
708
+ if (typeof value !== "number") return;
709
+ current[name] = value;
710
+ native.applyParams({ [name]: value });
711
+ },
712
+ getParameter: (name) => current[name],
713
+ connect: (destination) => connect(native.output, destination),
714
+ disconnect: disconnectOutput
715
+ };
716
+ }
717
+
718
+ // src/effects/effectsRack.ts
719
+ import { connect as connect5, disconnect as disconnect3 } from "tone";
720
+ import { isNativeGlobalContext as isNativeGlobalContext2, getGlobalAudioContext } from "@waveform-playlist/playout";
721
+ import {
722
+ createValueSource,
723
+ ensureEffectPrepared as ensureEffectPrepared2,
724
+ getEffectDefinitions as getEffectDefinitions2
725
+ } from "@waveform-playlist/core";
726
+
817
727
  // src/effects/effectFactory.ts
818
728
  import {
819
729
  Reverb,
@@ -836,8 +746,9 @@ import {
836
746
  Limiter,
837
747
  Gate,
838
748
  StereoWidener,
839
- connect
749
+ connect as connect2
840
750
  } from "tone";
751
+ import { getGlobalContext } from "@waveform-playlist/playout";
841
752
  function asEffectConstructor(ctor) {
842
753
  return ctor;
843
754
  }
@@ -878,11 +789,13 @@ function createEffectInstance(definition, initialParams) {
878
789
  const value = (_a = initialParams == null ? void 0 : initialParams[param.name]) != null ? _a : param.default;
879
790
  options[param.name] = value;
880
791
  });
792
+ getGlobalContext();
881
793
  const effect = new Constructor(options);
882
794
  const instanceId = generateInstanceId();
883
795
  const effectRecord = effect;
884
796
  return {
885
- effect,
797
+ input: effect,
798
+ output: effect,
886
799
  id: definition.id,
887
800
  instanceId,
888
801
  dispose() {
@@ -947,11 +860,11 @@ function createEffectChain(effects) {
947
860
  throw new Error("Cannot create effect chain with no effects");
948
861
  }
949
862
  for (let i = 0; i < effects.length - 1; i++) {
950
- connect(effects[i].effect, effects[i + 1].effect);
863
+ connect2(effects[i].output, effects[i + 1].input);
951
864
  }
952
865
  return {
953
- input: effects[0].effect,
954
- output: effects[effects.length - 1].effect,
866
+ input: effects[0].input,
867
+ output: effects[effects.length - 1].output,
955
868
  dispose() {
956
869
  effects.forEach((e) => e.dispose());
957
870
  }
@@ -973,7 +886,7 @@ function loadWamModule() {
973
886
  }
974
887
 
975
888
  // src/effects/wamEffectFactory.ts
976
- import { connect as connect2, disconnect } from "tone";
889
+ import { connect as connect3, disconnect as disconnect2 } from "tone";
977
890
  var wamInstanceCounter = 0;
978
891
  function createWamEffectInstance(plugin) {
979
892
  var _a, _b, _c;
@@ -983,7 +896,8 @@ function createWamEffectInstance(plugin) {
983
896
  kind: "wam",
984
897
  plugin,
985
898
  url: plugin.url,
986
- effect: node,
899
+ input: node,
900
+ output: node,
987
901
  id: "wam:" + ((_c = (_b = (_a = plugin.descriptor) == null ? void 0 : _a.name) != null ? _b : plugin.url) != null ? _c : "plugin"),
988
902
  instanceId,
989
903
  dispose: () => {
@@ -1003,13 +917,14 @@ function createWamEffectInstance(plugin) {
1003
917
  },
1004
918
  getParameter: () => void 0,
1005
919
  // WAM params are async; read via the plugin GUI
1006
- connect: (destination) => connect2(node, destination),
1007
- disconnect: () => disconnect(node)
920
+ connect: (destination) => connect3(node, destination),
921
+ disconnect: () => disconnect2(node)
1008
922
  };
1009
923
  }
1010
924
 
1011
925
  // src/effects/offlineChain.ts
1012
- import { connect as connect3 } from "tone";
926
+ import { connect as connect4 } from "tone";
927
+ import { ensureEffectPrepared } from "@waveform-playlist/core";
1013
928
  function buildOfflineChain(entries, getLivePlugin, rawContext) {
1014
929
  return __async(this, null, function* () {
1015
930
  const instances = [];
@@ -1018,10 +933,15 @@ function buildOfflineChain(entries, getLivePlugin, rawContext) {
1018
933
  };
1019
934
  try {
1020
935
  for (const entry of entries) {
1021
- if (entry.kind === "native") {
936
+ if (entry.kind === "tone") {
1022
937
  instances.push(createEffectInstance(entry.definition, entry.params));
1023
938
  continue;
1024
939
  }
940
+ if (entry.kind === "custom") {
941
+ yield ensureEffectPrepared(entry.definition.id, rawContext);
942
+ instances.push(createCustomEffectInstance(entry.definition.id, rawContext, entry.params));
943
+ continue;
944
+ }
1025
945
  const livePlugin = getLivePlugin(entry.instanceId);
1026
946
  if (!livePlugin) {
1027
947
  throw new Error(
@@ -1043,601 +963,489 @@ function buildOfflineChain(entries, getLivePlugin, rawContext) {
1043
963
  function connectOfflineChain(from, instances, to) {
1044
964
  let current = from;
1045
965
  for (const inst of instances) {
1046
- connect3(current, inst.effect);
1047
- current = inst.effect;
966
+ connect4(current, inst.input);
967
+ current = inst.output;
1048
968
  }
1049
- connect3(current, to);
969
+ connect4(current, to);
1050
970
  }
1051
971
 
1052
- // src/hooks/useDynamicEffects.ts
1053
- import { Analyser as Analyser2, connect as connect4 } from "tone";
1054
- function useDynamicEffects(fftSize = 256) {
1055
- const [activeEffects, setActiveEffects] = useState2([]);
1056
- const activeEffectsRef = useRef3(activeEffects);
1057
- activeEffectsRef.current = activeEffects;
1058
- const effectInstancesRef = useRef3(/* @__PURE__ */ new Map());
1059
- const isMountedRef = useRef3(true);
1060
- const analyserRef = useRef3(null);
1061
- const graphNodesRef = useRef3(null);
1062
- const rebuildChain = useCallback2((effects) => {
1063
- const nodes = graphNodesRef.current;
1064
- if (!nodes) return;
1065
- const { masterGainNode, destination, analyserNode } = nodes;
1066
- try {
1067
- masterGainNode.disconnect();
1068
- } catch (e) {
1069
- console.warn("[waveform-playlist] Error disconnecting master effects chain:", e);
1070
- }
1071
- const audible = effects.filter((ae) => !(ae.kind === "wam" && ae.bypassed));
1072
- const instances = audible.map((ae) => effectInstancesRef.current.get(ae.instanceId)).filter((inst) => inst !== void 0);
1073
- if (instances.length === 0) {
1074
- masterGainNode.connect(analyserNode);
1075
- analyserNode.connect(destination);
1076
- } else {
1077
- let currentNode = masterGainNode;
1078
- instances.forEach((inst) => {
1079
- try {
1080
- inst.disconnect();
1081
- } catch (e) {
1082
- console.warn(`[waveform-playlist] Error disconnecting effect "${inst.id}":`, e);
1083
- }
1084
- connect4(currentNode, inst.effect);
1085
- currentNode = inst.effect;
1086
- });
1087
- connect4(currentNode, analyserNode);
1088
- analyserNode.connect(destination);
1089
- }
1090
- }, []);
1091
- const addEffect = useCallback2((effectId) => {
1092
- const definition = getEffectDefinition(effectId);
1093
- if (!definition) {
1094
- console.error(`Unknown effect: ${effectId}`);
1095
- return;
1096
- }
1097
- const params = {};
1098
- definition.parameters.forEach((p) => {
1099
- params[p.name] = p.default;
1100
- });
1101
- const instance = createEffectInstance(definition, params);
1102
- effectInstancesRef.current.set(instance.instanceId, instance);
1103
- const newActiveEffect = {
1104
- instanceId: instance.instanceId,
1105
- effectId: definition.id,
1106
- kind: "native",
1107
- definition,
1108
- params,
1109
- bypassed: false
1110
- };
1111
- setActiveEffects((prev) => [...prev, newActiveEffect]);
1112
- }, []);
1113
- const addWamEffect = useCallback2((url, initialState) => __async(null, null, function* () {
1114
- var _a, _b;
1115
- if (!isNativeGlobalContext()) {
1116
- throw new Error(
1117
- "[waveform-playlist] WAM plugins require a native AudioContext. Call configureGlobalContext({ nativeAudioContext: true }) from @waveform-playlist/playout before any audio initialization."
1118
- );
1119
- }
1120
- const wam = yield loadWamModule();
1121
- const ctx = getGlobalAudioContext();
1122
- const { hostGroupId } = yield wam.ensureWamHost(ctx);
1123
- const plugin = yield wam.createWamInstance(
1124
- url,
1125
- ctx,
1126
- hostGroupId,
1127
- initialState !== void 0 ? { initialState } : void 0
1128
- );
1129
- if (!isMountedRef.current) {
972
+ // src/effects/chainTopology.ts
973
+ function isDisconnectBypassed(effect) {
974
+ return effect.bypassed && effect.wetParam === void 0;
975
+ }
976
+ function chainTopologyKey(effects) {
977
+ return effects.filter((effect) => !isDisconnectBypassed(effect)).map((effect) => effect.instanceId).join("|");
978
+ }
979
+
980
+ // src/effects/effectsRack.ts
981
+ var NATIVE_CONTEXT_HINT = "Call configureGlobalContext({ nativeAudioContext: true }) from @waveform-playlist/playout before any audio initialization.";
982
+ var NO_EFFECTS = [];
983
+ var UNWIRED = "\0unwired";
984
+ function message(err) {
985
+ return err instanceof Error ? err.message : String(err);
986
+ }
987
+ var collectedRacks;
988
+ function disposeWhenCollected(rack, instances) {
989
+ if (collectedRacks === void 0) {
990
+ const Registry = globalThis.FinalizationRegistry;
991
+ collectedRacks = Registry ? new Registry((orphaned) => {
992
+ orphaned.forEach((instance) => instance.dispose());
993
+ orphaned.clear();
994
+ }) : null;
995
+ }
996
+ collectedRacks == null ? void 0 : collectedRacks.register(rack, instances);
997
+ }
998
+ var EffectsRack = class {
999
+ constructor() {
1000
+ this.handle = createValueSource(NO_EFFECTS);
1001
+ this.instances = /* @__PURE__ */ new Map();
1002
+ this.attachment = null;
1003
+ this.wiredKey = "";
1004
+ /** Bumped by clear(): an add that was awaiting across it is dropped. */
1005
+ this.generation = 0;
1006
+ /**
1007
+ * Put the chain between two nodes of the live graph. Returns the function
1008
+ * that detaches it from `to`, for when that part of the graph is disposed.
1009
+ * A second attach replaces the first; the first one's detach then only
1010
+ * removes its own edges.
1011
+ */
1012
+ this.attach = (from, to) => {
1013
+ const previous = this.attachment;
1014
+ this.attachment = { from, to };
1130
1015
  try {
1131
- plugin.destroy();
1016
+ this.wire(this.list(), false);
1132
1017
  } catch (err) {
1133
- console.warn(
1134
- "[waveform-playlist] Error destroying WAM plugin after unmount: " + (err instanceof Error ? err.message : String(err))
1135
- );
1018
+ this.attachment = previous;
1019
+ this.wiredKey = UNWIRED;
1020
+ throw err;
1136
1021
  }
1137
- throw new Error(
1138
- "[waveform-playlist] addWamEffect aborted: hook unmounted before the plugin finished loading."
1139
- );
1140
- }
1141
- const instance = createWamEffectInstance(plugin);
1142
- effectInstancesRef.current.set(instance.instanceId, instance);
1143
- const definition = {
1144
- id: instance.id,
1145
- name: (_b = (_a = plugin.descriptor) == null ? void 0 : _a.name) != null ? _b : url,
1146
- category: "wam",
1147
- description: "WAM plugin",
1148
- parameters: []
1022
+ return () => {
1023
+ var _a;
1024
+ this.instances.forEach((instance) => {
1025
+ try {
1026
+ disconnect3(instance.output, to);
1027
+ } catch (e) {
1028
+ }
1029
+ });
1030
+ if (((_a = this.attachment) == null ? void 0 : _a.to) === to) {
1031
+ this.attachment = null;
1032
+ }
1033
+ };
1149
1034
  };
1150
- setActiveEffects((prev) => [
1151
- ...prev,
1152
- {
1153
- instanceId: instance.instanceId,
1154
- effectId: instance.id,
1155
- kind: "wam",
1156
- url,
1157
- definition,
1158
- params: {},
1159
- bypassed: false
1035
+ /**
1036
+ * Add a built-in effect, or a type registered with `registerEffect()`, by
1037
+ * id. A built-in is in the list before this returns; a registered type is
1038
+ * added once its `prepare` hook has run on the live context. Resolves with
1039
+ * the new entry's instanceId; rejects for an unknown id.
1040
+ */
1041
+ this.add = (effectId) => __async(this, null, function* () {
1042
+ const builtIn = getEffectDefinition(effectId);
1043
+ if (builtIn) {
1044
+ const params = {};
1045
+ builtIn.parameters.forEach((parameter) => {
1046
+ params[parameter.name] = parameter.default;
1047
+ });
1048
+ const instance2 = createEffectInstance(builtIn, params);
1049
+ return this.append(instance2, __spreadValues({
1050
+ effectId,
1051
+ kind: "tone",
1052
+ definition: builtIn,
1053
+ params,
1054
+ bypassed: false
1055
+ }, instance2.getParameter("wet") !== void 0 ? { wetParam: "wet" } : {}));
1160
1056
  }
1161
- ]);
1162
- return instance.instanceId;
1163
- }), []);
1164
- const getWamPlugin = useCallback2((instanceId) => {
1165
- const inst = effectInstancesRef.current.get(instanceId);
1166
- return (inst == null ? void 0 : inst.kind) === "wam" ? inst.plugin : void 0;
1167
- }, []);
1168
- const removeEffect = useCallback2((instanceId) => {
1169
- const instance = effectInstancesRef.current.get(instanceId);
1170
- if (instance) {
1171
- instance.dispose();
1172
- effectInstancesRef.current.delete(instanceId);
1173
- }
1174
- setActiveEffects((prev) => prev.filter((e) => e.instanceId !== instanceId));
1175
- }, []);
1176
- const updateParameter = useCallback2(
1177
- (instanceId, paramName, value) => {
1178
- const instance = effectInstancesRef.current.get(instanceId);
1179
- if (instance) {
1180
- instance.setParameter(paramName, value);
1057
+ const registered = getEffectDefinitions2().get(effectId);
1058
+ if (!registered) {
1059
+ throw new Error(
1060
+ '[waveform-playlist] Unknown effect "' + effectId + '". It is neither a built-in effect nor a type registered with registerEffect() from @waveform-playlist/core.'
1061
+ );
1181
1062
  }
1182
- setActiveEffects(
1183
- (prev) => prev.map(
1184
- (e) => e.instanceId === instanceId ? __spreadProps(__spreadValues({}, e), { params: __spreadProps(__spreadValues({}, e.params), { [paramName]: value }) }) : e
1185
- )
1186
- );
1187
- },
1188
- []
1189
- );
1190
- const toggleBypass = useCallback2((instanceId) => {
1191
- var _a;
1192
- const effect = activeEffectsRef.current.find((e) => e.instanceId === instanceId);
1193
- if (!effect) return;
1194
- const newBypassed = !effect.bypassed;
1195
- if (effect.kind === "wam") {
1196
- setActiveEffects(
1197
- (prev) => prev.map((e) => e.instanceId === instanceId ? __spreadProps(__spreadValues({}, e), { bypassed: newBypassed }) : e)
1198
- );
1199
- return;
1200
- }
1201
- const instance = effectInstancesRef.current.get(instanceId);
1202
- if (instance) {
1203
- const originalWet = (_a = effect.params.wet) != null ? _a : 1;
1204
- instance.setParameter("wet", newBypassed ? 0 : originalWet);
1205
- }
1206
- setActiveEffects(
1207
- (prev) => prev.map((e) => e.instanceId === instanceId ? __spreadProps(__spreadValues({}, e), { bypassed: newBypassed }) : e)
1208
- );
1209
- }, []);
1210
- const reorderEffects = useCallback2((fromIndex, toIndex) => {
1211
- setActiveEffects((prev) => {
1212
- const newEffects = [...prev];
1213
- const [removed] = newEffects.splice(fromIndex, 1);
1214
- newEffects.splice(toIndex, 0, removed);
1215
- return newEffects;
1216
- });
1217
- }, []);
1218
- const clearAllEffects = useCallback2(() => {
1219
- effectInstancesRef.current.forEach((inst) => inst.dispose());
1220
- effectInstancesRef.current.clear();
1221
- setActiveEffects([]);
1222
- }, []);
1223
- useEffect2(() => {
1224
- rebuildChain(activeEffects);
1225
- }, [activeEffects, rebuildChain]);
1226
- const masterEffects = useCallback2(
1227
- (masterGainNode, destination, _isOffline) => {
1228
- const analyserNode = new Analyser2("fft", fftSize);
1229
- analyserRef.current = analyserNode;
1230
- graphNodesRef.current = {
1231
- masterGainNode,
1232
- destination,
1233
- analyserNode
1234
- };
1235
- const effects = activeEffectsRef.current;
1236
- const audible = effects.filter((ae) => !(ae.kind === "wam" && ae.bypassed));
1237
- const instances = audible.map((ae) => effectInstancesRef.current.get(ae.instanceId)).filter((inst) => inst !== void 0);
1238
- if (instances.length === 0) {
1239
- masterGainNode.connect(analyserNode);
1240
- analyserNode.connect(destination);
1241
- } else {
1242
- let currentNode = masterGainNode;
1243
- instances.forEach((inst) => {
1244
- connect4(currentNode, inst.effect);
1245
- currentNode = inst.effect;
1246
- });
1247
- connect4(currentNode, analyserNode);
1248
- analyserNode.connect(destination);
1063
+ if (!isNativeGlobalContext2()) {
1064
+ throw new Error(
1065
+ "[waveform-playlist] Custom effects require a native AudioContext. " + NATIVE_CONTEXT_HINT
1066
+ );
1249
1067
  }
1250
- return function cleanup() {
1251
- analyserNode.dispose();
1252
- analyserRef.current = null;
1253
- graphNodesRef.current = null;
1254
- };
1255
- },
1256
- [fftSize]
1257
- // Only fftSize - reads effects from ref
1258
- );
1259
- useEffect2(() => {
1260
- isMountedRef.current = true;
1261
- const effectInstances = effectInstancesRef.current;
1262
- return () => {
1263
- isMountedRef.current = false;
1264
- effectInstances.forEach((inst) => inst.dispose());
1265
- effectInstances.clear();
1266
- };
1267
- }, []);
1268
- const createOfflineEffectsFunction = useCallback2(() => {
1269
- const nonBypassed = activeEffects.filter((e) => !e.bypassed);
1270
- if (nonBypassed.length === 0) {
1271
- return void 0;
1272
- }
1273
- const hasWam = nonBypassed.some((e) => e.kind === "wam");
1274
- return (masterGainNode, destination, _isOffline) => __async(null, null, function* () {
1275
- if (hasWam && !isNativeGlobalContext()) {
1068
+ const audioContext = getGlobalAudioContext();
1069
+ const generation = this.generation;
1070
+ yield ensureEffectPrepared2(effectId, audioContext);
1071
+ if (generation !== this.generation) {
1276
1072
  throw new Error(
1277
- "[waveform-playlist] WAV export with WAM effects requires a native AudioContext. Call configureGlobalContext({ nativeAudioContext: true }) from @waveform-playlist/playout before any audio initialization."
1073
+ '[waveform-playlist] addEffect("' + effectId + '") aborted: the effects chain was cleared before the effect was ready.'
1278
1074
  );
1279
1075
  }
1280
- const rawContext = masterGainNode.context.rawContext;
1281
- const { instances, dispose } = yield buildOfflineChain(
1282
- nonBypassed,
1283
- (instanceId) => {
1284
- const inst = effectInstancesRef.current.get(instanceId);
1285
- return (inst == null ? void 0 : inst.kind) === "wam" ? inst.plugin : void 0;
1286
- },
1287
- rawContext
1288
- );
1289
- connectOfflineChain(masterGainNode, instances, destination);
1290
- return dispose;
1291
- });
1292
- }, [activeEffects]);
1293
- return {
1294
- activeEffects,
1295
- availableEffects: effectDefinitions,
1296
- addEffect,
1297
- addWamEffect,
1298
- getWamPlugin,
1299
- removeEffect,
1300
- updateParameter,
1301
- toggleBypass,
1302
- reorderEffects,
1303
- clearAllEffects,
1304
- masterEffects,
1305
- createOfflineEffectsFunction,
1306
- analyserRef
1307
- };
1308
- }
1309
-
1310
- // src/hooks/useTrackDynamicEffects.ts
1311
- import { useState as useState3, useCallback as useCallback3, useRef as useRef4, useEffect as useEffect3 } from "react";
1312
- import { isNativeGlobalContext as isNativeGlobalContext2, getGlobalAudioContext as getGlobalAudioContext2 } from "@waveform-playlist/playout";
1313
- import { connect as connect5 } from "tone";
1314
- function useTrackDynamicEffects() {
1315
- const [trackEffectsState, setTrackEffectsState] = useState3(
1316
- /* @__PURE__ */ new Map()
1317
- );
1318
- const trackEffectInstancesRef = useRef4(/* @__PURE__ */ new Map());
1319
- const isMountedRef = useRef4(true);
1320
- const trackGraphNodesRef = useRef4(/* @__PURE__ */ new Map());
1321
- const rebuildTrackChain = useCallback3((trackId, trackEffects) => {
1322
- const nodes = trackGraphNodesRef.current.get(trackId);
1323
- if (!nodes) return;
1324
- const { graphEnd, masterGainNode } = nodes;
1325
- const instancesMap = trackEffectInstancesRef.current.get(trackId);
1326
- try {
1327
- graphEnd.disconnect();
1328
- } catch (e) {
1329
- console.warn(`[waveform-playlist] Error disconnecting track "${trackId}" effect chain:`, e);
1330
- }
1331
- const audible = trackEffects.filter((ae) => !(ae.kind === "wam" && ae.bypassed));
1332
- const instances = audible.map((ae) => instancesMap == null ? void 0 : instancesMap.get(ae.instanceId)).filter((inst) => inst !== void 0);
1333
- if (instances.length === 0) {
1334
- graphEnd.connect(masterGainNode);
1335
- } else {
1336
- let currentNode = graphEnd;
1337
- instances.forEach((inst) => {
1338
- try {
1339
- inst.disconnect();
1340
- } catch (e) {
1341
- console.warn(
1342
- `[waveform-playlist] Error disconnecting effect "${inst.id}" on track "${trackId}":`,
1343
- e
1344
- );
1345
- }
1346
- connect5(currentNode, inst.effect);
1347
- currentNode = inst.effect;
1348
- });
1349
- connect5(currentNode, masterGainNode);
1350
- }
1351
- }, []);
1352
- const addEffectToTrack = useCallback3((trackId, effectId) => {
1353
- const definition = getEffectDefinition(effectId);
1354
- if (!definition) {
1355
- console.error(`Unknown effect: ${effectId}`);
1356
- return;
1357
- }
1358
- const params = {};
1359
- definition.parameters.forEach((p) => {
1360
- params[p.name] = p.default;
1361
- });
1362
- const instance = createEffectInstance(definition, params);
1363
- if (!trackEffectInstancesRef.current.has(trackId)) {
1364
- trackEffectInstancesRef.current.set(trackId, /* @__PURE__ */ new Map());
1365
- }
1366
- trackEffectInstancesRef.current.get(trackId).set(instance.instanceId, instance);
1367
- const newActiveEffect = {
1368
- instanceId: instance.instanceId,
1369
- effectId: definition.id,
1370
- kind: "native",
1371
- definition,
1372
- params,
1373
- bypassed: false
1374
- };
1375
- setTrackEffectsState((prev) => {
1376
- const newState = new Map(prev);
1377
- const existing = newState.get(trackId) || [];
1378
- newState.set(trackId, [...existing, newActiveEffect]);
1379
- return newState;
1076
+ const definition = getEffectDefinitions2().get(effectId);
1077
+ if (!definition) {
1078
+ throw new Error(
1079
+ '[waveform-playlist] addEffect("' + effectId + '") aborted: the effect type was unregistered before the effect was ready.'
1080
+ );
1081
+ }
1082
+ const instance = createCustomEffectInstance(effectId, audioContext, definition.defaults);
1083
+ return this.append(instance, __spreadValues({
1084
+ effectId,
1085
+ kind: "custom",
1086
+ definition: toEffectDefinition(effectId, definition),
1087
+ params: __spreadValues({}, definition.defaults),
1088
+ bypassed: false
1089
+ }, definition.wetParam !== void 0 ? { wetParam: definition.wetParam } : {}));
1380
1090
  });
1381
- }, []);
1382
- const addWamEffectToTrack = useCallback3(
1383
- (trackId, url, initialState) => __async(null, null, function* () {
1091
+ /** Host a WAM plugin from a module URL and append it. Requires native-context mode. */
1092
+ this.addWam = (url, initialState) => __async(this, null, function* () {
1384
1093
  var _a, _b;
1385
1094
  if (!isNativeGlobalContext2()) {
1386
1095
  throw new Error(
1387
- "[waveform-playlist] WAM plugins require a native AudioContext. Call configureGlobalContext({ nativeAudioContext: true }) from @waveform-playlist/playout before any audio initialization."
1096
+ "[waveform-playlist] WAM plugins require a native AudioContext. " + NATIVE_CONTEXT_HINT
1388
1097
  );
1389
1098
  }
1099
+ const generation = this.generation;
1390
1100
  const wam = yield loadWamModule();
1391
- const ctx = getGlobalAudioContext2();
1392
- const { hostGroupId } = yield wam.ensureWamHost(ctx);
1101
+ const audioContext = getGlobalAudioContext();
1102
+ const { hostGroupId } = yield wam.ensureWamHost(audioContext);
1393
1103
  const plugin = yield wam.createWamInstance(
1394
1104
  url,
1395
- ctx,
1105
+ audioContext,
1396
1106
  hostGroupId,
1397
1107
  initialState !== void 0 ? { initialState } : void 0
1398
1108
  );
1399
- if (!isMountedRef.current) {
1109
+ if (generation !== this.generation) {
1400
1110
  try {
1401
1111
  plugin.destroy();
1402
1112
  } catch (err) {
1403
1113
  console.warn(
1404
- "[waveform-playlist] Error destroying WAM plugin after unmount: " + (err instanceof Error ? err.message : String(err))
1114
+ "[waveform-playlist] Error destroying a WAM plugin dropped by clear(): " + message(err)
1405
1115
  );
1406
1116
  }
1407
1117
  throw new Error(
1408
- "[waveform-playlist] addWamEffectToTrack aborted: hook unmounted before the plugin finished loading."
1118
+ "[waveform-playlist] addWamEffect aborted: the effects chain was cleared before the plugin finished loading."
1409
1119
  );
1410
1120
  }
1411
1121
  const instance = createWamEffectInstance(plugin);
1412
- if (!trackEffectInstancesRef.current.has(trackId)) {
1413
- trackEffectInstancesRef.current.set(trackId, /* @__PURE__ */ new Map());
1414
- }
1415
- trackEffectInstancesRef.current.get(trackId).set(instance.instanceId, instance);
1416
- const definition = {
1417
- id: instance.id,
1418
- name: (_b = (_a = plugin.descriptor) == null ? void 0 : _a.name) != null ? _b : url,
1419
- category: "wam",
1420
- description: "WAM plugin",
1421
- parameters: []
1422
- };
1423
- setTrackEffectsState((prev) => {
1424
- const newState = new Map(prev);
1425
- const existing = newState.get(trackId) || [];
1426
- newState.set(trackId, [
1427
- ...existing,
1428
- {
1429
- instanceId: instance.instanceId,
1430
- effectId: instance.id,
1431
- kind: "wam",
1432
- url,
1433
- definition,
1434
- params: {},
1435
- bypassed: false
1436
- }
1437
- ]);
1438
- return newState;
1122
+ return this.append(instance, {
1123
+ effectId: instance.id,
1124
+ kind: "wam",
1125
+ url,
1126
+ definition: {
1127
+ id: instance.id,
1128
+ name: (_b = (_a = plugin.descriptor) == null ? void 0 : _a.name) != null ? _b : url,
1129
+ category: "wam",
1130
+ description: "WAM plugin",
1131
+ parameters: []
1132
+ },
1133
+ params: {},
1134
+ bypassed: false
1439
1135
  });
1440
- return instance.instanceId;
1441
- }),
1442
- []
1443
- );
1444
- const getTrackWamPlugin = useCallback3(
1445
- (trackId, instanceId) => {
1446
- const instancesMap = trackEffectInstancesRef.current.get(trackId);
1447
- const inst = instancesMap == null ? void 0 : instancesMap.get(instanceId);
1448
- return (inst == null ? void 0 : inst.kind) === "wam" ? inst.plugin : void 0;
1449
- },
1450
- []
1451
- );
1452
- const removeEffectFromTrack = useCallback3((trackId, instanceId) => {
1453
- const instancesMap = trackEffectInstancesRef.current.get(trackId);
1454
- const instance = instancesMap == null ? void 0 : instancesMap.get(instanceId);
1455
- if (instance) {
1456
- instance.dispose();
1457
- instancesMap == null ? void 0 : instancesMap.delete(instanceId);
1458
- }
1459
- setTrackEffectsState((prev) => {
1460
- const newState = new Map(prev);
1461
- const existing = newState.get(trackId) || [];
1462
- newState.set(
1463
- trackId,
1464
- existing.filter((e) => e.instanceId !== instanceId)
1465
- );
1466
- return newState;
1467
1136
  });
1468
- }, []);
1469
- const updateTrackEffectParameter = useCallback3(
1470
- (trackId, instanceId, paramName, value) => {
1471
- const instancesMap = trackEffectInstancesRef.current.get(trackId);
1472
- const instance = instancesMap == null ? void 0 : instancesMap.get(instanceId);
1137
+ /** Live plugin handle for a hosted WAM entry (for GUI mounting via WamEffectGui). */
1138
+ this.getWamPlugin = (instanceId) => {
1139
+ const instance = this.instances.get(instanceId);
1140
+ return (instance == null ? void 0 : instance.kind) === "wam" ? instance.plugin : void 0;
1141
+ };
1142
+ this.remove = (instanceId) => {
1143
+ const next = this.list().filter((effect) => effect.instanceId !== instanceId);
1144
+ if (next.length !== this.list().length) this.commit(next);
1145
+ const instance = this.instances.get(instanceId);
1473
1146
  if (instance) {
1474
- instance.setParameter(paramName, value);
1147
+ this.instances.delete(instanceId);
1148
+ instance.dispose();
1475
1149
  }
1476
- setTrackEffectsState((prev) => {
1477
- const newState = new Map(prev);
1478
- const existing = newState.get(trackId) || [];
1479
- newState.set(
1480
- trackId,
1481
- existing.map(
1482
- (e) => e.instanceId === instanceId ? __spreadProps(__spreadValues({}, e), { params: __spreadProps(__spreadValues({}, e.params), { [paramName]: value }) }) : e
1483
- )
1484
- );
1485
- return newState;
1486
- });
1487
- },
1488
- []
1489
- );
1490
- const toggleBypass = useCallback3((trackId, instanceId) => {
1491
- var _a;
1492
- const trackEffects = trackEffectsStateRef.current.get(trackId) || [];
1493
- const effect = trackEffects.find((e) => e.instanceId === instanceId);
1494
- if (!effect) return;
1495
- const newBypassed = !effect.bypassed;
1496
- if (effect.kind === "wam") {
1497
- setTrackEffectsState((prev) => {
1498
- const newState = new Map(prev);
1499
- const existing = newState.get(trackId) || [];
1500
- newState.set(
1501
- trackId,
1502
- existing.map((e) => e.instanceId === instanceId ? __spreadProps(__spreadValues({}, e), { bypassed: newBypassed }) : e)
1150
+ };
1151
+ /** Set a parameter on the live effect. Never rewires the chain. */
1152
+ this.updateParameter = (instanceId, name, value) => {
1153
+ var _a;
1154
+ const effect = this.list().find((entry) => entry.instanceId === instanceId);
1155
+ if (!effect) return;
1156
+ if (effect.kind === "custom" && typeof value !== "number") return;
1157
+ if (!(effect.bypassed && name === effect.wetParam)) {
1158
+ (_a = this.instances.get(instanceId)) == null ? void 0 : _a.setParameter(name, value);
1159
+ }
1160
+ this.commit(
1161
+ this.list().map(
1162
+ (entry) => entry.instanceId === instanceId ? __spreadProps(__spreadValues({}, entry), { params: __spreadProps(__spreadValues({}, entry.params), { [name]: value }) }) : entry
1163
+ )
1164
+ );
1165
+ };
1166
+ this.toggleBypass = (instanceId) => {
1167
+ var _a;
1168
+ const effect = this.list().find((entry) => entry.instanceId === instanceId);
1169
+ if (!effect) return;
1170
+ const bypassed = !effect.bypassed;
1171
+ if (effect.wetParam !== void 0) {
1172
+ const wet = effect.params[effect.wetParam];
1173
+ (_a = this.instances.get(instanceId)) == null ? void 0 : _a.setParameter(effect.wetParam, bypassed ? 0 : typeof wet === "number" ? wet : 1);
1174
+ }
1175
+ this.commit(
1176
+ this.list().map((entry) => entry.instanceId === instanceId ? __spreadProps(__spreadValues({}, entry), { bypassed }) : entry)
1177
+ );
1178
+ };
1179
+ this.reorder = (fromIndex, toIndex) => {
1180
+ const current = this.list();
1181
+ if (fromIndex === toIndex || fromIndex < 0 || fromIndex >= current.length || toIndex < 0 || toIndex >= current.length) {
1182
+ return;
1183
+ }
1184
+ const next = [...current];
1185
+ const [moved] = next.splice(fromIndex, 1);
1186
+ next.splice(toIndex, 0, moved);
1187
+ this.commit(next);
1188
+ };
1189
+ /**
1190
+ * Remove and dispose every effect. An add that is still waiting (a
1191
+ * registered effect's `prepare`, a WAM plugin loading) is dropped too: its
1192
+ * promise rejects and nothing is appended after the clear.
1193
+ */
1194
+ this.clear = () => {
1195
+ this.generation++;
1196
+ let failure;
1197
+ let failed = false;
1198
+ try {
1199
+ if (this.list().length > 0) this.commit(NO_EFFECTS);
1200
+ } catch (err) {
1201
+ failed = true;
1202
+ failure = err;
1203
+ }
1204
+ this.instances.forEach((instance) => instance.dispose());
1205
+ this.instances.clear();
1206
+ if (failed) {
1207
+ this.wiredKey = UNWIRED;
1208
+ this.handle.publish(NO_EFFECTS);
1209
+ throw failure;
1210
+ }
1211
+ };
1212
+ /**
1213
+ * Builds this chain again on an offline context, for WAV export, from the
1214
+ * chain as it is when called: built-ins are re-created, WAM plugins
1215
+ * re-instantiated with the live plugin's state, registered effects prepared
1216
+ * and created on the offline context. With no active effect it connects
1217
+ * `from` straight to `to`. It rejects rather than render without an effect
1218
+ * the live chain has. Resolves with the cleanup for the offline instances.
1219
+ */
1220
+ this.renderOffline = (from, to) => __async(this, null, function* () {
1221
+ const entries = this.list().filter((effect) => !effect.bypassed);
1222
+ if (entries.some((effect) => effect.kind !== "tone") && !isNativeGlobalContext2()) {
1223
+ throw new Error(
1224
+ "[waveform-playlist] WAV export with WAM or custom effects requires a native AudioContext. " + NATIVE_CONTEXT_HINT
1503
1225
  );
1504
- return newState;
1505
- });
1226
+ }
1227
+ const rawContext = from.context.rawContext;
1228
+ const { instances, dispose } = yield buildOfflineChain(entries, this.getWamPlugin, rawContext);
1229
+ connectOfflineChain(from, instances, to);
1230
+ return dispose;
1231
+ });
1232
+ disposeWhenCollected(this, this.instances);
1233
+ }
1234
+ /** The effects in chain order. A new array on every change. */
1235
+ get effects() {
1236
+ return this.handle.source;
1237
+ }
1238
+ list() {
1239
+ return this.handle.source.getSnapshot();
1240
+ }
1241
+ /**
1242
+ * Wire the graph for `next` if its topology differs, then publish it. If
1243
+ * the wiring throws (a node on another context, for instance) the previous
1244
+ * list is wired back and nothing is published, so the list always describes
1245
+ * what is connected.
1246
+ */
1247
+ commit(next) {
1248
+ if (chainTopologyKey(next) !== this.wiredKey) {
1249
+ const previous = this.list();
1250
+ try {
1251
+ this.wire(next, true);
1252
+ } catch (err) {
1253
+ try {
1254
+ this.wire(previous, true);
1255
+ } catch (restoreErr) {
1256
+ console.warn(
1257
+ "[waveform-playlist] Could not restore an effects chain after a failed change: " + message(restoreErr)
1258
+ );
1259
+ }
1260
+ throw err;
1261
+ }
1262
+ }
1263
+ this.handle.publish(next);
1264
+ }
1265
+ audibleInstances(effects) {
1266
+ return effects.filter((effect) => !isDisconnectBypassed(effect)).map((effect) => this.instances.get(effect.instanceId)).filter((instance) => instance !== void 0);
1267
+ }
1268
+ /**
1269
+ * Connect from → effect 1 → … → to. `rewire` first cuts what was there:
1270
+ * `from`'s outgoing edges, and the output of EVERY instance, including the
1271
+ * ones a bypass has taken out of the chain (an effect that makes sound
1272
+ * with nothing connected to its input must fall silent as well).
1273
+ */
1274
+ wire(effects, rewire) {
1275
+ const key = chainTopologyKey(effects);
1276
+ const attachment = this.attachment;
1277
+ if (!attachment) {
1278
+ this.wiredKey = key;
1506
1279
  return;
1507
1280
  }
1508
- const instancesMap = trackEffectInstancesRef.current.get(trackId);
1509
- const instance = instancesMap == null ? void 0 : instancesMap.get(instanceId);
1510
- if (instance) {
1511
- const originalWet = (_a = effect.params.wet) != null ? _a : 1;
1512
- instance.setParameter("wet", newBypassed ? 0 : originalWet);
1281
+ const { from, to } = attachment;
1282
+ this.wiredKey = UNWIRED;
1283
+ if (rewire) {
1284
+ try {
1285
+ from.disconnect();
1286
+ } catch (err) {
1287
+ console.warn("[waveform-playlist] Error disconnecting an effects chain: " + message(err));
1288
+ }
1513
1289
  }
1514
- setTrackEffectsState((prev) => {
1515
- const newState = new Map(prev);
1516
- const existing = newState.get(trackId) || [];
1517
- newState.set(
1518
- trackId,
1519
- existing.map((e) => e.instanceId === instanceId ? __spreadProps(__spreadValues({}, e), { bypassed: newBypassed }) : e)
1520
- );
1521
- return newState;
1522
- });
1523
- }, []);
1524
- const clearTrackEffects = useCallback3((trackId) => {
1525
- const instancesMap = trackEffectInstancesRef.current.get(trackId);
1526
- if (instancesMap) {
1527
- instancesMap.forEach((inst) => inst.dispose());
1528
- instancesMap.clear();
1290
+ this.instances.forEach((instance) => instance.disconnect());
1291
+ const chain = this.audibleInstances(effects);
1292
+ if (chain.length === 0) {
1293
+ from.connect(to);
1294
+ } else {
1295
+ let current = from;
1296
+ for (const instance of chain) {
1297
+ connect5(current, instance.input);
1298
+ current = instance.output;
1299
+ }
1300
+ connect5(current, to);
1529
1301
  }
1530
- setTrackEffectsState((prev) => {
1531
- const newState = new Map(prev);
1532
- newState.set(trackId, []);
1533
- return newState;
1534
- });
1535
- }, []);
1536
- const trackEffectsStateRef = useRef4(trackEffectsState);
1537
- trackEffectsStateRef.current = trackEffectsState;
1538
- const getTrackEffectsFunction = useCallback3(
1539
- (trackId) => {
1540
- return (graphEnd, masterGainNode, _isOffline) => {
1541
- trackGraphNodesRef.current.set(trackId, {
1542
- graphEnd,
1543
- masterGainNode
1544
- });
1545
- const trackEffects = trackEffectsStateRef.current.get(trackId) || [];
1546
- const instancesMap = trackEffectInstancesRef.current.get(trackId);
1547
- const audible = trackEffects.filter((ae) => !(ae.kind === "wam" && ae.bypassed));
1548
- const instances = audible.map((ae) => instancesMap == null ? void 0 : instancesMap.get(ae.instanceId)).filter((inst) => inst !== void 0);
1549
- if (instances.length === 0) {
1550
- graphEnd.connect(masterGainNode);
1551
- } else {
1552
- let currentNode = graphEnd;
1553
- instances.forEach((inst) => {
1554
- connect5(currentNode, inst.effect);
1555
- currentNode = inst.effect;
1556
- });
1557
- connect5(currentNode, masterGainNode);
1302
+ this.wiredKey = key;
1303
+ }
1304
+ append(instance, entry) {
1305
+ this.instances.set(instance.instanceId, instance);
1306
+ try {
1307
+ this.commit([...this.list(), __spreadProps(__spreadValues({}, entry), { instanceId: instance.instanceId })]);
1308
+ } catch (err) {
1309
+ this.instances.delete(instance.instanceId);
1310
+ instance.dispose();
1311
+ throw err;
1312
+ }
1313
+ return instance.instanceId;
1314
+ }
1315
+ };
1316
+
1317
+ // src/hooks/useDynamicEffects.ts
1318
+ function useDynamicEffects(fftSize = 256) {
1319
+ const [rack] = useState(() => new EffectsRack());
1320
+ const analyserRef = useRef2(null);
1321
+ const masterEffects = useCallback2(
1322
+ (masterGainNode, destination, _isOffline) => {
1323
+ const analyserNode = new Analyser2("fft", fftSize);
1324
+ analyserRef.current = analyserNode;
1325
+ const detach = rack.attach(masterGainNode, analyserNode);
1326
+ analyserNode.connect(destination);
1327
+ return function cleanup() {
1328
+ detach();
1329
+ analyserNode.dispose();
1330
+ if (analyserRef.current === analyserNode) {
1331
+ analyserRef.current = null;
1558
1332
  }
1559
- return function cleanup() {
1560
- trackGraphNodesRef.current.delete(trackId);
1561
- };
1562
1333
  };
1563
1334
  },
1564
- []
1565
- // No dependencies - stable function that reads from refs
1335
+ [rack, fftSize]
1566
1336
  );
1567
- useEffect3(() => {
1568
- trackEffectsState.forEach((effects, trackId) => {
1569
- rebuildTrackChain(trackId, effects);
1570
- });
1571
- }, [trackEffectsState, rebuildTrackChain]);
1572
- useEffect3(() => {
1573
- isMountedRef.current = true;
1574
- const trackEffectInstances = trackEffectInstancesRef.current;
1575
- return () => {
1576
- isMountedRef.current = false;
1577
- trackEffectInstances.forEach((instancesMap) => {
1578
- instancesMap.forEach((inst) => inst.dispose());
1579
- instancesMap.clear();
1580
- });
1581
- trackEffectInstances.clear();
1582
- };
1583
- }, []);
1584
- const createOfflineTrackEffectsFunction = useCallback3(
1337
+ const createOfflineEffectsFunction = useMemo(() => {
1338
+ const offline = (masterGainNode, destination) => rack.renderOffline(masterGainNode, destination);
1339
+ return () => offline;
1340
+ }, [rack]);
1341
+ const availableEffects = getAvailableEffects();
1342
+ return useMemo(
1343
+ () => ({
1344
+ effects: rack.effects,
1345
+ availableEffects,
1346
+ addEffect: rack.add,
1347
+ addWamEffect: rack.addWam,
1348
+ getWamPlugin: rack.getWamPlugin,
1349
+ removeEffect: rack.remove,
1350
+ updateParameter: rack.updateParameter,
1351
+ toggleBypass: rack.toggleBypass,
1352
+ reorderEffects: rack.reorder,
1353
+ clearAllEffects: rack.clear,
1354
+ masterEffects,
1355
+ createOfflineEffectsFunction,
1356
+ analyserRef
1357
+ }),
1358
+ [rack, availableEffects, masterEffects, createOfflineEffectsFunction]
1359
+ );
1360
+ }
1361
+
1362
+ // src/hooks/useTrackDynamicEffects.ts
1363
+ import { useCallback as useCallback3, useMemo as useMemo2, useState as useState2 } from "react";
1364
+ function useTrackDynamicEffects() {
1365
+ const [store] = useState2(() => ({
1366
+ racks: /* @__PURE__ */ new Map(),
1367
+ effectsFunctions: /* @__PURE__ */ new Map(),
1368
+ offlineFunctions: /* @__PURE__ */ new Map()
1369
+ }));
1370
+ const rackFor = useCallback3(
1585
1371
  (trackId) => {
1586
- const trackEffects = trackEffectsState.get(trackId) || [];
1587
- const nonBypassed = trackEffects.filter((e) => !e.bypassed);
1588
- if (nonBypassed.length === 0) {
1589
- return void 0;
1590
- }
1591
- const hasWam = nonBypassed.some((e) => e.kind === "wam");
1592
- return (graphEnd, masterGainNode, _isOffline) => __async(null, null, function* () {
1593
- if (hasWam && !isNativeGlobalContext2()) {
1594
- throw new Error(
1595
- "[waveform-playlist] WAV export with WAM effects requires a native AudioContext. Call configureGlobalContext({ nativeAudioContext: true }) from @waveform-playlist/playout before any audio initialization."
1596
- );
1597
- }
1598
- const rawContext = graphEnd.context.rawContext;
1599
- const { instances, dispose } = yield buildOfflineChain(
1600
- nonBypassed,
1601
- (instanceId) => {
1602
- var _a;
1603
- const inst = (_a = trackEffectInstancesRef.current.get(trackId)) == null ? void 0 : _a.get(instanceId);
1604
- return (inst == null ? void 0 : inst.kind) === "wam" ? inst.plugin : void 0;
1605
- },
1606
- rawContext
1607
- );
1608
- connectOfflineChain(graphEnd, instances, masterGainNode);
1609
- return dispose;
1610
- });
1372
+ const existing = store.racks.get(trackId);
1373
+ if (existing) return existing;
1374
+ const rack = new EffectsRack();
1375
+ store.racks.set(trackId, rack);
1376
+ return rack;
1611
1377
  },
1612
- [trackEffectsState]
1378
+ [store]
1613
1379
  );
1614
- return {
1615
- trackEffectsState,
1616
- addEffectToTrack,
1617
- addWamEffectToTrack,
1618
- getTrackWamPlugin,
1619
- removeEffectFromTrack,
1620
- updateTrackEffectParameter,
1621
- toggleBypass,
1622
- clearTrackEffects,
1623
- getTrackEffectsFunction,
1624
- createOfflineTrackEffectsFunction,
1625
- availableEffects: effectDefinitions
1626
- };
1380
+ const actions = useMemo2(
1381
+ () => ({
1382
+ getTrackEffects: (trackId) => rackFor(trackId).effects,
1383
+ addEffectToTrack: (trackId, effectId) => rackFor(trackId).add(effectId),
1384
+ addWamEffectToTrack: (trackId, url, initialState) => rackFor(trackId).addWam(url, initialState),
1385
+ getTrackWamPlugin: (trackId, instanceId) => {
1386
+ var _a;
1387
+ return (_a = store.racks.get(trackId)) == null ? void 0 : _a.getWamPlugin(instanceId);
1388
+ },
1389
+ removeEffectFromTrack: (trackId, instanceId) => {
1390
+ var _a;
1391
+ return (_a = store.racks.get(trackId)) == null ? void 0 : _a.remove(instanceId);
1392
+ },
1393
+ updateTrackEffectParameter: (trackId, instanceId, paramName, value) => {
1394
+ var _a;
1395
+ return (_a = store.racks.get(trackId)) == null ? void 0 : _a.updateParameter(instanceId, paramName, value);
1396
+ },
1397
+ toggleBypass: (trackId, instanceId) => {
1398
+ var _a;
1399
+ return (_a = store.racks.get(trackId)) == null ? void 0 : _a.toggleBypass(instanceId);
1400
+ },
1401
+ reorderTrackEffects: (trackId, fromIndex, toIndex) => {
1402
+ var _a;
1403
+ return (_a = store.racks.get(trackId)) == null ? void 0 : _a.reorder(fromIndex, toIndex);
1404
+ },
1405
+ clearTrackEffects: (trackId) => {
1406
+ var _a;
1407
+ return (_a = store.racks.get(trackId)) == null ? void 0 : _a.clear();
1408
+ },
1409
+ getTrackEffectsFunction: (trackId) => {
1410
+ const existing = store.effectsFunctions.get(trackId);
1411
+ if (existing) return existing;
1412
+ const effectsFunction = (trackInput, faderInput, _isOffline) => rackFor(trackId).attach(trackInput, faderInput);
1413
+ store.effectsFunctions.set(trackId, effectsFunction);
1414
+ return effectsFunction;
1415
+ },
1416
+ createOfflineTrackEffectsFunction: (trackId) => {
1417
+ const existing = store.offlineFunctions.get(trackId);
1418
+ if (existing) return existing;
1419
+ const offline = (trackInput, faderInput) => rackFor(trackId).renderOffline(trackInput, faderInput);
1420
+ store.offlineFunctions.set(trackId, offline);
1421
+ return offline;
1422
+ }
1423
+ }),
1424
+ [store, rackFor]
1425
+ );
1426
+ const availableEffects = getAvailableEffects();
1427
+ return useMemo2(() => __spreadProps(__spreadValues({}, actions), { availableEffects }), [actions, availableEffects]);
1428
+ }
1429
+
1430
+ // src/hooks/useActiveEffects.ts
1431
+ import { useSyncExternalStore } from "react";
1432
+ function useActiveEffects(effects) {
1433
+ return useSyncExternalStore(effects.subscribe, effects.getSnapshot, effects.getSnapshot);
1627
1434
  }
1628
1435
 
1629
1436
  // src/hooks/useExportWav.ts
1630
- import { useState as useState4, useCallback as useCallback4 } from "react";
1437
+ import { useState as useState3, useCallback as useCallback4 } from "react";
1631
1438
  import {
1632
1439
  gainToDb,
1633
1440
  trackChannelCount,
1441
+ createPanStage,
1634
1442
  applyFadeIn,
1635
1443
  applyFadeOut
1636
1444
  } from "@waveform-playlist/core";
1637
- import { getUnderlyingAudioParam, getGlobalAudioContext as getGlobalAudioContext3 } from "@waveform-playlist/playout";
1445
+ import { getGlobalAudioContext as getGlobalAudioContext2 } from "@waveform-playlist/playout";
1638
1446
 
1639
1447
  // src/utils/renderToneOffline.ts
1640
- import { getContext as getContext2, setContext, OfflineContext } from "tone";
1448
+ import { getContext, setContext, OfflineContext } from "tone";
1641
1449
  import { isNativeGlobalContext as isNativeGlobalContext3 } from "@waveform-playlist/playout";
1642
1450
  var renderQueue = Promise.resolve();
1643
1451
  function renderToneOffline(build, duration, channels, sampleRate) {
@@ -1658,7 +1466,7 @@ function renderToneOfflineSerial(build, duration, channels, sampleRate) {
1658
1466
  sampleRate
1659
1467
  })
1660
1468
  ) : new OfflineContext(channels, duration, sampleRate);
1661
- const previousContext = getContext2();
1469
+ const previousContext = getContext();
1662
1470
  setContext(offlineContext);
1663
1471
  try {
1664
1472
  yield build(offlineContext);
@@ -1745,9 +1553,9 @@ function downloadBlob(blob, filename) {
1745
1553
 
1746
1554
  // src/hooks/useExportWav.ts
1747
1555
  function useExportWav() {
1748
- const [isExporting, setIsExporting] = useState4(false);
1749
- const [progress, setProgress] = useState4(0);
1750
- const [error, setError] = useState4(null);
1556
+ const [isExporting, setIsExporting] = useState3(false);
1557
+ const [progress, setProgress] = useState3(0);
1558
+ const [error, setError] = useState3(null);
1751
1559
  const exportWav = useCallback4(
1752
1560
  (_0, _1, ..._2) => __async(null, [_0, _1, ..._2], function* (tracks, trackStates, options = {}) {
1753
1561
  const {
@@ -1771,7 +1579,7 @@ function useExportWav() {
1771
1579
  if (mode === "individual" && (trackIndex === void 0 || trackIndex < 0 || trackIndex >= tracks.length)) {
1772
1580
  throw new Error("Invalid track index for individual export");
1773
1581
  }
1774
- const sampleRate = getGlobalAudioContext3().sampleRate;
1582
+ const sampleRate = getGlobalAudioContext2().sampleRate;
1775
1583
  let totalDurationSamples = 0;
1776
1584
  for (const track of tracks) {
1777
1585
  for (const clip of track.clips) {
@@ -1781,8 +1589,17 @@ function useExportWav() {
1781
1589
  }
1782
1590
  totalDurationSamples += Math.round(sampleRate * 0.1);
1783
1591
  const duration = totalDurationSamples / sampleRate;
1784
- const tracksToRender = mode === "individual" ? [{ track: tracks[trackIndex], state: trackStates[trackIndex], index: trackIndex }] : tracks.map((track, index) => ({ track, state: trackStates[index], index }));
1785
- const hasSolo = mode === "master" && trackStates.some((state) => state.soloed);
1592
+ const stateOf = (index) => {
1593
+ var _a;
1594
+ return (_a = trackStates[index]) != null ? _a : {
1595
+ muted: tracks[index].muted,
1596
+ soloed: tracks[index].soloed,
1597
+ volume: tracks[index].volume,
1598
+ pan: tracks[index].pan
1599
+ };
1600
+ };
1601
+ const tracksToRender = mode === "individual" ? [{ track: tracks[trackIndex], state: stateOf(trackIndex), index: trackIndex }] : tracks.map((track, index) => ({ track, state: stateOf(index), index }));
1602
+ const hasSolo = mode === "master" && tracks.some((_, index) => stateOf(index).soloed);
1786
1603
  const reportProgress = (p) => {
1787
1604
  setProgress(p);
1788
1605
  onProgress == null ? void 0 : onProgress(p);
@@ -1810,8 +1627,8 @@ function useExportWav() {
1810
1627
  duration
1811
1628
  };
1812
1629
  } catch (err) {
1813
- const message = err instanceof Error ? err.message : "Export failed";
1814
- setError(message);
1630
+ const message2 = err instanceof Error ? err.message : "Export failed";
1631
+ setError(message2);
1815
1632
  throw err;
1816
1633
  } finally {
1817
1634
  setIsExporting(false);
@@ -1828,7 +1645,7 @@ function useExportWav() {
1828
1645
  }
1829
1646
  function renderOffline(tracksToRender, hasSolo, duration, sampleRate, applyEffects, effectsFunction, createOfflineTrackEffects, onProgress) {
1830
1647
  return __async(this, null, function* () {
1831
- const { Volume: Volume2, Gain: Gain2, Panner, Player, ToneAudioBuffer } = yield import("tone");
1648
+ const { Volume, Gain, Player, ToneAudioBuffer, connect: connect6 } = yield import("tone");
1832
1649
  onProgress(0.1);
1833
1650
  const audibleTracks = tracksToRender.filter(({ state }) => {
1834
1651
  if (state.muted && !state.soloed) return false;
@@ -1843,7 +1660,7 @@ function renderOffline(tracksToRender, hasSolo, duration, sampleRate, applyEffec
1843
1660
  try {
1844
1661
  const audioBuffer = yield renderToneOffline(
1845
1662
  (context) => __async(null, null, function* () {
1846
- const masterVolume = new Volume2(0);
1663
+ const masterVolume = new Volume(0);
1847
1664
  if (effectsFunction && applyEffects) {
1848
1665
  const cleanup = yield effectsFunction(masterVolume, context.destination, true);
1849
1666
  if (cleanup) cleanups.push(cleanup);
@@ -1851,18 +1668,24 @@ function renderOffline(tracksToRender, hasSolo, duration, sampleRate, applyEffec
1851
1668
  masterVolume.connect(context.destination);
1852
1669
  }
1853
1670
  for (const { track, state } of audibleTracks) {
1854
- const trackVolume = new Volume2(gainToDb(state.volume));
1855
- const trackPan = new Panner({ pan: state.pan, channelCount: trackChannelCount(track) });
1856
- const trackMute = new Gain2(state.muted ? 0 : 1);
1671
+ const trackInput = new Gain({ gain: 1 });
1672
+ const trackVolume = new Volume(gainToDb(state.volume));
1673
+ const trackPan = createPanStage(
1674
+ context.rawContext,
1675
+ state.pan,
1676
+ trackChannelCount(track)
1677
+ );
1678
+ const trackMute = new Gain(state.muted ? 0 : 1);
1857
1679
  const trackEffects = createOfflineTrackEffects == null ? void 0 : createOfflineTrackEffects(track.id);
1858
1680
  if (trackEffects && applyEffects) {
1859
- const cleanup = yield trackEffects(trackMute, masterVolume, true);
1681
+ const cleanup = yield trackEffects(trackInput, trackVolume, true);
1860
1682
  if (cleanup) cleanups.push(cleanup);
1861
1683
  } else {
1862
- trackMute.connect(masterVolume);
1684
+ trackInput.connect(trackVolume);
1863
1685
  }
1864
- trackPan.connect(trackMute);
1865
- trackVolume.connect(trackPan);
1686
+ trackMute.connect(masterVolume);
1687
+ connect6(trackPan.output, trackMute);
1688
+ trackVolume.connect(trackPan.input);
1866
1689
  for (const clip of track.clips) {
1867
1690
  const {
1868
1691
  audioBuffer: clipBuffer,
@@ -1884,18 +1707,18 @@ function renderOffline(tracksToRender, hasSolo, duration, sampleRate, applyEffec
1884
1707
  const offset = offsetSamples / sampleRate;
1885
1708
  const toneBuffer = new ToneAudioBuffer(clipBuffer);
1886
1709
  const player = new Player(toneBuffer);
1887
- const fadeGain = new Gain2(clipGain);
1710
+ const fadeGain = new Gain(clipGain);
1888
1711
  player.connect(fadeGain);
1889
- fadeGain.connect(trackVolume);
1712
+ fadeGain.connect(trackInput);
1890
1713
  if (applyEffects) {
1891
- const audioParam = getUnderlyingAudioParam(fadeGain.gain);
1892
- if (audioParam) {
1893
- applyClipFades(audioParam, clipGain, startTime, clipDuration, fadeIn, fadeOut);
1894
- } else if (fadeIn || fadeOut) {
1895
- console.warn(
1896
- '[waveform-playlist] Cannot apply fades for clip "' + (clip.name || clip.id) + '" - AudioParam not accessible'
1897
- );
1898
- }
1714
+ applyClipFades(
1715
+ fadeGain.input.gain,
1716
+ clipGain,
1717
+ startTime,
1718
+ clipDuration,
1719
+ fadeIn,
1720
+ fadeOut
1721
+ );
1899
1722
  }
1900
1723
  player.start(startTime, offset, clipDuration);
1901
1724
  }
@@ -1943,160 +1766,37 @@ function applyClipFades(gainParam, clipGain, startTime, clipDuration, fadeIn, fa
1943
1766
  }
1944
1767
  }
1945
1768
 
1946
- // src/hooks/useDynamicTracks.ts
1947
- import { useState as useState5, useCallback as useCallback5, useRef as useRef5, useEffect as useEffect4 } from "react";
1948
- import { createTrack as createTrack2, createClipFromSeconds as createClipFromSeconds2 } from "@waveform-playlist/core";
1949
- import { getGlobalAudioContext as getGlobalAudioContext4 } from "@waveform-playlist/playout";
1950
- function getSourceName(source) {
1951
- var _a, _b, _c, _d, _e;
1952
- if (source instanceof File) {
1953
- return source.name.replace(/\.[^/.]+$/, "");
1954
- }
1955
- if (source instanceof Blob) {
1956
- return "Untitled";
1957
- }
1958
- if (typeof source === "string") {
1959
- return (_b = (_a = source.split("/").pop()) == null ? void 0 : _a.replace(/\.[^/.]+$/, "")) != null ? _b : "Untitled";
1960
- }
1961
- return (_e = (_d = source.name) != null ? _d : (_c = source.src.split("/").pop()) == null ? void 0 : _c.replace(/\.[^/.]+$/, "")) != null ? _e : "Untitled";
1962
- }
1963
- function decodeSource(source, audioContext, signal) {
1964
- return __async(this, null, function* () {
1965
- const name = getSourceName(source);
1966
- if (source instanceof Blob) {
1967
- const arrayBuffer2 = yield source.arrayBuffer();
1968
- signal == null ? void 0 : signal.throwIfAborted();
1969
- const audioBuffer2 = yield audioContext.decodeAudioData(arrayBuffer2);
1970
- return { audioBuffer: audioBuffer2, name };
1971
- }
1972
- const url = typeof source === "string" ? source : source.src;
1973
- const response = yield fetch(url, { signal });
1974
- if (!response.ok) throw new Error(`Failed to fetch ${url}: ${response.statusText}`);
1975
- const arrayBuffer = yield response.arrayBuffer();
1976
- signal == null ? void 0 : signal.throwIfAborted();
1977
- const audioBuffer = yield audioContext.decodeAudioData(arrayBuffer);
1978
- return { audioBuffer, name };
1979
- });
1980
- }
1981
- function useDynamicTracks() {
1982
- const [tracks, setTracks] = useState5([]);
1983
- const [loadingCount, setLoadingCount] = useState5(0);
1984
- const [errors, setErrors] = useState5([]);
1985
- const cancelledRef = useRef5(false);
1986
- const loadingIdsRef = useRef5(/* @__PURE__ */ new Set());
1987
- const abortControllersRef = useRef5(/* @__PURE__ */ new Map());
1988
- useEffect4(() => {
1989
- const controllers = abortControllersRef.current;
1990
- return () => {
1991
- cancelledRef.current = true;
1992
- for (const controller of controllers.values()) {
1993
- controller.abort();
1994
- }
1995
- controllers.clear();
1996
- };
1997
- }, []);
1998
- const addTracks = useCallback5((sources) => {
1999
- if (sources.length === 0) return;
2000
- const audioContext = getGlobalAudioContext4();
2001
- const placeholders = sources.map((source) => ({
2002
- track: createTrack2({ name: `${getSourceName(source)} (loading...)`, clips: [] }),
2003
- source
2004
- }));
2005
- setTracks((prev) => [...prev, ...placeholders.map((p) => p.track)]);
2006
- setLoadingCount((prev) => prev + sources.length);
2007
- for (const { track, source } of placeholders) {
2008
- loadingIdsRef.current.add(track.id);
2009
- const controller = new AbortController();
2010
- abortControllersRef.current.set(track.id, controller);
2011
- (() => __async(null, null, function* () {
2012
- try {
2013
- const { audioBuffer, name } = yield decodeSource(source, audioContext, controller.signal);
2014
- const clip = createClipFromSeconds2({
2015
- audioBuffer,
2016
- startTime: 0,
2017
- duration: audioBuffer.duration,
2018
- offset: 0,
2019
- name
2020
- });
2021
- if (!cancelledRef.current && loadingIdsRef.current.has(track.id)) {
2022
- setTracks(
2023
- (prev) => prev.map((t) => t.id === track.id ? __spreadProps(__spreadValues({}, t), { name, clips: [clip] }) : t)
2024
- );
2025
- }
2026
- } catch (error) {
2027
- if (error instanceof DOMException && error.name === "AbortError") return;
2028
- console.warn("[waveform-playlist] Error loading audio:", error);
2029
- if (!cancelledRef.current && loadingIdsRef.current.has(track.id)) {
2030
- setTracks((prev) => prev.filter((t) => t.id !== track.id));
2031
- setErrors((prev) => [
2032
- ...prev,
2033
- {
2034
- name: getSourceName(source),
2035
- error: error instanceof Error ? error : new Error(String(error))
2036
- }
2037
- ]);
2038
- }
2039
- } finally {
2040
- abortControllersRef.current.delete(track.id);
2041
- if (!cancelledRef.current && loadingIdsRef.current.delete(track.id)) {
2042
- setLoadingCount((prev) => prev - 1);
2043
- }
2044
- }
2045
- }))();
2046
- }
2047
- }, []);
2048
- const removeTrack = useCallback5((trackId) => {
2049
- setTracks((prev) => prev.filter((t) => t.id !== trackId));
2050
- const controller = abortControllersRef.current.get(trackId);
2051
- if (controller) {
2052
- controller.abort();
2053
- abortControllersRef.current.delete(trackId);
2054
- }
2055
- if (loadingIdsRef.current.delete(trackId)) {
2056
- setLoadingCount((prev) => prev - 1);
2057
- }
2058
- }, []);
2059
- return {
2060
- tracks,
2061
- addTracks,
2062
- removeTrack,
2063
- loadingCount,
2064
- isLoading: loadingCount > 0,
2065
- errors
2066
- };
2067
- }
2068
-
2069
1769
  // src/hooks/useOutputMeter.ts
2070
- import { useEffect as useEffect5, useState as useState6, useRef as useRef6, useCallback as useCallback6 } from "react";
2071
- import { getGlobalContext } from "@waveform-playlist/playout";
2072
- import { gainToNormalized } from "@waveform-playlist/core";
1770
+ import { useEffect, useState as useState4, useRef as useRef3, useCallback as useCallback5 } from "react";
1771
+ import { getGlobalContext as getGlobalContext2 } from "@waveform-playlist/playout";
1772
+ import {
1773
+ createValueSource as createValueSource2,
1774
+ readMeterMessage,
1775
+ silentMeterLevels
1776
+ } from "@waveform-playlist/core";
2073
1777
  import { meterProcessorUrl } from "@waveform-playlist/worklets";
2074
- var PEAK_DECAY = 0.98;
2075
1778
  function useOutputMeter(options = {}) {
2076
1779
  const { channelCount = 2, updateRate = 60, isPlaying = false } = options;
2077
- const [levels, setLevels] = useState6(() => new Array(channelCount).fill(0));
2078
- const [peakLevels, setPeakLevels] = useState6(() => new Array(channelCount).fill(0));
2079
- const [rmsLevels, setRmsLevels] = useState6(() => new Array(channelCount).fill(0));
2080
- const workletNodeRef = useRef6(null);
2081
- const smoothedPeakRef = useRef6(new Array(channelCount).fill(0));
2082
- const [meterError, setMeterError] = useState6(null);
2083
- const resetPeak = useCallback6(
2084
- () => setPeakLevels(new Array(channelCount).fill(0)),
2085
- [channelCount]
1780
+ const [{ source: meter, publish }] = useState4(
1781
+ () => createValueSource2(silentMeterLevels(channelCount))
2086
1782
  );
2087
- useEffect5(() => {
1783
+ const workletNodeRef = useRef3(null);
1784
+ const smoothedPeakRef = useRef3([]);
1785
+ const [meterError, setMeterError] = useState4(null);
1786
+ const resetPeak = useCallback5(() => {
1787
+ const current = meter.getSnapshot();
1788
+ publish(__spreadProps(__spreadValues({}, current), { peakLevels: current.peakLevels.map(() => 0) }));
1789
+ }, [meter, publish]);
1790
+ useEffect(() => {
2088
1791
  if (!isPlaying) {
2089
- const zeros = new Array(channelCount).fill(0);
2090
- smoothedPeakRef.current = new Array(channelCount).fill(0);
2091
- setLevels(zeros);
2092
- setRmsLevels(zeros);
2093
- setPeakLevels(zeros);
1792
+ smoothedPeakRef.current = [];
1793
+ publish(silentMeterLevels(channelCount));
2094
1794
  }
2095
- }, [isPlaying, channelCount]);
2096
- useEffect5(() => {
1795
+ }, [isPlaying, channelCount, publish]);
1796
+ useEffect(() => {
2097
1797
  let isMounted = true;
2098
1798
  const setup = () => __async(null, null, function* () {
2099
- const context = getGlobalContext();
1799
+ const context = getGlobalContext2();
2100
1800
  const rawCtx = context.rawContext;
2101
1801
  yield rawCtx.audioWorklet.addModule(meterProcessorUrl);
2102
1802
  if (!isMounted) return;
@@ -2114,26 +1814,16 @@ function useOutputMeter(options = {}) {
2114
1814
  };
2115
1815
  const destination = context.destination;
2116
1816
  destination.chain(workletNode);
2117
- smoothedPeakRef.current = new Array(channelCount).fill(0);
1817
+ smoothedPeakRef.current = [];
2118
1818
  workletNode.port.onmessage = (event) => {
2119
- var _a;
2120
1819
  if (!isMounted) return;
2121
- const data = event.data;
2122
- const workletChannels = data.length / 2;
2123
- const smoothed = smoothedPeakRef.current;
2124
- const peakValues = [];
2125
- const rmsValues = [];
2126
- for (let ch = 0; ch < workletChannels; ch++) {
2127
- smoothed[ch] = Math.max(data[ch], ((_a = smoothed[ch]) != null ? _a : 0) * PEAK_DECAY);
2128
- peakValues.push(gainToNormalized(smoothed[ch]));
2129
- rmsValues.push(gainToNormalized(data[workletChannels + ch]));
2130
- }
2131
- setLevels(peakValues);
2132
- setRmsLevels(rmsValues);
2133
- setPeakLevels((prev) => peakValues.map((val, i) => {
2134
- var _a2;
2135
- return Math.max((_a2 = prev[i]) != null ? _a2 : 0, val);
2136
- }));
1820
+ const reading = readMeterMessage({
1821
+ data: event.data,
1822
+ previousSmoothedPeaks: smoothedPeakRef.current,
1823
+ heldPeakLevels: meter.getSnapshot().peakLevels
1824
+ });
1825
+ smoothedPeakRef.current = reading.smoothedPeaks;
1826
+ publish(reading.levels);
2137
1827
  };
2138
1828
  });
2139
1829
  setup().catch((err) => {
@@ -2146,7 +1836,7 @@ function useOutputMeter(options = {}) {
2146
1836
  isMounted = false;
2147
1837
  if (workletNodeRef.current) {
2148
1838
  try {
2149
- const context = getGlobalContext();
1839
+ const context = getGlobalContext2();
2150
1840
  context.destination.chain();
2151
1841
  } catch (err) {
2152
1842
  console.warn("[waveform-playlist] Failed to restore destination chain:", String(err));
@@ -2160,43 +1850,64 @@ function useOutputMeter(options = {}) {
2160
1850
  workletNodeRef.current = null;
2161
1851
  }
2162
1852
  };
2163
- }, [channelCount, updateRate]);
2164
- return { levels, peakLevels, rmsLevels, resetPeak, error: meterError };
1853
+ }, [channelCount, updateRate, meter, publish]);
1854
+ return { meter, resetPeak, error: meterError };
2165
1855
  }
2166
1856
 
2167
1857
  // src/components/ExportControls.tsx
2168
1858
  import { BaseControlButton } from "@waveform-playlist/ui-components";
2169
1859
 
2170
- // src/WaveformPlaylistContext.tsx
2171
- import {
2172
- createContext,
2173
- useContext,
2174
- useState as useState7,
2175
- useEffect as useEffect6,
2176
- useRef as useRef7,
2177
- useCallback as useCallback7,
2178
- useMemo as useMemo2
2179
- } from "react";
2180
- import { ThemeProvider } from "styled-components";
2181
- import { PlaylistEngine } from "@waveform-playlist/engine";
2182
- import {
2183
- defaultTheme
2184
- } from "@waveform-playlist/ui-components";
2185
- import { jsx } from "react/jsx-runtime";
2186
- var PlaybackAnimationContext = createContext(null);
2187
- var PlaylistStateContext = createContext(null);
2188
- var PlaylistControlsContext = createContext(null);
2189
- var PlaylistDataContext = createContext(null);
2190
- var usePlaylistData = () => {
2191
- const context = useContext(PlaylistDataContext);
2192
- if (!context) {
2193
- throw new Error("usePlaylistData must be used within WaveformPlaylistProvider");
1860
+ // src/contexts/playlistContexts.ts
1861
+ import { createContext, use } from "react";
1862
+ var WEB_AUDIO = "WaveformPlaylistProvider";
1863
+ var MEDIA_ELEMENT = "MediaElementPlaylistProvider";
1864
+ var BLOCKED = /* @__PURE__ */ Symbol("waveform-playlist.blocked-context");
1865
+ var slot = () => createContext(null);
1866
+ var IsPlayingContext = slot();
1867
+ var PlaybackRefsContext = slot();
1868
+ var SelectionContext = slot();
1869
+ var CurrentTimeContext = slot();
1870
+ var ActiveAnnotationContext = slot();
1871
+ var AnnotationsContext = slot();
1872
+ var AnnotationOptionsContext = slot();
1873
+ var PlaybackControlsContext = slot();
1874
+ var PlaylistViewContext = slot();
1875
+ var PlaylistSettingsContext = slot();
1876
+ var PlaylistZoomContext = slot();
1877
+ var SelectedRowContext = slot();
1878
+ var ArrangementContext = slot();
1879
+ var EditorControlsContext = slot();
1880
+ var EngineRefsContext = slot();
1881
+ var LoopContext = slot();
1882
+ var SelectedTrackIdContext = slot();
1883
+ var UndoRedoContext = slot();
1884
+ var PlaylistTimelineContext = slot();
1885
+ var PlaylistMixerContext = slot();
1886
+ var TrackReorderPreviewContext = slot();
1887
+ var TrimPreviewContext = slot();
1888
+ var TrimPreviewPeaksContext = slot();
1889
+ var RecordingArmContext = slot();
1890
+ var PlaybackRateContext = slot();
1891
+ var MediaElementTrackContext = slot();
1892
+ function useSlot(context, hookName, needs) {
1893
+ const value = use(context);
1894
+ if (value === BLOCKED) {
1895
+ const nearest = needs === WEB_AUDIO ? MEDIA_ELEMENT : WEB_AUDIO;
1896
+ throw new Error(
1897
+ `${hookName} needs ${needs}, and the nearest playlist provider here is ${nearest}, which does not provide it`
1898
+ );
2194
1899
  }
2195
- return context;
2196
- };
1900
+ if (!value) {
1901
+ throw new Error(`${hookName} must be used within ${needs}`);
1902
+ }
1903
+ return value;
1904
+ }
1905
+ var EITHER = `${WEB_AUDIO} or ${MEDIA_ELEMENT}`;
1906
+ var usePlaylistTimeline = () => useSlot(PlaylistTimelineContext, "usePlaylistTimeline", WEB_AUDIO);
1907
+ var usePlaylistMixer = () => useSlot(PlaylistMixerContext, "usePlaylistMixer", WEB_AUDIO);
2197
1908
 
2198
1909
  // src/components/ExportControls.tsx
2199
- import { jsx as jsx2 } from "react/jsx-runtime";
1910
+ import { jsx } from "react/jsx-runtime";
2200
1911
  var ExportWavButton = ({
2201
1912
  label = "Export WAV",
2202
1913
  filename = "export",
@@ -2210,7 +1921,8 @@ var ExportWavButton = ({
2210
1921
  onExportComplete,
2211
1922
  onExportError
2212
1923
  }) => {
2213
- const { tracks, trackStates } = usePlaylistData();
1924
+ const { tracks } = usePlaylistTimeline();
1925
+ const { trackStates } = usePlaylistMixer();
2214
1926
  const { exportWav, isExporting, progress } = useExportWav();
2215
1927
  const handleExport = () => __async(null, null, function* () {
2216
1928
  try {
@@ -2230,7 +1942,7 @@ var ExportWavButton = ({
2230
1942
  }
2231
1943
  });
2232
1944
  const buttonLabel = isExporting ? `Exporting ${Math.round(progress * 100)}%` : label;
2233
- return /* @__PURE__ */ jsx2(
1945
+ return /* @__PURE__ */ jsx(
2234
1946
  BaseControlButton,
2235
1947
  {
2236
1948
  onClick: handleExport,
@@ -2242,20 +1954,23 @@ var ExportWavButton = ({
2242
1954
  };
2243
1955
 
2244
1956
  // src/components/WamEffectGui.tsx
2245
- import { useEffect as useEffect7, useRef as useRef8 } from "react";
2246
- import { jsx as jsx3 } from "react/jsx-runtime";
1957
+ import { useEffect as useEffect2, useRef as useRef4 } from "react";
1958
+ import { jsx as jsx2 } from "react/jsx-runtime";
2247
1959
  var WamEffectGui = ({ plugin, className }) => {
2248
- const hostRef = useRef8(null);
2249
- useEffect7(() => {
1960
+ const hostRef = useRef4(null);
1961
+ useEffect2(() => {
2250
1962
  const host = hostRef.current;
2251
1963
  if (!plugin || !host) return;
2252
1964
  let cancelled = false;
2253
1965
  let gui = null;
1966
+ let pluginOwnsGui = false;
2254
1967
  (() => __async(null, null, function* () {
2255
1968
  var _a;
2256
1969
  try {
2257
- if (plugin.createGui) {
2258
- gui = yield plugin.createGui();
1970
+ const own = plugin.createGui ? yield plugin.createGui() : void 0;
1971
+ if (own instanceof HTMLElement) {
1972
+ gui = own;
1973
+ pluginOwnsGui = true;
2259
1974
  } else {
2260
1975
  const wam = yield loadWamModule();
2261
1976
  gui = yield wam.createWamParameterPanel(
@@ -2263,7 +1978,7 @@ var WamEffectGui = ({ plugin, className }) => {
2263
1978
  );
2264
1979
  }
2265
1980
  if (cancelled) {
2266
- if (gui) {
1981
+ if (gui && pluginOwnsGui) {
2267
1982
  try {
2268
1983
  (_a = plugin.destroyGui) == null ? void 0 : _a.call(plugin, gui);
2269
1984
  } catch (destroyErr) {
@@ -2288,6 +2003,7 @@ var WamEffectGui = ({ plugin, className }) => {
2288
2003
  cancelled = true;
2289
2004
  if (gui) {
2290
2005
  gui.remove();
2006
+ if (!pluginOwnsGui) return;
2291
2007
  try {
2292
2008
  (_a = plugin.destroyGui) == null ? void 0 : _a.call(plugin, gui);
2293
2009
  } catch (destroyErr) {
@@ -2298,22 +2014,23 @@ var WamEffectGui = ({ plugin, className }) => {
2298
2014
  }
2299
2015
  };
2300
2016
  }, [plugin]);
2301
- return /* @__PURE__ */ jsx3("div", { ref: hostRef, className: className != null ? className : "wam-effect-gui" });
2017
+ return /* @__PURE__ */ jsx2("div", { ref: hostRef, className: className != null ? className : "wam-effect-gui" });
2302
2018
  };
2303
2019
  export {
2304
2020
  ExportWavButton,
2305
2021
  WamEffectGui,
2022
+ createCustomEffectInstance,
2306
2023
  createEffectChain,
2307
2024
  createEffectInstance,
2308
2025
  createWamEffectInstance,
2309
2026
  effectCategories,
2310
2027
  effectDefinitions,
2028
+ getAvailableEffects,
2311
2029
  getEffectDefinition,
2312
2030
  getEffectsByCategory,
2313
2031
  loadWamModule,
2314
- useAudioTracks,
2032
+ useActiveEffects,
2315
2033
  useDynamicEffects,
2316
- useDynamicTracks,
2317
2034
  useExportWav,
2318
2035
  useMasterAnalyser,
2319
2036
  useOutputMeter,