diff --git a/changelog/2026-11-20-octatrack-usb-audio-package.md b/changelog/2026-11-20-octatrack-usb-audio-package.md new file mode 100644 index 0000000000..71811f2d69 --- /dev/null +++ b/changelog/2026-11-20-octatrack-usb-audio-package.md @@ -0,0 +1,3 @@ +Octatrack base 0.7.12 installs USB Audio 0.3.0-experimental as one module. Existing sets restore their saved destination, layout and routing. Open PROJ > MODWERK > SETTINGS > USB AUDIO to choose the destination and layout. +Choose PRE LEVEL or POST LEVEL on the eight track stems in the 16- and 20-channel layouts. Main and Cue keep their own stereo pairs. +OUTBOX 8 sends your choice of source or silence on each of four stereo USB pairs. Map the matching physical outputs once in Elektron’s app. diff --git a/public/octatrack-modules/usb-audio-out-tracks-main-cue/0.3.0-experimental.mwrm b/public/octatrack-modules/usb-audio-out-tracks-main-cue/0.3.0-experimental.mwrm new file mode 100644 index 0000000000..5207362f97 Binary files /dev/null and b/public/octatrack-modules/usb-audio-out-tracks-main-cue/0.3.0-experimental.mwrm differ diff --git a/scripts/build-usb-audio-packages.py b/scripts/build-usb-audio-packages.py index 9a5bb7886b..7efaeaba31 100644 --- a/scripts/build-usb-audio-packages.py +++ b/scripts/build-usb-audio-packages.py @@ -19,7 +19,6 @@ SOURCE = ROOT / 'sdk/octabam/modules/usb-audio-out-tracks-main-cue/layouts' OUTPUT = ROOT / 'src/engine/assets/usb-audio-packages.json' REVISION = '7b2984c859732ae6c797ae49c7d61d250b1b6519' -VERSION = '0.2.0-experimental' LAYOUTS = [('tracks-main-cue', 0, 'TRACKS MAIN CUE', 20), ('tracks', 1, 'TRACKS', 16), ('tracks-post', 5, 'TRACKS POST', 16), ('main-cue', 3, 'MAIN CUE', 4), ('main', 4, 'MAIN', 2), ('master', 2, 'MASTER', 2)] @@ -113,7 +112,8 @@ def assemble(label, source, include='', post=False): midi['detours'] = [row for row in midi['detours'] if row['address'] != 0x4001e606] hooks = {key: audio[key] + midi[key] for key in audio} assert len(hooks['detours']) == 14 and len(hooks['refs']) == 4 and len(hooks['pokes']) == 1 - return dict(schema=1, version=VERSION, revision=json.loads((ROOT / 'sdk/catalog.json').read_text())['sourceRevision'], upstreamRevision=REVISION, sources=sources, common=common, layouts=layouts, hooks=hooks) + version = json.loads((SOURCE.parent / 'octamod.module.json').read_text())['version'] + return dict(schema=1, version=version, revision=json.loads((ROOT / 'sdk/catalog.json').read_text())['sourceRevision'], upstreamRevision=REVISION, sources=sources, common=common, layouts=layouts, hooks=hooks) if __name__ == '__main__': diff --git a/scripts/octatrack-module-packages.py b/scripts/octatrack-module-packages.py index 9294f8d002..23a6f80acc 100644 --- a/scripts/octatrack-module-packages.py +++ b/scripts/octatrack-module-packages.py @@ -14,6 +14,10 @@ APP = Path(__file__).resolve().parents[1] +def preparing_ports(): + return any(arg.partition('=')[0] == '--prepare-ports' for arg in sys.argv[1:]) + + def lag_guard(builder, check): """USB packages at an older version than the catalogue, by manifest index. @@ -103,7 +107,7 @@ def build_for_check(entry, *args, **kwargs): def run(builder): try: - if '--prepare-ports' in sys.argv[1:]: + if preparing_ports(): builder.main() elif '--check' in sys.argv[1:]: check_packages(builder) @@ -299,7 +303,7 @@ def reconstructed_build(entry, out, *args, **kwargs): os.chdir(APP) # Python's -X utf8 does not propagate to the builder's Python children. os.environ['PYTHONUTF8'] = '1' - if '--prepare-ports' in sys.argv[1:]: + if preparing_ports(): return run(builder) check = '--check' in sys.argv[1:] manifest, held, failed = lag_guard(builder, check) @@ -329,4 +333,24 @@ def reconstructed_build(entry, out, *args, **kwargs): if __name__ == '__main__': - main() + try: + main() + except SystemExit as result: + if result.code not in (None, 0): + raise + if preparing_ports() or {'--help', '-h'}.intersection(sys.argv[1:]): + sys.exit(0) + release_catalog = json.loads((APP / 'sdk/catalog.json').read_text()) + if any(row['id'] == 'usb-audio-out-tracks-main-cue' for row in release_catalog['modules']): + # The configurable USB function owns one package outside the ordinary + # effect list. Rebuild its bytes and binding with the same release. + from argparse import ArgumentParser + options = ArgumentParser(add_help=False) + options.add_argument('--check', action='store_true') + options.add_argument('--stock', type=Path) + options.add_argument('--upstream', type=Path, default=Path.home() / '.cache/modwerk-upstream/elekloader') + args, _ = options.parse_known_args() + spec = importlib.util.spec_from_file_location('usb_audio_release', APP / 'scripts/octatrack-usb-audio-release.py') + release = importlib.util.module_from_spec(spec) + spec.loader.exec_module(release) + release.generate(args.check, args.stock, args.upstream) diff --git a/scripts/octatrack-usb-audio-release.py b/scripts/octatrack-usb-audio-release.py new file mode 100644 index 0000000000..7e8d5c6e3b --- /dev/null +++ b/scripts/octatrack-usb-audio-release.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Build or verify the single USB Audio runtime package and its published manifest entry.""" +import argparse +import hashlib +import json +import shutil +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SDK = ROOT / 'sdk/machines/octatrack' +sys.path.insert(0, str(SDK / 'module-adapters')) +import usb_audio_package as audio + + +def generate(check, stock=None, upstream=None): + module = json.loads((ROOT / 'sdk/octatrack/modules' / audio.MODULE / 'octamod.module.json').read_text()) + manifest_path = ROOT / 'src/engine/assets/octatrack-module-packages.json' + manifest = json.loads(manifest_path.read_text()) + path = Path('octatrack-modules') / audio.MODULE / (module['version'] + '.mwrm') + output = ROOT / 'public' / path + if check and not shutil.which('m68k-elf-gcc') and stock is None: + data = output.read_bytes() + print('USB Audio compiler unavailable, checking the published bytes and metadata') + else: + data, _ = audio.build(None, release=True, stock=stock, upstream=upstream) + packages = audio.load('usb_audio_package_metadata', SDK / 'elekloader/module_packages.py') + entry = dict(name='USB Audio', version=module['version'], path=str(path.as_posix()), bytes=len(data), + sha256=hashlib.sha256(data).hexdigest(), **packages.capabilities(data), installPresets=True, + requiredBase=json.loads((SDK / 'base-binding.json').read_text())['identity']) + if check: + if manifest.get('usbAudio', {}).get('configurable') != entry or output.read_bytes() != data: + raise ValueError('Rebuild the configurable USB Audio release package and catalogue') + else: + output.parent.mkdir(parents=True, exist_ok=True) + output.write_bytes(data) + manifest.setdefault('usbAudio', {})['configurable'] = entry + manifest_path.write_text(json.dumps(manifest, indent=2) + '\n') + print('USB Audio', entry['version'], entry['sha256']) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--check', action='store_true') + parser.add_argument('--stock', type=Path) + parser.add_argument('--upstream', type=Path, default=Path.home() / '.cache/modwerk-upstream/elekloader') + args = parser.parse_args() + generate(args.check, args.stock, args.upstream) diff --git a/scripts/verify-octatrack-usb-audio-package.mjs b/scripts/verify-octatrack-usb-audio-package.mjs new file mode 100644 index 0000000000..977f97b417 --- /dev/null +++ b/scripts/verify-octatrack-usb-audio-package.mjs @@ -0,0 +1,253 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// USB Audio as a runtime package on a private Octatrack base in ot_emu (usb_audio_package.py, usb_function.c). +// +// python3 -B sdk/machines/octatrack/module-adapters/usb_audio_package.py -o /private/usb-audio.mwrm +// ot_emu --image BUILD/MAIN.raw --usb-host /tmp/ot-usb.sock --frame --ms 900000 & # the adapted ot_emu; --frame runs the producer +// node scripts/verify-octatrack-usb-audio-package.mjs /tmp/ot-usb.sock /private/usb-audio.mwrm +// +// On a base with USB MIDI alone: a trial of the package makes the base reconnect; the host then reads a configuration +// with AudioControl and AudioStreaming behind the base's own interfaces, the clock source answers its sample rate, +// alternate setting 1 opens the stream and EP3 IN sends packets of whole frames of the layout at the high-speed rate; +// alternate setting 0 closes it; a rollback takes the function out again and the configuration is the first one. +// With `setting`, on a development base (--dev) booted with a card (ot_emu --card): the panel opens PROJ > MODWERK > +// SETTINGS, open USB AUDIO and select OFF and, in the twenty-channel layout, MAIN + CUE ONLY; each choice is in the base's battery-RAM +// store, and the stream goes on under it with whole packets: of zeros under OFF, with silent track channels under +// MAIN + CUE ONLY. +// The emulated unit runs as the bench drives it, so the key presses and RAM reads between the bursts advance its +// producer while nothing polls EP3: the ring then runs past its 1024 frames and the counters show an overrun or +// two. The same control traffic with no setting change does it too (20 November 2026); a host polls all the time. +// Emulator evidence of the package's and the base's code only: no host driver, no audio content check, no hardware. +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { sha } from '../vendor/elekloader/kit/src/bytes.ts' +import { UploadSession } from '../src/engine/elekloader/upload-session.ts' +import { findVendorInterface, UsbVendorTransport } from '../src/engine/elekloader/upload-usb.ts' +import { diagnostics } from '../src/dev/octatrack-usb-lifecycle.ts' +import { Bench, device } from './usb-bench.mjs' +import registry from '../sdk/machines/octatrack/events.json' with { type: 'json' } + +const [socket, file, frame = '80', setting] = process.argv.slice(2) +if (!socket || !file || ![8, 16, 32, 64, 80].includes(Number(frame)) || (setting && setting !== 'setting')) throw new Error('Usage: verify-octatrack-usb-audio-package.mjs BENCH-SOCKET usb-audio.mwrm [FRAME-BYTES: 80 (default, 20 channels), 64 TRACKS, 32 OUTBOX, 16 MAIN CUE, 8 MASTER or MAIN] [setting]') +const AC = 4, AS = 5, CLOCK = 0x10, FRAME_BYTES = Number(frame) // a frame: 4 bytes a sample for each channel of the layout +const wait = ms => new Promise(resolve => setTimeout(resolve, ms)) +const bench = new Bench(socket) +await bench.ready() +const unit = device(bench) + +async function enumerate(speed = 'hs') { + await bench.command('speed ' + speed); await bench.command('reset'); await wait(300) + assert.equal((await bench.controlIn(0x80, 6, 0x0100, 0, 18))?.length, 18) + await bench.transaction(async () => { await bench.setup(0x00, 5, 1, 0, 0); await bench.command('in 0 64') }) + const header = await bench.controlIn(0x80, 6, 0x0200, 0, 9) + const cfg = await bench.controlIn(0x80, 6, 0x0200, 0, header.readUInt16LE(2)) + const other = await bench.controlIn(0x80, 6, 0x0700, 0, 512) + await bench.transaction(async () => { await bench.setup(0x00, 9, 1, 0, 0); await bench.command('in 0 64') }) + const interfaces = [] + for (let i = 0; i + 2 <= cfg.length && cfg[i] >= 2; i += cfg[i]) if (cfg[i + 1] === 4) interfaces.push({ interfaceNumber: cfg[i + 2], alternate: cfg[i + 3], alternates: [{ + interfaceClass: cfg[i + 5], interfaceSubclass: cfg[i + 6], interfaceProtocol: cfg[i + 7], endpoints: Array.from({ length: cfg[i + 4] }) }] }) + return { cfg, other, interfaces, total: header.readUInt16LE(2), count: header[4] } +} +const first = await enumerate(), index = findVendorInterface(first) +const transport = new UsbVendorTransport(unit, index, { pollMs: 5 }) +const identity = await transport.identify() +console.log(`base ${identity.base.slice(0, 16)}…: configuration ${first.total} bytes, ${first.count} interfaces`) +assert.equal(first.count, 4, 'a base with USB MIDI alone') +const usb = async () => { const reply = await bench.controlIn(0xc1, 41, 0, index, 8); return reply ? [...reply] : null } +assert.deepEqual(await usb(), [0, 0, 0, 0, 0, 0, 0, 0]) +const data = new Uint8Array(readFileSync(file)), pkg = { base: identity.base, data, sha256: sha(data) } + +const configurable = Buffer.from(data).readUInt16BE(66) === 7 + +async function stopping(step) { + for (const start = Date.now(); ; await wait(200)) { + try { return await step() } catch (error) { if (!['unsafe', 'needs-recovery'].includes(error.status?.result) || Date.now() - start > 5000) throw error } + } +} +let reconnectCount = 0 +async function settle(label, live, speed = 'hs') { + const expected = (reconnectCount + 1) & 255 + const seen = [] + let now + for (const start = Date.now(); Date.now() - start < 240000; await wait(20)) { + const s = await usb(), key = JSON.stringify(s?.slice(0, 5)) + if (seen.at(-1) !== key) { seen.push(key); console.log(` ${label}: USB FUNCTION ${key}`) } + if (s?.[3] !== expected) continue // a panel key can arrive before the UI tick handles it + if (s[0] === 3 && !now) now = await enumerate(speed) + if (s[0] === 0 && s[1] === live && s[2] === live) { + assert.ok(now, label + ': the unit went off the bus and came back') + reconnectCount = expected + return now + } + } + throw new Error(label + ': the reconnect did not settle') +} +const noData = (type, request, value, target) => bench.transaction(async () => { + await bench.setup(type, request, value, target, 0) + return (await bench.command('in 0 64'))[2] !== 'stall' +}) +const alternate = async () => (await bench.controlIn(0x81, 10, 0, AS, 1))?.[0] + +const session = await UploadSession.connect(transport, identity.base, { timeoutMs: 30000 }) +await session.stage(pkg); await session.activate(); await session.startTrial() +let now = await settle('trial', 1) +assert.equal(now.count, 6) +if (configurable) { + const bytes = Buffer.from(data), hook = registry.events.find(event => event.event === 'ot_settings').index + const record = 76 + 4*bytes.readUInt32BE(20) + (bytes.readUInt32BE(76 + 4*hook) & 0xffffff) + if (bytes.readUInt32BE(record) === 3) { + const expected = bytes.readUInt32BE(record + 20) + let initial + for (let i=0; i<100 && initial === undefined; ++i) { + initial = (await transport.settingPresets())?.get(0x8c3a257f) + if (initial === undefined) await wait(80) + } + assert.equal(initial, expected, 'the release base reports the installed set preset') + const records=[] + for (let at=0; at=2); records.push(now.cfg.subarray(at,at+now.cfg[at])) } + const stream = records.find(r=>r[0]===16 && r[1]===0x24 && r[2]===1) + assert.equal(stream[10], FRAME_BYTES/4, 'the USB descriptor matches the imported layout') + console.log(' migrated preset', expected.toString(16), 'channels', stream[10]) + } +} +assert.ok(now.total > first.total && now.other.length === now.total) +assert.equal(now.cfg.subarray(5, first.total).toString('hex'), first.cfg.subarray(5).toString('hex'), 'the base’s own part is unchanged') +const audio = now.interfaces.filter(i => i.interfaceNumber >= AC) +assert.deepEqual(audio.map(i => [i.interfaceNumber, i.alternate, i.alternates[0].interfaceClass, i.alternates[0].interfaceSubclass, i.alternates[0].endpoints.length]), + [[AC, 0, 1, 1, 0], [AS, 0, 1, 2, 0], [AS, 1, 1, 2, 1]], 'AudioControl, and AudioStreaming with its streaming alternate') +console.log(` configuration ${now.total} bytes, ${now.count} interfaces: AudioControl ${AC}, AudioStreaming ${AS}`) +assert.ok((await diagnostics(unit, index)).active, 'the trial is still open after the base’s own reconnect') + +// The clock source: 44.1 kHz, valid; its range has one entry. A control nobody implements stalls. +assert.equal((await bench.controlIn(0xa1, 1, 0x0100, CLOCK << 8 | AC, 4))?.toString('hex'), '44ac0000') +assert.equal((await bench.controlIn(0xa1, 1, 0x0200, CLOCK << 8 | AC, 1))?.toString('hex'), '01') +assert.equal((await bench.controlIn(0xa1, 2, 0x0100, CLOCK << 8 | AC, 14))?.subarray(0, 2).toString('hex'), '0100') +assert.equal(await bench.controlIn(0xa1, 1, 0x0300, CLOCK << 8 | AC, 1), null) +if (configurable) { + const setRate = rate => { + const payload = Buffer.alloc(4) + payload.writeUInt32LE(rate) + return bench.controlOut(0x21, 1, 0x0100, CLOCK << 8 | AC, payload) + } + assert.equal(await setRate(44100), true, 'fixed clock acknowledges its supported rate') + assert.equal(await setRate(48000), false, 'fixed clock stalls an unsupported rate') +} +assert.equal((await transport.identify()).base, identity.base) + +// dev.c: keys as the panel reports them (request 5), RAM read-only (15 and 16). +const dev = async (request, value, length) => { + const reply = await unit.controlTransferIn({ requestType: 'vendor', recipient: 'interface', request, value, index }, length) + assert.equal(reply.status, 'ok', 'a development base answers request ' + request) + return new Uint8Array(reply.data.buffer, reply.data.byteOffset, reply.data.byteLength) +} +const KEY = { UP: 0x33, DOWN: 0x20, RIGHT: 0x21, YES: 0x31, NO: 0x32, PROJ: 0x1c } +const press = async (...names) => { for (const name of names) { await dev(5, KEY[name] | 0x100, 1); await wait(120); await dev(5, KEY[name], 1); await wait(1200) } } +const STORE = 0x100f9000 // settings.c: 'MWS1', then eight entries of a label's hash and its choice +const kept = async () => { await dev(15, STORE >>> 16, 1); const m = Buffer.from(await dev(16, STORE & 0xffff, 68)); return m } +let hash = 2166136261 +for (const c of 'USB AUDIO') hash = Math.imul(hash ^ c.charCodeAt(0), 16777619) >>> 0 +const choice = async () => { const m = await kept(); if (m.readUInt32BE(0) !== 0x4d575331) return undefined + for (let i = 0; i < 8; ++i) if (m.readUInt32BE(4 + 8 * i) === hash) return m.readUInt32BE(8 + 8 * i) } +/** YES on the open page, then the kept choice once it is `want`: the emulated panel runs far below real time. */ +const take = async (want, label) => { + await press('YES') + for (const start = Date.now(); Date.now() - start < 60000; await wait(500)) if (await choice() === want) return + assert.equal(await choice(), want, label) +} +if (setting) { // the page is opened before the stream: it never holds the panel, and stays open under it + assert.equal(await choice(), undefined, 'nothing kept before the player chooses') + await press('PROJ', 'DOWN', 'DOWN', 'DOWN', 'DOWN', 'RIGHT', 'DOWN', 'DOWN', 'DOWN', 'DOWN', 'DOWN', 'YES', 'YES') // MODWERK, SETTINGS, USB AUDIO + if (configurable) await press('DOWN', 'DOWN', 'DOWN', 'YES') // OUTPUT MODE +} + +// The stream: alternate setting 1, then EP3 IN at the high-speed poll rate. +assert.equal(await alternate(), 0) +await bench.command('isohz 4000') +assert.ok(await noData(0x01, 11, 1, AS), 'SET_INTERFACE alternate 1') +assert.equal(await alternate(), 1) +const lengths = [] +let nonempty = 0 +for (let i = 0; i < 256 && nonempty < 16; ++i) { + const reply = await bench.command('in 3 1024') + assert.notEqual(reply[2], 'stall') + const packet = Buffer.from(reply[2] ?? '', 'hex') + lengths.push(packet.length) + if (!packet.length) continue + assert.ok(packet.length % FRAME_BYTES === 0 && [10, 11, 12].includes(packet.length / FRAME_BYTES), `a packet of ${packet.length} bytes is not 10 to 12 whole frames`) + ++nonempty +} +assert.equal(nonempty, 16, 'sixteen packets with audio frames; lengths ' + lengths.join(',')) +console.log(` stream: ${lengths.length} polls, 16 packets of ${[...new Set(lengths.filter(Boolean))].sort().join(' or ')} bytes`) +const first16 = async (label, bytes = FRAME_BYTES, sizes = [10, 11, 12]) => { + const packets = [] + for (let i = 0; i < 256 && packets.length < 16; ++i) { + const packet = Buffer.from((await bench.command('in 3 1024'))[2] ?? '', 'hex') + if (!packet.length) continue + assert.ok(packet.length % bytes === 0 && sizes.includes(packet.length / bytes), `${label}: a packet of ${packet.length} bytes`) + packets.push(packet) + } + assert.equal(packets.length, 16, label + ': sixteen packets') + return packets +} +if (setting) { + await press('DOWN') + assert.equal(await choice(), undefined, 'browsing leaves the stored choice untouched') + await take(1, 'selecting OFF stores it') + for (const packet of await first16('OFF')) assert.ok(packet.every(byte => byte === 0), 'OFF sends packets of zeros') + console.log(' setting: OFF kept in battery RAM; 16 whole packets of zeros') + if (FRAME_BYTES === 80) { + await press('DOWN') + await take(2, 'the twenty-channel layout offers MAIN + CUE ONLY') + for (const packet of await first16('MAIN + CUE ONLY')) for (let at = 0; at < packet.length; at += 80) + assert.ok(packet.subarray(at, at + 64).every(byte => byte === 0), 'MAIN + CUE ONLY: the sixteen track channels are silent') + console.log(' setting: MAIN + CUE ONLY kept; 16 whole packets with silent track channels') + } + await press('UP') + if (FRAME_BYTES === 80) await press('UP') + await take(0, 'select ALL CHANNELS') + await first16('ALL CHANNELS') + if (configurable) { + const openFormat = async (channels, speed) => { + const { cfg } = await settle('panel format', 1, speed) + const records = [] + for (let i = 0; i < cfg.length; i += cfg[i]) { assert.ok(cfg[i] >= 2); records.push(cfg.subarray(i, i + cfg[i])) } + assert.equal(records.find(r => r[0] === 16 && r[1] === 0x24 && r[2] === 1)[10], channels) + await bench.command('isohz ' + (speed === 'fs' ? 1000 : 4000)) + assert.ok(await noData(0x01, 11, 1, AS)) + await first16('panel format', channels * 4, speed === 'fs' ? [43,44,45] : [10,11,12]) + } + await press('NO', 'UP', 'YES', 'DOWN') + await take(0x80432120, 'POST LEVEL on 20 channels') + await first16('20 channels post') + await press('NO', 'UP', 'YES', 'DOWN', 'YES') + await openFormat(16, 'hs') + assert.equal(await choice(), 0x80432124, 'same eight post-level stems in the 16-channel layout') + await press('NO', 'UP', 'YES', 'DOWN', 'YES') + await openFormat(8, 'hs') + await press('NO', 'DOWN', 'DOWN', 'DOWN', 'DOWN', 'YES', 'UP') + await take(0x80432064, 'Outbox pair 1 set to OFF') + for (const packet of await first16('Outbox pair 1 off', 32)) { + for (let i = 0; i < packet.length; i += 32) assert.ok(packet.subarray(i,i+8).every(b => b === 0)) + } + await press('NO', 'UP', 'UP', 'UP', 'UP', 'YES', 'UP', 'YES') + await openFormat(2, 'fs') + console.log(' same package: 20 and 16 post, 8 routed Outbox channels, stereo at full speed') + } + await press('NO', 'NO') + console.log(' setting: back to ALL CHANNELS; the stream goes on') +} +const counters = await bench.controlIn(0xc0, 0x55, 0, 0, 60) +assert.equal(counters?.length, 60) +console.log(` counters: consumed ${counters.readUInt32BE(0)}, overruns ${counters.readUInt32BE(8)}, underruns ${counters.readUInt32BE(12)}`) +assert.ok(counters.readUInt32BE(0) > 0, 'frames were pulled from the ring') +assert.ok(await noData(0x01, 11, 0, AS), 'SET_INTERFACE alternate 0') +assert.equal(await alternate(), 0) +assert.ok((await diagnostics(unit, index)).active, 'the trial is still open after the stream') + +await stopping(() => session.holdTrial()); await stopping(() => session.rollback()) +now = await settle('rollback', 0) +assert.equal(now.count, 4) +assert.equal(now.cfg.toString('hex'), first.cfg.toString('hex')) +assert.equal(await bench.controlIn(0xa1, 1, 0x0100, CLOCK << 8 | AC, 4), null, 'no clock source without the module') +await session.leaveUploadMode() +console.log('USB Audio as a package in the emulator: it enumerates behind the base’s interfaces, answers its clock, streams packets of whole frames at high speed, closes, and a rollback takes it out.') +process.exit(0) diff --git a/sdk/approvals/usb-audio-out-tracks-main-cue-build-approval.json b/sdk/approvals/usb-audio-out-tracks-main-cue-build-approval.json index d68ce75cf8..6d4d0806d9 100644 --- a/sdk/approvals/usb-audio-out-tracks-main-cue-build-approval.json +++ b/sdk/approvals/usb-audio-out-tracks-main-cue-build-approval.json @@ -1,15 +1,14 @@ { "kind": "owner-approved-update", "id": "usb-audio-out-tracks-main-cue", - "version": "0.2.0-experimental", + "version": "0.3.0-experimental", "sourceSha256": "ef05f5f2f91a1402ccbdfaf80468b02677699b52c8c4796b8690a7f00f23858b", "approvedBy": "repeat98", - "approvedOn": "2026-10-08", + "approvedOn": "2026-11-20", "waived": [ - "current-build-hardware", "chip-worst-case-cycles", "complete-memory-bounds" ], - "ownerStatement": "ok let's push and release, I approve no hardware testing", - "reason": "Owner approved release of the reviewed experimental USB / Outbox configuration after software verification, without physical testing. Chip timing and complete hardware memory bounds remain unmeasured; source integrity, shared composition, packaging, provenance and documentation checks remain required. This approval covers only this version and exact native source." + "ownerStatement": "Approved the two resource exceptions for 0.3.0-experimental subject to a passing reconnect, Keep and physical power-cycle test.", + "reason": "Worst-case ColdFire cycles and the complete memory bound including stack and DMA are unmeasured. The owner approved these two measurement exceptions on this version and native source. Release requires the exact build to pass the Octatrack reconnect, Keep and physical power-cycle tests. The default package SHA-256 is 0ac4d6a58a437706e85ab8b577da26dfe88c5c866c5d7a008665fbe2fefcf11f." } diff --git a/sdk/catalog.json b/sdk/catalog.json index ff94422e33..07bc92a345 100644 --- a/sdk/catalog.json +++ b/sdk/catalog.json @@ -64,7 +64,7 @@ }, { "id": "usb-audio-out-tracks-main-cue", - "version": "0.2.0-experimental", + "version": "0.3.0-experimental", "addedAt": "2026-10-01T09:19:37Z" }, { diff --git a/sdk/machines/octatrack/module-adapters/standalone-recipes.json b/sdk/machines/octatrack/module-adapters/standalone-recipes.json index 023965efd5..52cf14617e 100644 --- a/sdk/machines/octatrack/module-adapters/standalone-recipes.json +++ b/sdk/machines/octatrack/module-adapters/standalone-recipes.json @@ -205,10 +205,10 @@ "src/engine/coldfire-elf.ts": "319ca0d835d1b0c602c8f4b06990016d0ebfe246cedbfc596cea3cc7adfe3cd2", "src/engine/module-build.ts": "dcd8397b8cecf6fab61debd9aa2f86f612da0ca6ccf363c79d56033bc170b993", "src/catalog/modules.ts": "14304ea8450f8ec7ecaaf3ccf9e764929161288babe7b34cb37ff41e44fe1b43", - "src/engine/assets/dsp-packages.json": "0620b5272f4a87d442dfa8f1568f1f008c125a8c4e65ca2de90fa6d7feeec11c", - "src/engine/assets/descriptor-recipes.json": "0273cbdc3f4406e07d767f2f7e14937ee5cb03b7e0f25add77698d1d82bdae3f", - "src/engine/assets/menu-recipes.json": "d344d9412891e89f65a1c47bf13310a72eef07bc19cb0fa87abf4d67caf4d188", - "src/engine/assets/rom-packages.json": "299e3d24dc3a46e562591d67bf3c066be2d205121be05e8f57e0c264e3ef0bde", + "src/engine/assets/dsp-packages.json": "60e98bb1e0c268144afd9f2dcae437ee7dbf9218fb81f198cd619ace6b349d88", + "src/engine/assets/descriptor-recipes.json": "47a5ac2a21e9884cb390e154127e3d086d5d740a47f4bedea9fea738199dc9dc", + "src/engine/assets/menu-recipes.json": "db5cb4f2f4cd4613e88eccf44124c506c73b3301cc500eb88627c51fb1981827", + "src/engine/assets/rom-packages.json": "57c7ca26a7c6b2c3dfca97c9d62ba8093b96c7977c17650df3848ffe6a51e325", "upstream/elekloader/link.py": "5d31157ccbe62807ff9f05fd47e1e55b54be0475ab53565e6607a56566603ba8", "upstream/elekloader/dsp.py": "9486d64eecee023670b716f6ae854996da02ee7c1a0efd5361cd963c756dbc69", "upstream/elekloader/patch.py": "77c0a74bf4b0ff8c5525d4c4b1bc42af765314a4601c0510577817a7487d8666", @@ -406,10 +406,10 @@ "src/engine/coldfire-elf.ts": "319ca0d835d1b0c602c8f4b06990016d0ebfe246cedbfc596cea3cc7adfe3cd2", "src/engine/module-build.ts": "dcd8397b8cecf6fab61debd9aa2f86f612da0ca6ccf363c79d56033bc170b993", "src/catalog/modules.ts": "14304ea8450f8ec7ecaaf3ccf9e764929161288babe7b34cb37ff41e44fe1b43", - "src/engine/assets/dsp-packages.json": "0620b5272f4a87d442dfa8f1568f1f008c125a8c4e65ca2de90fa6d7feeec11c", - "src/engine/assets/descriptor-recipes.json": "0273cbdc3f4406e07d767f2f7e14937ee5cb03b7e0f25add77698d1d82bdae3f", - "src/engine/assets/menu-recipes.json": "d344d9412891e89f65a1c47bf13310a72eef07bc19cb0fa87abf4d67caf4d188", - "src/engine/assets/rom-packages.json": "299e3d24dc3a46e562591d67bf3c066be2d205121be05e8f57e0c264e3ef0bde", + "src/engine/assets/dsp-packages.json": "60e98bb1e0c268144afd9f2dcae437ee7dbf9218fb81f198cd619ace6b349d88", + "src/engine/assets/descriptor-recipes.json": "47a5ac2a21e9884cb390e154127e3d086d5d740a47f4bedea9fea738199dc9dc", + "src/engine/assets/menu-recipes.json": "db5cb4f2f4cd4613e88eccf44124c506c73b3301cc500eb88627c51fb1981827", + "src/engine/assets/rom-packages.json": "57c7ca26a7c6b2c3dfca97c9d62ba8093b96c7977c17650df3848ffe6a51e325", "upstream/elekloader/link.py": "5d31157ccbe62807ff9f05fd47e1e55b54be0475ab53565e6607a56566603ba8", "upstream/elekloader/dsp.py": "9486d64eecee023670b716f6ae854996da02ee7c1a0efd5361cd963c756dbc69", "upstream/elekloader/patch.py": "77c0a74bf4b0ff8c5525d4c4b1bc42af765314a4601c0510577817a7487d8666", diff --git a/sdk/machines/octatrack/module-adapters/usb-audio-reconstruction.json b/sdk/machines/octatrack/module-adapters/usb-audio-reconstruction.json new file mode 100644 index 0000000000..bba7e75632 --- /dev/null +++ b/sdk/machines/octatrack/module-adapters/usb-audio-reconstruction.json @@ -0,0 +1,33 @@ +{ + "schema": 1, + "imageSha256": "ce2a01bae2aa15225cbb486e0643d16d5ddb8aa97fc099756cdc5399c7f1e64d", + "sources": { + "generatedAssembly": "eb1a19b38fc770625df2cb40ca21c1b9310a02fc06b70bc21811720e2d959a4b", + "sdk/machines/octatrack/module-adapters/usb_audio_settings.c": "7dc0405687c8a49571e933fb0cda3b5813a509b0ff3236be87bc3f3105739c0a", + "sdk/machines/octatrack/include/modwerk_events.h": "ed5c70c2eb4b82e3d393a60dd95a1257e8f6afc4642390564cee5d60cfc96dcc" + }, + "copies": [ + { + "offset": 1120, + "length": 12, + "address": 1073858896, + "sha256": "adf82a9ab72faf6ad2a911fa873acbf3195bd4a8a4a73771edb96a383405204c", + "purpose": "Authored audio_pkt_build + 556 in the USB Audio image" + }, + { + "offset": 3284, + "length": 6, + "address": 1073863924, + "sha256": "868378f30d4ed1251a28851782180b919dbfbd18ea839b594142244f6e06fb8a", + "purpose": "Authored uac2_set_done + 52 in the USB Audio image" + }, + { + "offset": 3290, + "length": 10, + "address": 1073864298, + "sha256": "c1ed73406504f0066c561fa89bfd547fa1c6825d89a28c3442c7997413e0b84c", + "purpose": "Authored uac2_set_done + 58 in the USB Audio image" + } + ], + "fills": [] +} diff --git a/sdk/machines/octatrack/module-adapters/usb_audio_configurable.py b/sdk/machines/octatrack/module-adapters/usb_audio_configurable.py new file mode 100644 index 0000000000..a15c7c67c7 --- /dev/null +++ b/sdk/machines/octatrack/module-adapters/usb_audio_configurable.py @@ -0,0 +1,202 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""The switchable UAC2 output on one 20-channel source ring. + +All layouts use the same aligned tracks, Main and Cue. The package publishes +only complete descriptor profiles. The base latches one while detached. +""" +import hashlib +import struct +import runpy +from types import SimpleNamespace +from pathlib import Path + +HERE = Path(__file__).resolve().parent +SOURCE_SHA = 'c1f39d2a21870cb5596c487388c61a1be1b9e35ec6860a9eb305268eca2287a8' + + +def checked(text, old, new): + if text.count(old) != 1: + raise ValueError('Configurable audio seam changed: ' + old[:64]) + return text.replace(old, new) + + +def configure_source(text): + # Use the existing per-sample POST_WORD and gain history for either stem + # layout. The independently timed Main and Cue writes below are shared. + for marker in ('| d2 = the stem', ' | The gain history', '| ==== TRACKS POST', ' .balign 4\npost_hidx:'): + old = '.if USB_LAYOUT == LAYOUT_TRACKS_POST\n' + marker + text = checked(text, old, '.if 1\n' + marker) + text = checked(text, 'audio_frame_shim_body:\n', '''audio_frame_shim_body: + mvzb mwua_post,%d0 + bsr post_frame + lea post_gtab,%a0 + movel %a0,mwua_gain +''') + start = text.index(' moveq #RB_TRACKS-1,%d7\n2: movel %a0@,%d2') + end = text.index(' bpl 2b\n', start) + len(' bpl 2b\n') + loop = text[start:end] + post = loop.replace('2: movel %a0@,%d2', '2: POST_WORD %a4@, 0').replace('movel %a0@(4),%d2', 'POST_WORD %a4@+, 4') + text = text[:start] + ''' tstb mwua_post + beq .Lpre_words + movel %a4,%sp@- + moveal mwua_gain,%a4 +''' + post + ''' movel %a4,mwua_gain + moveal %sp@+,%a4 + bra .Lstems_done +.Lpre_words: +''' + loop + '.Lstems_done:\n' + text[end:] + text = checked(text, ' movel %d4,aud_produced\n.endif\n', ' movel %d4,aud_produced\n bsr post_emac_leave\n.endif\n') + text = checked(text, ' tstb usbaudio_alt\n bnes .Lproduce', ''' tstb mwua_off + beqs .Loutput_on + addql #8,aud_produced + addql #8,aud_produced + bra .Loutput_idle +.Loutput_on: + tstb usbaudio_alt + bnes .Lproduce''') + text = checked(text, ' moveq #1,%d0\n moveb %d0,aud_closed', '.Loutput_idle:\n moveq #1,%d0\n moveb %d0,aud_closed') + # Initialize only the transmitted words while OFF, for every width and + # speed. The first producing block on resume clears the old ring cushion. + text = checked(text, ' moveal %a3,%a1\n movel %d4,%d3', ''' moveal %a3,%a1 + tstb mwua_off + beq .Laudio_copy + bsr mwua_packet_bytes + lsrl #2,%d6 +.Lzero_packet: + clrl %a1@+ + subql #1,%d6 + bne .Lzero_packet + bra .Lcopied +.Laudio_copy: + movel %d4,%d3''') + # Full speed has room for one pair. Track layouts retain their stereo sum. + # Buses, T8 and the first Outbox pair come from the aligned source ring. + text = checked(text, ' beqs .Lcopy_fs\n', ''' bnes .Lwide_ring + tstb mwua_fs_sum + bne .Lcopy_fs +.Lwide_ring: +''') + text = text.replace(' bsr audio_copy80', ' bsr mwua_route') + start = text.index(' movel %d4,%d6\n', text.index('\n.Lcopied:')) + end = text.index('6: | ---- the dTD:', start) + text = text[:start] + ' bsr mwua_packet_bytes\n' + text[end:] + # A full-speed sourced pair needs the same delay as the high-speed ring. + text = checked(text, ' tstb aud_hs\n beq 97f', ' tstb aud_hs\n bne 96f\n tstb mwua_fs_sum\n bne 97f\n96:') + cap = ' movel #(0x60000000+(PKT_MAX_HS<<16)),%d0' + text = checked(text, cap, ''' mvzb mwua_pairs,%d0 + moveq #96,%d1 + mulu.l %d1,%d0 + swap %d0 + oril #0x60000000,%d0''') + text += ''' + .text +mwua_packet_bytes: | d4 frames; d6 result, d1 scratch + movel %d4,%d6 + lsll #3,%d6 + tstb aud_hs + beqs 1f + mvzb mwua_pairs,%d1 + mulu.l %d1,%d6 +1: rts +mwua_route: | a0 dTD, a3 buffer, a5 wrap, a6 slot + tstb aud_hs + beqs 1f + tstb mwua_direct + bne audio_copy80 + moveq #0,%d1 + bras 2f +1: moveq #1,%d1 +2: movel %a0,%sp@- + movel %d1,%sp@- + movel %d0,%sp@- + movel %a2,%sp@- + movel %a1,%sp@- + bsr mwua_copy + moveal %sp@,%a1 + movel %sp@(8),%d4 + lea %sp@(16),%sp + moveal %sp@+,%a0 + bsr mwua_packet_bytes + addal %d6,%a1 + rts + .bss + .balign 4 +mwua_gain: .space 4 +''' + return text + + +def source(root, module, layout, functions, load, sine_curve, package_hooks): + path = root / 'sdk/octatrack/modules' / module / 'layouts/usbaudio.s' + raw = path.read_bytes() + if hashlib.sha256(raw).hexdigest() != SOURCE_SHA: + raise ValueError('Review the licensed multi-layout producer before adapting it.') + post = load('usb_post', HERE.parent / 'elekloader/usb_post.py') + text = functions.packet_readiness(functions.audio_source(raw.decode())) + text = functions.audio_storage_source(text) + text = checked(text, ' .include "remix.inc"', functions.audio_include(layout) + post.include(sine_curve(post))) + text = configure_source(text) + text = package_hooks(text) + text = checked(text, ' jsr audio_frame_shim', ' jsr mwua_begin_frame\n jsr audio_frame_shim') + # Reuse the licensed fixed-clock SET_CUR handler as an ev_usb_control + # callback. d2 is callee-saved and carries the verified request length. + start = text.index('.Lctrl_set:\n') + end = text.index('.Lctrl_stock:\n', start) + set_cur = text[start:end].replace('jmp SETIFACE_DONE', 'bra .Lclock_answered').replace('.Lctrl_stock', '.Lclock_reject') + set_cur = checked(set_cur, 'movel #0x00408080,%d0', 'movel #0x00048080,%d0') + text = text[:start] + set_cur + '''.Lclock_answered: + moveq #1,%d0 + bra .Lclock_return +.Lclock_reject: + moveq #0,%d0 +.Lclock_return: + movel %sp@+,%d2 + rts +''' + text[end:] + text = checked(text, ' beq .Lctrl_set', ' beq .Lctrl_stock') + text = checked(text, ' movel EP0_BUF,%d0', ''' movel EP0OUT_DTD+4,%d0 + andil #0x7fff0068,%d0 | reject a short or failed clock write + bne 1f + movel EP0_BUF,%d0''') + text = checked(text, '.Lmwc_class:\n', '''.Lmwc_class: + cmpil #0x21,%d0 + bne .Lclock_get + tstb SETUP_WVALH-1 + bne .Lmwc_no + tstb 0x46c8ce0f + bne .Lmwc_no + movel %d2,%sp@- + mvzb 0x46c8ce0e,%d2 + bra .Lctrl_set +.Lclock_get: +''') + text = checked(text, 'mwua_bus_end: ', 'mwua_bus_end:\n clrb uac2_set_pending\n | ') + return text + + +def records(root, module, supported, functions, usb, function_block, descriptor_records): + descriptors = SimpleNamespace(**runpy.run_path(str(root / 'sdk/octatrack/modules' / module / 'layouts/descriptors.py'))) + keys = [supported[i] for i in (0,1,3,4,0)] + names = ('mwua_fs','mwua_hs','mwua_other_fs','mwua_other_hs') + speeds = ((False, False),(True, False),(False, True),(True, True)) + rows = [] + for hs, other in speeds: + blocks = [function_block(functions, usb, descriptors, key, hs, other) for key in keys] + if hs: + # The Outbox profile has four stereo outputs, 12 frames per poll. + records = [bytearray(r) for r in descriptor_records(blocks[-1])] + for r in records: + if r[:3] == bytes([17,0x24,2]): r[8] = 8 + if r[:3] == bytes([16,0x24,1]): r[10] = 8 + if r[:3] == bytes([7,5,0x83]): struct.pack_into(' MODWERK > SETTINGS: ALL CHANNELS, OFF and, in the twenty-channel layout, + MAIN + CUE ONLY; issue 1512) is the package's ot_settings record, read by the producer through the seams pull + request 1517 made for a linked base; +- its transfer descriptors are aligned at run time: a package's image sits at a 16-byte boundary of the pool, and + the controller needs 32; +- USB AUDIO OUT TRACKS POST takes its gain curve as the computed quarter sine (owner, 20 November 2026), not as + the stock DSP table a linked base reads from the owner's OS: a package carries no stock data. The stock table + is that sine to within 64 of 2^23 (usb_post.py refuses any other), so a stem's level differs from a linked + base's by at most that. +""" +import argparse +import hashlib +import json +import math +import importlib.util +import struct +import subprocess +import sys +import tempfile +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[3] +MODULE = 'usb-audio-out-tracks-main-cue' +TITLE = 'USB AUDIO' +SUPPORTED = ('USB AUDIO OUT TRACKS MAIN CUE', 'USB AUDIO OUT TRACKS', 'USB AUDIO OUT MASTER', 'USB AUDIO OUT MAIN CUE', + 'USB AUDIO OUT MAIN', 'USB AUDIO OUT TRACKS POST') +USB_EP0_SEND = 0x4001d498 # stock: usb_ep0_send(length, buffer), the routine EP0_SEND_TAIL (0x4001de5c) calls + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module) + return module + + +def once(text, old, new, what): + if text.count(old) != 1: + raise ValueError('The authored USB Audio source changed at %s; review the package seam.' % what) + return text.replace(old, new) + + +def function_block(functions, usb, descriptors, layout, high_speed, other_speed): + """The audio function's descriptors as they follow the base's own in a composed configuration.""" + without = functions.configuration(usb, descriptors, high_speed, other_speed, None) + whole = functions.configuration(usb, descriptors, high_speed, other_speed, layout) + block = whole[len(without):] + if (whole[9:len(without)] != without[9:] or whole[4] != without[4] + 2 + or struct.unpack_from(' MODWERK > SETTINGS, the package's ot_settings record), read by the + producer every frame. Written for a base that linked USB Audio in and tried on a unit there (pull request + 1517, 13 November 2026); in a package it has run in the emulator only. + + OFF: silence. The frame hook takes its no-host path, writes nothing to the ring and only counts the block's + sixteen frames, so the packet clock and its servo run on; the builder copies nothing and sends each packet + from a buffer zeroed once (the first packet each of the NSLOT buffers carries after the choice). A host sees + an ordinary stream of silence, whenever it opens it. When the player chooses again the first produced block + zeroes the cushion the reader is in, as at any start, so nothing from before OFF is sent. Two other ways + were tried on the owner's MKII with Windows 11 (13 November 2026): with the endpoint taken down under an + open stream no packet was collected again after it came back, and with empty packets the recording skipped + 42 to 71 frames shortly after about half of the resumes, the unit's own counters unbroken. MAIN + CUE ONLY (the + twenty-channel layout, at high speed: full speed sends the tracks' sum): the producer leaves each frame's + sixteen track words in the ring as they were, and the packet builder copies only the frame's last sixteen + bytes (MAIN and CUE) into the packet. What a stream costs is its memory traffic, through the 80 KB ring and + the controller's uncached buffers (owner's MKII, 13 November 2026, the frame interrupt's share while + playing: all channels 65.4 %, track words cleared in the ring and copied 64.1 %, cleared and not copied + 61.5 %, neither 55.6 %, no stream 38.6 %). The track bytes of a packet buffer are zeroed once, in the first + packet each of the NSLOT buffers carries after the choice. When the choice ends the builder keeps its short + copy for MW_MIX_HOLD more packets, over a thousand frames: by then the producer has rewritten every ring + slot, so no track word from before or during the choice is ever sent. A packet copied whole, or a + full-speed one, starts both counts again. The hook also writes which choices its layout offers (bit 0 all, 1 MAIN + CUE + only, 2 off). The descriptors, the packet sizes and the import stay as they are. + """ + if key not in layouts or 'modwerk_usb_audio' in text or '.Lmw_' in text: + raise ValueError('Choose an explicit supported USB output layout for an unswitched producer.') + wanted = (' tstb usbaudio_alt\n bnes .Lproduce\n' + " tstb aud_force | the harness's switch (usb_align): produce\n" + ' bnes .Lproduce | with no host and EP3 left alone\n') + tracks = ' moveq #RB_TRACKS-1,%d7\n2: movel %a0@,%d2 | track L\n' + after = (' lea %a0@(128),%a0 | next track, same frame\n subql #1,%d7\n bpl 2b\n' + '.if USB_LAYOUT == LAYOUT_TRACKS_MAIN_CUE\n') + buffer = ' moveal #(aud_bufs+UNCACHED),%a3\n addal %d0,%a3\n moveal %a3,%a1\n' + copy, helpers = ' bsr audio_copy80', '| Copy d0 (>= 1) 8-byte stereo-sum frames from %a2 to %a1, both advanced.\naudio_copy8:\n' + if any(text.count(seam) != 1 for seam in (wanted, tracks, after, buffer, helpers)) or text.count(copy) != 3 or \ + text.count('\n.Lcopied:\n') != 1 or text.count(' movel %d4,usbaudio_lastn\n') != 1 or \ + text.index(' movel %d4,usbaudio_lastn\n') > text.index(buffer): + raise ValueError('The authored audio producer changed; review the on-device switch.') + caps = 7 if layouts[key] == 0 else 5 + text = text.replace(wanted, """ moveq #%d,%%d0 | what this layout offers (mwua_setting) + moveb %%d0,modwerk_usb_audio_caps + tstb modwerk_usb_audio_off | the player's OFF: as with no host, the + beqs .Lmw_on | block's frames counted for the packet clock + addql #8,aud_produced + addql #8,aud_produced + bras .Lmw_idle +.Lmw_on: +""" % caps + wanted + '.Lmw_idle:\n') + text = text.replace(tracks, """.if USB_LAYOUT == LAYOUT_TRACKS_MAIN_CUE + tstb modwerk_usb_audio_mix | MAIN + CUE ONLY: silent track channels + beqs .Lmw_tracks + movel %a1,%d0 + beqs .Lmw_tracks | full speed sends the tracks' sum: copy them + lea %a3@(64),%a3 | the track words stay as they were: the builder does not send them + bra .Lmw_tracks_done +.Lmw_tracks: +.endif +""" + tracks) + text = text.replace(after, after.replace('.if USB_LAYOUT', '.Lmw_tracks_done:\n.endif\n.if USB_LAYOUT', 1).replace( + ' bpl 2b\n', ' bpl 2b\n.if USB_LAYOUT == LAYOUT_TRACKS_MAIN_CUE\n', 1)) + text = text.replace(buffer, buffer + """ tstb modwerk_usb_audio_off | OFF: a packet of silence, nothing copied + beqs .Lmw_send + bsr mw_off_packet + bra .Lcopied +.Lmw_send: + clrl mw_off_clean +.if USB_LAYOUT == LAYOUT_TRACKS_MAIN_CUE + bsr mw_mix_packet | MAIN + CUE ONLY: this buffer's track bytes are zero +.endif +""") + text = text.replace(copy, ' bsr mw_copy80') + return text.replace(helpers, """| OFF (Modwerk, usb_audio_package.py). Before a packet's copy, %a3 its buffer: zero the whole buffer of the first +| packet each of the NSLOT buffers carries after the choice; the builder then skips the copy. Any packet that is +| copied starts the count again. Uses d0-d1/a2, which the builder loads after this or no longer needs. +mw_off_packet: + movel mw_off_clean,%d0 + moveq #NSLOT,%d1 + cmpl %d1,%d0 + bccs 9f | every buffer is zero + addql #1,%d0 + movel %d0,mw_off_clean + moveal %a3,%a2 + movel #PKT_BUF/4-1,%d1 +7: clrl %a2@+ + subql #1,%d1 + bpls 7b +9: rts + .bss + .balign 4 +mw_off_clean: .space 4 | packets since OFF whose buffer was zeroed + .text +.if USB_LAYOUT == LAYOUT_TRACKS_MAIN_CUE +| MAIN + CUE ONLY (Modwerk, usb_audio_package.py). Before a packet is copied, %a3 its buffer: count the packets +| since the choice, and zero the track bytes of the first each of the NSLOT buffers carries (every frame a packet +| can hold). Any other packet starts the count again. Uses d0-d1/a2, which the builder loads after this. +mw_mix_packet: + tstb aud_hs + beqs 8f | full speed: the sum's packets, copied whole + tstb modwerk_usb_audio_mix + beqs 5f + moveq #MW_MIX_HOLD,%d0 | chosen: the short copy, and for this many packets after + movel %d0,mw_mix_hold + bras 6f +5: movel mw_mix_hold,%d0 + beqs 8f | not chosen, and the ring is the producer's again + subql #1,%d0 + movel %d0,mw_mix_hold +6: moveq #1,%d0 + moveb %d0,mw_mix_short + movel mw_mix_clean,%d0 + moveq #NSLOT,%d1 + cmpl %d1,%d0 + bccs 9f | every buffer's track bytes are zero + addql #1,%d0 + movel %d0,mw_mix_clean + moveal %a3,%a2 + moveq #PKT_MAX_HS/80-1,%d1 +7: .rept 16 + clrl %a2@+ + .endr + lea %a2@(16),%a2 + subql #1,%d1 + bpls 7b +9: rts +8: clrl mw_mix_clean + clrl mw_mix_hold + clrb mw_mix_short + rts +| audio_copy80's call: a short packet (mw_mix_packet) takes d0 (>= 1) frames' last sixteen bytes from %a2 to %a1, +| both advanced by the whole 80-byte slot. Clobbers d1-d4. +mw_copy80: + tstb mw_mix_short + beq audio_copy80 +1: moveml %a2@(64),%d1-%d4 + moveml %d1-%d4,%a1@(64) + lea %a2@(80),%a2 + lea %a1@(80),%a1 + subql #1,%d0 + bnes 1b + rts + .bss + .balign 4 +mw_mix_clean: .space 4 | packets since MAIN + CUE ONLY whose buffer's track bytes were zeroed +mw_mix_hold: .space 4 | packets the short copy still holds after the choice ended +mw_mix_short: .space 1 | this packet is copied short + .text +.set MW_MIX_HOLD, 96 | x 11 frames a packet: more than the ring's AUD_FRAMES +.else +.set mw_copy80, audio_copy80 +.endif +""" + helpers) + + +def sine_curve(usb_post): + """The first quarter of a 1024-step sine in 24 bits: the curve usb_post.py checks the stock table against.""" + return usb_post.validate(round(math.sin(2 * math.pi * i / 1024) * 0x7fffff) for i in range(usb_post.COUNT)) + + +def source(functions, usb, layout): + """The adapted unit: the authored source, the linked base's adaptations, the package seams, the handlers.""" + path, _ = usb.audio_paths(layout) + text, include = functions.audio_source(path.read_text()), functions.audio_include(layout) + if layout == usb.POST_LAYOUT: + usb_post = load('modwerk_usb_post', ROOT / 'sdk/machines/octatrack/elekloader/usb_post.py') + include += usb_post.include(sine_curve(usb_post)) + else: + text = functions.packet_readiness(text) + text = functions.audio_storage_source(audio_switch(text, layout, functions.AUDIO_LAYOUTS)) + text = once(text, ' .include "remix.inc"', include, 'its include') + return package_hooks(text) + setting(functions.AUDIO_LAYOUTS[layout] == 0) + + +def package_hooks(text): + # The hooks: each shim at a site the base owns returns to the base instead of chaining or rejoining stock. + text = once(text, ' jmp usbmidi_rx_isr_shim | USB MIDI\'s shim, whose detour this one stands in for', + ' moveq #0,%d0 | package: ev_usb_isr, the base goes on to USB MIDI itself\n rts', + 'the interrupt shim\'s tail') + text = once(text, '9: clrl 0x46104d4e | displaced\n jmp 0x4000d9a6\n', + '9: rts | package: ev_usb_frame, the base replays the displaced clear\n', + 'the producer\'s tail') + # Transfer descriptors at a 32-byte boundary found at run time (mwua_frame), with the room for it. + aligned = ' moveal #(aud_dtds+UNCACHED),' + if text.count(aligned) != 3: + raise ValueError('The authored USB Audio source names its transfer descriptors elsewhere; review the alignment.') + text = text.replace(aligned, ' moveal mwua_dtds,') + text = once(text, 'aud_dtds: .space NSLOT*32 ', 'aud_dtds: .space NSLOT*32+32 ', 'its transfer descriptors') + return text + HANDLERS + + +HANDLERS = ''' +| ---- the package's handlers (Modwerk, usb_audio_package.py) ----------------- +| C convention: d0-d1/a0-a1 free, the rest kept; each returns 0 in d0 unless it says otherwise. + .text + .balign 2 + .global mwua_isr, mwua_bus_end, mwua_frame, mwua_control + .type mwua_isr,@function +mwua_isr: | ev_usb_isr: retire EP3 IN's completion + jmp audio_isr_shim + .size mwua_isr, .-mwua_isr + .type mwua_bus_end,@function +mwua_bus_end: | ev_usb_bus_end: alternate setting 0; the frame interrupt tears EP3 down + bsr audio_alt0_request + moveq #0,%d0 + rts + .size mwua_bus_end, .-mwua_bus_end + .type mwua_frame,@function +mwua_frame: | ev_usb_frame: the producer, which uses every register + lea %sp@(-44),%sp + moveml %d2-%d7/%a2-%a6,%sp@ + movel #(aud_dtds+UNCACHED+31),%d0 + andil #0xffffffe0,%d0 + movel %d0,mwua_dtds | the controller keeps bits 31:5 of a dTD pointer + jsr audio_frame_shim + moveml %sp@,%d2-%d7/%a2-%a6 + lea %sp@(44),%sp + moveq #0,%d0 + rts + .size mwua_frame, .-mwua_frame +| ev_usb_control: audio_ctrl_shim's requests (the clock source's sample rate and validity, and the vendor read of +| the counters), answered with stock's usb_ep0_send(min(wLength, length), buffer). Returns 1 when it answered. + .type mwua_control,@function +mwua_control: + mvzb SETUP_BMREQ,%d0 + cmpil #0xc0,%d0 + bnes .Lmwc_class + mvzb SETUP_BREQ,%d0 + cmpil #0x55,%d0 + bne .Lmwc_no + lea usbaudio_consumed,%a0 + moveq #60,%d0 + bra .Lmwc_send +.Lmwc_class: + cmpil #0xa1,%d0 | class GET, interface recipient + bne .Lmwc_no + mvzb SETUP_IFACE,%d0 + cmpil #UAC2_AC_IFACE,%d0 + bne .Lmwc_no + mvzb SETUP_WIDXH,%d0 + cmpil #UAC2_CLOCK_ID,%d0 + bne .Lmwc_no + mvzb SETUP_WVALH,%d0 | control selector + mvzb SETUP_BREQ,%d1 | 1 = CUR, 2 = RANGE + cmpil #1,%d0 | CS_SAM_FREQ_CONTROL + beqs .Lmwc_freq + cmpil #2,%d0 | CS_CLOCK_VALID_CONTROL + bne .Lmwc_no + cmpil #1,%d1 + bne .Lmwc_no + lea uac2_clock_valid,%a0 + moveq #1,%d0 + bras .Lmwc_send +.Lmwc_freq: + cmpil #1,%d1 + bnes .Lmwc_range + lea uac2_freq_cur,%a0 + moveq #4,%d0 + bras .Lmwc_send +.Lmwc_range: + cmpil #2,%d1 + bne .Lmwc_no + lea uac2_freq_range,%a0 + moveq #14,%d0 +.Lmwc_send: + mvzb 0x46c8ce0f,%d1 | SETUP wLength, little-endian + lsll #8,%d1 + movel %d1,%a1 + mvzb 0x46c8ce0e,%d1 + addl %a1,%d1 + cmpl %d1,%d0 + blss 1f + movel %d1,%d0 +1: movel %a0,%sp@- + movel %d0,%sp@- + jsr MW_USB_EP0_SEND + addql #8,%sp + moveq #1,%d0 + rts +.Lmwc_no: + moveq #0,%d0 + rts + .size mwua_control, .-mwua_control + + .data + .balign 4 + .global mwua_function, mwua_dtds +mwua_dtds: .long 0 | the transfer descriptors, at their 32-byte boundary (uncached alias) +''' + + +def setting(mix): + """The package's row on PROJ > MODWERK > SETTINGS (events.json ot_settings): what the unit sends while a host has + the stream open. OFF is the second choice in every layout, so the base's kept choice means the same in each; + MAIN + CUE ONLY is the twenty-channel layout's alone.""" + names = ['ALL CHANNELS', 'OFF'] + (['MAIN + CUE ONLY'] if mix else []) + out = ['| ---- the on-device setting (Modwerk, usb_audio_package.py) ------------------', + ' .text', ' .balign 2', ' .global mwua_setting_apply', ' .type mwua_setting_apply,@function', + 'mwua_setting_apply: | apply(choice): 0 all channels, 1 off, 2 MAIN + CUE only', + ' movel %sp@(4),%d0', ' moveq #1,%d1', ' cmpl %d0,%d1', ' seq %d1', + ' moveb %d1,modwerk_usb_audio_off', ' moveq #2,%d1', ' cmpl %d0,%d1', ' seq %d1', + ' moveb %d1,modwerk_usb_audio_mix', ' rts', ' .size mwua_setting_apply, .-mwua_setting_apply', + ' .data', ' .balign 4', ' .global mwua_setting', + 'mwua_setting:', ' .long 1, mwua_set_label, %d, mwua_set_choices, mwua_setting_apply, 0' % len(names), + 'mwua_set_choices: .long ' + ', '.join('mwua_set_%d' % i for i in range(len(names))), + 'mwua_set_label: .asciz "USB AUDIO"'] + out += ['mwua_set_%d: .asciz "%s"' % pair for pair in enumerate(names)] + out += ['modwerk_usb_audio_off: .byte 0', 'modwerk_usb_audio_mix: .byte 0', 'modwerk_usb_audio_caps: .byte 0', ' .balign 4'] + return '\n'.join(out) + '\n' + + +def record(blocks): + """struct modwerk_usb_function (include/modwerk_events.h) and its four descriptor blocks.""" + if len({len(b) for b in blocks}) != 1: + raise ValueError('The four configurations give the audio function blocks of different lengths.') + names = ('mwua_fs', 'mwua_hs', 'mwua_os_fs', 'mwua_os_hs') + interfaces = sum(1 for b in [blocks[0]] for r in _records(b) if r[1] == 4 and r[3] == 0) + out = ['mwua_function:', ' .long 1, 32', ' .short %d, %d' % (interfaces, len(blocks[0])), + ' .long 0x00080000 | endpoint 3 IN', ' .long ' + ', '.join(names)] + for name, block in zip(names, blocks): + out.append('%s: .byte %s' % (name, ', '.join('0x%02x' % b for b in block))) + return '\n'.join(out) + '\n .balign 4\n' + + +def _records(data): + at = 0 + while at < len(data): + yield data[at:at + data[at]] + at += data[at] + + +RECIPE = HERE / 'usb-audio-reconstruction.json' + + +def capture_release(loader, image, protected, sources, stock, upstream): + from elekloader import formats + parsed, device, original = formats.load(str(stock)) + main = formats.main_image(parsed, device) + if device.key != 'octatrack' or original.version != '1.40C' or hashlib.sha256(main).hexdigest() != original.main_sha256: + raise ValueError('Original Octatrack 1.40C required') + packages = load('usb_audio_runs', HERE.parent / 'elekloader/module_packages.py') + scanner = load('usb_audio_stock_runs', HERE.parent / 'elekloader/check_stock_free.py') + source_runtime = load('usb_audio_source_runtime', ROOT / 'scripts/source-runtime-package.py') + spans = set() + for at, counted in packages.runs(image, main).items(): + if counted >= packages.LIMIT: + spans.update(range(at, at + packages.SEED)) + for _, at, n, _ in scanner.stock_runs({'sections': {'image': {'parts': [['hex', image.hex()]]}}}, + scanner.haystacks(stock, upstream), 16): + spans.update(range(at, at + n)) + for word in protected: + spans.difference_update(range(word, word + 4)) + copies = [] + for at in sorted(spans): + if copies and at == copies[-1]['offset'] + copies[-1]['length']: + copies[-1]['length'] += 1 + else: + copies.append(dict(offset=at, length=1, address=0)) + base = json.loads((ROOT / 'src/engine/assets/octatrack-base.elemod').read_text()) + recipe = dict(schema=1, imageSha256=hashlib.sha256(image).hexdigest(), sources=sources, copies=copies, fills=[]) + return source_runtime.bounded_capture(recipe, image, main, device.main_load, base, loader.site_events()) + + +def build(layout, cross='m68k-elf-', *, release=False, capture=None, stock=None, upstream=None): + if layout is not None and layout not in SUPPORTED: + raise ValueError('Not built as a package yet: ' + layout) + sys.path.insert(0, str(ROOT / 'sdk/runtime/loader')) + import build as loader + usb = load('modwerk_usb_base', ROOT / 'sdk/machines/octatrack/elekloader/usb_base.py') + functions = load('modwerk_base_usb_functions', HERE / 'base_usb_functions.py') + if layout is None: + configurable = load('modwerk_usb_configurable', HERE / 'usb_audio_configurable.py') + descriptors, block_length = configurable.records(ROOT, MODULE, SUPPORTED, functions, usb, function_block, _records) + text = configurable.source(ROOT, MODULE, SUPPORTED[0], functions, load, sine_curve, package_hooks) + descriptors + else: + descriptors = load('modwerk_authored_usb_descriptors', usb.audio_paths(layout)[1]) + blocks = [function_block(functions, usb, descriptors, layout, hs, other) + for hs, other in ((False, False), (True, False), (False, True), (True, True))] + block_length = len(blocks[0]) + text = source(functions, usb, layout) + record(blocks) + with tempfile.TemporaryDirectory() as tmp: + tmp = Path(tmp) + (tmp / 'usbaudio.s').write_text(text) + subprocess.run([cross + 'as', '-mcpu=54455', '--defsym', 'MW_USB_EP0_SEND=%#x' % USB_EP0_SEND, + str(tmp / 'usbaudio.s'), '-o', str(tmp / 'usbaudio.o')], check=True) + objects = [tmp / 'usbaudio.o'] + if layout is None: + objects.append(tmp / 'settings.o') + subprocess.run([cross + 'gcc', *loader.CFLAGS, '-I', str(HERE.parent / 'include'), '-c', + str(HERE / 'usb_audio_settings.c'), '-o', str(objects[-1])], check=True) + image, symbols, bss, offsets = loader.link_units(objects, cross, 0, tmp, anywhere=True) + sites = [] + for address, guard, shim in usb.AUDIO_DETOURS: + if shim == 'audio_frame_shim': # the base's own site on a base with function slots: ev_usb_frame + continue + code = loader.OPCODES['jmp'] + struct.pack('>I', symbols[shim]) + sites.append((address, hashlib.sha256(bytes.fromhex(guard)).digest(), code, [2], 0, len(guard) // 2)) + if len(sites) != 3: + raise ValueError('USB Audio\'s own stock sites changed.') + loader.unevented(sites) + entries = [dict(event='ot_usb_functions', fn='mwua_function', order=50), dict(event='ev_usb_isr', fn='mwua_isr', order=50), + dict(event='ev_usb_bus_end', fn='mwua_bus_end', order=50), dict(event='ev_usb_control', fn='mwua_control', order=50), + dict(event='ev_usb_frame', fn='mwua_frame', order=50), dict(event='ot_settings', fn='mwua_setting', order=50)] + hooks = loader.subscribe([loader.NONE] * len(loader.HANDLERS), entries, symbols) + # Inventory kind 7 is the configurable package. Kinds 1-6 identify the older + # fixed layouts so the site can still select their exact Undo package. + copies, fills = [], [] + if release or capture: + if layout is not None: + raise ValueError('The release package configures every layout.') + sources = {'generatedAssembly': hashlib.sha256(text.encode()).hexdigest()} + for path in (HERE / 'usb_audio_settings.c', HERE.parent / 'include/modwerk_events.h'): + sources[str(path.relative_to(ROOT))] = hashlib.sha256(path.read_bytes()).hexdigest() + preset = symbols['mwua_setting'] + 20 + if capture: + if capture.exists() or not stock or not upstream: + raise ValueError('Capture requires original stock, upstream tools and a new recipe path.') + loader.firmware_codec.use_elekloader(upstream.resolve()) + recipe = capture_release(loader, image, [*offsets, preset], sources, stock, upstream) + for item in recipe['copies']: + at = item['offset'] + labels = [(address, name) for name, address in symbols.items() if address <= at and name[0].islower()] + address, label = max(labels) + item['purpose'] = f'Authored {label} + {at - address} in the USB Audio image' + capture.write_text(json.dumps(recipe, indent=2) + '\n') + else: + recipe = json.loads(RECIPE.read_text()) + authored = image + recipe_api = load('usb_audio_reconstruction', HERE / 'stock_recipe.py') + image, copies, fills = recipe_api.apply(image, [*offsets, preset], recipe, sources) + loader.unevented(sites, copies) + base = json.loads((ROOT / 'src/engine/assets/octatrack-base.elemod').read_text()) + for _, address, n, _ in copies: + if address < 0x40000400 or address + n > 0x400de1e0 or any( + address < int(site['addr'], 16) + site['len'] and int(site['addr'], 16) < address + n + for site in base['sites']): + raise ValueError('USB Audio reconstruction requires unmodified, readable stock data.') + if stock: + loader.check_stock(sites, stock, upstream) + from elekloader import formats + parsed, device, original = formats.load(str(stock)) + main = formats.main_image(parsed, device) + if device.key != 'octatrack' or original.version != '1.40C' or hashlib.sha256(main).hexdigest() != original.main_sha256: + raise ValueError('Original Octatrack 1.40C required') + rebuilt = bytearray(image) + for at, address, n, digest in copies: + start = address - device.main_load + block = main[start:start + n] + if start < 0 or len(block) != n or hashlib.sha256(block).digest() != digest: + raise ValueError('The original OS differs from the reconstruction record.') + rebuilt[at:at + n] = block + for at, n, value in fills: + rebuilt[at:at + n] = bytes([value])*n + if rebuilt != authored: + raise ValueError('The installed image differs from the compiled module.') + data = loader.package(image, bss, hooks, offsets, sites, name=MODULE, hashed=True, title=TITLE, abi=8, + copies=copies, fills=fills, + layout=7 if layout is None else functions.AUDIO_LAYOUTS[layout] + 1) + if release and stock: + packages = load('usb_audio_package_scan', HERE.parent / 'elekloader/module_packages.py') + scanner = load('usb_audio_image_scan', HERE.parent / 'elekloader/check_stock_free.py') + runs = packages.runs(data, main) + if max(runs.values(), default=0) >= packages.LIMIT or scanner.stock_runs( + {'sections': {'package': {'parts': [['hex', data.hex()]]}}}, scanner.haystacks(stock, upstream), 16): + raise ValueError('The USB Audio release contains a stock span.') + return data, dict(image=len(image), bss=bss, relocations=len(offsets), sites=[hex(s[0]) for s in sites], + block=block_length, stock_sites=sites) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split('\n\n')[0]) + parser.add_argument('-o', '--output', type=Path, required=True) + parser.add_argument('--layout', choices=SUPPORTED, help='build a legacy single-layout comparison package') + parser.add_argument('--cross', default='m68k-elf-') + parser.add_argument('--stock', type=Path, help='check the three sites\' guards against this OS file') + parser.add_argument('--upstream', type=Path, help='the Elekloader checkout --stock is read with') + parser.add_argument('--release', action='store_true', help='build from the reviewed stock reconstruction recipe') + parser.add_argument('--capture-recipe', type=Path, help='record hash-only reconstruction data for review') + args = parser.parse_args() + data, facts = build(args.layout, args.cross, release=args.release, capture=args.capture_recipe, stock=args.stock, upstream=args.upstream) + if args.stock: + if not args.upstream: + parser.error('--stock needs --upstream') + sys.path.insert(0, str(ROOT / 'sdk/runtime/loader')) + import build as loader + loader.check_stock(facts['stock_sites'], args.stock, args.upstream) + args.output.write_bytes(data) + print('%s: %s, %d bytes of code and data, %d of bss, %d relocations, sites %s, a %d-byte function block' % ( + args.output, args.layout or 'configurable USB Audio', facts['image'], facts['bss'], facts['relocations'], ', '.join(facts['sites']), facts['block'])) + + +if __name__ == '__main__': + main() diff --git a/sdk/machines/octatrack/unused-hooks.json b/sdk/machines/octatrack/unused-hooks.json index 08369c4e91..051810cb35 100644 --- a/sdk/machines/octatrack/unused-hooks.json +++ b/sdk/machines/octatrack/unused-hooks.json @@ -3,12 +3,6 @@ "unused": { "ot_midi_generators": "base table since #775, its reader host-tested; VECTOR MIDI contributed in VECTOR 0.3.0 (#1339) and left with 0.3.1 (#1342), its own module pending", "ev_bank_write": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", - "ev_project_reload": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending", - "ot_settings": "Staged in #1848 for USB Audio 0.3 (#1831). Its runtime package subscribes when the installer switches from the linked 0.7.11 layouts to base 0.7.12.", - "ot_usb_functions": "Staged in #1848 for USB Audio 0.3 (#1831). Its runtime package subscribes when the installer switches from the linked 0.7.11 layouts to base 0.7.12.", - "ev_usb_isr": "Staged in #1848 for USB Audio 0.3 (#1831). Its runtime package subscribes when the installer switches from the linked 0.7.11 layouts to base 0.7.12.", - "ev_usb_bus_end": "Staged in #1848 for USB Audio 0.3 (#1831). Its runtime package subscribes when the installer switches from the linked 0.7.11 layouts to base 0.7.12.", - "ev_usb_control": "Staged in #1848 for USB Audio 0.3 (#1831). Its runtime package subscribes when the installer switches from the linked 0.7.11 layouts to base 0.7.12.", - "ev_usb_frame": "Staged in #1848 for USB Audio 0.3 (#1831). Its runtime package subscribes when the installer switches from the linked 0.7.11 layouts to base 0.7.12." + "ev_project_reload": "added in #1564 for MIDI Scenes and Kits, which keep data per project, bank and Part; first module pending" } } diff --git a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/README.md b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/README.md index 922c846c79..a8fb91d2e7 100644 --- a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/README.md +++ b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/README.md @@ -1,123 +1,72 @@ -# USB Audio 0.2 +# USB Audio ## Overview -Send Octatrack audio over class-compliant USB at 44.1 kHz, 24 bits. Choose -Computer for recording, or Outbox 8 for physical outputs. This experimental -release is owner-approved without current-build hardware tests. Chip timing -and complete hardware memory bounds remain unmeasured. - -The selectable layouts and shared USB stack are imported from Octabam -`7b2984c859732ae6c797ae49c7d61d250b1b6519`, under MIT. The classic -twenty-channel source and its USB MIDI/reset fixes are retained from 0.1.4; -configurations without `usbAudio` settings keep that code path. +Install USB Audio once to record the Octatrack on a computer or route four stereo USB pairs to Outbox 8. The Octatrack sends 24-bit audio at 44.1 kHz. Pick the destination and sources on the instrument. ## Controls -There is no new Octatrack page or panel control. Open USB Audio setup in -Modwerk, choose a destination and one audio source, then save: - -| Audio to send | USB channels | Signal tap | -| --- | ---: | --- | -| Main mix | 2 | Final stereo Main mix | -| Main + Cue mixes | 4 | Final Main and separate Cue | -| Track 8 / Master | 2 | Track 8 after effects, before LEVEL; enable MASTER TRACK for a master mix | -| 8 tracks before track levels | 16 | Track pairs before LEVEL | -| 8 tracks following track levels | 16 | Track LEVEL, mute, solo and XLV/crossfader applied | -| 8 tracks + Main + Cue | 20 | Eight tracks before LEVEL, plus Main and Cue | - -Tracks following LEVEL exclude MAIN LEVEL and master effects on tracks 1–7. -With a master track, tracks 1–7 lead track 8 by 32 samples. The USB channel -map is sequential in the order shown in Modwerk. Four Outbox selectors name -physical stereo outputs; their helper text names the USB source pair. Off -sends no signal to that physical pair. Duplicate assignments are permitted. -Assign in order uses the first four available stereo signals and leaves -remaining outputs off. A smaller audio source turns unavailable assignments -off and reports that change. Destination/tab changes preserve draft choices; -only Add to configuration / Save setup stores them. Discard restores saved -settings. Copy assignments copies the plan for the external Outbox app. +Open **PROJ → MODWERK → SETTINGS**, highlight **USB AUDIO** and press **YES**. Open a field to see all its choices and the active selection. Use the arrows to browse, **YES** to select and **NO** to go back. + +| Field | Choices on the Octatrack | +| --- | --- | +| SEND TO | COMPUTER or OUTBOX 8 | +| LAYOUT | Eight tracks plus Main and Cue (20 channels), eight tracks (16), Main and Cue (4), Main (2), or Track 8/Master (2) | +| TRACK TAP | PRE LEVEL or POST LEVEL for either eight-track layout. POST follows track LEVEL, mutes, solo and crossfader. Main and Cue keep their channel pairs. | +| OUTPUT MODE | ALL CHANNELS or OFF. The 20-channel layout also offers MAIN + CUE ONLY. | +| Outbox pairs | Choose a source from the selected layout for each of the four stereo pairs. Choose OFF for silence. A source can feed more than one pair. | + +Track 8/Master sends track 8 after effects and before LEVEL. Enable MASTER TRACK on the Octatrack to use it as the master mix. The POST LEVEL stems for tracks 1–7 exclude MAIN LEVEL and master effects. With a master track, those stems lead track 8 by 32 samples. ## Usage -Use the configurator to choose the source before building the firmware. +For recording, choose COMPUTER and the layout you want, then select Octatrack as the audio input in your DAW. Stop recording before a layout change that changes the number of channels. The USB device reconnects so the host can see the new inputs. -### Record a mix or send Main + Cue to Outbox +When you load an existing Modwerk set, its saved destination, layout, track tap and Outbox assignments supply the initial settings. A classic set without USB settings starts with eight PRE LEVEL stereo tracks followed by Main and Cue. -1. Choose and save: open USB Audio setup, choose Outbox 8 and Main + Cue mixes, then Assign in order. Save the setup to the named configuration and build locally from your own OS 1.40C file. -2. Connect and route: connect the Octatrack USB port to Outbox 8. In Elektron's Outbox app, match Main / USB 1/2 to physical outputs 1/2 and Cue / USB 3/4 to physical outputs 3/4. Modwerk stores this plan; it does not program the Outbox hardware. -3. Use and reset: Main is the final stereo mix; Cue is the separate stereo Cue bus. Outputs 5/6 and 7/8 are off. To use different signals, change and save the source and assignments, rebuild, and update the external app. Stop the stream before changing cabling. +### Record a mix or send Main + Cue to Outbox -[Open Elektron's Outbox app](https://app.elektron.se/outbox8). Choose Computer and Use classic 20-channel setup to return to the previous implementation. +1. Load the USB Audio module. Open PROJ > MODWERK > SETTINGS > USB AUDIO and select OUTBOX 8 under SEND TO. +2. Choose MAIN + CUE under LAYOUT. Set OUT 1/2 to MAIN and OUT 3/4 to CUE. Pick OFF for the remaining outputs. +3. In the Outbox app assign the four USB pairs to their corresponding physical outputs. You can now change the source for each pair on the Octatrack. -For a computer, select the Octatrack USB audio input in your DAW and use -the shown stereo channel pairs. Full multichannel operation needs a -high-speed host. USB input / Crossbar are outside this release. No sample -rate, bit depth or native track-control defaults are changed by the GUI. +[Open Elektron’s Outbox app](https://app.elektron.se/outbox8). ## Compatibility and limitations -- Original Octatrack OS 1.40C only; inherited stock is recovered and guarded - from the visitor's verified local file. No firmware is distributed. -- Like every DRAM module, the build gives up about 10 MB of sample memory - to the platform reserve; the finished build shows how much it reserves. A - project that filled Flex and recorder memory on the stock OS can then show - OUT OF MEMORY when a Flex sample loads. Shorten the recorder reservation - in the project's memory settings or the recorders' RLEN, or load long - samples into a Static machine - ([#433](https://github.com/repeat98/modwerk/issues/433)). -- One USB audio source per build. The required shared USB MIDI receiver, - clock timestamp path and combined ISR are included. -- Outbox UAC2 accepts the 44.1 kHz SET_CUR control data stage and rejects - unsupported rates. Hardware handshake operation has not been tested. -- At full speed, track layouts fall back to a stereo sum and Main + Cue - to Main. Full multichannel operation requires high-speed USB. -- The selected shared stack produces only while streaming, clears the - startup cushion on reopening, and requests alternate setting 0 on USB - reset/session end. Cable recovery and startup audio on actual hardware - are untested. Windows and Linux host behaviour are untested. -- Classic configurations preserve their older source path and schema. - New backups use schema 4 and include the USB settings and routing plan. - Old configurations are not silently assigned new audio settings. -- Post-LEVEL tap timing and master exclusions are described above. - Current-build hardware, real-chip cycles, canaries, and complete memory - bounds are unmeasured. Historical upstream results do not qualify 0.2. +USB Audio 0.3.0-experimental requires the configurable USB Audio hooks introduced in Modwerk’s Octatrack base 0.7.12. If you use base 0.7.11 or earlier, update the base, then load your existing set to restore its saved routing. + +- Built for Octatrack OS 1.40C. USB Audio supports output only. Multichannel recording needs a high-speed USB connection. +- The DRAM platform reserves about 10 MB of sample memory. A project that filled Flex and recorder memory can show OUT OF MEMORY. Shorten its recorder reservation or use a Static machine for long samples. [Memory guidance](https://github.com/repeat98/modwerk/issues/433). +- The physical Outbox 8 and Windows and Linux hosts remain untested on this release candidate. ## Tests and measurements -[TESTING.md](TESTING.md) records commands, evidence and coverage limits. -[evidence/layouts.json](evidence/layouts.json) contains hashes and linked -section sizes for six layouts alone, with Quantizer, and with Tape Echo + -Euclid. The shared build/import pipeline reproduces the source-only -packages in isolation, without firmware or network. Original firmware -integrity, stock descriptor/curve checks and packaging round trips remain -required. - -CPU badges are relative estimates. Pinned upstream streaming USB-hook -instruction counts per 16-sample block are Main/Cue 827, pre-LEVEL Tracks -2,639, Tracks + Main + Cue 3,438 and post-LEVEL Tracks 4,278. Main and Track 8 -are low source estimates with comparable timing unreported. These are port -instruction observations, not chip cycle or whole-device CPU percentages. -Linked section sizes do not establish complete stack / DMA bounds. +The default 0.3 package contains 10,288 bytes of initialized image and 94,152 bytes of BSS. Worst-case ColdFire cycles and complete memory use including stack and DMA remain unmeasured. See the build-specific reconnect, recording and persistence results in [TESTING.md](TESTING.md). Historical 0.2 layout sizes and source hashes are in [evidence/layouts.json](evidence/layouts.json). ## Authorship and licences -Mark Roberts (markandrus/octemu) wrote USB audio/MIDI; Bryan T contributed -Main/Cue channels and alignment work; Sam Banks and Octabam contributors +Mark Roberts (markandrus/octemu) wrote USB audio/MIDI. Bryan T contributed +Main/Cue channels and alignment work. Sam Banks and Octabam contributors added layouts, shared-stack integration and Outbox support. allmyfriendsaresynths (@clickysteve) contributed the post-LEVEL gain engine. Modwerk adds -the configurator, configuration persistence and shared-composer packaging. -The imported source is MIT: see [LICENSE](LICENSE), source comments, +the configurator, on-instrument settings, saved routing and module packaging. +The imported source is available under the MIT licence. See [LICENSE](LICENSE), source comments, [layouts/UPSTREAM-AUDIO.md](layouts/UPSTREAM-AUDIO.md) and [layouts/UPSTREAM-POST.md](layouts/UPSTREAM-POST.md). Exact imported file identities are in the source-only package and SDK import record. See [LEGACY.md](LEGACY.md) for preserved classic documentation and historical measurements. Elektron rights remain reserved for locally recovered stock. + ## Screens and audio -This automatic USB contribution adds no dedicated Octatrack page or -controls, so `access.noUiReason` documents the narrow publication -exception. Modwerk's existing module page presents the setup and USB -channel map. No hardware LCD image, host enumeration screenshot or audio -capture is claimed. Current software-only verification and the hardware -waiver are stated explicitly in TESTING.md. +These MKII emulator captures show the settings list, USB Audio fields, track tap and Outbox source assignments. [Capture details](media/capture.json). + +![The SETTINGS list with USB AUDIO selected](media/ot-settings.png) + +![USB Audio fields and their selected values](media/ot-usb-audio.png) + +![PRE LEVEL and POST LEVEL choices](media/ot-track-tap.png) + +![Sources for the four Outbox stereo pairs](media/ot-outbox-pairs.png) diff --git a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/TESTING.md b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/TESTING.md index 82059ae807..1af6994884 100644 --- a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/TESTING.md +++ b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/TESTING.md @@ -1,4 +1,24 @@ -# USB Audio 0.2 testing +# USB Audio testing + +## 0.3.0-experimental on an Octatrack MKII, 20 November 2026 + +The four [menu captures](media/capture.json) show the 0.7.12 release candidate `254c5a75a139` running the migrated Outbox set in the MKII emulator. They show the settings list, USB Audio fields, both stem taps and the four output assignments. The images were taken from the display bytes sent to the emulated panel. + +**Release build 0.7.12 `254c5a75a139` passed reconnect, Keep and physical cold restoration.** The MKII recorded and undid eight migrated sets across all five channel counts. Both Track 8/Master trials reconnected, every Undo restored the baseline, and the instrument self-test passed. After Keep and a physical power cycle the release base read the same preset and saved-set checksum from the card without uploading a module. macOS recorded 89,088 stereo frames. A final power cycle restored the original ten modules and their full checksum. The [release record](../../../../docs/verification/2026-11-20-octatrack-usb-audio-package.md#release-verification-on-base-0712) gives the image hashes, channel and frame counts, Outbox pair results and hardware limits. + +**Earlier development base 0.7.11 `c7eba65fa9ec` also passed reconnect, Keep and card restoration.** On the owner’s Octatrack MKII, macOS recorded eight RAM trials at 44.1 kHz. The widths in order were 16, 2, 2, 4, 8, 16, 20 and 2 channels. Both Track 8/Master trials recorded 88,576 frames. Every Undo restored the starting set checksum and the base’s four USB interfaces. The panel tick advanced after all eight. The base counted 16 attachments across eight installs and eight Undos. The additional attachment retry did not run during this sequence. + +The standalone self-test reported one intact module and zero failures. Keep reported one saved module. The owner power-cycled the unit with its usual card seated. The flashed base restored the ten original modules. RAM-booting the identical 0.7.11 base after the physical power cycle restored the kept Track 8/Master preset `0x80000110` and the exact pre-cycle set checksum without a module upload. macOS then recorded 89,088 stereo frames. A final power cycle restored the ten original modules and their complete starting checksum. The release base ran from RAM throughout. Windows, Linux and physical Outbox outputs were unavailable. The eight-channel USB recording had identical nonzero audio on the two Main assignments and silence on the Off pair in all 88,576 frames. + +**Earlier candidate failed on Track 8/Master.** The rebuilt base `e0cbd7173d0b` passed seven RAM trials on the MKII. On the eighth trial it acknowledged the migrated Track 8/Master set and disappeared from USB before recording. The hub failed to enable the port. A software Undo could not be confirmed. The candidate was never kept. The same configurable module recorded at 2, 4, 8, 16 and 20 channels. Both 16-channel post-LEVEL trials returned to the original USB configuration and set checksum after Undo. The UI tick continued advancing after each of the seven successful reconnects. During the eighth trial the owner confirmed that the panel still responded. A cold start restored the original flashed base and all ten modules, with an exact match to the starting saved-set checksum. A physical Outbox was unavailable. + +**The previous base `a2ae64eb82bc` failed during Undo.** Two saved 0.2 configurations restored the selected destination, layout and routing on an Octatrack MKII. macOS recorded 89,600 frames each on eight and sixteen channels. Undo restored USB after the Outbox trial. After the sixteen-channel post-LEVEL trial the panel froze and USB disappeared. A cold start restored the responsive instrument and all ten original modules. That earlier candidate did not reach Keep or the cold-start test. + +The release package is 11,804 bytes. Its loader header declares 10,288 bytes of initialized image and 94,152 bytes of zero-initialized storage, 230 relocations, and three guarded sites. These figures exclude loader bookkeeping, stack use, and shared base reservations. The [0.3 owner exception](../../../approvals/usb-audio-out-tracks-main-cue-build-approval.json) covers worst-case ColdFire cycles and the complete memory bound including stack and DMA. It is conditional on reconnect, Keep and physical power-cycle verification on the release build. + +Build identities, retained freeze diagnostics and the recovery check are in the [unit verification record](../../../../docs/verification/2026-11-20-octatrack-usb-audio-package.md#migrated-sets-on-the-03-release-candidate). + +## Historical 0.2 testing Version: `0.2.0-experimental`. Selected-layout source revision: `7b2984c859732ae6c797ae49c7d61d250b1b6519`. diff --git a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/capture.json b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/capture.json new file mode 100644 index 0000000000..9ca424d7a7 --- /dev/null +++ b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/capture.json @@ -0,0 +1,178 @@ +{ + "firmware": "1.40C", + "sourceRevision": "506d0ecf7c97a17c1906422c25cafafb77b3086d", + "moduleVersion": "0.3.0-experimental", + "setup": "Octatrack MKII panel in ot_emu, stopped transport, Outbox preset loaded from the disposable card. Actual panel output at 6\u00d7 integer scale.", + "output": "Decoded LCD blocks from the emulator panel transmit stream using Octabam PanelLink.", + "imageSha256": "08e13819fc8fade5b1c69f4086537b648d0c4b4f60df78119e1b966a3e05af7a", + "emulatorSha256": "a2151c36f1f1f4e04b9eb9a43c61a4a36079c6384092fa2547e45709418b32dc", + "cardSha256": "cb03f60e670ed47afffa454f46539aa90cdf7a0cbf2e5dbd559e35dba9d38043", + "keyMs": 150, + "plan": [ + { + "wait": 3000 + }, + { + "press": [ + "YES" + ] + }, + { + "wait": 3000 + }, + { + "press": [ + "NO" + ] + }, + { + "wait": 300 + }, + { + "press": [ + "MENU" + ] + }, + { + "wait": 200 + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "RIGHT" + ] + }, + { + "wait": 200 + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "YES" + ] + }, + { + "wait": 300 + }, + { + "capture": "ot-settings.png" + }, + { + "press": [ + "YES" + ] + }, + { + "wait": 300 + }, + { + "capture": "ot-usb-audio.png" + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "YES" + ] + }, + { + "wait": 300 + }, + { + "capture": "ot-track-tap.png" + }, + { + "press": [ + "NO" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "press": [ + "DOWN" + ] + }, + { + "wait": 300 + }, + { + "capture": "ot-outbox-pairs.png" + } + ], + "screenshots": { + "ot-settings.png": "470c542f70e1121220d954b5c44f1972f6420d5dca7dfadfc801e02ff3307e0b", + "ot-usb-audio.png": "eab450c221d757813f9d23987466566454e252dfcee9316199ae21eebce0c5de", + "ot-track-tap.png": "bfaa7930eb1f537ec6b4069a0c5c22e4c3f74d2c70ba258dd7f836cd7846a461", + "ot-outbox-pairs.png": "a0fc17d440e47a71a08feb3f8f7d83dfe25c64a39620d04f8ac5c9519e8cfd74" + } +} diff --git a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-outbox-pairs.png b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-outbox-pairs.png new file mode 100644 index 0000000000..971347e8f1 Binary files /dev/null and b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-outbox-pairs.png differ diff --git a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-settings.png b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-settings.png new file mode 100644 index 0000000000..22e3716240 Binary files /dev/null and b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-settings.png differ diff --git a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-track-tap.png b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-track-tap.png new file mode 100644 index 0000000000..8638d7aab8 Binary files /dev/null and b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-track-tap.png differ diff --git a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-usb-audio.png b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-usb-audio.png new file mode 100644 index 0000000000..987106ce17 Binary files /dev/null and b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/media/ot-usb-audio.png differ diff --git a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/octamod.module.json b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/octamod.module.json index 50493f2be3..a84b8611e9 100644 --- a/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/octamod.module.json +++ b/sdk/octatrack/modules/usb-audio-out-tracks-main-cue/octamod.module.json @@ -1,8 +1,77 @@ { "schemaVersion": 2, - "version": "0.2.0-experimental", + "version": "0.3.0-experimental", "nativeManifest": "manifest.py", - "media": [], + "media": [ + { + "path": "media/ot-settings.png", + "captureType": "emulator", + "caption": "Open PROJ, choose MODWERK and open SETTINGS. Highlight USB AUDIO and press YES.", + "alt": "SETTINGS lists USB AUDIO with a right-facing selection arrow and YES OPEN.", + "credit": "Modwerk, Octatrack MKII emulator capture", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "SETTINGS", + "shows": "location", + "firmware": "1.40C", + "moduleVersion": "0.3.0-experimental", + "imageSha256": "08e13819fc8fade5b1c69f4086537b648d0c4b4f60df78119e1b966a3e05af7a", + "setup": "Octatrack MKII panel in ot_emu, stopped transport, Outbox preset loaded from the disposable card. Actual panel output at 6× integer scale." + } + }, + { + "path": "media/ot-usb-audio.png", + "captureType": "emulator", + "caption": "Open SEND TO to choose a computer or Outbox 8. Open LAYOUT to choose which tracks or mixes to send.", + "alt": "USB AUDIO shows SEND TO set to OUTBOX 8, LAYOUT to 20 CH, TRACK TAP to PRE LEVEL and OUTPUT MODE to ALL.", + "credit": "Modwerk, Octatrack MKII emulator capture", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "USB AUDIO", + "shows": "location-and-controls", + "firmware": "1.40C", + "moduleVersion": "0.3.0-experimental", + "imageSha256": "08e13819fc8fade5b1c69f4086537b648d0c4b4f60df78119e1b966a3e05af7a", + "setup": "Octatrack MKII panel in ot_emu, stopped transport, Outbox preset loaded from the disposable card. Actual panel output at 6× integer scale." + } + }, + { + "path": "media/ot-track-tap.png", + "captureType": "emulator", + "caption": "On either track layout, open TRACK TAP. Choose PRE LEVEL for stems before track level, or POST LEVEL to record level changes.", + "alt": "TRACK TAP shows PRE LEVEL selected and POST LEVEL below it.", + "credit": "Modwerk, Octatrack MKII emulator capture", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "TRACK TAP", + "shows": "controls", + "firmware": "1.40C", + "moduleVersion": "0.3.0-experimental", + "imageSha256": "08e13819fc8fade5b1c69f4086537b648d0c4b4f60df78119e1b966a3e05af7a", + "setup": "Octatrack MKII panel in ot_emu, stopped transport, Outbox preset loaded from the disposable card. Actual panel output at 6× integer scale." + } + }, + { + "path": "media/ot-outbox-pairs.png", + "captureType": "emulator", + "caption": "With OUTBOX 8 selected, open each output pair and choose its source. Here the first two pairs carry Main, the third is silent and the last carries Cue.", + "alt": "USB AUDIO shows OUT 1/2 MAIN, OUT 3/4 MAIN, OUT 5/6 OFF and OUT 7/8 CUE, with OUT 7/8 highlighted.", + "credit": "Modwerk, Octatrack MKII emulator capture", + "license": "LicenseRef-OT-UI-Documentation", + "source": "original", + "otUi": { + "page": "USB AUDIO outputs", + "shows": "controls", + "firmware": "1.40C", + "moduleVersion": "0.3.0-experimental", + "imageSha256": "08e13819fc8fade5b1c69f4086537b648d0c4b4f60df78119e1b966a3e05af7a", + "setup": "Octatrack MKII panel in ot_emu, stopped transport, Outbox preset loaded from the disposable card. Actual panel output at 6× integer scale." + } + } + ], "id": "usb-audio-out-tracks-main-cue", "key": "USB AUDIO OUT TRACKS MAIN CUE", "name": "USB Audio", @@ -21,17 +90,17 @@ "label": "USB AUDIO", "family": "USB audio", "summary": "Record stereo mixes or individual tracks over USB, or send them to Outbox 8 at 44.1 kHz and 24 bits.", - "overview": "Choose one USB output layout in Modwerk: Main, Main + Cue, Track 8 / Master, eight tracks before LEVEL, eight tracks following LEVEL, or eight tracks plus Main and Cue. The updated shared USB stack supports the Outbox 8 44.1 kHz handshake. Modwerk stores a routing plan; apply its USB channel pairs separately in Elektron\u2019s Outbox app. Existing configurations without USB settings keep the classic twenty-channel implementation.", + "overview": "Install USB Audio once. Open PROJ > MODWERK > SETTINGS > USB AUDIO to choose a computer layout, a track tap, or four stereo sends for Outbox 8. Existing Modwerk sets supply their saved routing when loaded.", "highlights": [ - "Six selectable stereo output layouts; 2 to 20 USB channels", - "Outbox 8 rate handshake and shared audio / MIDI reset handling", - "Saved four-pair Outbox routing plan and per-layout CPU estimates" + "Stereo mixes or eight track stems, plus optional Main and Cue", + "Pre-LEVEL or post-LEVEL stems in both track layouts", + "Four assignable Outbox stereo pairs, including duplicates and silence" ], "usage": [ - "Open USB Audio setup, choose Computer or Outbox 8, and select the audio to send. Read the signal-tap description and save the setup before adding it.", - "For Outbox 8, assign up to four stereo sources to the physical outputs. Match the shown USB pairs in Elektron\u2019s Outbox app; Modwerk does not program the Outbox.", - "For Computer, select the Octatrack USB input in your recording software and use the shown stereo channel pairs. Full multichannel operation requires high-speed USB.", - "To return to the classic twenty-channel source, choose Computer and Use classic 20-channel setup. This removes the new settings; existing saved configurations without USB settings keep their prior code path." + "Install USB Audio and open PROJ > MODWERK > SETTINGS > USB AUDIO.", + "Choose COMPUTER and a LAYOUT. In either track layout, choose PRE LEVEL or POST LEVEL under TRACK TAP.", + "Choose OUTBOX 8 and select the source or OFF for each output pair. Map the four USB pairs to their physical outputs in the Outbox app.", + "Open OUTPUT MODE to silence USB Audio or to send only Main and Cue in the twenty-channel layout." ] }, "controls": [], @@ -39,31 +108,24 @@ "firmware": "1.40C", "effectId": null, "location": "USB", - "conflicts": [ - "usb-audio-out-main", - "usb-audio-out-main-cue", - "usb-audio-out-master", - "usb-audio-out-tracks" - ], + "conflicts": [], "limitations": [ "Output only, fixed 44.1 kHz / 24-bit; USB input and Crossbar variants are excluded.", - "One audio layout per build; shared USB MIDI is included.", "Like every DRAM module, gives up about 10 MB of sample memory: projects that filled Flex/recorder memory can show OUT OF MEMORY. Shorten recorder reservations or load long samples into Static (#433).", - "Outbox assignments are a plan and must be applied in Elektron\u2019s Outbox app.", "At full speed, track feeds fall back to a stereo sum and Main + Cue to Main.", - "Post-LEVEL tracks exclude MAIN LEVEL and master effects on tracks 1\u20137. With a master track, tracks 1\u20137 lead track 8 by 32 samples.", - "Current-build Octatrack / Outbox operation, chip timing, complete memory bounds, Windows and Linux host behavior are not tested." + "Post-LEVEL tracks exclude MAIN LEVEL and master effects on tracks 1–7. With a master track, tracks 1–7 lead track 8 by 32 samples.", + "The current build ran on an Octatrack MKII with macOS. Physical Outbox 8 outputs, Windows and Linux hosts, worst-case ColdFire cycles and complete memory bounds remain untested." ] }, "resources": { - "recorded": "29 Sep 2026 (upstream record)", + "recorded": "20 November 2026, configurable release package", "storage": { - "label": "Audio rings", - "display": "Depends on USB layout", + "label": "Runtime memory", + "display": "Full bound unmeasured", "value": null, "unit": "bytes", "method": "unmeasured", - "conditions": "Exact linked section sizes are recorded per layout in evidence/layouts.json; the historical 88 KiB figure applies to the classic twenty-channel path. Complete stack / DMA and hardware memory bounds have not been measured.", + "conditions": "USB Audio 0.3 allocates 10,288 initialized bytes and 94,152 zero-initialized bytes for every layout. The complete bound including stack and DMA remains unmeasured.", "source": "README.md" }, "processing": { @@ -92,16 +154,16 @@ "memory": { "level": "moderate", "basis": "source-estimate", - "rationale": "The selected source determines the static audio ring footprint. Linked sections are recorded for all six layouts in evidence/layouts.json. This tier describes source allocation sizes, not a complete hardware memory bound.", + "rationale": "All layouts use the same release package. Its linked section sizes are recorded in TESTING.md. Complete memory use including stack and DMA remains unmeasured.", "source": "README.md" } } }, "tests": { "report": "TESTING.md", - "summary": "Software checks cover six source-only layouts, GNU runtime linking, guarded hooks, packaging and configuration persistence. Owner approved this experimental release without physical hardware testing. Hardware operation, real-chip timing and complete memory bounds remain unmeasured.", - "hardwareStatus": "untested", - "evidenceRevision": "7b2984c859732ae6c797ae49c7d61d250b1b6519", + "summary": "On an Octatrack MKII, macOS recorded all five widths. Track 8/Master reconnected and survived Undo twice. Keep and card restoration after a physical power cycle passed on the same release image. See TESTING.md for build identities and limits.", + "hardwareStatus": "reported", + "evidenceRevision": "d55bb5f4df08451efa4fe6f9feac2f23c985a2a2", "gates": [ "tools/verify/verify_usb.py", "tools/verify/verify_usb_align.py" @@ -110,12 +172,17 @@ "tutorial": { "title": "Record a mix or send Main + Cue to Outbox", "steps": [ - "Choose and save: open USB Audio setup, choose Outbox 8 and Main + Cue mixes, then Assign in order. Save the setup to the named configuration and build locally from your own OS 1.40C file.", - "Connect and route: connect the Octatrack USB port to Outbox 8. In Elektron's Outbox app, match Main / USB 1/2 to physical outputs 1/2 and Cue / USB 3/4 to physical outputs 3/4. Modwerk stores this plan; it does not program the Outbox hardware.", - "Use and reset: Main is the final stereo mix; Cue is the separate stereo Cue bus. Outputs 5/6 and 7/8 are off. To use different signals, change and save the source and assignments, rebuild, and update the external app. Stop the stream before changing cabling." + "Load the USB Audio module. Open PROJ > MODWERK > SETTINGS > USB AUDIO and select OUTBOX 8 under SEND TO.", + "Choose MAIN + CUE under LAYOUT. Set OUT 1/2 to MAIN and OUT 3/4 to CUE. Pick OFF for the remaining outputs.", + "In the Outbox app assign the four USB pairs to their corresponding physical outputs. You can now change the source for each pair on the Octatrack." ] }, - "screenshots": [], + "screenshots": [ + "media/ot-settings.png", + "media/ot-usb-audio.png", + "media/ot-track-tap.png", + "media/ot-outbox-pairs.png" + ], "screenshotStyle": "black-and-white" } }, @@ -130,13 +197,17 @@ "declaration": "Imported original/MIT-licensed sources with upstream copyright, author attribution and exact commit pins retained. No firmware, extracted stock routines, recordings or screenshots imported. Contributor licensing statements are retained in LICENSE; owner/reviewer verification is required before publication and is not automatic legal clearance." }, "access": { - "location": "The Octatrack USB port and your recording host\u2019s audio input selector.", + "location": "PROJ > MODWERK > SETTINGS > USB AUDIO", "steps": [ - "Open USB Audio setup, choose Computer or Outbox 8, and select the audio to send. Read the signal-tap description and save the setup before adding it.", - "For Outbox 8, assign up to four stereo sources to the physical outputs. Match the shown USB pairs in Elektron\u2019s Outbox app; Modwerk does not program the Outbox.", - "For Computer, select the Octatrack USB input in your recording software and use the shown stereo channel pairs. Full multichannel operation requires high-speed USB." + "Open SETTINGS, highlight USB AUDIO and press YES. Open a field to see its choices. Press YES to select one or NO to go back.", + "For a computer, choose COMPUTER and a layout. TRACK TAP offers PRE LEVEL and POST LEVEL for the 16- and 20-channel track layouts.", + "For Outbox 8, choose OUTBOX 8 and assign the four stereo pairs. In the Outbox app, map USB pairs 1–4 to the four desired physical output pairs. Subsequent source changes take place on the Octatrack." ], - "screenshots": [], - "noUiReason": "This automatic USB output contribution adds no dedicated OT page, chooser entry or panel controls. Access is through the USB connection and the host\u2019s audio input selector. The reviewer must verify this absence of OT UI against the pinned source before publication." + "screenshots": [ + "media/ot-settings.png", + "media/ot-usb-audio.png", + "media/ot-track-tap.png", + "media/ot-outbox-pairs.png" + ] } } diff --git a/sdk/tests/test_usb_audio_package.py b/sdk/tests/test_usb_audio_package.py new file mode 100644 index 0000000000..46fbe5f88d --- /dev/null +++ b/sdk/tests/test_usb_audio_package.py @@ -0,0 +1,128 @@ +# SPDX-License-Identifier: GPL-3.0-or-later +"""USB Audio as a runtime package (module-adapters/usb_audio_package.py): what the builder makes of the authored source.""" +import importlib.util +import shutil +import struct +import sys +import subprocess +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +OT = ROOT / 'sdk/machines/octatrack' +sys.path.insert(0, str(OT)) +import events # noqa: E402 + + +def load(name, path): + spec = importlib.util.spec_from_file_location(name, path) + module = importlib.util.module_from_spec(spec); spec.loader.exec_module(module) + return module + + +builder = load('usb_audio_package', OT / 'module-adapters/usb_audio_package.py') +usb = load('modwerk_usb_base', OT / 'elekloader/usb_base.py') +functions = load('modwerk_base_usb_functions', OT / 'module-adapters/base_usb_functions.py') +LAYOUT = 'USB AUDIO OUT TRACKS MAIN CUE' + + +class UsbAudioPackage(unittest.TestCase): + def test_configurable_packet_router_and_saved_settings(self): + with tempfile.TemporaryDirectory() as temp: + exe = Path(temp) / 'router' + subprocess.run(['cc', '-std=c99', '-Wall', '-Wextra', '-Werror', '-I', OT / 'include', + OT / 'elekloader/test_usb_audio_settings.c', '-o', exe], check=True) + subprocess.run([exe], check=True) + + @unittest.skipUnless(shutil.which('m68k-elf-gcc'), 'no ColdFire toolchain') + def test_one_configurable_package_describes_every_output_width(self): + data, facts = builder.build(None) + self.assertEqual(struct.unpack_from('>H', data, 66)[0], 7) + self.assertLess(facts['image'] + facts['bss'], 128 * 1024) + hook_count = struct.unpack_from('>I', data, 20)[0] + hook_index = next(e['index'] for e in events.load()['events'] if e['event'] == 'ot_usb_functions') + function = struct.unpack_from('>I', data, 76 + hook_index * 4)[0] & 0xffffff + image_at = 76 + hook_count * 4 + image = data[image_at:image_at + facts['image']] + self.assertGreater(hook_count, hook_index) + self.assertEqual(struct.unpack_from('>IIHHI', image, function), (2, 36, 2, facts['block'], 0x80000)) + self.assertEqual(struct.unpack_from('>HBB', image, function+32), (5,0,0)) + for speed, offset in enumerate(struct.unpack_from('>4I', image, function+16)): + for i, width in enumerate([20,16,4,2,8]): + at = offset + i*facts['block'] + descriptors = list(builder._records(image[at:at+facts['block']])) + channels = width if speed % 2 else 2 + self.assertEqual(next(r[8] for r in descriptors if r[:3] == bytes([17,0x24,2])), channels) + self.assertEqual(next(r[10] for r in descriptors if r[:3] == bytes([16,0x24,1])), channels) + endpoint = next(r for r in descriptors if r[:3] == bytes([7,5,0x83])) + self.assertEqual(int.from_bytes(endpoint[4:6], 'little'), channels * 4 * (12 if speed % 2 else 45)) + + def test_the_function_block_is_what_a_linked_base_sends_behind_its_own_interfaces(self): + descriptors = load('descriptors', usb.audio_paths(LAYOUT)[1]) + blocks = [builder.function_block(functions, usb, descriptors, LAYOUT, hs, other) + for hs, other in ((False, False), (True, False), (False, True), (True, True))] + self.assertEqual(len({len(b) for b in blocks}), 1) + for (hs, other), block in zip(((False, False), (True, False), (False, True), (True, True)), blocks): + without = functions.configuration(usb, descriptors, hs, other, None) + whole = functions.configuration(usb, descriptors, hs, other, LAYOUT) + self.assertEqual(without[9:] + block, whole[9:]) + self.assertLessEqual(len(without) + len(block), functions.SLOT) + records = list(builder._records(block)) + self.assertEqual(sum(len(r) for r in records), len(block)) + self.assertEqual(records[0][:4], bytes([8, 11, 4, 2])) # the association: two interfaces from 4 + self.assertEqual(sorted({r[2] for r in records if r[1] == 4}), [4, 5]) + self.assertEqual([r[2] for r in records if r[1] == 5], [0x83]) # endpoint 3 IN alone + self.assertIn('.short 2, %d' % len(blocks[0]), builder.record(blocks)) + + def test_the_source_keeps_the_import_and_changes_only_its_guarded_seams(self): + text = builder.source(functions, usb, LAYOUT) + self.assertNotIn('usbmidi_rx_isr_shim', text.split('| ---- the package', 1)[0].split('audio_isr_shim:', 1)[1].split('\n\n', 1)[0]) + self.assertNotIn('jmp 0x4000d9a6', text) # the base replays the frame site's displaced clear + self.assertNotIn('#(aud_dtds+UNCACHED),', text) # every use reads the run-time boundary + self.assertEqual(text.count('moveal mwua_dtds,'), 3) + self.assertIn('.set UAC2_AC_IFACE, 4 ', text) + with self.assertRaisesRegex(ValueError, 'Not built as a package yet'): + builder.build('USB AUDIO IN') + + def test_the_setting_offers_main_and_cue_only_in_the_twenty_channel_layout(self): + twenty, tracks = builder.source(functions, usb, LAYOUT), builder.source(functions, usb, 'USB AUDIO OUT TRACKS') + self.assertIn(' .long 1, mwua_set_label, 3, mwua_set_choices, mwua_setting_apply, 0', twenty) + self.assertIn(' .long 1, mwua_set_label, 2, mwua_set_choices, mwua_setting_apply, 0', tracks) + for text in (twenty, tracks): # OFF is the second choice everywhere: the kept choice means the same + self.assertIn('mwua_set_0: .asciz "ALL CHANNELS"\nmwua_set_1: .asciz "OFF"\n', text) + self.assertIn(' tstb modwerk_usb_audio_off | the player\'s OFF', text) + self.assertIn('mwua_set_2: .asciz "MAIN + CUE ONLY"', twenty) + self.assertNotIn('mwua_set_2', tracks) + + def test_tracks_post_takes_the_computed_sine_and_no_stock_table(self): + usb_post = load('usb_post', OT / 'elekloader/usb_post.py') + curve = builder.sine_curve(usb_post) + self.assertEqual((len(curve), curve[0], curve[1], curve[255]), (256, 0, 51472, 8388449)) + self.assertEqual(curve, sorted(set(curve))) + text = builder.source(functions, usb, usb.POST_LAYOUT) + self.assertIn('.set USB_LAYOUT, 5', text) + self.assertIn('.macro POST_XLV_TABLE\n .long 0x000000\n .long 0x00c910\n', text) + self.assertNotIn('MW_AUDIO_READY', text) # the 20-channel packet watermark is not POST's + self.assertEqual(text.count('moveal mwua_dtds,'), 3) + + def test_the_package_subscribes_to_the_four_hooks_and_carries_three_guarded_sites(self): + if not shutil.which('m68k-elf-as'): + self.skipTest('no m68k-elf-as') + data, facts = builder.build(LAYOUT) + self.assertEqual((data[:4], struct.unpack_from('>H', data, 4)[0]), (b'MWRM', 8)) + self.assertEqual(facts['sites'], ['0x4001dd04', '0x4001d824', '0x4001d4b2']) + self.assertLess(facts['image'], 8192) + self.assertLess(facts['image'] + facts['bss'], 128 * 1024) + image, bss, relocations, hooks, sites = struct.unpack_from('>IIIII', data, 8) + self.assertEqual((image, bss, relocations, sites), (facts['image'], facts['bss'], facts['relocations'], 3)) + words = struct.unpack_from('>%dI' % hooks, data, 76) + by_name = {e['event']: e['index'] for e in events.load()['events']} + subscribed = {name for name, index in by_name.items() if index < hooks and words[index] != 0xffffffff} + self.assertEqual(subscribed, {'ot_usb_functions', 'ev_usb_isr', 'ev_usb_bus_end', 'ev_usb_control', 'ev_usb_frame', 'ot_settings'}) + self.assertTrue(all(w == 0xffffffff for w in words[:4])) # no tick, draw, key or encoder handler + self.assertEqual(struct.unpack_from('>H', data, 66)[0], 1) # its layout number: the define of TRACKS MAIN CUE, plus one + + +if __name__ == '__main__': + unittest.main() diff --git a/src/App.tsx b/src/App.tsx index 90101f1d95..25f0eb9125 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -55,7 +55,7 @@ import type { HubView, SetAction } from './components/OctatrackHub' import type { OctatrackLink } from './engine/elekloader/octatrack-link' import type { BaseLayout } from './engine/elekloader/base-variants' import type { BaseGuideFailure, BaseGuideStage } from './components/BaseInstallDialog' -import { missingFromProject, sameModules, UNIT_STATE, unitState, type LastSeen } from './config/inventory' +import { inventoryUsbAudio, matchesUsbAudio, missingFromProject, sameModules, UNIT_STATE, unitState, type LastSeen } from './config/inventory' import { ShareModuleButton } from './community/ShareModuleButton' import { useBaseInstallPrompt } from './hooks/useBaseInstallPrompt' import { OctatrackLinkContext, useInventory, useMissing } from './hooks/useOctatrackLink' @@ -450,8 +450,10 @@ export default function App() { const [putBackId, setPutBackId] = useState(), [putBackOff, setPutBackOff] = useState([]) function putBack(last: LastSeen) { setPutBackOff(last.offIds ?? []) - const id = configurationsFor('octatrack').find(set => sameModules(set.moduleIds.filter(module => !comesWithBase(module)), last.moduleIds))?.id - ?? workspace.importConfiguration('From my Octatrack', last.moduleIds, true, undefined, 'octatrack', undefined, last.removedStockFx) + const matches = configurationsFor('octatrack').filter(set => sameModules(set.moduleIds.filter(module => !comesWithBase(module)), last.moduleIds) && + matchesUsbAudio(set.usbAudio, last)) + const id = (matches.find(set => set.id === active?.id) ?? matches[0])?.id + ?? workspace.importConfiguration('From my Octatrack', last.moduleIds, true, undefined, 'octatrack', last.usbAudio, last.removedStockFx) setPutBackId(id); setLoadingSet(id) } // Replaces the modules a new one cannot run beside. Adding last goes through toggleModule, which also opens USB setup. @@ -493,7 +495,12 @@ export default function App() { if (action === 'share') window.location.hash = 'forum/new?category=configs&machine=' + configurationDevice(item) else setConfigDialog(action) } - function saveUnitAsSet() { if (inventory) { workspace.importConfiguration('From my Octatrack', inventory.moduleIds, true, undefined, 'octatrack', undefined, inventory.removedStockFx); openEditedSet('octatrack') } } + function saveUnitAsSet() { + if (!inventory) return + const audio = inventoryUsbAudio(usbLink?.getState().identity?.base, inventory) + workspace.importConfiguration('From my Octatrack', audio.moduleIds, true, undefined, 'octatrack', audio.usbAudio, inventory.removedStockFx) + openEditedSet('octatrack') + } // Routes that browse a library: they get the search field and, on phones, the category chips under the app bar. const libraryNav = onLibrary || route === 'module-sets' @@ -532,7 +539,7 @@ export default function App() { {!!selectedIds.length && } void importSelection(event)} aria-label="Import module set backup"/>{importError&&

{importError}

}} - grid={<>{availabilityError &&

{availabilityError}

} id === USB_AUDIO_MODULE && active?.usbAudio ? usbAudioLayout(active.usbAudio.layout).name + ' · 0.2 experimental' : !isModuleAvailable(id, betaAccess) ? 'Temporarily unavailable' : MODULES.find(module => module.id === id)?.detail ?? ''} onOpen={setOpenModule} onRemove={toggleModule} onKeep={toggleModule} onSaveUnit={saveUnitAsSet} />} + grid={<>{availabilityError &&

{availabilityError}

} id === USB_AUDIO_MODULE && active?.usbAudio ? usbAudioLayout(active.usbAudio.layout).name : !isModuleAvailable(id, betaAccess) ? 'Temporarily unavailable' : MODULES.find(module => module.id === id)?.detail ?? ''} onOpen={setOpenModule} onRemove={toggleModule} onKeep={toggleModule} onSaveUnit={saveUnitAsSet} />} card={ { setBaseLayoutWanted(layout); setBaseInstall('manual') }} />} /> const categoryNav =