-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.ts
194 lines (178 loc) · 5.38 KB
/
graph.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { Node } from "./webAudioNodes";
export interface BaseNode {
children?: BaseNode[];
type: string;
key?: string;
parent?: BaseNode;
auxConnections?: string[];
backingNode?: any;
props?: any;
}
export type FindNode = (key: string) => Node | undefined;
export interface AudioGraphDelegate {
createNode: (
type: Node["type"],
findNode: FindNode,
getSample: (key: string) => AudioBuffer | undefined,
key?: string,
) => any;
deleteNode: (node: Node) => void;
updateNode: (node: Node, findNode: FindNode) => void;
connectNodes: (src: Node, dest: Node) => void;
start: (step?: number) => void;
stop: () => void;
isPlaying: () => boolean;
initialize: () => Promise<void>;
}
type NodeProps<T extends BaseNode["type"]> = Extract<
Node,
{ type: T }
>["props"];
export class AudioGraph {
constructor(private delegate: AudioGraphDelegate) {}
private currentRoot: Node | null = null;
private nodeStore: Map<string, Node> = new Map();
private sampleStore: Map<string, AudioBuffer> = new Map();
async render(newRoot: Node) {
await this.delegate.initialize();
newRoot = this.buildAudioGraph({
newNode: newRoot,
currentNode: this.currentRoot,
parent: null,
});
this.currentRoot = newRoot;
this.setupAuxConnections(this.currentRoot!);
}
public isPlaying() {
return this.delegate.isPlaying();
}
start(startStep?: number) {
this.delegate.start(startStep);
}
stop() {
this.delegate.stop();
}
setProperty<T extends Node["type"], P extends keyof NodeProps<T>>(
nodeKey: string,
nodeType: T,
propId: P,
value: NodeProps<T>[P],
) {
if (!this.currentRoot) {
return;
}
const node = this.nodeStore.get(nodeKey);
if (!node) {
return;
}
if (node.type === nodeType) {
node.props[propId] = value;
this.delegate.updateNode(node, (key) => this.nodeStore.get(key));
} else {
throw new Error(
`Node types were incompatible ${nodeType} and ${node.type}`,
);
}
}
addSample(key: string, buffer: AudioBuffer) {
this.sampleStore.set(key, buffer);
}
/// Recursively builds a WebAudio graph by diffing the new tree (rooted at newNode) with
/// the current tree, then adding, removing, or updating nodes and their connections
/// to fulfill the requested state.
///
/// Returns the Node created for `newNode`, or null if none was created.
private buildAudioGraph({
newNode,
currentNode,
parent,
}: {
newNode: Node;
currentNode: Node | null;
parent: Node | null;
}): Node {
const keyMatch =
newNode.key !== undefined && newNode.key === currentNode?.key;
const addNode =
!keyMatch && (!currentNode || newNode.type !== currentNode.type);
if (addNode) {
if (currentNode) {
// Remove existing node
this.delegate.deleteNode(currentNode);
}
newNode.parent = parent ?? undefined;
newNode.backingNode = this.delegate.createNode(
newNode.type,
(key) => this.nodeStore.get(key),
(key) => this.sampleStore.get(key),
newNode.key,
);
if (parent) {
this.delegate.connectNodes(newNode, parent);
}
} else {
newNode.parent = currentNode.parent;
newNode.backingNode = currentNode.backingNode;
}
const updatedNode = this.applyChildNodeUpdates(newNode, currentNode);
this.delegate.updateNode(updatedNode, (key) => this.nodeStore.get(key));
if (updatedNode.key) {
this.nodeStore.set(updatedNode.key, updatedNode);
}
return updatedNode;
}
/// Recursively iterates over the children of newNode and currentNode and adds or
/// removes AudioNodes from the tree to satisfy the requested state.
private applyChildNodeUpdates(
newParent: Node,
currentParent: Node | null,
): Node {
if (newParent.children) {
for (let index = 0; index < newParent.children.length; ++index) {
const newChild = newParent.children[index];
const currentChild =
currentParent &&
currentParent.children &&
currentParent.children.length > index
? currentParent.children[index]
: null;
newParent.children![index] = this.buildAudioGraph({
newNode: newChild as Node,
currentNode: currentChild as Node,
parent: newParent,
});
}
}
// Delete removed children
const numNewChildren = newParent.children ? newParent.children.length : 0;
if (
currentParent &&
currentParent.children &&
currentParent.children.length > numNewChildren
) {
// Delete any children that are no longer in the child array
for (let i = numNewChildren; i < currentParent.children!.length; ++i) {
this.delegate.deleteNode(currentParent.children![i] as Node);
}
}
return newParent;
}
private setupAuxConnections(node: Node) {
if (node.auxConnections) {
node.auxConnections.forEach((key) => {
const auxNode = this.nodeStore.get(key);
if (auxNode) {
this.delegate.connectNodes(node, auxNode);
} else {
throw new Error(
`Failed to make aux connection to node with key: ${key}`,
);
}
node.children?.forEach((child) =>
this.setupAuxConnections(child as Node),
);
});
}
node.children?.forEach((child) => this.setupAuxConnections(child));
}
}