@playcraft/common 0.1.67 → 0.1.68

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.
Files changed (56) hide show
  1. package/dist/agent-tools/replica-validation.d.ts +12 -12
  2. package/dist/audio-library-stream.d.ts +65 -0
  3. package/dist/audio-library-stream.d.ts.map +1 -0
  4. package/dist/audio-library-stream.js +87 -0
  5. package/dist/audio-library-stream.js.map +1 -0
  6. package/dist/cloud-workspace/runtime/animation-editor.d.ts +1 -1
  7. package/dist/cloud-workspace/runtime/artifacts.d.ts +7 -7
  8. package/dist/cloud-workspace/runtime/asset-generation-tools.d.ts +9 -9
  9. package/dist/cloud-workspace/runtime/asset-generation.d.ts +29 -29
  10. package/dist/cloud-workspace/runtime/asset-library-import.d.ts +31 -1
  11. package/dist/cloud-workspace/runtime/asset-library-import.d.ts.map +1 -1
  12. package/dist/cloud-workspace/runtime/asset-library-save.d.ts +6 -6
  13. package/dist/cloud-workspace/runtime/audio-delivery.d.ts +75 -0
  14. package/dist/cloud-workspace/runtime/audio-delivery.d.ts.map +1 -0
  15. package/dist/cloud-workspace/runtime/audio-delivery.js +122 -0
  16. package/dist/cloud-workspace/runtime/audio-delivery.js.map +1 -0
  17. package/dist/cloud-workspace/runtime/audio-dynamic-document.d.ts +68 -0
  18. package/dist/cloud-workspace/runtime/audio-dynamic-document.d.ts.map +1 -0
  19. package/dist/cloud-workspace/runtime/audio-dynamic-document.js +120 -0
  20. package/dist/cloud-workspace/runtime/audio-dynamic-document.js.map +1 -0
  21. package/dist/cloud-workspace/runtime/audio-export.d.ts +3 -3
  22. package/dist/cloud-workspace/runtime/audio-hybrid-player.d.ts +22 -0
  23. package/dist/cloud-workspace/runtime/audio-hybrid-player.d.ts.map +1 -0
  24. package/dist/cloud-workspace/runtime/audio-hybrid-player.js +456 -0
  25. package/dist/cloud-workspace/runtime/audio-hybrid-player.js.map +1 -0
  26. package/dist/cloud-workspace/runtime/audio-library.d.ts +418 -0
  27. package/dist/cloud-workspace/runtime/audio-library.d.ts.map +1 -0
  28. package/dist/cloud-workspace/runtime/audio-library.js +155 -0
  29. package/dist/cloud-workspace/runtime/audio-library.js.map +1 -0
  30. package/dist/cloud-workspace/runtime/audio-prerender-player.d.ts +31 -0
  31. package/dist/cloud-workspace/runtime/audio-prerender-player.d.ts.map +1 -0
  32. package/dist/cloud-workspace/runtime/audio-prerender-player.js +178 -0
  33. package/dist/cloud-workspace/runtime/audio-prerender-player.js.map +1 -0
  34. package/dist/cloud-workspace/runtime/chat-realtime.d.ts +2 -2
  35. package/dist/cloud-workspace/runtime/delivery.d.ts +4 -4
  36. package/dist/cloud-workspace/runtime/events.d.ts +4 -4
  37. package/dist/cloud-workspace/runtime/index.d.ts +5 -0
  38. package/dist/cloud-workspace/runtime/index.d.ts.map +1 -1
  39. package/dist/cloud-workspace/runtime/index.js +5 -0
  40. package/dist/cloud-workspace/runtime/index.js.map +1 -1
  41. package/dist/cloud-workspace/runtime/level-editor-agent.d.ts +4 -4
  42. package/dist/cloud-workspace/runtime/library-attachments.d.ts +60 -0
  43. package/dist/cloud-workspace/runtime/library-attachments.d.ts.map +1 -1
  44. package/dist/cloud-workspace/runtime/library-attachments.js +4 -0
  45. package/dist/cloud-workspace/runtime/library-attachments.js.map +1 -1
  46. package/dist/cloud-workspace/runtime/model-build-inputs.d.ts +1 -1
  47. package/dist/cloud-workspace/runtime/model-production.d.ts +64 -64
  48. package/dist/cloud-workspace/runtime/model-quality.d.ts +73 -73
  49. package/dist/cloud-workspace/runtime/model-validation.d.ts +1 -1
  50. package/dist/cloud-workspace/runtime/operations.d.ts +55 -25
  51. package/dist/cloud-workspace/runtime/operations.d.ts.map +1 -1
  52. package/dist/cloud-workspace/runtime/parameter-agent.d.ts +2 -2
  53. package/dist/cloud-workspace/runtime/previews.d.ts +3 -3
  54. package/dist/cloud-workspace/runtime/workspace-notifications.d.ts +1 -1
  55. package/dist/cloud-workspace/runtime/workspace-ui.d.ts +6 -6
  56. package/package.json +5 -1
@@ -0,0 +1,120 @@
1
+ import { assertUniqueJsonKeys, audioSha256 } from './audio-document.js';
2
+ import { AudioRenderError } from './audio-synthesizer.js';
3
+ export const AUDIO_DYNAMIC_ENGINE = { id: 'playcraft-webaudio-program', version: '1.0.0' };
4
+ export const AUDIO_DYNAMIC_LIMITS = { programBytes: 65536, assets: 8, states: 16, layers: 4,
5
+ samples: 4, sampleSeconds: 2, sampleFrames: 88200, totalSampleFrames: 352800,
6
+ sampleBytes: 176444, inputBytes: 2 * 1024 * 1024, graphNodes: 4096,
7
+ noiseFrames: 2646000, durationSeconds: 60, simultaneousVoices: 32 };
8
+ function programFailure(code = 'invalid_audio_program') { throw new AudioRenderError(code); }
9
+ function programRecord(value, keys) {
10
+ if (!value || typeof value !== 'object' || Array.isArray(value)
11
+ || ![Object.prototype, null].includes(Object.getPrototypeOf(value))
12
+ || Object.keys(value).some(key => !keys.includes(key)))
13
+ programFailure();
14
+ return value;
15
+ }
16
+ function programNumber(value, min, max, integer = false) {
17
+ if (typeof value !== 'number' || !Number.isFinite(value) || value < min || value > max
18
+ || integer && !Number.isInteger(value))
19
+ programFailure();
20
+ return value;
21
+ }
22
+ function programId(value) {
23
+ if (typeof value !== 'string' || !/^[a-z][a-z0-9_-]{0,63}$/.test(value))
24
+ programFailure();
25
+ return value;
26
+ }
27
+ function programArray(value, min, max) {
28
+ if (!Array.isArray(value) || value.length < min || value.length > max)
29
+ programFailure();
30
+ return value;
31
+ }
32
+ function programDependency(value, maxBytes = 65536) {
33
+ const record = programRecord(value, ['path', 'contentHash', 'size']);
34
+ if (typeof record.path !== 'string' || record.path.length > 1024
35
+ || !/^dist\/audio\/[a-zA-Z0-9._/-]+$/.test(record.path)
36
+ || record.path.split('/').some(segment => !segment || segment === '.' || segment === '..')
37
+ || !record.path.split('/').some(segment => /^[a-f0-9]{64}$/.test(segment))
38
+ || typeof record.contentHash !== 'string' || !/^[a-f0-9]{64}$/.test(record.contentHash))
39
+ programFailure();
40
+ return { path: record.path, contentHash: record.contentHash, size: programNumber(record.size, 1, maxBytes, true) };
41
+ }
42
+ /** A separate project program; this does not extend either existing sound source format. */
43
+ export function validateAudioDynamicProgram(value) {
44
+ const raw = programRecord(value, ['format', 'formatVersion', 'name', 'transition', 'masterGain', 'initialState', 'assets', 'states']);
45
+ if (raw.format !== 'playcraft.audio-program' || raw.formatVersion !== 1 || raw.transition !== 'restart'
46
+ || typeof raw.name !== 'string' || !raw.name.length || raw.name.length > 128)
47
+ programFailure();
48
+ const assets = programArray(raw.assets, 1, 8).map(value => {
49
+ const asset = programRecord(value, ['id', 'kind', 'source', 'manifest', 'file']);
50
+ const id = programId(asset.id);
51
+ if (asset.kind === 'synth') {
52
+ if (asset.file !== undefined)
53
+ programFailure();
54
+ const source = programDependency(asset.source), manifest = programDependency(asset.manifest);
55
+ if (!/\/sound\.(pcaudio|pcscore)\.json$/.test(source.path) || !manifest.path.endsWith('/manifest.json')
56
+ || source.path.slice(0, source.path.lastIndexOf('/')) !== manifest.path.slice(0, manifest.path.lastIndexOf('/')))
57
+ programFailure();
58
+ return { id, kind: 'synth', source, manifest };
59
+ }
60
+ if (asset.kind !== 'sample' || asset.source !== undefined || asset.manifest !== undefined)
61
+ programFailure();
62
+ const file = programDependency(asset.file, AUDIO_DYNAMIC_LIMITS.sampleBytes);
63
+ if (!file.path.endsWith('.wav') || file.size < 46)
64
+ programFailure();
65
+ return { id, kind: 'sample', file };
66
+ });
67
+ if (new Set(assets.map(asset => asset.id)).size !== assets.length || assets.filter(asset => asset.kind === 'sample').length > 4)
68
+ programFailure();
69
+ const states = programArray(raw.states, 1, 16).map(value => {
70
+ const state = programRecord(value, ['id', 'durationSeconds', 'layers']);
71
+ const layers = programArray(state.layers, 1, 4).map(value => {
72
+ const layer = programRecord(value, ['assetId', 'gain', 'pitchSemitones', 'lowpassHz', 'loop', 'rangeBeats']);
73
+ const assetId = programId(layer.assetId), asset = assets.find(asset => asset.id === assetId);
74
+ if (!asset || typeof layer.loop !== 'boolean')
75
+ programFailure();
76
+ let rangeBeats = null;
77
+ if (layer.rangeBeats !== null && layer.rangeBeats !== undefined) {
78
+ const range = programRecord(layer.rangeBeats, ['start', 'end']);
79
+ rangeBeats = { start: programNumber(range.start, 0, 256), end: programNumber(range.end, 0, 256) };
80
+ if (rangeBeats.end <= rangeBeats.start || asset.kind !== 'synth' || !asset.source.path.endsWith('.pcscore.json'))
81
+ programFailure();
82
+ }
83
+ return { assetId, gain: programNumber(layer.gain ?? 1, 0, 1),
84
+ pitchSemitones: programNumber(layer.pitchSemitones ?? 0, -24, 24, true),
85
+ lowpassHz: layer.lowpassHz == null ? null : programNumber(layer.lowpassHz, 20, 20000), loop: layer.loop, rangeBeats };
86
+ });
87
+ if (new Set(layers.map(layer => layer.assetId)).size !== layers.length)
88
+ programFailure();
89
+ return { id: programId(state.id), durationSeconds: programNumber(state.durationSeconds, 0.05, 60), layers };
90
+ });
91
+ const initialState = programId(raw.initialState);
92
+ if (new Set(states.map(state => state.id)).size !== states.length || !states.some(state => state.id === initialState))
93
+ programFailure();
94
+ const program = { format: 'playcraft.audio-program', formatVersion: 1, name: raw.name,
95
+ transition: 'restart', masterGain: programNumber(raw.masterGain, 0, 1), initialState, assets, states };
96
+ if (new TextEncoder().encode(JSON.stringify(program) + '\n').length > 65536)
97
+ programFailure('audio_program_budget_exceeded');
98
+ return program;
99
+ }
100
+ export function parseAudioDynamicProgram(input) {
101
+ if ((typeof input === 'string' ? new TextEncoder().encode(input).length : input.byteLength) > 65536)
102
+ programFailure('audio_program_budget_exceeded');
103
+ try {
104
+ const text = typeof input === 'string' ? input : new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(input);
105
+ assertUniqueJsonKeys(text);
106
+ return validateAudioDynamicProgram(JSON.parse(text));
107
+ }
108
+ catch (error) {
109
+ if (error instanceof AudioRenderError)
110
+ throw error;
111
+ return programFailure();
112
+ }
113
+ }
114
+ export const serializeAudioDynamicProgram = (program) => JSON.stringify(validateAudioDynamicProgram(program)) + '\n';
115
+ export function audioDynamicProgramSemanticHash(program) {
116
+ const { name: _name, ...content } = validateAudioDynamicProgram(program);
117
+ return audioSha256(JSON.stringify(content));
118
+ }
119
+ export const isAudioDynamicProgramPath = (path) => path.toLowerCase().endsWith('.pcaudioprogram.json');
120
+ //# sourceMappingURL=audio-dynamic-document.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audio-dynamic-document.js","sourceRoot":"","sources":["../../../src/cloud-workspace/runtime/audio-dynamic-document.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,wBAAwB,CAAC;AAE1D,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,EAAE,EAAE,4BAA4B,EAAE,OAAO,EAAE,OAAO,EAAW,CAAC;AACpG,MAAM,CAAC,MAAM,oBAAoB,GAAG,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,CAAC;IACzF,OAAO,EAAE,CAAC,EAAE,aAAa,EAAE,CAAC,EAAE,YAAY,EAAE,KAAK,EAAE,iBAAiB,EAAE,MAAM;IAC5E,WAAW,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,GAAG,IAAI,GAAG,IAAI,EAAE,UAAU,EAAE,IAAI;IAClE,WAAW,EAAE,OAAO,EAAE,eAAe,EAAE,EAAE,EAAE,kBAAkB,EAAE,EAAE,EAAW,CAAC;AAU/E,SAAS,cAAc,CAAC,IAAI,GAAG,uBAAuB,IAAW,MAAM,IAAI,gBAAgB,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;AACpG,SAAS,aAAa,CAAC,KAAc,EAAE,IAAc;IACnD,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;WAC1D,CAAC,CA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workspaceAudioExportOptionsSchema: z.ZodObject<{
13
13
  format: z.ZodEnum<{
14
- mp3: "mp3";
15
- ogg: "ogg";
16
- opus: "opus";
17
14
  wav: "wav";
15
+ opus: "opus";
16
+ ogg: "ogg";
17
+ mp3: "mp3";
18
18
  }>;
19
19
  bitrate: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
20
20
  sampleRate: z.ZodOptional<z.ZodCoercedNumber<unknown>>;
@@ -0,0 +1,22 @@
1
+ import { type AudioDynamicProgram } from './audio-dynamic-document.js';
2
+ export type AudioHybridFiles = Readonly<Record<string, Uint8Array | readonly number[]>>;
3
+ /** Only canonical platform waveforms are accepted; no unbounded compressed-audio decoder is invoked. */
4
+ export declare function readAudioHybridSample(bytes: Uint8Array): Float32Array<ArrayBuffer>;
5
+ /** State changes stop and restart a declared finite window; they are not continuous modulation. */
6
+ export declare function createAudioHybridPlayer(context: AudioContext, programValue: AudioDynamicProgram, files: AudioHybridFiles): {
7
+ prepare: () => Promise<void>;
8
+ play: (requestedState?: string) => Promise<{
9
+ stop: () => void;
10
+ ended: Promise<void>;
11
+ }>;
12
+ stop: () => void;
13
+ setState: (next: string) => Promise<{
14
+ stop: () => void;
15
+ ended: Promise<void>;
16
+ } | undefined>;
17
+ dispose: () => void;
18
+ readonly state: string;
19
+ readonly activeCount: number;
20
+ };
21
+ export declare function renderAudioDynamicProgram(programValue: AudioDynamicProgram, files: AudioHybridFiles, stateId?: string, OfflineConstructor?: typeof OfflineAudioContext): Promise<AudioBuffer>;
22
+ //# sourceMappingURL=audio-hybrid-player.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"audio-hybrid-player.d.ts","sourceRoot":"","sources":["../../../src/cloud-workspace/runtime/audio-hybrid-player.ts"],"names":[],"mappings":"AAIA,OAAO,EACmB,KAAK,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAExF,MAAM,MAAM,gBAAgB,GAAG,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,UAAU,GAAG,SAAS,MAAM,EAAE,CAAC,CAAC,CAAC;AAmBxF,wGAAwG;AACxG,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,UAAU,GAAG,YAAY,CAAC,WAAW,CAAC,CAclF;AA8KD,mGAAmG;AACnG,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,mBAAmB,EAAE,KAAK,EAAE,gBAAgB;;;;;;;qBAsD9F,MAAM;;;;;;;EAOhC;AAED,wBAAsB,yBAAyB,CAAC,YAAY,EAAE,mBAAmB,EAAE,KAAK,EAAE,gBAAgB,EACxG,OAAO,CAAC,EAAE,MAAM,EAAE,kBAAkB,GAAE,OAAO,mBAAoD,GAAG,OAAO,CAAC,WAAW,CAAC,CAczH"}
@@ -0,0 +1,456 @@
1
+ import { audioSha256 } from './audio-document.js';
2
+ import { AudioRenderError, buildAudioGraph } from './audio-synthesizer.js';
3
+ import { buildScoreGraph, soundPcmMetrics } from './score-synthesizer.js';
4
+ import { AUDIO_DYNAMIC_LIMITS, validateAudioDynamicProgram } from './audio-dynamic-document.js';
5
+ function hybridFail(code = 'invalid_audio_program') { throw new AudioRenderError(code); }
6
+ function hybridFinite(value, min, max) {
7
+ if (!Number.isFinite(value) || value < min || value > max)
8
+ hybridFail();
9
+ return value;
10
+ }
11
+ function hybridBytes(files, ref) {
12
+ if (!Object.prototype.hasOwnProperty.call(files, ref.path))
13
+ hybridFail('audio_dependency_missing');
14
+ const value = files[ref.path];
15
+ if (!(value instanceof Uint8Array) && (!Array.isArray(value) || value.some(n => !Number.isInteger(n) || n < 0 || n > 255)))
16
+ hybridFail('audio_dependency_mismatch');
17
+ if (value.length !== ref.size)
18
+ hybridFail('audio_dependency_mismatch');
19
+ const bytes = new Uint8Array(value);
20
+ if (audioSha256(bytes) !== ref.contentHash)
21
+ hybridFail('audio_dependency_mismatch');
22
+ return bytes;
23
+ }
24
+ /** Only canonical platform waveforms are accepted; no unbounded compressed-audio decoder is invoked. */
25
+ export function readAudioHybridSample(bytes) {
26
+ if (bytes.length < 46 || bytes.length > AUDIO_DYNAMIC_LIMITS.sampleBytes)
27
+ hybridFail('unsupported_audio_sample_format');
28
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
29
+ const word = (offset, text) => [...text].every((letter, index) => view.getUint8(offset + index) === letter.charCodeAt(0));
30
+ if (!word(0, 'RIFF') || !word(8, 'WAVE') || !word(12, 'fmt ') || !word(36, 'data')
31
+ || view.getUint32(4, true) !== bytes.length - 8 || view.getUint32(16, true) !== 16
32
+ || view.getUint16(20, true) !== 1 || view.getUint16(22, true) !== 1 || view.getUint32(24, true) !== 44100
33
+ || view.getUint32(28, true) !== 88200 || view.getUint16(32, true) !== 2 || view.getUint16(34, true) !== 16
34
+ || view.getUint32(40, true) !== bytes.length - 44 || (bytes.length - 44) % 2)
35
+ hybridFail('unsupported_audio_sample_format');
36
+ const frames = (bytes.length - 44) / 2;
37
+ if (frames > 88200)
38
+ hybridFail('audio_program_budget_exceeded');
39
+ const samples = new Float32Array(frames);
40
+ for (let index = 0; index < frames; index++)
41
+ samples[index] = view.getInt16(44 + index * 2, true) / 32768;
42
+ return samples;
43
+ }
44
+ // Full source/provenance schemas run at compilation. These independent allocation guards also run in delivered modules.
45
+ function hybridSource(bytes) {
46
+ if (bytes.length > 65536)
47
+ hybridFail('audio_program_budget_exceeded');
48
+ let document;
49
+ try {
50
+ document = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
51
+ }
52
+ catch {
53
+ return hybridFail();
54
+ }
55
+ if (!document?.content || document.formatVersion !== 1 || document.engine?.version !== '1.0.0')
56
+ hybridFail();
57
+ hybridFinite(document.content.masterGain, 0, 1);
58
+ if (document.format === 'playcraft.audio') {
59
+ const content = document.content;
60
+ if (document.engine.id !== 'playcraft-webaudio-sfx' || content.kind !== 'synth-sfx'
61
+ || !Array.isArray(content.voices) || content.voices.length < 1 || content.voices.length > 4
62
+ || !Array.isArray(content.automation) || content.automation.length > 8)
63
+ hybridFail();
64
+ hybridFinite(content.durationSeconds, 0.05, 10);
65
+ for (const voice of content.voices) {
66
+ hybridFinite(voice.startSeconds, 0, 10);
67
+ hybridFinite(voice.durationSeconds, 0.001, 10);
68
+ hybridFinite(voice.gain, 0, 1);
69
+ if (voice.startSeconds + voice.durationSeconds > content.durationSeconds + 1e-9 || !voice.envelope)
70
+ hybridFail();
71
+ for (const key of ['attackSeconds', 'decaySeconds', 'releaseSeconds'])
72
+ hybridFinite(voice.envelope[key], 0, 10);
73
+ hybridFinite(voice.envelope.sustainLevel, 0, 1);
74
+ if (voice.source?.kind === 'oscillator') {
75
+ hybridFinite(voice.source.frequencyHz, 20, 16000);
76
+ if (!['sine', 'triangle', 'square', 'sawtooth', 'custom'].includes(voice.source.waveform))
77
+ hybridFail();
78
+ if (voice.source.waveform === 'custom') {
79
+ if (!Array.isArray(voice.source.harmonics) || !voice.source.harmonics.length || voice.source.harmonics.length > 8)
80
+ hybridFail();
81
+ for (const harmonic of voice.source.harmonics) {
82
+ if (!Number.isInteger(harmonic.ratio))
83
+ hybridFail();
84
+ hybridFinite(harmonic.ratio, 1, 16);
85
+ hybridFinite(harmonic.amplitude, 0, 1);
86
+ hybridFinite(harmonic.phaseRadians, -Math.PI, Math.PI);
87
+ }
88
+ }
89
+ }
90
+ else if (voice.source?.kind !== 'noise' || !['white', 'pink', 'brown'].includes(voice.source.color))
91
+ hybridFail();
92
+ if (voice.filter) {
93
+ hybridFinite(voice.filter.cutoffHz, 40, 16000);
94
+ hybridFinite(voice.filter.resonance, 0.1, 12);
95
+ }
96
+ }
97
+ for (const curve of content.automation) {
98
+ if (!Array.isArray(curve.points) || curve.points.length < 2 || curve.points.length > 32
99
+ || !['linear', 'step'].includes(curve.interpolation) || typeof curve.target !== 'string')
100
+ hybridFail();
101
+ for (const point of curve.points) {
102
+ hybridFinite(point.timeSeconds, 0, 10);
103
+ hybridFinite(point.value, 0, 16000);
104
+ }
105
+ }
106
+ }
107
+ else if (document.format === 'playcraft.score') {
108
+ const content = document.content;
109
+ if (document.engine.id !== 'playcraft-webaudio-score' || content.kind !== 'score'
110
+ || !Array.isArray(content.tracks) || !content.tracks.length || content.tracks.length > 8)
111
+ hybridFail();
112
+ hybridFinite(content.tempoBpm, 40, 240);
113
+ hybridFinite(content.lengthBeats, 1, 256);
114
+ let notes = 0;
115
+ for (const track of content.tracks) {
116
+ if (!Array.isArray(track.notes) || !Array.isArray(track.automation) || track.automation.length > 1)
117
+ hybridFail();
118
+ notes += track.notes.length;
119
+ for (const curve of track.automation)
120
+ if (!Array.isArray(curve.points) || curve.points.length > 32)
121
+ hybridFail();
122
+ }
123
+ if (!notes || notes > 512 || content.lengthBeats * 60 / content.tempoBpm > 60)
124
+ hybridFail('audio_program_budget_exceeded');
125
+ }
126
+ else
127
+ hybridFail();
128
+ return document;
129
+ }
130
+ function hybridLayer(asset, settings) {
131
+ if (asset.kind === 'sample') {
132
+ if (settings.rangeBeats)
133
+ hybridFail('invalid_score_selection');
134
+ return { settings, asset, duration: asset.samples.length / 44100 / (2 ** (settings.pitchSemitones / 12)), voices: 1, nodes: 4, noiseFrames: 0 };
135
+ }
136
+ const document = JSON.parse(JSON.stringify(asset.document));
137
+ let duration, voices, nodes, noiseFrames = 0;
138
+ if (document.format === 'playcraft.audio') {
139
+ if (settings.rangeBeats)
140
+ hybridFail('invalid_score_selection');
141
+ const ratio = 2 ** (settings.pitchSemitones / 12);
142
+ for (const voice of document.content.voices) {
143
+ if (voice.source.kind === 'noise') {
144
+ if (settings.pitchSemitones)
145
+ hybridFail('unsupported_audio_modulation');
146
+ noiseFrames += Math.ceil(voice.durationSeconds * 44100);
147
+ }
148
+ else {
149
+ voice.source.frequencyHz = hybridFinite(voice.source.frequencyHz * ratio, 20, 16000);
150
+ if (voice.source.waveform === 'custom' && Math.max(...voice.source.harmonics.map(item => item.ratio)) * voice.source.frequencyHz >= 22050)
151
+ hybridFail('unsupported_audio_modulation');
152
+ }
153
+ }
154
+ for (const curve of document.content.automation)
155
+ if (curve.target.endsWith('.frequencyHz')) {
156
+ for (const point of curve.points)
157
+ point.value = hybridFinite(point.value * ratio, 20, 16000);
158
+ }
159
+ for (const voice of document.content.voices)
160
+ if (voice.source.kind === 'oscillator' && voice.source.waveform === 'custom') {
161
+ const curve = document.content.automation.find(curve => curve.target === `voices.${voice.id}.frequencyHz`);
162
+ const frequency = Math.max(voice.source.frequencyHz, ...(curve?.points.map(point => point.value) ?? []));
163
+ if (frequency * Math.max(...voice.source.harmonics.map(item => item.ratio)) >= 22050)
164
+ hybridFail('unsupported_audio_modulation');
165
+ }
166
+ duration = document.content.durationSeconds;
167
+ voices = document.content.voices.length;
168
+ nodes = 4 + voices * 7;
169
+ }
170
+ else {
171
+ const content = document.content, range = settings.rangeBeats ?? (settings.loop
172
+ ? { start: content.loop.startBeat, end: content.loop.endBeat } : { start: 0, end: content.lengthBeats });
173
+ if (range.start < 0 || range.end > content.lengthBeats || range.end <= range.start)
174
+ hybridFail('invalid_score_selection');
175
+ duration = (range.end - range.start) * 60 / content.tempoBpm;
176
+ const solo = content.tracks.some(track => track.solo && !track.muted), events = [];
177
+ let noteCount = 0;
178
+ for (const track of content.tracks) {
179
+ for (const note of track.notes)
180
+ note.pitch = hybridFinite(note.pitch + settings.pitchSemitones, 0, 127);
181
+ if (track.muted || solo && !track.solo)
182
+ continue;
183
+ for (const note of track.notes)
184
+ if (note.velocity > 0 && note.startBeat < range.end && note.startBeat + note.durationBeats > range.start) {
185
+ noteCount++;
186
+ events.push({ at: Math.max(range.start, note.startBeat), delta: 1 }, { at: Math.min(range.end, note.startBeat + note.durationBeats), delta: -1 });
187
+ if (track.instrument === 'drums' && note.pitch >= 45)
188
+ noiseFrames += Math.ceil(Math.min(note.durationBeats * 60 / content.tempoBpm, note.pitch >= 66 ? 0.045 : 0.12) * 44100);
189
+ }
190
+ }
191
+ let active = 0;
192
+ voices = 0;
193
+ for (const event of events.sort((a, b) => a.at - b.at || a.delta - b.delta)) {
194
+ active += event.delta;
195
+ voices = Math.max(voices, active);
196
+ }
197
+ nodes = 4 + content.tracks.length * 2 + noteCount * 4;
198
+ }
199
+ if (duration <= 0 || !Number.isFinite(duration) || settings.loop && duration < 0.05)
200
+ hybridFail('invalid_audio_program');
201
+ return { settings, asset: { kind: 'synth', document }, duration, voices, nodes, noiseFrames };
202
+ }
203
+ function prepareHybrid(programValue, files) {
204
+ const program = validateAudioDynamicProgram(programValue), assets = new Map();
205
+ const dependencies = program.assets.flatMap(asset => asset.kind === 'synth' ? [asset.source, asset.manifest] : [asset.file]);
206
+ if (dependencies.reduce((n, ref) => n + ref.size, 0) > AUDIO_DYNAMIC_LIMITS.inputBytes
207
+ || Object.keys(files).some(path => !dependencies.some(ref => ref.path === path)))
208
+ hybridFail('audio_program_budget_exceeded');
209
+ let sampleFrames = 0;
210
+ for (const asset of program.assets) {
211
+ if (asset.kind === 'synth') {
212
+ hybridBytes(files, asset.manifest);
213
+ const document = hybridSource(hybridBytes(files, asset.source));
214
+ if ((document.format === 'playcraft.score') !== asset.source.path.endsWith('.pcscore.json'))
215
+ hybridFail('audio_dependency_mismatch');
216
+ assets.set(asset.id, { kind: 'synth', document });
217
+ }
218
+ else {
219
+ const samples = readAudioHybridSample(hybridBytes(files, asset.file));
220
+ sampleFrames += samples.length;
221
+ assets.set(asset.id, { kind: 'sample', samples });
222
+ }
223
+ }
224
+ if (sampleFrames > AUDIO_DYNAMIC_LIMITS.totalSampleFrames)
225
+ hybridFail('audio_program_budget_exceeded');
226
+ const states = program.states.map(state => {
227
+ const layers = state.layers.map(layer => hybridLayer(assets.get(layer.assetId), layer));
228
+ const voices = layers.reduce((sum, layer) => sum + layer.voices, 0);
229
+ let nodes = 1, noiseFrames = 0;
230
+ for (const layer of layers) {
231
+ const repetitions = layer.settings.loop ? Math.ceil(state.durationSeconds / layer.duration) : 1;
232
+ nodes += repetitions * layer.nodes;
233
+ noiseFrames += repetitions * layer.noiseFrames;
234
+ }
235
+ if (voices > 32 || nodes > AUDIO_DYNAMIC_LIMITS.graphNodes || noiseFrames > AUDIO_DYNAMIC_LIMITS.noiseFrames)
236
+ hybridFail('audio_program_budget_exceeded');
237
+ return { id: state.id, duration: state.durationSeconds, voices, layers };
238
+ });
239
+ return { program, states };
240
+ }
241
+ function buildHybridLayer(context, layer, destination, start, remaining, sampleBuffers) {
242
+ const nodes = [], inner = [];
243
+ let source, disposed = false;
244
+ const dispose = () => {
245
+ if (disposed)
246
+ return;
247
+ disposed = true;
248
+ for (const graph of inner)
249
+ graph.dispose();
250
+ if (source) {
251
+ try {
252
+ source.stop(context.currentTime);
253
+ }
254
+ catch { /* Already ended. */ }
255
+ }
256
+ for (const node of nodes) {
257
+ try {
258
+ node.disconnect();
259
+ }
260
+ catch { /* Already disconnected. */ }
261
+ }
262
+ };
263
+ try {
264
+ const gain = context.createGain();
265
+ nodes.push(gain);
266
+ gain.gain.setValueAtTime(layer.settings.gain, start);
267
+ gain.connect(destination);
268
+ let target = gain;
269
+ if (layer.settings.lowpassHz !== null) {
270
+ const filter = context.createBiquadFilter();
271
+ nodes.push(filter);
272
+ filter.type = 'lowpass';
273
+ filter.Q.setValueAtTime(Math.SQRT1_2, start);
274
+ filter.frequency.setValueAtTime(layer.settings.lowpassHz, start);
275
+ filter.connect(gain);
276
+ target = filter;
277
+ }
278
+ const duration = Math.min(layer.duration, remaining);
279
+ if (layer.asset.kind === 'sample') {
280
+ source = context.createBufferSource();
281
+ nodes.push(source);
282
+ let buffer = sampleBuffers.get(layer.asset.samples);
283
+ if (!buffer) {
284
+ buffer = context.createBuffer(1, layer.asset.samples.length, 44100);
285
+ buffer.getChannelData(0).set(layer.asset.samples);
286
+ sampleBuffers.set(layer.asset.samples, buffer);
287
+ }
288
+ source.buffer = buffer;
289
+ source.playbackRate.setValueAtTime(2 ** (layer.settings.pitchSemitones / 12), start);
290
+ source.connect(target);
291
+ source.start(start);
292
+ source.stop(start + duration);
293
+ }
294
+ else {
295
+ const document = layer.asset.document;
296
+ inner.push(document.format === 'playcraft.score' ? buildScoreGraph(context, document, target, start, { loop: layer.settings.loop, selection: { trackIds: [], noteIds: [], rangeBeats: layer.settings.rangeBeats } })
297
+ : buildAudioGraph(context, document, target, start));
298
+ }
299
+ return { nodes: [...nodes, ...inner.flatMap(graph => graph.nodes)], durationSeconds: duration, dispose };
300
+ }
301
+ catch (error) {
302
+ dispose();
303
+ throw error;
304
+ }
305
+ }
306
+ /** State changes stop and restart a declared finite window; they are not continuous modulation. */
307
+ export function createAudioHybridPlayer(context, programValue, files) {
308
+ const prepared = prepareHybrid(programValue, files), owned = new Set();
309
+ let stateId = prepared.program.initialState, disposed = false, generation = 0, starting = false;
310
+ const host = globalThis;
311
+ const pool = host[Symbol.for('playcraft.audio.player.v1.0.0')] ??= { instances: new Set(), cache: new Map(), pending: new Map() };
312
+ const stop = () => { generation++; for (const item of [...owned])
313
+ item.stop(); };
314
+ const play = async (requestedState = stateId) => {
315
+ if (disposed || context.state === 'closed')
316
+ hybridFail('audio_player_disposed');
317
+ if (starting)
318
+ hybridFail('audio_budget_exceeded');
319
+ const state = prepared.states.find(state => state.id === requestedState);
320
+ if (!state)
321
+ hybridFail('invalid_audio_state');
322
+ if (pool.instances.size >= 8 || [...pool.instances].reduce((n, item) => n + item.voices, 0) + state.voices > 32)
323
+ hybridFail('audio_voice_budget_exceeded');
324
+ const currentGeneration = generation;
325
+ let stopped = false, timer, master;
326
+ const sampleBuffers = new Map();
327
+ const scheduled = [];
328
+ let resolveEnded, rejectEnded;
329
+ const ended = new Promise((resolve, reject) => { resolveEnded = resolve; rejectEnded = reject; });
330
+ void ended.catch(() => undefined);
331
+ const cleanup = () => {
332
+ if (stopped)
333
+ return;
334
+ stopped = true;
335
+ if (timer)
336
+ clearInterval(timer);
337
+ for (const item of scheduled.splice(0))
338
+ item.graph.dispose();
339
+ sampleBuffers.clear();
340
+ master?.disconnect();
341
+ pool.instances.delete(instance);
342
+ owned.delete(instance);
343
+ resolveEnded();
344
+ };
345
+ const instance = { voices: state.voices, stop: cleanup };
346
+ pool.instances.add(instance);
347
+ owned.add(instance);
348
+ starting = true;
349
+ try {
350
+ if (context.state === 'suspended')
351
+ await context.resume();
352
+ if (stopped || disposed || currentGeneration !== generation)
353
+ hybridFail('audio_playback_cancelled');
354
+ const start = context.currentTime + 0.01, end = start + state.duration;
355
+ master = context.createGain();
356
+ master.gain.setValueAtTime(prepared.program.masterGain, start);
357
+ master.gain.setValueAtTime(0, end);
358
+ master.connect(context.destination);
359
+ const cursors = state.layers.map(layer => ({ layer, next: start, count: 0 }));
360
+ const schedule = (cursor) => {
361
+ const graph = buildHybridLayer(context, cursor.layer, master, cursor.next, end - cursor.next, sampleBuffers);
362
+ const graphEnd = Math.min(end, cursor.next + cursor.layer.duration);
363
+ cursor.next = graphEnd;
364
+ cursor.count++;
365
+ scheduled.push({ graph, end: graphEnd });
366
+ };
367
+ for (const cursor of cursors)
368
+ schedule(cursor);
369
+ const tick = () => {
370
+ if (stopped || context.state === 'suspended')
371
+ return;
372
+ if (context.state === 'closed') {
373
+ cleanup();
374
+ return;
375
+ }
376
+ for (let i = scheduled.length - 1; i >= 0; i--)
377
+ if (scheduled[i].end <= context.currentTime)
378
+ scheduled.splice(i, 1)[0].graph.dispose();
379
+ if (context.currentTime >= end) {
380
+ cleanup();
381
+ return;
382
+ }
383
+ try {
384
+ for (const cursor of cursors)
385
+ if (cursor.layer.settings.loop && cursor.next < end - 1e-9
386
+ && cursor.next <= context.currentTime + Math.min(0.1, cursor.layer.duration * 0.8)) {
387
+ if (cursor.next < context.currentTime)
388
+ hybridFail('audio_scheduler_underrun');
389
+ schedule(cursor);
390
+ }
391
+ }
392
+ catch (error) {
393
+ rejectEnded(error);
394
+ cleanup();
395
+ }
396
+ };
397
+ tick();
398
+ if (!stopped)
399
+ timer = setInterval(tick, 10);
400
+ stateId = requestedState;
401
+ return { stop: cleanup, ended };
402
+ }
403
+ catch (error) {
404
+ cleanup();
405
+ throw error;
406
+ }
407
+ finally {
408
+ starting = false;
409
+ }
410
+ };
411
+ return { prepare: async () => { if (disposed)
412
+ hybridFail('audio_player_disposed'); }, play, stop,
413
+ setState: async (next) => {
414
+ if (disposed)
415
+ hybridFail('audio_player_disposed');
416
+ if (!prepared.states.some(state => state.id === next))
417
+ hybridFail('invalid_audio_state');
418
+ // A suspended start is canceled without queueing another resume; the next explicit play uses the latest state.
419
+ const restart = owned.size > 0;
420
+ stop();
421
+ stateId = next;
422
+ return restart && !starting ? play(next) : undefined;
423
+ },
424
+ dispose: () => { disposed = true; stop(); prepared.states.length = 0; }, get state() { return stateId; }, get activeCount() { return owned.size; } };
425
+ }
426
+ export async function renderAudioDynamicProgram(programValue, files, stateId, OfflineConstructor = globalThis.OfflineAudioContext) {
427
+ const prepared = prepareHybrid(programValue, files), state = prepared.states.find(state => state.id === (stateId ?? prepared.program.initialState));
428
+ if (!state)
429
+ hybridFail('invalid_audio_state');
430
+ if (!OfflineConstructor)
431
+ hybridFail('engine_unavailable');
432
+ const context = new OfflineConstructor(1, Math.ceil(state.duration * 44100), 44100), graphs = [];
433
+ const sampleBuffers = new Map();
434
+ const master = context.createGain();
435
+ master.gain.setValueAtTime(prepared.program.masterGain, 0);
436
+ master.connect(context.destination);
437
+ try {
438
+ for (const layer of state.layers)
439
+ for (let start = 0; start < state.duration - 1e-9; start += layer.duration) {
440
+ graphs.push(buildHybridLayer(context, layer, master, start, state.duration - start, sampleBuffers));
441
+ if (!layer.settings.loop)
442
+ break;
443
+ }
444
+ const buffer = await context.startRendering(), metrics = soundPcmMetrics(buffer);
445
+ if (metrics.peak > 0.98)
446
+ throw new AudioRenderError('render_peak_exceeded', metrics);
447
+ return buffer;
448
+ }
449
+ finally {
450
+ for (const graph of graphs)
451
+ graph.dispose();
452
+ sampleBuffers.clear();
453
+ master.disconnect();
454
+ }
455
+ }
456
+ //# sourceMappingURL=audio-hybrid-player.js.map