-
Notifications
You must be signed in to change notification settings - Fork 26
/
base_plugin.ts
372 lines (341 loc) 路 10.6 KB
/
base_plugin.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
import type { ParamDescriptor, LabelText, AudioPluginDescriptor, EntityId } from './descriptors';
import type { Song } from './models/song';
import * as _ from 'underscore';
import { nanoid } from 'nanoid';
import { WidgetType } from '.';
import type {
TuneflowPluginOptions,
TuneflowPluginTriggerData,
TuneflowPluginTriggerType,
} from './descriptors/plugin';
type RunParameters = { [paramName: string]: any };
export interface ReadAPIs {
readAudioBuffer: (audioFile: string | File) => Promise<AudioBuffer | null | undefined>;
readPluginSpec: (specPath: string) => Promise<any>;
/** Read a file with an allowed extension type. */
readFile: (filePath: string) => Promise<Uint8Array | null>;
resolvePath: (path1: string, path2: string) => Promise<string>;
translateLabel: (label: LabelText) => string;
serializeSong: (song: Song) => Promise<string>;
serializeSongAsUint8Array: (song: Song) => Promise<Uint8Array>;
deserializeSong: (encodedSong: string, keepPluginStates?: boolean) => Promise<Song>;
deserializeSongFromUint8Array: (
encodedSong: Uint8Array,
keepPluginStates?: boolean,
) => Promise<Song>;
getAvailableAudioPlugins: () => Promise<AudioPluginDescriptor[]>;
getFilesInDirectory: (directoryPath: string) => Promise<string[]>;
}
/**
* The base class of a plugin.
*
* All plugins should be a sub-class of this plugin in order to run in the pipeline.
*/
export class TuneflowPlugin {
private instanceIdInternal = TuneflowPlugin.generatePluginIdInternal();
enabledInternal = true;
private paramsResultInternal: RunParameters = {};
// @ts-ignore
private generatedTrackIdsInternal: string[] = [];
private isRollbackable = false;
/** Cache for the Song instance that was successfully produced in the last pipeline run. */
// @ts-ignore
private songCacheInternal?: Song;
readonly allowManualApplyAdjust = false;
readonly allowReset = false;
// @ts-ignore
readonly trigger?: TuneflowPluginTriggerData = undefined;
/** The execution progress. */
private progress: number | null = null;
private isExecuting = false;
private isPreparingForRunInternal = false;
// @ts-ignore
private hasInjectedDataInternal = false;
// ============ PUBLIC OVERWRITABLE ================
/**
* The unique id to identify the plugin provider.
*
* For example:
* `friday-core`, `some-corp`, etc.
*/
static providerId(): string {
throw new Error('providerId() should be overwritten.');
}
/**
* The unique plugin id under the provider's namespace.
*
* For example:
* `melody-extractor`, `tune-analyzer`, etc.
*/
static pluginId(): string {
throw new Error('pluginId() should be overwritten.');
}
/**
* Initializes the plugin instance.
*
* Override this method to initialize your plugin before it starts running.
*
* @param song The current version of the song, read-only.
* @param readApis Apis to read data.
*/
// eslint-disable-next-line @typescript-eslint/no-unused-vars
protected async init(song: Song, readApis: ReadAPIs) {}
/**
* Specify params to get from user input.
*
* Param input widgets will be displayed on the UI, and the inputs will be collected and fed into @run method.
*
* If you don't need any param, return `{}`;
*/
params(): { [paramName: string]: ParamDescriptor } {
return {};
}
/**
* The main logic here.
*
* It should return a map that contains the produced artifacts of this plugin.
* Each artifact goes under a different artifactId.
*
* For example: `{ 'artifactId1': <output1>, 'artifactId2': <output2> }`
*
* @param song The song that is being processed. You can directly modify the song
* by calling its methods.
* @param params The results collected from user input specified by the `params` method.
* @param readApis The APIs to read data.
*
*/
async run(
// eslint-disable-next-line
song: Song,
// eslint-disable-next-line
params: RunParameters,
// eslint-disable-next-line
readApis: ReadAPIs,
): Promise<void> {}
/**
* Called when the plugin execution is cancelled.
*/
onCancel() {
// Do nothing by default.
}
// ============ PUBLIC NO OVERWRITE ================
/**
* Creates a plugin instance and initializes it.
* @param song The current version of the song.
*/
public static async create(
song: Song,
readApis: ReadAPIs,
options: TuneflowPluginOptions,
triggerType?: TuneflowPluginTriggerType,
triggeringEntities?: EntityId[] | null,
) {
const plugin = new this();
// @ts-ignore
plugin.allowManualApplyAdjust = options.allowManualApplyAdjust;
// @ts-ignore
plugin.allowReset = options.allowReset;
// @ts-ignore
plugin.trigger = triggerType
? {
type: triggerType,
entities: triggeringEntities,
}
: undefined;
plugin.resetInternal();
await plugin.init(song, readApis);
return plugin;
}
public get instanceId() {
return this.instanceIdInternal;
}
/**
* DO NOT overwrite this method.
*
* Gets a typed param.
* @param params The `params` from `run` method input.
*/
public getParam<T>(params: RunParameters, paramName: string) {
return params[paramName] as T;
}
/**
* DO NOT overwrite this method.
* @final
* @returns Whether all params has been set.
*/
public hasAllParamsSet(): boolean {
for (const paramName of _.keys(this.params())) {
const paramProvided = this.isParamProvided(paramName);
if (!paramProvided) {
return false;
}
}
return true;
}
public isParamProvided(paramName: string) {
if (this.params()[paramName].optional) {
return true;
}
const paramResult = this.paramsResultInternal[paramName];
if (paramResult === undefined || paramResult === null) {
return false;
}
// If the param is a non-primitive value(like an object),
// we need to do additional check.
const paramDescriptor = this.params()[paramName];
const paramWidgetType = paramDescriptor.widget.type;
switch (paramWidgetType) {
case WidgetType.Input:
case WidgetType.Pitch:
case WidgetType.Slider:
case WidgetType.TrackSelector:
case WidgetType.Select:
case WidgetType.SelectList:
case WidgetType.Switch:
case WidgetType.InputNumber:
case WidgetType.FileSelector:
// Nothing else to check.
return true;
case WidgetType.MultiTrackSelector:
return paramResult.length > 0;
case WidgetType.TrackPitchSelector:
return (
paramResult.track !== undefined &&
paramResult.track !== null &&
paramResult.pitch !== undefined &&
paramResult.pitch !== null
);
case WidgetType.InstrumentSelector:
return (
paramResult.program !== undefined &&
paramResult.program !== null &&
paramResult.isDrum !== undefined &&
paramResult.isDrum !== null
);
case WidgetType.MultiSourceAudioSelector:
return (
paramResult !== undefined &&
paramResult !== null &&
paramResult.audioInfo !== undefined &&
paramResult.audioInfo !== null
);
case WidgetType.None:
return paramResult !== undefined && paramResult !== null;
case WidgetType.TextArea:
return paramResult !== '';
default:
throw new Error(
`Param nullness check needs to be implemented for widget type ${paramWidgetType}. Either use default nullness check or define custom logic.`,
);
}
}
/**
* DO NOT overwrite this method.
* @final
* @returns The unique identifier for the plugin CLASS, which is the combination of providerId and moduleId. NOTE: this is not the id of the plugin instance.
*/
public static id(): string {
return TuneflowPlugin.getPluginFullId(this.providerId(), this.pluginId());
}
public static getPluginFullId(providerId: string, pluginId: string) {
return `${providerId}^_^${pluginId}`;
}
/**
* DO NOT overwrite this method.
* @final
* @returns The universal unique identifier for this artifact.
*/
public static getPrefixedArtifactId(artifactId: string) {
return `${this.id()}.${artifactId}`;
}
/** Sets the current execution progress (0 - 1). */
public setProgress(progress: number | null) {
this.progress = progress;
}
/**
* Gets the current execution progress.
*
* Only numeric return is considered valid.
*/
public getProgress() {
return this.progress;
}
/** Whether the `run` method is running. */
public getIsExecuting() {
return this.isExecuting;
}
/** Whether the plugin's params and other data is being prepared. */
public getIsPreparingForRun() {
return this.isPreparingForRunInternal;
}
// ============ INTERNAL BELOW ================
/**
* DO NOT overwrite this method.
*
* The host of the pipeline should call this method to set params for the plugins before running the pipeline.
* @final
*/
public setParamsInternal(params: { [paramName: string]: any }) {
this.paramsResultInternal = params;
this.maybeSyncEnabledWithParamsReadiness();
}
/**
* DO NOT overwrite this method.
* @final
*/
public getParamsInternal() {
return this.paramsResultInternal;
}
/**
* DO NOT overwrite this method.
*
* Resets the parameters of this plugin.
* @final
*/
public resetParamsInternal() {
for (const key of _.keys(this.params())) {
const paramDescriptor = this.params()[key];
if (paramDescriptor.injectFrom && this.isParamProvided(key)) {
continue;
}
this.paramsResultInternal[key] = paramDescriptor.defaultValue;
}
this.maybeSyncEnabledWithParamsReadiness();
}
/**
* DO NOT overwrite this method.
*
* Resets the whole plugin, including states.
* @final
*/
public resetInternal() {
this.resetParamsInternal();
if (this.allowManualApplyAdjust) {
this.enabledInternal = false;
}
}
public setEnabledInternal(enabled: boolean) {
const prevEnabled = this.enabledInternal;
this.enabledInternal = enabled;
if (prevEnabled && !enabled) {
// Disabled.
try {
this.onCancel();
} catch (e: any) {
console.error(e);
}
}
}
/**
* If the plugin is manually enabled, and params are not ready,
* the plugin should be disabled.
*/
private maybeSyncEnabledWithParamsReadiness() {
if (this.allowManualApplyAdjust && !this.hasAllParamsSet()) {
this.setEnabledInternal(false);
}
}
private static generatePluginIdInternal() {
return nanoid(10);
}
}