# Savoy MPC public API and integration

MPC is part of the existing Savoy Audio CDN, alongside Audio, WAM, STEM and Mobile.
Canonical source: `shared/audio/mpc/`. Current release: **1.0.1**.

Base URL: `https://cdn.svysnds.com/mpc/v1.0.1/`.
Use a pinned URL in production. `/mpc/v1/` is the mutable major alias.
Classic script: `/mpc/v1.0.1/savoy-mpc.js`; `await SavoyMpc.load('metadata')`
returns an ESM namespace. No audio or ZIP runtime loads until explicitly requested.

## Capability entry points

| Entry relative to base | Use |
|---|---|
| `index.js` | Existing broad API plus public MpcWamPlayback, discovery and optional ZIP loader |
| `project.js` | Open/attach projects, source adaptation, multi-project discovery and parser injection |
| `metadata.js` | Read-only production metadata, graph/query views and analyzed chord candidates |
| `midi.js` | Piano roll projection, MIDI export/planning and single-timeline transport |
| `audio.js` | Sample/program audition, approximate drum/sequence/pad rendering, bundles, WAM playback |
| `sampler.js` | Convert/load observed MPC programs into the existing Sampler WAM |
| `editing.js` | Experimental non-destructive rename/repackage operations |
| `wam.js` | Optional provider-driven WAM runtime/transactional instrument adapter |
| `discovery.js` | DOM-free file/folder/archive project discovery |
| `dependencies.js` | Optional browser `loadZipLibrary()`; Node hosts inject a compatible constructor |
| `browser/project-opener.js` | Explicit browser-only `<mpc-project-opener>` UI; requires DOM/custom elements |

`index.js` is DOM-free on import. Browser operations still require their facilities
when called. Node XML parsing needs `setXmlDocumentParser(parser)`; browser XML
uses DOMParser. The parser hook is module-scoped, so configure it before concurrent
work. Do not import the browser component in a Node/SSR entry.

## Opening projects and discovery

```js
import {discoverMpcProjects,loadZipLibrary,productionMetadataFor}
  from 'https://cdn.svysnds.com/mpc/v1.0.1/index.js';
const zipReader = await loadZipLibrary(); // explicit; browser only
const found = await discoverMpcProjects(selectedFiles, {zipReader});
// Show found.projects and let the user choose; never silently choose a project.
const session = await found.projects[0].open(); // example after selection
const metadata = await productionMetadataFor(session);
```

- `loadProjectSource(input,{zipReader?,archiveLimits?}) -> Promise<source>` accepts
  File/Blob or selected File collection. The older source adapter chooses the
  shallowest XPJ when several exist; use discovery for user-facing multi-project input.
- `discoverMpcProjects(input,{zipReader?,progress?}) -> Promise<{projects,warnings}>`.
  Project choices expose `{id,name,origin,path,companionCount,match,getSource(),open()}`.
  Matches are `matched`, `unmatched` or `ambiguous`; do not turn ambiguity into certainty.
- `openProject(input,options?) -> Promise<session>` adapts a source then parses it.
- `openProjectFromSource(source) -> Promise<session>` parses a previously selected source.
- `attachFiles(session,files)` and `attachFilesWithCompanions(session,files)` update
  the selected input set; the latter reparses companion-dependent interpretation.
- Sources contain XPJ plus lazy `{path,filename,bytes,readBlob()}` entries and an
  audio index. Sessions contain `{source,project,model,relationships,samples}`.
- `createAudioIndex(entries)`, `resolveSample(reference,source)`,
  `resolveProjectSamples(project,source)`, `audioBlob(entry)` retain existing semantics.
  Missing from selected inputs is not proof of absence from every external drive.

ZIP reader is injected; `loadZipLibrary()` reuses the existing WAM MPC sampler's
JSZip asset and loader on this CDN. No second ZIP distribution is added. Source
imports reject unsafe/ambiguous paths and over-budget declared uncompressed sizes
before entry inflation. Default source limits: 20,000 entries, 1 GiB declared total,
100 MiB XPJ. `archiveLimits` can set positive maxEntries/maxUncompressedBytes for
loadProjectSource/openProject. Discovery retains 50,000 entries, 500 projects,
maximum nested depth 2 and a 2 GiB compressed archive check; each archive's declared
uncompressed budget is 1 GiB. These are limits, not a promise that a phone can
handle inputs near them. ZIP readers without size metadata cannot receive the
same pre-inflate guarantee; mobile memory acceptance remains necessary.

## Production metadata and graph queries

`productionMetadataFor(session) -> Promise<object>` returns a detached read-only
interpretation: version/source notes, project/global/master tempo evidence,
per-sequence saved tempo/length/meter, plugin and insert inventories, saved
performance settings, progression-file discovery and limitations/provenance.
Unknown values remain unknown/null. MPC 2.x SXQ MIDI header 120 BPM is not promoted
to an authoritative saved sequence tempo. Opaque plugin state is identified rather
than interpreted or dumped as a playable preset.

`analyzedMidiChordCandidates(model,{maxPerSequence=128})` returns analysis candidates,
not saved authoritative chord progressions. `buildProjectGraph(model)`
produces sequence/track/program/sample relationships. `sequenceTrackContext`,
`sampleUsesAtPath`, `sampleAssignmentsAtPath`, `sequencePianoRollData` are existing
read-only queries/projections. Source file objects are never changed by inspection.
See the supplied production metadata reference and machine export inventory:
[MPC_API.json](MPC_API.json).

## MIDI, rendering and sampler interoperability

- `encodeSequenceMidi(sequence,model=null,{trackId=null})`, `sequenceMidiFilename(...)`,
  `trackMidiFilename(...)`, `batchMidiExportPlan(model)` retain the supplied export
  API; inspect the actual option contract/source inventory before custom export logic.
- `planMidiPlayback(sequence,sequenceNode,{trackId=null})` requires resolved saved
  PPQN/BPM/length. Notes/timing and unsupported conditions are not fabricated.
- `new MpcMidiTransport({context,dispatch,onPosition?,onEnded?,...})` schedules one
  plan; `play(plan,{loop,startAtSeconds,startPositionSeconds})`, `replaceEvents(...)`,
  `stop()` own its transport. Session Grid's independent clip launcher remains an
  app-specific orchestration layer, not an extra promise of this transport.
- `programExportPlan`, `planDrumTrackRender`, `renderDrumTrackWav`,
  `planSequenceAudioRender`, `renderSequenceWav`, `planDrumPadSplits`,
  `renderDrumPadSplits`, `buildTrackBundle`, `planSequenceDrumBundle`,
  `buildSequenceDrumBundle` preserve the supplied dry rendering/export behavior.
- `audioLibraryFor(source)` / `createAudioLibrary(source)` cache lazy sample decode;
  `createInstrumentAudio(...)` and `liveProgramMix(...)` preserve observed program,
  pad and track mix semantics. Use original track IDs, not visual row positions.

Rendered audio is an approximation of supported MIDI/sample triggers. It does not
recreate proprietary MPC plugins, effects, envelopes, automation or all choke
behavior. MIDI export is Standard MIDI File, not a native SXQ write-back. Export
plans/manifests disclose unresolved/omitted tracks. No universal resampler,
time-stretcher or MPC hardware engine is implied.

Use `await samplerProgramFor(program,source)` or
`await loadSamplerProgram(node,audioContext,program,source,{onProgress})` from
`sampler.js` to feed the existing Savoy `mpc-sampler` WAM. Saved velocity ranges
starting at zero require note-on conversion to 1–127. The adapter discloses that
conversion in warnings, preserves original metadata, and reuses the existing
loader/normalizer/worklet. Missing/ambiguous samples or unresolved key tracking
are refused. Raw Inspector export manifests are not silently rewritten. The sampler's normalized worklet program and the
MPC project's full model serve different purposes; neither parser nor DSP engine
was replaced to force them into one schema. Generic playback of exported MIDI
can also use Savoy Audio's existing MIDI backend.

## WAM and lifecycle

```js
import {MpcWamPlayback} from 'https://cdn.svysnds.com/mpc/v1.0.1/audio.js';
import {createWamRuntime} from 'https://cdn.svysnds.com/mpc/v1.0.1/wam.js';
const playback = new MpcWamPlayback({wamRuntime:createWamRuntime(),onStatus:console.log});
// On a trusted user tap: await playback.play(session, selection, options);
// On project replacement: await playback.reset(); // retain warm context/manager
// On application teardown: await playback.destroy(); // close owned resources
```

Selection is the existing sequence/track graph selection, not an arbitrary ID:
use the proof apps and `buildProjectGraph`/`sequenceTrackContext`. Public controls
include `playing`, `busy`, `cacheStats`, `play`, `pause`, `stop`, `seek`,
`setTrackMixStates`, `changeInstrument`, `prepareInstrumentForEditing`,
`createInstrumentGui`, `invalidateSequence`, `followSelection`, `reset`, `destroy`.
The engine owns its created AudioContext/manager. `reset()` deliberately keeps
warm resources; `destroy()` is idempotent terminal cleanup. Do not call play after destroy.
Dispose GUI leases before replacing their owning instrument.

`createWamRuntime({registries=[],...urlOverrides})` supports existing override names
and registry providers. It uses the existing WAM host, SDK, catalog, Tone asset
and registry descriptors. No built-in instrument list is copied. `listInstruments()`
and `loadInstrumentCatalog()` expose the discovered list; initialize(context)
creates the host environment for that context. WAM initialization currently loads
Tone for the adapter's instrument path; inspection/MIDI export/sample-only rendering
never requires it. Existing non-sample lanes may substitute a compatible WAM synth;
that does not reproduce the saved MPC-native plugin preset.

## Editing and browser picker

`editableProjectSummary(session)` and
`exportEditedMpcProject(session,{projectName?,sequences?,programs?},{zipReader,...})`
retain non-destructive rename/repackage behavior. Export reparses and validates
links before returning `{blob,filename,report}`. It produces a new archive; never
write over an original project. Native MPC software/hardware acceptance remains
required; support for unknown layouts is deliberately conservative.

Import browser/project-opener.js only when using the UI. The picker exposes
`zipReader`, `open()`, `close()`, `scan(files)`, `select(project)` and emits composed
`mpc-projects-discovered` and `mpc-project-selected` events. It remains an optional
component; the core has no UI dependency. Close/remove it during app teardown.
Serve on HTTPS for audio/device features and preserve trusted Safari gestures.

[Review, known limits and proof apps](MPC_REVIEW.md).

[Deployed verification and test results](MPC_TEST_RESULTS.md).
