mirror of
https://codeberg.org/uzu/strudel
synced 2026-07-13 06:19:33 -04:00
Merge branch 'main' into vanillarepl
This commit is contained in:
@@ -1,6 +1,9 @@
|
||||
name: Build and Deploy to beta (warm.strudel.cc)
|
||||
|
||||
on: [workflow_dispatch]
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
# Allow one concurrent deployment
|
||||
concurrency:
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# changelog
|
||||
|
||||
NOTE: you can generate this with `node warm.js`. it might still not be perfectly sorted...
|
||||
|
||||
## november 2025
|
||||
|
||||
- 2025-11-27T22:03:53+01:00 [perf] in `noise`, let noiseMix do the disconnect when it exists by jeromew in: [#1783](https://codeberg.org/uzu/strudel/pulls/1783)
|
||||
- 2025-11-27T22:01:01+01:00 Bug Fix: Retries for sounds tab by glossing in: [#1754](https://codeberg.org/uzu/strudel/pulls/1754)
|
||||
- 2025-11-27T20:36:46+01:00 [hydra] return the hydra object when await initHydra(..) is called by jeromew in: [#1784](https://codeberg.org/uzu/strudel/pulls/1784)
|
||||
- 2025-11-27T20:36:14+01:00 Use errorLogger for query and tonal errors by glossing in: [#1782](https://codeberg.org/uzu/strudel/pulls/1782)
|
||||
- 2025-11-27T20:27:10+01:00 [perf] level 5 `connect-leak` on `vowel` by jeromew in: [#1779](https://codeberg.org/uzu/strudel/pulls/1779)
|
||||
- 2025-11-26T08:23:38+01:00 feat: add prebake script import button for loading .strudel files by daslyfe in: [#1774](https://codeberg.org/uzu/strudel/pulls/1774)
|
||||
- 2025-11-26T07:39:28+01:00 Fix Sampler port trampling by Dayglo in: [#1717](https://codeberg.org/uzu/strudel/pulls/1717)
|
||||
- 2025-11-25T20:59:09+01:00 Feat: Hook up octave and fix example by glossing in: [#1773](https://codeberg.org/uzu/strudel/pulls/1773)
|
||||
- 2025-11-25T20:48:09+01:00 [perf] fix `connect-leak` in `tremolo` param by jeromew in: [#1780](https://codeberg.org/uzu/strudel/pulls/1780)
|
||||
- 2025-11-24T17:51:20+01:00 filter modulation improvements! by daslyfe in: [#1769](https://codeberg.org/uzu/strudel/pulls/1769)
|
||||
- 2025-11-24T01:20:53+01:00 Add o as a synonym for orbit by daslyfe in: [#1766](https://codeberg.org/uzu/strudel/pulls/1766)
|
||||
- 2025-11-23T22:23:26+01:00 [perf] fix `connect-leak` in `fm` modulation by jeromew in: [#1758](https://codeberg.org/uzu/strudel/pulls/1758)
|
||||
- 2025-11-23T09:47:24+01:00 Fix interoperability issue between `all` and `await initHydra()` by jeromew in: [#1663](https://codeberg.org/uzu/strudel/pulls/1663)
|
||||
- 2025-11-23T04:23:06+01:00 Bug fix: Swap l/r gains with temp variable by glossing in: [#1768](https://codeberg.org/uzu/strudel/pulls/1768)
|
||||
- 2025-11-23T00:52:28+01:00 FIX: prevent LFO filter modulation from popping from negative values by daslyfe in: [#1767](https://codeberg.org/uzu/strudel/pulls/1767)
|
||||
- 2025-11-21T01:56:11+01:00 Bug Fix: Use frac due to negative frequencies from FM by glossing in: [#1759](https://codeberg.org/uzu/strudel/pulls/1759)
|
||||
- 2025-11-20T19:48:16+01:00 [perf] fix `connect-leak` added by #1742 when noise() is not used by jeromew in: [#1757](https://codeberg.org/uzu/strudel/pulls/1757)
|
||||
- 2025-11-20T14:51:00+01:00 [perf] fix `connect-leak` in `delay` effect by jeromew in: [#1755](https://codeberg.org/uzu/strudel/pulls/1755)
|
||||
- 2025-11-20T14:49:41+01:00 [perf] fix `connect leak` when .noise() is in the mix by jeromew in: [#1742](https://codeberg.org/uzu/strudel/pulls/1742)
|
||||
- 2025-11-18T23:52:45+01:00 wchooseCycles has now notes in an example by scrappy_fiddler in: [#1748](https://codeberg.org/uzu/strudel/pulls/1748)
|
||||
- 2025-11-17T05:31:54+01:00 Feature: Partials by glossing in: [#1659](https://codeberg.org/uzu/strudel/pulls/1659)
|
||||
- 2025-11-16T22:06:14+01:00 README: update superdough documentation by TristanMlct in: [#1741](https://codeberg.org/uzu/strudel/pulls/1741)
|
||||
- 2025-11-16T21:08:54+01:00 Worklet optimizations by glossing in: [#1730](https://codeberg.org/uzu/strudel/pulls/1730)
|
||||
- 2025-11-15T14:59:30+01:00 [perf] disconnect Offline AudioNode connections in generateReverb by jeromew in: [#1740](https://codeberg.org/uzu/strudel/pulls/1740)
|
||||
- 2025-11-15T14:57:47+01:00 [perf] disconnect `send` effect AudioNode when `room` is used by jeromew in: [#1736](https://codeberg.org/uzu/strudel/pulls/1736)
|
||||
- 2025-11-12T21:22:34+01:00 [supradough] fix: unstable filter by froos in: [#1593](https://codeberg.org/uzu/strudel/pulls/1593)
|
||||
- 2025-11-12T21:12:07+01:00 Fix link syntax in `project-start` by Kissaki in: [#1724](https://codeberg.org/uzu/strudel/pulls/1724)
|
||||
- 2025-11-12T21:06:13+01:00 Fix web README sample code by Kissaki in: [#1725](https://codeberg.org/uzu/strudel/pulls/1725)
|
||||
- 2025-11-12T20:59:39+01:00 Fix typo: 'studel' -> 'strudel' by drhayes in: [#1726](https://codeberg.org/uzu/strudel/pulls/1726)
|
||||
- 2025-11-12T15:23:41+01:00 fix for node 24 support in tests - #1718 by ausav in: [#1719](https://codeberg.org/uzu/strudel/pulls/1719)
|
||||
- 2025-11-11T09:00:49+01:00 soundAlias example fix by PepsiiMan in: [#1720](https://codeberg.org/uzu/strudel/pulls/1720)
|
||||
- 2025-11-10T08:18:36+01:00 fix: Make Supradough package build by munshkr in: [#1711](https://codeberg.org/uzu/strudel/pulls/1711)
|
||||
- 2025-11-10T08:18:00+01:00 added docs for spaces in scale names by ondras in: [#1715](https://codeberg.org/uzu/strudel/pulls/1715)
|
||||
- 2025-11-10T02:44:01+01:00 Feature: LFOs for Filters by glossing in: [#1636](https://codeberg.org/uzu/strudel/pulls/1636)
|
||||
- 2025-11-05T17:07:00+01:00 improvement: sync midi messages to audio context clock by daslyfe in: [#1708](https://codeberg.org/uzu/strudel/pulls/1708)
|
||||
- 2025-11-04T19:36:14+01:00 Add stick button mappings to gamepad implementation and improve docs by kaosuryoko in: [#1696](https://codeberg.org/uzu/strudel/pulls/1696)
|
||||
- 2025-11-04T19:29:35+01:00 Refactor sound stopping and triggering logic in SoundsTab component by IJOL in: [#1688](https://codeberg.org/uzu/strudel/pulls/1688)
|
||||
- 2025-11-04T19:13:21+01:00 Add setting to toggle pattern auto-start on pattern change by moumar in: [#1690](https://codeberg.org/uzu/strudel/pulls/1690)
|
||||
- 2025-11-04T18:58:50+01:00 Voicings JSDoc by sharkeys_lunchbox in: [#1686](https://codeberg.org/uzu/strudel/pulls/1686)
|
||||
- 2025-11-01T07:50:40+01:00 FIX: Loading local samples uses too much memory by daslyfe in: [#1706](https://codeberg.org/uzu/strudel/pulls/1706)
|
||||
|
||||
|
||||
## october 2025
|
||||
|
||||
- 2025-10-28T22:58:24+01:00 Bug Fix: Handle scale-for-notes when n also supplied by glossing in: [#1625](https://codeberg.org/uzu/strudel/pulls/1625)
|
||||
- 2025-10-28T22:51:16+01:00 Repurpose vim shortcuts for usability by dtricks in: [#1624](https://codeberg.org/uzu/strudel/pulls/1624)
|
||||
- 2025-10-28T22:35:21+01:00 Add support for euclidian in mondo with `bd&3:8` by TristanCacqueray in: [#1630](https://codeberg.org/uzu/strudel/pulls/1630)
|
||||
- 2025-10-27T10:42:07+01:00 Use bunny cdn for all samples and json files by yaxu in: [#1701](https://codeberg.org/uzu/strudel/pulls/1701)
|
||||
- 2025-10-26T22:52:54+01:00 degithub - switch some samples to bunnycdn by yaxu in: [#1697](https://codeberg.org/uzu/strudel/pulls/1697)
|
||||
- 2025-10-26T17:09:22+01:00 Fix ZZFX example by moumar in: [#1685](https://codeberg.org/uzu/strudel/pulls/1685)
|
||||
- 2025-10-23T15:56:04+02:00 Make osc port and host configurable. Changes dependencies. by yaxu in: [#1682](https://codeberg.org/uzu/strudel/pulls/1682)
|
||||
- 2025-10-23T03:47:31+02:00 Adds back shape to superdough by glossing in: [#1672](https://codeberg.org/uzu/strudel/pulls/1672)
|
||||
- 2025-10-22T22:15:19+02:00 Fix sampler.mjs githubPath by jeromew in: [#1684](https://codeberg.org/uzu/strudel/pulls/1684)
|
||||
- 2025-10-22T16:20:50+02:00 Fix onPaint for widgets by yaxu in: [#1658](https://codeberg.org/uzu/strudel/pulls/1658)
|
||||
- 2025-10-22T15:19:12+02:00 Fix a bug introduced by #4e17cfbdd6 by milliganf in: [#1679](https://codeberg.org/uzu/strudel/pulls/1679)
|
||||
- 2025-10-18T04:29:20+02:00 Bug Fix: Wavetable: phase wrapping at 1 and detune by glossing in: [#1620](https://codeberg.org/uzu/strudel/pulls/1620)
|
||||
- 2025-10-16T20:26:28+02:00 github samples: default to "samples" if repository is not specified by prezmop in: [#1644](https://codeberg.org/uzu/strudel/pulls/1644)
|
||||
- 2025-10-16T17:33:39+02:00 Docs: add example of custom chained function by dariusk in: [#1642](https://codeberg.org/uzu/strudel/pulls/1642)
|
||||
- 2025-10-14T12:39:48+02:00 textbox by yaxu in: [#1650](https://codeberg.org/uzu/strudel/pulls/1650)
|
||||
- 2025-10-13T07:05:57+02:00 Feature: Wavetable FM by glossing in: [#1623](https://codeberg.org/uzu/strudel/pulls/1623)
|
||||
- 2025-10-12T20:43:42+02:00 fix: repair REPL sample sources and URL concat (#1640) by erikfox in: [#1646](https://codeberg.org/uzu/strudel/pulls/1646)
|
||||
- 2025-10-10T11:25:02+02:00 Add control-metadata by yaxu in: [#1634](https://codeberg.org/uzu/strudel/pulls/1634)
|
||||
- 2025-10-07T22:59:39+02:00 Fix MQTT: change the trigger handler to match new hap by jurrchen in: [#1629](https://codeberg.org/uzu/strudel/pulls/1629)
|
||||
- 2025-10-05T21:42:19+02:00 Fix case sensitivity for synonym search by vvolhejn in: [#1618](https://codeberg.org/uzu/strudel/pulls/1618)
|
||||
- 2025-10-01T08:56:35+02:00 Optimize wavetable synth by glossing in: [#1613](https://codeberg.org/uzu/strudel/pulls/1613)
|
||||
- 2025-10-01T02:02:33+02:00 fix: pattern switching by daslyfe in: [#1616](https://codeberg.org/uzu/strudel/pulls/1616)
|
||||
|
||||
## September 2025
|
||||
|
||||
- 2025-09-29T02:10:54+02:00 fix wavetable JSON by daslyfe in: [#1611](https://codeberg.org/uzu/strudel/pulls/1611)
|
||||
- 2025-09-28T21:28:16+02:00 rename wavetable controls to match existing naming conventions by daslyfe in: [#1610](https://codeberg.org/uzu/strudel/pulls/1610)
|
||||
- 2025-09-27T23:28:13+02:00 Feature: Wavetable synth improvements by glossing in: [#1607](https://codeberg.org/uzu/strudel/pulls/1607)
|
||||
- 2025-09-27T21:43:10+02:00 wavetable improvements by daslyfe in: [#1608](https://codeberg.org/uzu/strudel/pulls/1608)
|
||||
- 2025-09-26T08:48:46+02:00 create orbit based DJ filter by daslyfe in: [#1603](https://codeberg.org/uzu/strudel/pulls/1603)
|
||||
- 2025-09-23T13:28:20+02:00 fix: time signal by daslyfe in: [#1583](https://codeberg.org/uzu/strudel/pulls/1583)
|
||||
- 2025-09-21T16:16:06+02:00 mondo: fix all + setcpm + setcps by froos in: [#1600](https://codeberg.org/uzu/strudel/pulls/1600)
|
||||
- 2025-09-19T21:59:43+02:00 fix: osc error message by froos in: [#1597](https://codeberg.org/uzu/strudel/pulls/1597)
|
||||
- 2025-09-18T21:09:56+02:00 osc: --debug flag to see incoming messages by froos in: [#1595](https://codeberg.org/uzu/strudel/pulls/1595)
|
||||
- 2025-09-17T14:12:10+02:00 simplify osc usage by froos in: [#1588](https://codeberg.org/uzu/strudel/pulls/1588)
|
||||
- 2025-09-16T16:59:58+02:00 dev: logger errors to console in dev mode by daslyfe in: [#1585](https://codeberg.org/uzu/strudel/pulls/1585)
|
||||
- 2025-09-15T22:52:14+02:00 add tic80 font by froos in: [#1579](https://codeberg.org/uzu/strudel/pulls/1579)
|
||||
- 2025-09-15T00:00:19+02:00 supradough: fix delay + add some jsdoc types by froos in: [#1578](https://codeberg.org/uzu/strudel/pulls/1578)
|
||||
+22
-17
@@ -4,20 +4,13 @@ Thanks for wanting to contribute!!! There are many ways you can add value to thi
|
||||
|
||||
## Move to codeberg
|
||||
|
||||
We are currently in the process of moving from github to codeberg -- not everything is working, please bear with us.
|
||||
|
||||
To update your local clone, you can run this command:
|
||||
|
||||
```
|
||||
git remote set-url origin git@codeberg.org:uzu/strudel.git
|
||||
```
|
||||
|
||||
Along with many other live coding projects, we have moved from Microsoft's Github platform to Codeberg for ethical reasons. Please don't fork the project back to github.
|
||||
|
||||
## Communication Channels
|
||||
|
||||
To get in touch with the contributors, either
|
||||
To get in touch with the community, either
|
||||
|
||||
- [join the Tidal Discord Channel](https://discord.com/invite/HGEdXmRkzT) and go to the #strudel channel
|
||||
- [join the Uzulang Discord Server](https://discord.com/invite/HGEdXmRkzT) and go to the strudel channels (Uzulangs are a family of live coding languages inspired by each other, including TidalCycles as well as Strudel)
|
||||
- Find related discussions on the [tidal club forum](https://club.tidalcycles.org/)
|
||||
|
||||
## Ask a Question
|
||||
@@ -36,22 +29,35 @@ Use one of the Communication Channels listed above and drop us a line or two!
|
||||
## Share Music
|
||||
|
||||
If you made some music with strudel, you can give back some love and share what you've done!
|
||||
Your creation could also be part of the random selection in the REPL if you want.
|
||||
Use one of the Communication Channels listed above.
|
||||
(There used to be a random selection of contributed patterns in the REPL, but that is unfortunately disabled for now due to abuse)
|
||||
|
||||
## Improve the Docs
|
||||
|
||||
If you find some weak spots in the [docs](https://strudel.cc/workshop/getting-started/),
|
||||
you can edit each file directly on codeburg. (we are currently fixing the "Edit this page" links in the right sidebar)
|
||||
If you find some weak spots in the [docs](https://strudel.cc/workshop/getting-started/), you can edit each file directly on codeberg. There are "Edit this page" links in the right sidebar that take you to the right place.
|
||||
|
||||
## Propose a Feature
|
||||
|
||||
If you want a specific feature that is not part of strudel yet, feel free to use one of the communication channels above.
|
||||
Maybe you even want to help with the implementation of that feature!
|
||||
If you want a specific feature that is not part of strudel yet, feel free to use one of the communication channels above. Please bear in mind that this is a free/open source project, oriented around collaborative discussion. Maybe you even want to help with the implementation of that feature!
|
||||
|
||||
## Contribute a feature
|
||||
|
||||
Pull requests welcome! Consider starting with discussion or proof-of-concept first, rather than do loads of work on something and then find it doesn't fit the collective goals of the project, or something like that.
|
||||
|
||||
At the time of writing we have a PR backlog, and generally prioritise bugfixes and contributions that have arisen through community discussion.
|
||||
|
||||
### AI/LLM policy
|
||||
|
||||
Strudel is a project handmade by humans, with thought and nuance.
|
||||
|
||||
If you have used LLMs (so called 'AI'), please detail that in the pull request. We are still developing our response to the onslaught of LLM technology, but for practical and legal reasons are currently not accepting wholly LLM-generated code. We are also not accepting PRs that add LLM features to strudel itself.
|
||||
|
||||
There are #llm-chat and #llm-share channels on our discord. Please do not discuss or share LLM-related things outside of those channels.
|
||||
|
||||
## Report a Bug
|
||||
|
||||
If you've found a bug, or some behaviour that does not seem right, you are welcome to file an [issue](https://codeberg.org/uzu/strudel/issues).
|
||||
|
||||
Please check that it has not been reported before.
|
||||
|
||||
## Fix a Bug
|
||||
@@ -118,8 +124,7 @@ There are also eslint extensions / plugins for most editors.
|
||||
|
||||
## Running all CI Checks
|
||||
|
||||
When opening a PR, the CI runner will automatically check the code style and eslint, as well as run all tests.
|
||||
You can run the same check with `pnpm check`
|
||||
When opening a PR, the CI runner will (once approved by a human) check the code style and eslint, as well as run all tests. You can run the same check with `pnpm check`.
|
||||
|
||||
## Package Workflow
|
||||
|
||||
|
||||
@@ -293,9 +293,9 @@ export class StrudelMirror {
|
||||
console.warn('first frame could not be painted');
|
||||
}
|
||||
}
|
||||
async evaluate() {
|
||||
async evaluate(autostart = true) {
|
||||
this.flash();
|
||||
await this.repl.evaluate(this.code);
|
||||
await this.repl.evaluate(this.code, autostart);
|
||||
}
|
||||
async stop() {
|
||||
this.repl.scheduler.stop();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { defaultKeymap } from '@codemirror/commands';
|
||||
import { Prec } from '@codemirror/state';
|
||||
import { Prec, EditorState } from '@codemirror/state';
|
||||
import { keymap, ViewPlugin } from '@codemirror/view';
|
||||
// import { searchKeymap } from '@codemirror/search';
|
||||
import { emacs } from '@replit/codemirror-emacs';
|
||||
@@ -133,5 +133,9 @@ const keymaps = {
|
||||
|
||||
export function keybindings(name) {
|
||||
const active = keymaps[name];
|
||||
return [active ? Prec.high(active()) : []];
|
||||
const extensions = active ? [Prec.high(active())] : [];
|
||||
if (name === 'vim') {
|
||||
extensions.push(EditorState.allowMultipleSelections.of(true));
|
||||
}
|
||||
return extensions;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { describe, bench } from 'vitest';
|
||||
|
||||
import { calculateSteps, rand, useRNG } from '../index.mjs';
|
||||
|
||||
const testingResolution = 128;
|
||||
|
||||
const _generateRandomPattern = () => rand.iter(testingResolution).fast(testingResolution).firstCycle();
|
||||
|
||||
describe('old random', () => {
|
||||
calculateSteps(true);
|
||||
bench(
|
||||
'+tactus',
|
||||
() => {
|
||||
useRNG('legacy');
|
||||
_generateRandomPattern();
|
||||
},
|
||||
{
|
||||
time: 1000,
|
||||
teardown() {
|
||||
useRNG('legacy');
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
calculateSteps(false);
|
||||
bench(
|
||||
'-tactus',
|
||||
() => {
|
||||
useRNG('precise');
|
||||
_generateRandomPattern();
|
||||
},
|
||||
{
|
||||
time: 1000,
|
||||
teardown() {
|
||||
useRNG('legacy');
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('random', () => {
|
||||
calculateSteps(true);
|
||||
bench('+tactus', _generateRandomPattern, { time: 1000 });
|
||||
|
||||
calculateSteps(false);
|
||||
bench('-tactus', _generateRandomPattern, { time: 1000 });
|
||||
});
|
||||
|
||||
calculateSteps(true);
|
||||
+241
-19
@@ -72,6 +72,27 @@ export function registerControl(names, ...aliases) {
|
||||
return bag;
|
||||
}
|
||||
|
||||
export function registerMultiControl(names, maxControls, ...aliases) {
|
||||
names = Array.isArray(names) ? names : [names];
|
||||
let bag = {};
|
||||
for (let i = 1; i <= maxControls; i++) {
|
||||
let theseAliases = [...aliases];
|
||||
let theseNames = [...names];
|
||||
if (i === 1) {
|
||||
// adds e.g. fm1 as an alias for fm
|
||||
const aliases1 = theseAliases.map((a) => `${a}1`);
|
||||
const names1 = theseNames.map((n) => `${n}1`);
|
||||
theseAliases = theseAliases.concat(aliases1).concat(names1);
|
||||
} else {
|
||||
theseAliases = theseAliases.map((a) => `${a}${i}`);
|
||||
theseNames = theseNames.map((n) => `${n}${i}`);
|
||||
}
|
||||
const subBag = registerControl(theseNames, ...theseAliases);
|
||||
bag = { ...bag, ...subBag };
|
||||
}
|
||||
return bag;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a sound / sample by name. When using mininotation, you can also optionally supply 'n' and 'gain' parameters
|
||||
* separated by ':'.
|
||||
@@ -380,12 +401,13 @@ export const { accelerate } = registerControl('accelerate');
|
||||
* Sets the velocity from 0 to 1. Is multiplied together with gain.
|
||||
*
|
||||
* @name velocity
|
||||
* @synonyms vel
|
||||
* @example
|
||||
* s("hh*8")
|
||||
* .gain(".4!2 1 .4!2 1 .4 1")
|
||||
* .velocity(".4 1")
|
||||
*/
|
||||
export const { velocity } = registerControl('velocity');
|
||||
export const { velocity, vel } = registerControl('velocity', 'vel');
|
||||
/**
|
||||
* Controls the gain by an exponential amount.
|
||||
*
|
||||
@@ -435,6 +457,9 @@ export const { attack, att } = registerControl('attack', 'att');
|
||||
* Whole numbers and simple ratios sound more natural,
|
||||
* while decimal numbers and complex ratios sound metallic.
|
||||
*
|
||||
* A number may be added afterwards to control the harmonicity of
|
||||
* any of the 8 individual FMs (e.g. `fmh2`)
|
||||
*
|
||||
* @name fmh
|
||||
* @param {number | Pattern} harmonicity
|
||||
* @example
|
||||
@@ -444,25 +469,40 @@ export const { attack, att } = registerControl('attack', 'att');
|
||||
* ._scope()
|
||||
*
|
||||
*/
|
||||
export const { fmh } = registerControl(['fmh', 'fmi'], 'fmh');
|
||||
export const { fmh, fmh1, fmh2, fmh3, fmh4, fmh5, fmh6, fmh7, fmh8 } = registerMultiControl(['fmh', 'fmi'], 8, 'fmh');
|
||||
|
||||
/**
|
||||
* Sets the Frequency Modulation of the synth.
|
||||
* Controls the modulation index, which defines the brightness of the sound.
|
||||
*
|
||||
* @name fm
|
||||
* A number may be added afterwards to control the modulation index of
|
||||
* any of the 8 individual FMs (e.g. `fm3`). Also, FMs may be routed into
|
||||
* each other with matrix commands like `fm13`, which would send `fm1` back into
|
||||
* `fm3`
|
||||
*
|
||||
* @name fmi
|
||||
* @param {number | Pattern} brightness modulation index
|
||||
* @synonyms fmi
|
||||
* @synonyms fm
|
||||
* @example
|
||||
* note("c e g b g e")
|
||||
* .fm("<0 1 2 8 32>")
|
||||
* ._scope()
|
||||
* @example
|
||||
* s("sine").note("F1").seg(8)
|
||||
* .fm(4).fm2(rand.mul(4)).fm3(saw.mul(8).slow(8))
|
||||
* .fmh(1.06).fmh2(10).fmh3(0.1)
|
||||
*
|
||||
*/
|
||||
export const { fmi, fm } = registerControl(['fmi', 'fmh'], 'fm');
|
||||
export const { fmi, fmi1, fmi2, fmi3, fmi4, fmi5, fmi6, fmi7, fmi8, fm, fm1, fm2, fm3, fm4, fm5, fm6, fm7, fm8 } =
|
||||
registerMultiControl(['fmi', 'fmh'], 8, 'fm');
|
||||
|
||||
// fm envelope
|
||||
/**
|
||||
* Ramp type of fm envelope. Exp might be a bit broken..
|
||||
*
|
||||
* A number may be added afterwards to control the envelope of
|
||||
* any of the 8 individual FMs (e.g. `fmenv4`)
|
||||
*
|
||||
* @name fmenv
|
||||
* @param {number | Pattern} type lin | exp
|
||||
* @example
|
||||
@@ -474,11 +514,19 @@ export const { fmi, fm } = registerControl(['fmi', 'fmh'], 'fm');
|
||||
* ._scope()
|
||||
*
|
||||
*/
|
||||
export const { fmenv } = registerControl('fmenv');
|
||||
export const { fmenv, fmenv1, fmenv2, fmenv3, fmenv4, fmenv5, fmenv6, fmenv7, fmenv8 } = registerMultiControl(
|
||||
'fmenv',
|
||||
8,
|
||||
);
|
||||
|
||||
/**
|
||||
* Attack time for the FM envelope: time it takes to reach maximum modulation
|
||||
*
|
||||
* A number may be added afterwards to control the attack of the envelope of
|
||||
* any of the 8 individual FMs (e.g. `fmatt5`)
|
||||
*
|
||||
* @name fmattack
|
||||
* @synonyms fmatt
|
||||
* @param {number | Pattern} time attack time
|
||||
* @example
|
||||
* note("c e g b g e")
|
||||
@@ -487,11 +535,33 @@ export const { fmenv } = registerControl('fmenv');
|
||||
* ._scope()
|
||||
*
|
||||
*/
|
||||
export const { fmattack } = registerControl('fmattack');
|
||||
export const {
|
||||
fmattack,
|
||||
fmattack1,
|
||||
fmattack2,
|
||||
fmattack3,
|
||||
fmattack4,
|
||||
fmattack5,
|
||||
fmattack6,
|
||||
fmattack7,
|
||||
fmattack8,
|
||||
fmatt,
|
||||
fmatt1,
|
||||
fmatt2,
|
||||
fmatt3,
|
||||
fmatt4,
|
||||
fmatt5,
|
||||
fmatt6,
|
||||
fmatt7,
|
||||
fmatt8,
|
||||
} = registerMultiControl('fmattack', 8, 'fmatt');
|
||||
|
||||
/**
|
||||
* Waveform of the fm modulator
|
||||
*
|
||||
* A number may be added afterwards to control the waveform
|
||||
* any of the 8 individual FMs (e.g. `fmwave6`)
|
||||
*
|
||||
* @name fmwave
|
||||
* @param {number | Pattern} wave waveform
|
||||
* @example
|
||||
@@ -500,12 +570,19 @@ export const { fmattack } = registerControl('fmattack');
|
||||
* n("0 1 2 3".fast(4)).chord("<Dm Am F G>").voicing().s("sawtooth").fmwave("brown").fm(.6)
|
||||
*
|
||||
*/
|
||||
export const { fmwave } = registerControl('fmwave');
|
||||
export const { fmwave, fmwave1, fmwave2, fmwave3, fmwave4, fmwave5, fmwave6, fmwave7, fmwave8 } = registerMultiControl(
|
||||
'fmwave',
|
||||
8,
|
||||
);
|
||||
|
||||
/**
|
||||
* Decay time for the FM envelope: seconds until the sustain level is reached after the attack phase.
|
||||
*
|
||||
* A number may be added afterwards to control the decay of the envelope of
|
||||
* any of the 8 individual FMs (e.g. `fmdec6`)
|
||||
*
|
||||
* @name fmdecay
|
||||
* @synonyms fmdec
|
||||
* @param {number | Pattern} time decay time
|
||||
* @example
|
||||
* note("c e g b g e")
|
||||
@@ -515,11 +592,35 @@ export const { fmwave } = registerControl('fmwave');
|
||||
* ._scope()
|
||||
*
|
||||
*/
|
||||
export const { fmdecay } = registerControl('fmdecay');
|
||||
export const {
|
||||
fmdecay,
|
||||
fmdecay1,
|
||||
fmdecay2,
|
||||
fmdecay3,
|
||||
fmdecay4,
|
||||
fmdecay5,
|
||||
fmdecay6,
|
||||
fmdecay7,
|
||||
fmdecay8,
|
||||
fmdec,
|
||||
fmdec1,
|
||||
fmdec2,
|
||||
fmdec3,
|
||||
fmdec4,
|
||||
fmdec5,
|
||||
fmdec6,
|
||||
fmdec7,
|
||||
fmdec8,
|
||||
} = registerMultiControl('fmdecay', 8, 'fmdec');
|
||||
|
||||
/**
|
||||
* Sustain level for the FM envelope: how much modulation is applied after the decay phase
|
||||
*
|
||||
* A number may be added afterwards to control the sustain of the envelope of
|
||||
* any of the 8 individual FMs (e.g. `fmsus7`)
|
||||
*
|
||||
* @name fmsustain
|
||||
* @synonyms fmsus
|
||||
* @param {number | Pattern} level sustain level
|
||||
* @example
|
||||
* note("c e g b g e")
|
||||
@@ -529,10 +630,69 @@ export const { fmdecay } = registerControl('fmdecay');
|
||||
* ._scope()
|
||||
*
|
||||
*/
|
||||
export const { fmsustain } = registerControl('fmsustain');
|
||||
// these are not really useful... skipping for now
|
||||
export const { fmrelease } = registerControl('fmrelease');
|
||||
export const { fmvelocity } = registerControl('fmvelocity');
|
||||
export const {
|
||||
fmsustain,
|
||||
fmsustain1,
|
||||
fmsustain2,
|
||||
fmsustain3,
|
||||
fmsustain4,
|
||||
fmsustain5,
|
||||
fmsustain6,
|
||||
fmsustain7,
|
||||
fmsustain8,
|
||||
fmsus,
|
||||
fmsus1,
|
||||
fmsus2,
|
||||
fmsus3,
|
||||
fmsus4,
|
||||
fmsus5,
|
||||
fmsus6,
|
||||
fmsus7,
|
||||
fmsus8,
|
||||
} = registerMultiControl('fmsustain', 8, 'fmsus');
|
||||
|
||||
/**
|
||||
* Release time for the FM envelope: how much modulation is applied after the note is released
|
||||
*
|
||||
* A number may be added afterwards to control the release of the envelope of
|
||||
* any of the 8 individual FMs (e.g. `fmrel8`)
|
||||
*
|
||||
* @name fmrelease
|
||||
* @synonyms fmrel
|
||||
* @param {number | Pattern} time release time
|
||||
*
|
||||
*/
|
||||
export const {
|
||||
fmrelease,
|
||||
fmrelease1,
|
||||
fmrelease2,
|
||||
fmrelease3,
|
||||
fmrelease4,
|
||||
fmrelease5,
|
||||
fmrelease6,
|
||||
fmrelease7,
|
||||
fmrelease8,
|
||||
fmrel,
|
||||
fmrel1,
|
||||
fmrel2,
|
||||
fmrel3,
|
||||
fmrel4,
|
||||
fmrel5,
|
||||
fmrel6,
|
||||
fmrel7,
|
||||
fmrel8,
|
||||
} = registerMultiControl('fmrelease', 8, 'fmrel');
|
||||
|
||||
// FM Matrix
|
||||
// Note: we do not declare top-level exports here since it would add
|
||||
// ~162 more explicit exports. This is likely fine as the most common use-case would be to at least
|
||||
// declare one other FM prior to utilizing the matrix functionality, but if we ever decide we need it,
|
||||
// TODO to add it explicitly / go with the globalThis approach
|
||||
for (let i = 0; i <= 8; i++) {
|
||||
for (let j = 0; j <= 8; j++) {
|
||||
registerControl(`fmi${i}${j}`, `fm${i}${j}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the sound bank to use. To be used together with `s`. The bank name (+ "_") will be prepended to the value of `s`.
|
||||
@@ -1294,6 +1454,8 @@ export const { fanchor } = registerControl('fanchor');
|
||||
*
|
||||
* @name lprate
|
||||
* @param {number | Pattern} rate rate in hertz
|
||||
* @example
|
||||
* note("<c c c# c c c4>*16").s("sawtooth").lpf(600).lprate("<4 8 2 1>")
|
||||
*/
|
||||
export const { lprate } = registerControl('lprate');
|
||||
|
||||
@@ -1302,6 +1464,8 @@ export const { lprate } = registerControl('lprate');
|
||||
*
|
||||
* @name lpsync
|
||||
* @param {number | Pattern} rate rate in cycles
|
||||
* @example
|
||||
* note("<c c c# c c c4>*16").s("sawtooth").lpf(600).lpsync("<4 8 2 1>")
|
||||
*/
|
||||
export const { lpsync } = registerControl('lpsync');
|
||||
|
||||
@@ -1310,8 +1474,22 @@ export const { lpsync } = registerControl('lpsync');
|
||||
*
|
||||
* @name lpdepth
|
||||
* @param {number | Pattern} depth depth of modulation
|
||||
* @example
|
||||
* note("<c c c# c c c4>*16").s("sawtooth").lpf(600).lpdepth("<1 .5 1.8 0>")
|
||||
*/
|
||||
|
||||
export const { lpdepth } = registerControl('lpdepth');
|
||||
/**
|
||||
* Depth of the LFO for the lowpass filter, in HZ
|
||||
*
|
||||
* @name lpdepthfrequency
|
||||
* @synonyms lpdepthfreq
|
||||
* @param {number | Pattern} depth depth of modulation
|
||||
* @example
|
||||
* note("<c c c# c c c4>*16").s("sawtooth").lpf(600).lpdepthfrequency("<200 500 100 0>")
|
||||
*/
|
||||
|
||||
export const { lpdepthfrequency, lpdepthfreq } = registerControl('lpdepthfrequency', 'lpdepthfreq');
|
||||
|
||||
/**
|
||||
* Shape of the LFO for the lowpass filter
|
||||
@@ -1361,6 +1539,18 @@ export const { bpsync } = registerControl('bpsync');
|
||||
*/
|
||||
export const { bpdepth } = registerControl('bpdepth');
|
||||
|
||||
/**
|
||||
* Depth of the LFO for the bandpass filter, in HZ
|
||||
*
|
||||
* @name bpdepthfrequency
|
||||
* @synonyms bpdepthfreq
|
||||
* @param {number | Pattern} depth depth of modulation
|
||||
* @example
|
||||
* note("<c c c# c c c4>*16").s("sawtooth").lpf(600).bpdepthfrequency("<200 500 100 0>")
|
||||
*/
|
||||
|
||||
export const { bpdepthfrequency, bpdepthfreq } = registerControl('bpdepthfrequency', 'bpdepthfreq');
|
||||
|
||||
/**
|
||||
* Shape of the LFO for the bandpass filter
|
||||
*
|
||||
@@ -1409,6 +1599,18 @@ export const { hpsync } = registerControl('hpsync');
|
||||
*/
|
||||
export const { hpdepth } = registerControl('hpdepth');
|
||||
|
||||
/**
|
||||
* Depth of the LFO for the hipass filter, in hz
|
||||
*
|
||||
* @name hpdepthfrequency
|
||||
* @synonyms hpdepthfreq
|
||||
* @param {number | Pattern} depth depth of modulation
|
||||
* @example
|
||||
* note("<c c c# c c c4>*16").s("sawtooth").lpf(600).hpdepthfrequency("<200 500 100 0>")
|
||||
*/
|
||||
|
||||
export const { hpdepthfrequency, hpdepthfreq } = registerControl('hpdepthfrequency', 'hpdepthfreq');
|
||||
|
||||
/**
|
||||
* Shape of the LFO for the highpass filter
|
||||
*
|
||||
@@ -1820,12 +2022,12 @@ export const { nudge } = registerControl('nudge');
|
||||
* Sets the default octave of a synth.
|
||||
*
|
||||
* @name octave
|
||||
* @synonyms oct
|
||||
* @param {number | Pattern} octave octave number
|
||||
* @example
|
||||
* n("0,4,7").s('supersquare').octave("<3 4 5 6>").osc()
|
||||
* @superDirtOnly
|
||||
* n("0,4,7").scale("F:minor").s('supersaw').octave("<0 1 2 3>")
|
||||
*/
|
||||
export const { octave } = registerControl('octave');
|
||||
export const { octave, oct } = registerControl('octave', 'oct');
|
||||
|
||||
// ['ophatdecay'],
|
||||
// TODO: example
|
||||
@@ -1833,6 +2035,7 @@ export const { octave } = registerControl('octave');
|
||||
* An `orbit` is a global parameter context for patterns. Patterns with the same orbit will share the same global effects.
|
||||
*
|
||||
* @name orbit
|
||||
* @synonyms o
|
||||
* @param {number | Pattern} number
|
||||
* @example
|
||||
* stack(
|
||||
@@ -1840,7 +2043,7 @@ export const { octave } = registerControl('octave');
|
||||
* s("~ sd ~ sd").delay(.5).delaytime(.125).orbit(2)
|
||||
* )
|
||||
*/
|
||||
export const { orbit } = registerControl('orbit');
|
||||
export const { orbit } = registerControl('orbit', 'o');
|
||||
// TODO: what is this? not found in tidal doc Answer: gain is limited to maximum of 2. This allows you to go over that
|
||||
export const { overgain } = registerControl('overgain');
|
||||
// TODO: what is this? not found in tidal doc. Similar to above, but limited to 1
|
||||
@@ -2550,8 +2753,13 @@ export const as = register('as', (mapping, pat) => {
|
||||
mapping = Array.isArray(mapping) ? mapping : [mapping];
|
||||
return pat.fmap((v) => {
|
||||
v = Array.isArray(v) ? v : [v];
|
||||
v = Object.fromEntries(mapping.map((prop, i) => [getControlName(prop), v[i]]));
|
||||
return v;
|
||||
const entries = [];
|
||||
for (let i = 0; i < mapping.length; ++i) {
|
||||
if (v[i] !== undefined) {
|
||||
entries.push([getControlName(mapping[i]), v[i]]);
|
||||
}
|
||||
}
|
||||
return Object.fromEntries(entries);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2583,3 +2791,17 @@ export const scrub = register(
|
||||
},
|
||||
false,
|
||||
);
|
||||
|
||||
/**
|
||||
* Transient shaper. Gives independent control over the emphasis on transients
|
||||
* and sustains
|
||||
*
|
||||
* @name transient
|
||||
* @param {number | Pattern} attack Emphasis on transients; between -1 (deaccentuate) and 1 (accentuate)
|
||||
* @param {number | Pattern} sustain Emphasis on the sustains; between -1 (deaccentuate) and 1 (accentuate)
|
||||
* @example
|
||||
* s("bd").transient("<-1 -0.5 0 0.5 1>")
|
||||
* @example
|
||||
* s("hh*16").bank("tr909").transient("<-1:1 1:-1>")
|
||||
*/
|
||||
export const { transient } = registerControl(['transient', 'transsustain']);
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
stateful.mjs - File of shame for stateful, impure and otherwise illegal pattern methods
|
||||
Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/index.mjs>
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import { register, reify, Pattern } from './pattern.mjs';
|
||||
|
||||
let timelines = {};
|
||||
|
||||
export const reset_state = function () {
|
||||
reset_timelines();
|
||||
};
|
||||
|
||||
export const reset_timelines = function () {
|
||||
timelines = {};
|
||||
};
|
||||
|
||||
/***
|
||||
* Allows you to switch a pattern between different 'timelines'. This is particularly useful when
|
||||
* live coding, for example when you want to cue a pattern up to play from its start.
|
||||
*
|
||||
* Timelines are specified by number, so that if you had a pattern like
|
||||
* `n("<0 1 2 3>").s("num").timeline(1)` playing, then changed the '1'
|
||||
* to '2', it would always align '0' to the nearest cycle. You will likely want to trigger
|
||||
* an evaluation a little bit before the cycle starts, to avoid missing events.
|
||||
*
|
||||
* After the first use, a timeline will continue with the same 'offset'. That is, if you change
|
||||
* a pattern without changing its timeline number, it will stay on that timeline without resetting.
|
||||
*
|
||||
* Rather than incrementing a timeline to reset it, it's easier to negate it, e.g. by switching between `-2`
|
||||
* and `2`. This is because when you negate a timeline it will always reset.
|
||||
*
|
||||
* You can also pattern the timeline if you want, to create strange resetting patterns.
|
||||
* @param {number | Pattern} timeline The timeline that the pattern should play on.
|
||||
* @example
|
||||
* n("<0 1 2 3>(3,8)")
|
||||
* .sound("num")
|
||||
* // resets the timeline every two cycles, by negating the timeline.
|
||||
* // in a lot of cases this will be edited by a human live coder
|
||||
* // rather than patterned!
|
||||
* .timeline("<2 -2>".slow(2))
|
||||
*/
|
||||
|
||||
export const timeline = register(
|
||||
'timeline',
|
||||
function (tpat, pat) {
|
||||
tpat = reify(tpat);
|
||||
const f = function (state) {
|
||||
// Is this called from the scheduler? (rather than from e.g. the visualiser)
|
||||
const scheduler = !!state.controls.cyclist;
|
||||
const timehaps = tpat.query(state);
|
||||
const result = [];
|
||||
for (const timehap of timehaps) {
|
||||
const tlid = timehap.value;
|
||||
let offset;
|
||||
if (tlid === 0) {
|
||||
offset = 0;
|
||||
} else if (tlid in timelines) {
|
||||
offset = timelines[tlid];
|
||||
} else {
|
||||
const timearc = timehap.wholeOrPart();
|
||||
if (!scheduler || state.span.begin.lt(timearc.midpoint())) {
|
||||
offset = timearc.begin;
|
||||
} else {
|
||||
// Sync to end of timearc if we first see it over halfway into its
|
||||
// timespan. Allows 'cuing up' next timeline when live coding.
|
||||
offset = timearc.end;
|
||||
}
|
||||
}
|
||||
if (scheduler) {
|
||||
// update state
|
||||
timelines[tlid] = offset;
|
||||
if (tlid !== 0) {
|
||||
delete timelines[-tlid];
|
||||
}
|
||||
}
|
||||
|
||||
const pathaps = pat
|
||||
.late(offset)
|
||||
.query(state.setSpan(timehap.part))
|
||||
.map((h) => h.setContext(h.combineContext(timehap)));
|
||||
result.push(...pathaps);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
return new Pattern(f, pat._steps);
|
||||
},
|
||||
false,
|
||||
);
|
||||
+12
-11
@@ -1,6 +1,6 @@
|
||||
/*
|
||||
index.mjs - <short description TODO>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/index.mjs>
|
||||
Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/index.mjs>
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
@@ -11,20 +11,21 @@ import createClock from './zyklus.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
export { Fraction, controls, createClock };
|
||||
export * from './controls.mjs';
|
||||
export * from './hap.mjs';
|
||||
export * from './pattern.mjs';
|
||||
export * from './signal.mjs';
|
||||
export * from './pick.mjs';
|
||||
export * from './state.mjs';
|
||||
export * from './timespan.mjs';
|
||||
export * from './util.mjs';
|
||||
export * from './speak.mjs';
|
||||
export * from './evaluate.mjs';
|
||||
export * from './repl.mjs';
|
||||
export * from './cyclist.mjs';
|
||||
export * from './evaluate.mjs';
|
||||
export * from './hap.mjs';
|
||||
export * from './impure.mjs';
|
||||
export * from './logger.mjs';
|
||||
export * from './pattern.mjs';
|
||||
export * from './pick.mjs';
|
||||
export * from './repl.mjs';
|
||||
export * from './signal.mjs';
|
||||
export * from './speak.mjs';
|
||||
export * from './state.mjs';
|
||||
export * from './time.mjs';
|
||||
export * from './timespan.mjs';
|
||||
export * from './ui.mjs';
|
||||
export * from './util.mjs';
|
||||
export { default as drawLine } from './drawLine.mjs';
|
||||
// below won't work with runtime.mjs (json import fails)
|
||||
/* import * as p from './package.json';
|
||||
|
||||
@@ -25,7 +25,7 @@ import {
|
||||
stringifyValues,
|
||||
} from './util.mjs';
|
||||
import drawLine from './drawLine.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
import { errorLogger, logger } from './logger.mjs';
|
||||
|
||||
let stringParser;
|
||||
|
||||
@@ -414,7 +414,7 @@ export class Pattern {
|
||||
try {
|
||||
return this.query(new State(new TimeSpan(begin, end), controls));
|
||||
} catch (err) {
|
||||
logger(`[query]: ${err.message}`, 'error');
|
||||
errorLogger(err, 'query');
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -574,7 +574,8 @@ export class Pattern {
|
||||
* Returns a new Pattern, which only returns haps that meet the given test.
|
||||
* @param {Function} hap_test - a function which returns false for haps to be removed from the pattern
|
||||
* @returns Pattern
|
||||
* @noAutocomplete
|
||||
* @example
|
||||
* s("bd*8").velocity(rand).filterHaps((h) => (h.whole.begin % 1) < h.value.velocity)
|
||||
*/
|
||||
filterHaps(hap_test) {
|
||||
return new Pattern((state) => this.query(state).filter(hap_test));
|
||||
@@ -585,7 +586,11 @@ export class Pattern {
|
||||
* inside haps.
|
||||
* @param {Function} value_test
|
||||
* @returns Pattern
|
||||
* @noAutocomplete
|
||||
* @example
|
||||
* const drums = s("bd sd bd sd")
|
||||
* kick: drums.filterValues((v) => v.s === 'bd').duck(2)
|
||||
* snare: drums.filterValues((v) => v.s === 'sd')
|
||||
* bass: s("saw!4").note("G#1").lpf(80).lpenv(4).orbit(2)
|
||||
*/
|
||||
filterValues(value_test) {
|
||||
return new Pattern((state) => this.query(state).filter((hap) => value_test(hap.value))).setSteps(this._steps);
|
||||
@@ -1587,7 +1592,13 @@ export const func = curry((a, b) => reify(b).func(a));
|
||||
*
|
||||
* @param {string | string[]} name name of the function, or an array of names to be used as synonyms
|
||||
* @param {function} func function with 1 or more params, where last is the current pattern
|
||||
* @noAutocomplete
|
||||
* @param {bool} patternify defaults to true; if set to false, you will have more control over the arguments to `func` as they will be
|
||||
* in their raw form and it will be up to you to patternify them and/or query them for values
|
||||
* @example
|
||||
* const vlpf = register('vlpf', (freq, pat) => {
|
||||
* return pat.fmap((v) => ({...v, cutoff: freq * (v.velocity ?? 1) }));
|
||||
* })
|
||||
* s("saw").seg(8).velocity(rand).vlpf(800)
|
||||
*
|
||||
*/
|
||||
export function register(name, func, patternify = true, preserveSteps = false, join = (x) => x.innerJoin()) {
|
||||
@@ -2234,7 +2245,7 @@ export const brak = register('brak', function (pat) {
|
||||
});
|
||||
|
||||
/**
|
||||
* Reverse all haps in a pattern
|
||||
* Reverse all cycles in a pattern. See also `revv` for reversing a whole pattern.
|
||||
*
|
||||
* @name rev
|
||||
* @memberof Pattern
|
||||
@@ -2266,6 +2277,23 @@ export const rev = register(
|
||||
true,
|
||||
);
|
||||
|
||||
/**
|
||||
* Reverse a whole pattern. See also `rev` for reversing each cycle.
|
||||
*
|
||||
* @name revv
|
||||
* @memberof Pattern
|
||||
* @returns Pattern
|
||||
* @example
|
||||
* // This is the same as `<[g e] [d c]>`. If `rev()` is used, you get
|
||||
* // the same as `<[d c] [g e]>`, where each cycle reverses, but the order of
|
||||
* // cycles stays the same.
|
||||
* note("<[c d] [e g]>").revv()
|
||||
*/
|
||||
export const revv = register('revv', function (pat) {
|
||||
const negateSpan = (span) => new TimeSpan(Fraction(0).sub(span.end), Fraction(0).sub(span.begin));
|
||||
return pat.withQuerySpan(negateSpan).withHapSpan(negateSpan);
|
||||
});
|
||||
|
||||
/** Like press, but allows you to specify the amount by which each
|
||||
* event is shifted. pressBy(0.5) is the same as press, while
|
||||
* pressBy(1/3) shifts each event by a third of its timespan.
|
||||
@@ -2659,8 +2687,13 @@ export const hsl = register('hsl', (h, s, l, pat) => {
|
||||
/**
|
||||
* Tags each Hap with an identifier. Good for filtering. The function populates Hap.context.tags (Array).
|
||||
* @name tag
|
||||
* @noAutocomplete
|
||||
* @param {string} tag anything unique
|
||||
* @example
|
||||
* s("saw!16").note("F1")
|
||||
* .lpf(tri.range(40, 80).slow(4)).lpenv(5).lpq(4).lpd(0.15)
|
||||
* .when(rand.late(0.1).gte(0.5), x => x.transpose("12").tag('altered'))
|
||||
* .when(rand.late(0.2).gte(0.5), x => x.s("square").tag('altered'))
|
||||
* .when("<0 1>", x => x.filter((hap) => hap.hasTag('altered')))
|
||||
*/
|
||||
Pattern.prototype.tag = function (tag) {
|
||||
return this.withContext((ctx) => ({ ...ctx, tags: (ctx.tags || []).concat([tag]) }));
|
||||
@@ -2671,15 +2704,16 @@ Pattern.prototype.tag = function (tag) {
|
||||
* @name filter
|
||||
* @param {Function} test function to test Hap
|
||||
* @example
|
||||
* s("hh!7 oh").filter(hap => hap.value.s==='hh')
|
||||
* s("hh!7 oh").filter(hap => hap.value.s === 'hh')
|
||||
*/
|
||||
export const filter = register('filter', (test, pat) => pat.withHaps((haps) => haps.filter(test)));
|
||||
|
||||
/**
|
||||
* Filters haps by their begin time
|
||||
* @name filterWhen
|
||||
* @noAutocomplete
|
||||
* @param {Function} test function to test Hap.whole.begin
|
||||
* @example
|
||||
* oneCycle: s("bd*4").filterWhen((t) => t < 1)
|
||||
*/
|
||||
export const filterWhen = register('filterWhen', (test, pat) => pat.filter((h) => test(h.whole.begin)));
|
||||
|
||||
|
||||
+21
-7
@@ -5,6 +5,7 @@ import { errorLogger, logger } from './logger.mjs';
|
||||
import { setTime } from './time.mjs';
|
||||
import { evalScope } from './evaluate.mjs';
|
||||
import { register, Pattern, isPattern, silence, stack } from './pattern.mjs';
|
||||
import { reset_state } from './impure.mjs';
|
||||
|
||||
export function repl({
|
||||
defaultOutput,
|
||||
@@ -52,6 +53,9 @@ export function repl({
|
||||
onToggle: (started) => {
|
||||
updateState({ started });
|
||||
onToggle?.(started);
|
||||
if (!started) {
|
||||
reset_state();
|
||||
}
|
||||
},
|
||||
setInterval,
|
||||
clearInterval,
|
||||
@@ -152,9 +156,9 @@ export function repl({
|
||||
// allows muting a pattern x with x_ or _x
|
||||
return silence;
|
||||
}
|
||||
if (id === '$') {
|
||||
if (id.includes('$')) {
|
||||
// allows adding anonymous patterns with $:
|
||||
id = `$${anonymousIndex}`;
|
||||
id = `${id}${anonymousIndex}`;
|
||||
anonymousIndex++;
|
||||
}
|
||||
pPatterns[id] = this;
|
||||
@@ -215,8 +219,19 @@ export function repl({
|
||||
let { pattern, meta } = await _evaluate(code, transpiler, transpilerOptions);
|
||||
if (Object.keys(pPatterns).length) {
|
||||
let patterns = [];
|
||||
let soloActive = false;
|
||||
for (const [key, value] of Object.entries(pPatterns)) {
|
||||
patterns.push(value.withState((state) => state.setControls({ id: key })));
|
||||
// handle soloed patterns ex: S$: s("bd!4")
|
||||
const isSolod = key.length > 1 && key.startsWith('S');
|
||||
if (isSolod && soloActive === false) {
|
||||
// first time we see a soloed pattern, clear existing patterns
|
||||
patterns = [];
|
||||
soloActive = true;
|
||||
}
|
||||
if (!soloActive || (soloActive && isSolod)) {
|
||||
const valWithState = value.withState((state) => state.setControls({ id: key }));
|
||||
patterns.push(valWithState);
|
||||
}
|
||||
}
|
||||
if (eachTransform) {
|
||||
// Explicit lambda so only element (not index and array) are passed
|
||||
@@ -227,14 +242,13 @@ export function repl({
|
||||
pattern = eachTransform(pattern);
|
||||
}
|
||||
if (allTransforms.length) {
|
||||
for (let i in allTransforms) {
|
||||
pattern = allTransforms[i](pattern);
|
||||
for (const transform of allTransforms) {
|
||||
pattern = transform(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
if (!isPattern(pattern)) {
|
||||
const message = `got "${typeof evaluated}" instead of pattern`;
|
||||
throw new Error(message + (typeof evaluated === 'function' ? ', did you forget to call a function?' : '.'));
|
||||
pattern = silence;
|
||||
}
|
||||
logger(`[eval] code updated`);
|
||||
pattern = await setPattern(pattern, autostart);
|
||||
|
||||
+172
-39
@@ -16,7 +16,7 @@ export function steady(value) {
|
||||
}
|
||||
|
||||
export const signal = (func) => {
|
||||
const query = (state) => [new Hap(undefined, state.span, func(state.span.begin))];
|
||||
const query = (state) => [new Hap(undefined, state.span, func(state.span.begin, state.controls))];
|
||||
return new Pattern(query);
|
||||
};
|
||||
|
||||
@@ -186,38 +186,97 @@ export const mouseY = signal(() => _mouseY);
|
||||
export const mousex = signal(() => _mouseX);
|
||||
export const mouseX = signal(() => _mouseX);
|
||||
|
||||
// random signals
|
||||
// Random number generators
|
||||
|
||||
const xorwise = (x) => {
|
||||
// Produce "Avalanche effect" where flipping a single bit of x
|
||||
// results in all output bits flipping with probability 0.5
|
||||
// See e.g. https://github.com/aappleby/smhasher/blob/0ff96f7835817a27d0487325b6c16033e2992eb5/src/MurmurHash3.cpp#L68-L77
|
||||
const _murmurHashFinalizer = (x) => {
|
||||
x |= 0;
|
||||
x ^= x >>> 16;
|
||||
x = Math.imul(x, 0x85ebca6b);
|
||||
x ^= x >>> 13;
|
||||
x = Math.imul(x, 0xc2b2ae35);
|
||||
x ^= x >>> 16;
|
||||
return x >>> 0; // unsigned
|
||||
};
|
||||
|
||||
// Convert t to a 32 bit integer, preserving temporal resolution down to 1/2^29
|
||||
const _tToT = (t) => {
|
||||
return Math.floor(t * 536870912);
|
||||
};
|
||||
|
||||
// Used to decorrelate nearby T, i, and seed prior to hashing
|
||||
const _decorrelate = (T, i = 0, seed = 0) => {
|
||||
const lowBits = (T >>> 0) >>> 0;
|
||||
const highBits = Math.floor(T / 4294967296) >>> 0; // 2^32
|
||||
let key = lowBits ^ Math.imul(highBits ^ 0x85ebca6b, 0xc2b2ae35);
|
||||
key ^= Math.imul(i ^ 0x7f4a7c15, 0x9e3779b9);
|
||||
key ^= Math.imul(seed ^ 0x165667b1, 0x27d4eb2d);
|
||||
return key >>> 0;
|
||||
};
|
||||
|
||||
const randAt = (T, i = 0, seed = 0) => {
|
||||
return _murmurHashFinalizer(_decorrelate(T, i, seed)) / 4294967296; // 2^32
|
||||
};
|
||||
|
||||
// n samples at time t
|
||||
const timeToRands = (t, n, seed = 0) => {
|
||||
const T = _tToT(t);
|
||||
if (n === 1) {
|
||||
return randAt(T, 0, seed);
|
||||
}
|
||||
const out = new Array(n);
|
||||
for (let i = 0; i < n; i++) out[i] = randAt(T, i, seed);
|
||||
return out;
|
||||
};
|
||||
|
||||
// Old random signals. Currently the default, but can also be chosen via
|
||||
// `useRNG('legacy')`
|
||||
|
||||
// stretch 300 cycles over the range of [0,2**29 == 536870912) then apply the xorshift algorithm
|
||||
const __xorwise = (x) => {
|
||||
const a = (x << 13) ^ x;
|
||||
const b = (a >> 17) ^ a;
|
||||
return (b << 5) ^ b;
|
||||
};
|
||||
|
||||
// stretch 300 cycles over the range of [0,2**29 == 536870912) then apply the xorshift algorithm
|
||||
const _frac = (x) => x - Math.trunc(x);
|
||||
|
||||
const timeToIntSeed = (x) => xorwise(Math.trunc(_frac(x / 300) * 536870912));
|
||||
|
||||
const intSeedToRand = (x) => (x % 536870912) / 536870912;
|
||||
|
||||
const timeToRand = (x) => Math.abs(intSeedToRand(timeToIntSeed(x)));
|
||||
|
||||
const timeToRandsPrime = (seed, n) => {
|
||||
const __frac = (x) => x - Math.trunc(x);
|
||||
const __timeToIntSeed = (x) => __xorwise(Math.trunc(__frac(x / 300) * 536870912));
|
||||
const __intSeedToRand = (x) => (x % 536870912) / 536870912;
|
||||
const __timeToRandsPrime = (seed, n) => {
|
||||
if (n === 1) {
|
||||
return Math.abs(__intSeedToRand(seed));
|
||||
}
|
||||
const result = [];
|
||||
// eslint-disable-next-line
|
||||
for (let i = 0; i < n; ++i) {
|
||||
result.push(intSeedToRand(seed));
|
||||
seed = xorwise(seed);
|
||||
for (let i = 0; i < n; i++) {
|
||||
result.push(__intSeedToRand(seed));
|
||||
seed = __xorwise(seed);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
const __timeToRands = (t, n) => __timeToRandsPrime(__timeToIntSeed(t), n);
|
||||
|
||||
const timeToRands = (t, n) => timeToRandsPrime(timeToIntSeed(t), n);
|
||||
// End old random
|
||||
|
||||
let RNG_MODE = 'legacy';
|
||||
export const getRandsAtTime = (t, n = 1, seed = 0) => {
|
||||
return RNG_MODE === 'legacy' ? __timeToRands(t + seed, n) : timeToRands(t, n, seed);
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets which random number generator to use. Historically Strudel would
|
||||
* use `useRNG('legacy')`, which remains the default. To use a new more statistically
|
||||
* precise RNG, try `useRNG('precise')`.
|
||||
*
|
||||
* @name useRNG
|
||||
* @param {string} mod - Mode. One of 'legacy', 'precise'
|
||||
* @example
|
||||
* useRNG('legacy')
|
||||
* // Repeats every 300 cycles
|
||||
* $: n(irand(50)).seg(16).scale("C:minor").ribbon(88, 32)
|
||||
* $: n(irand(50)).seg(16).scale("C:minor").ribbon(388, 32)
|
||||
*/
|
||||
export const useRNG = (mode = 'legacy') => (RNG_MODE = mode);
|
||||
|
||||
/**
|
||||
* A discrete pattern of numbers from 0 to n-1
|
||||
@@ -300,13 +359,13 @@ export const binaryNL = (n, nBits = 16) => {
|
||||
* .partials(randL(8))
|
||||
*/
|
||||
export const randL = (n) => {
|
||||
return signal((t) => (nVal) => timeToRands(t, nVal).map(Math.abs)).appLeft(reify(n));
|
||||
return signal((t) => (nVal) => getRandsAtTime(t, nVal).map(Math.abs)).appLeft(reify(n));
|
||||
};
|
||||
|
||||
export const randrun = (n) => {
|
||||
return signal((t) => {
|
||||
return signal((t, controls) => {
|
||||
// Without adding 0.5, the first cycle is always 0,1,2,3,...
|
||||
const rands = timeToRands(t.floor().add(0.5), n);
|
||||
const rands = getRandsAtTime(t.floor().add(0.5), n, controls.randSeed);
|
||||
const nums = rands
|
||||
.map((n, i) => [n, i])
|
||||
.sort((a, b) => (a[0] > b[0]) - (a[0] < b[0]))
|
||||
@@ -347,6 +406,37 @@ export const scramble = register('scramble', (n, pat) => {
|
||||
return _rearrangeWith(_irand(n)._segment(n), n, pat);
|
||||
});
|
||||
|
||||
/**
|
||||
* Modify a pattern by applying a function to the `randomSeed` control if present
|
||||
*
|
||||
* @param {Function} func Function from seed (or undefined) to seed (or undefined)
|
||||
* @param {Pattern} pat Pattern to update
|
||||
* @returns Pattern
|
||||
*/
|
||||
export const withSeed = (func, pat) => {
|
||||
return new Pattern((state) => {
|
||||
let { randSeed, ...controls } = state.controls;
|
||||
randSeed = func(randSeed);
|
||||
return pat.query(state.setControls({ ...controls, randSeed }));
|
||||
}, pat._steps);
|
||||
};
|
||||
|
||||
/**
|
||||
* Change the seed for random signals. Normally, random signals depend on time,
|
||||
* so two patterns at the same time will have the same random values. Specifying
|
||||
* a new seed changes the signal output by `rand`. This also affects other functions
|
||||
* that use randomness, like `shuffle` and `sometimes`.
|
||||
*
|
||||
* @name seed
|
||||
* @param {number} n A new seed. Can be any number.
|
||||
* @example
|
||||
* $: s("hh*4").degrade();
|
||||
* $: s("bd*4").degrade().seed(1); // Will degrade different events from the hi-hat
|
||||
*/
|
||||
export const seed = register('seed', (n, pat) => {
|
||||
return withSeed(() => n, pat);
|
||||
});
|
||||
|
||||
/**
|
||||
* A continuous pattern of random numbers, between 0 and 1.
|
||||
*
|
||||
@@ -356,7 +446,7 @@ export const scramble = register('scramble', (n, pat) => {
|
||||
* s("bd*4,hh*8").cutoff(rand.range(500,8000))
|
||||
*
|
||||
*/
|
||||
export const rand = signal(timeToRand);
|
||||
export const rand = signal((t, controls) => getRandsAtTime(t, 1, controls.randSeed));
|
||||
/**
|
||||
* A continuous pattern of random numbers, between -1 and 1
|
||||
*/
|
||||
@@ -524,7 +614,7 @@ export const wchoose = (...pairs) => wchooseWith(rand, ...pairs);
|
||||
* @example
|
||||
* wchooseCycles(["bd",10], ["hh",1], ["sd",1]).s().fast(8)
|
||||
* @example
|
||||
* wchooseCycles(["bd bd bd",5], ["hh hh hh",3], ["sd sd sd",1]).fast(4).s()
|
||||
* wchooseCycles(["c c c",5], ["a a a",3], ["f f f",1]).fast(4).note()
|
||||
* @example
|
||||
* // The probability can itself be a pattern
|
||||
* wchooseCycles(["bd(3,8)","<5 0>"], ["hh hh hh",3]).fast(4).s()
|
||||
@@ -533,36 +623,32 @@ export const wchooseCycles = (...pairs) => _wchooseWith(rand.segment(1), ...pair
|
||||
|
||||
export const wrandcat = wchooseCycles;
|
||||
|
||||
function _perlin(t) {
|
||||
function _perlin(t, seed = 0) {
|
||||
let ta = Math.floor(t);
|
||||
let tb = ta + 1;
|
||||
const smootherStep = (x) => 6.0 * x ** 5 - 15.0 * x ** 4 + 10.0 * x ** 3;
|
||||
const interp = (x) => (a) => (b) => a + smootherStep(x) * (b - a);
|
||||
const v = interp(t - ta)(timeToRand(ta))(timeToRand(tb));
|
||||
const ra = getRandsAtTime(ta, 1, seed);
|
||||
const rb = getRandsAtTime(tb, 1, seed);
|
||||
const v = interp(t - ta)(ra)(rb);
|
||||
return v;
|
||||
}
|
||||
export const perlinWith = (tpat) => {
|
||||
return tpat.fmap(_perlin);
|
||||
};
|
||||
|
||||
function _berlin(t) {
|
||||
function _berlin(t, seed = 0) {
|
||||
const prevRidgeStartIndex = Math.floor(t);
|
||||
const nextRidgeStartIndex = prevRidgeStartIndex + 1;
|
||||
|
||||
const prevRidgeBottomPoint = timeToRand(prevRidgeStartIndex);
|
||||
const nextRidgeTopPoint = timeToRand(nextRidgeStartIndex) + prevRidgeBottomPoint;
|
||||
const prevRidgeBottomPoint = getRandsAtTime(prevRidgeStartIndex, 1, seed);
|
||||
const height = getRandsAtTime(nextRidgeStartIndex, 1, seed);
|
||||
const nextRidgeTopPoint = prevRidgeBottomPoint + height;
|
||||
|
||||
const currentPercent = (t - prevRidgeStartIndex) / (nextRidgeStartIndex - prevRidgeStartIndex);
|
||||
const interp = (a, b, t) => {
|
||||
return a + (b - a) * t;
|
||||
return a + t * (b - a);
|
||||
};
|
||||
return interp(prevRidgeBottomPoint, nextRidgeTopPoint, currentPercent) / 2;
|
||||
}
|
||||
|
||||
export const berlinWith = (tpat) => {
|
||||
return tpat.fmap(_berlin);
|
||||
};
|
||||
|
||||
/**
|
||||
* Generates a continuous pattern of [perlin noise](https://en.wikipedia.org/wiki/Perlin_noise), in the range 0..1.
|
||||
*
|
||||
@@ -572,7 +658,7 @@ export const berlinWith = (tpat) => {
|
||||
* s("bd*4,hh*8").cutoff(perlin.range(500,8000))
|
||||
*
|
||||
*/
|
||||
export const perlin = perlinWith(time.fmap((v) => Number(v)));
|
||||
export const perlin = signal((t, controls) => _perlin(t, controls.randSeed));
|
||||
|
||||
/**
|
||||
* Generates a continuous pattern of [berlin noise](conceived by Jame Coyne and Jade Rowland as a joke but turned out to be surprisingly cool and useful,
|
||||
@@ -584,7 +670,7 @@ export const perlin = perlinWith(time.fmap((v) => Number(v)));
|
||||
* n("0!16".add(berlin.fast(4).mul(14))).scale("d:minor")
|
||||
*
|
||||
*/
|
||||
export const berlin = berlinWith(time.fmap((v) => Number(v)));
|
||||
export const berlin = signal((t, controls) => _berlin(t, controls.randSeed));
|
||||
|
||||
export const degradeByWith = register(
|
||||
'degradeByWith',
|
||||
@@ -882,3 +968,50 @@ export const whenKey = register('whenKey', function (input, func, pat) {
|
||||
export const keyDown = register('keyDown', function (pat) {
|
||||
return pat.fmap(_keyDown);
|
||||
});
|
||||
|
||||
/**
|
||||
* A pattern measuring the duration of events,
|
||||
* in cycles per event. `cyclesPer` doesn't have structure itself, but takes structure, and therefore
|
||||
* event durations, from the pattern that it is combined with.
|
||||
* For example `cyclesPer.struct("1 1 [1 1] 1")` would give the same as `"0.25 0.25 [0.125 0.125] 0.25"`.
|
||||
* See also its reciprocal, `per`, also known as `perCycle`.
|
||||
* @example
|
||||
* // Shorter events are lower in pitch
|
||||
* sound("saw saw [saw saw] saw")
|
||||
* .note(cyclesPer.range(50, 100))
|
||||
* @example
|
||||
* sound("bd sd [bd bd] sd*4 [- sd] [bd [bd bd]]")
|
||||
* .note(cyclesPer.add(20))
|
||||
*/
|
||||
export const cyclesPer = new Pattern(function (state) {
|
||||
return [new Hap(undefined, state.span, state.span.duration)];
|
||||
});
|
||||
|
||||
/**
|
||||
* A pattern measuring the 'shortness' of events, or in other words, the duration of pattern events,
|
||||
* in events per cycle. `per` doesn't have structure itself, but takes structure, and therefore
|
||||
* event durations, from the pattern that it is combined with.
|
||||
* For example `per.struct("1 1 [1 1] 1")` would give the same as `"4 4 [8 8] 4"`.
|
||||
* See also its reciprocal, `cyclesPer`.
|
||||
* @synonyms perCycle
|
||||
* @example
|
||||
* // Shorter events are more distorted
|
||||
* n("0 0*2 0 0*2 0 [0 0 0]@2").sound("bd")
|
||||
* .distort(per.div(2))
|
||||
*/
|
||||
export const per = new Pattern(function (state) {
|
||||
return [new Hap(undefined, state.span, Fraction(1).div(state.span.duration))];
|
||||
});
|
||||
|
||||
export const perCycle = per;
|
||||
|
||||
/**
|
||||
* Like `per` but measures the shortness of events according to an exponential curve. In
|
||||
* particular, where the event duration halves, the
|
||||
* returned value increases by one. `perx.struct("1 1 [1 [1 1]] 1")` would therefore be
|
||||
* the same as `"3 3 [4 [5 5]] 3"`.
|
||||
*/
|
||||
export const perx = new Pattern(function (state) {
|
||||
const n = Fraction(1).div(state.span.duration);
|
||||
return [new Hap(undefined, state.span, Math.log(n) / Math.log(2) + 1)];
|
||||
});
|
||||
|
||||
@@ -586,6 +586,18 @@ describe('Pattern', () => {
|
||||
.map((a) => a.value),
|
||||
).toStrictEqual(['c', 'b', 'a']);
|
||||
});
|
||||
it('Does not reverse the order of cycles', () => {
|
||||
expect(fastcat('a', 'b', 'c', 'd').slow(2).rev().fast(2).sortHapsByPart().firstCycle()).toStrictEqual(
|
||||
fastcat('b', 'a', 'd', 'c').firstCycle(),
|
||||
);
|
||||
});
|
||||
});
|
||||
describe('revv()', () => {
|
||||
it('Does reverse the order of cycles', () => {
|
||||
expect(fastcat('a', 'b', 'c', 'd').slow(2).revv().fast(2).sortHapsByPart().firstCycle()).toStrictEqual(
|
||||
fastcat('d', 'c', 'b', 'a').firstCycle(),
|
||||
);
|
||||
});
|
||||
});
|
||||
describe('sequence()', () => {
|
||||
it('Can work like fastcat', () => {
|
||||
@@ -728,20 +740,6 @@ describe('Pattern', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
describe('signal()', () => {
|
||||
it('Can make saw/saw2', () => {
|
||||
expect(saw.struct(true, true, true, true).firstCycle()).toStrictEqual(
|
||||
sequence(0, 1 / 4, 1 / 2, 3 / 4).firstCycle(),
|
||||
);
|
||||
|
||||
expect(saw2.struct(true, true, true, true).firstCycle()).toStrictEqual(sequence(-1, -0.5, 0, 0.5).firstCycle());
|
||||
});
|
||||
it('Can make isaw/isaw2', () => {
|
||||
expect(isaw.struct(true, true, true, true).firstCycle()).toStrictEqual(sequence(1, 0.75, 0.5, 0.25).firstCycle());
|
||||
|
||||
expect(isaw2.struct(true, true, true, true).firstCycle()).toStrictEqual(sequence(1, 0.5, 0, -0.5).firstCycle());
|
||||
});
|
||||
});
|
||||
describe('_setContext()', () => {
|
||||
it('Can set the hap context', () => {
|
||||
expect(
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
signal.test.mjs - <short description TODO>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/test/pattern.test.mjs>
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import Fraction from 'fraction.js';
|
||||
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
import { saw, saw2, isaw, isaw2, per, perx, cyclesPer } from '../signal.mjs';
|
||||
import { fastcat, sequence, State, TimeSpan, Hap } from '../index.mjs';
|
||||
|
||||
const st = (begin, end) => new State(ts(begin, end));
|
||||
const ts = (begin, end) => new TimeSpan(Fraction(begin), Fraction(end));
|
||||
const hap = (whole, part, value, context = {}) => new Hap(whole, part, value, context);
|
||||
|
||||
const third = Fraction(1, 3);
|
||||
const twothirds = Fraction(2, 3);
|
||||
|
||||
const sameFirst = (a, b) => {
|
||||
return expect(a.sortHapsByPart().firstCycle()).toStrictEqual(b.sortHapsByPart().firstCycle());
|
||||
};
|
||||
|
||||
describe('signal()', () => {
|
||||
it('Can make saw/saw2', () => {
|
||||
expect(saw.struct(true, true, true, true).firstCycle()).toStrictEqual(
|
||||
sequence(0, 1 / 4, 1 / 2, 3 / 4).firstCycle(),
|
||||
);
|
||||
|
||||
expect(saw2.struct(true, true, true, true).firstCycle()).toStrictEqual(sequence(-1, -0.5, 0, 0.5).firstCycle());
|
||||
});
|
||||
it('Can make isaw/isaw2', () => {
|
||||
expect(isaw.struct(true, true, true, true).firstCycle()).toStrictEqual(sequence(1, 0.75, 0.5, 0.25).firstCycle());
|
||||
|
||||
expect(isaw2.struct(true, true, true, true).firstCycle()).toStrictEqual(sequence(1, 0.5, 0, -0.5).firstCycle());
|
||||
});
|
||||
});
|
||||
|
||||
describe('cyclesPer', () => {
|
||||
it('gives cycles per hap', () => {
|
||||
sameFirst(
|
||||
cyclesPer.struct(true, true, true, fastcat(true, true)),
|
||||
sequence(0.25, 0.25, 0.25, fastcat(0.125, 0.125)).fmap(Fraction),
|
||||
);
|
||||
});
|
||||
});
|
||||
describe('per', () => {
|
||||
it('gives haps per cycle', () => {
|
||||
sameFirst(per.struct(true, true, true, fastcat(true, true)), sequence(4, 4, 4, fastcat(8, 8)).fmap(Fraction));
|
||||
});
|
||||
});
|
||||
|
||||
describe('perx', () => {
|
||||
it('gives exponential haps per cycle', () => {
|
||||
sameFirst(
|
||||
perx.struct(true, true, true, fastcat(true, fastcat(true, true))),
|
||||
sequence(3, 3, 3, fastcat(4, fastcat(5, 5))),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -35,6 +35,7 @@ export async function initHydra(options = {}) {
|
||||
hydra.synth.s0.init({ src: canvas });
|
||||
}
|
||||
}
|
||||
return hydra;
|
||||
}
|
||||
|
||||
export function clearHydra() {
|
||||
|
||||
+26
-9
@@ -479,14 +479,24 @@ Pattern.prototype.midi = function (midiport, options = {}) {
|
||||
|
||||
let listeners = {};
|
||||
const refs = {};
|
||||
const refsByChan = {};
|
||||
|
||||
/**
|
||||
* MIDI input: Opens a MIDI input port to receive MIDI control change messages.
|
||||
*
|
||||
* The output is a function that accepts a midi cc value to query as well as (optionally) a midi channel
|
||||
* @param {string | number} input MIDI device name or index defaulting to 0
|
||||
* @returns {Function}
|
||||
* @returns {function(number, number=): Pattern} A function from (cc, channel?) to a pattern.
|
||||
* When queried, the pattern will produces the most recently received midi value (normalized to 0 to 1)
|
||||
* that came through that cc number (and channel, if provided)
|
||||
* @example
|
||||
* let cc = await midin('IAC Driver Bus 1')
|
||||
* const cc = await midin('IAC Driver Bus 1')
|
||||
* note("c a f e").lpf(cc(0).range(0, 1000)).lpq(cc(1).range(0, 10)).sound("sawtooth")
|
||||
* @example
|
||||
* const allCC = await midin('IAC Driver Bus 1')
|
||||
* const cc = (ccNum) => allCC(ccNum, 2) // just channel 2
|
||||
* note("c a f e").s("saw")
|
||||
* .when(cc(0).gt(0), x => x.postgain(0))
|
||||
*/
|
||||
export async function midin(input) {
|
||||
if (isPattern(input)) {
|
||||
@@ -511,17 +521,24 @@ export async function midin(input) {
|
||||
}`,
|
||||
);
|
||||
}
|
||||
// ensure refs for this input are initialized
|
||||
if (!refs[input]) {
|
||||
refs[input] = {};
|
||||
}
|
||||
const cc = (cc) => ref(() => refs[input][cc] || 0);
|
||||
refs[input] ??= {};
|
||||
refsByChan[input] ??= {};
|
||||
const cc = (cc, chan) => {
|
||||
if (chan !== undefined) {
|
||||
return ref(() => refsByChan[input][cc]?.[chan] || 0);
|
||||
}
|
||||
return ref(() => refs[input][cc] || 0);
|
||||
};
|
||||
|
||||
listeners[input] && device.removeListener('midimessage', listeners[input]);
|
||||
listeners[input] = (e) => {
|
||||
const cc = e.dataBytes[0];
|
||||
const ccNum = e.dataBytes[0];
|
||||
const v = e.dataBytes[1];
|
||||
refs[input] && (refs[input][cc] = v / 127);
|
||||
const chan = e.message.channel;
|
||||
const scaled = v / 127;
|
||||
refsByChan[input][ccNum] ??= {};
|
||||
refsByChan[input][ccNum][chan] = scaled;
|
||||
refs[input][ccNum] = scaled;
|
||||
};
|
||||
device.addListener('midimessage', listeners[input]);
|
||||
return cc;
|
||||
|
||||
@@ -9,6 +9,7 @@ import readline from 'readline';
|
||||
import os from 'os';
|
||||
|
||||
const LOG = !!process.env.LOG || false;
|
||||
const PORT = process.env.PORT || 5432;
|
||||
const VALID_AUDIO_EXTENSIONS = ['wav', 'mp3', 'ogg'];
|
||||
|
||||
const isAudioFile = (f) => {
|
||||
@@ -54,7 +55,6 @@ async function getBanks(directory, flat = false) {
|
||||
banks[bank].push(subDir);
|
||||
return subDir;
|
||||
});
|
||||
banks._base = `http://localhost:5432`;
|
||||
return { banks, files };
|
||||
}
|
||||
|
||||
@@ -134,8 +134,6 @@ const server = http.createServer(async (req, res) => {
|
||||
readStream.pipe(res);
|
||||
});
|
||||
|
||||
// eslint-disable-next-line
|
||||
const PORT = process.env.PORT || 5432;
|
||||
const IP_ADDRESS = '0.0.0.0';
|
||||
let IP;
|
||||
const networkInterfaces = os.networkInterfaces();
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
getADSRValues,
|
||||
getPitchEnvelope,
|
||||
getVibratoOscillator,
|
||||
onceEnded,
|
||||
releaseAudioNode,
|
||||
} from '@strudel/webaudio';
|
||||
import gm from './gm.mjs';
|
||||
|
||||
@@ -170,12 +172,11 @@ export function registerSoundfonts() {
|
||||
|
||||
bufferSource.stop(envEnd);
|
||||
const stop = (releaseTime) => {};
|
||||
bufferSource.onended = () => {
|
||||
bufferSource.disconnect();
|
||||
vibratoOscillator?.stop();
|
||||
node.disconnect();
|
||||
onceEnded(bufferSource, () => {
|
||||
releaseAudioNode(bufferSource);
|
||||
releaseAudioNode(vibratoOscillator);
|
||||
onended();
|
||||
};
|
||||
});
|
||||
return { node, stop };
|
||||
},
|
||||
{ type: 'soundfont', prebake: true, fonts },
|
||||
|
||||
@@ -5,6 +5,11 @@ export const setDefaultAudioContext = () => {
|
||||
return audioContext;
|
||||
};
|
||||
|
||||
export const setAudioContext = (context) => {
|
||||
audioContext = context;
|
||||
return audioContext;
|
||||
};
|
||||
|
||||
export const getAudioContext = () => {
|
||||
if (!audioContext) {
|
||||
return setDefaultAudioContext();
|
||||
|
||||
@@ -25,7 +25,7 @@ if (typeof DelayNode !== 'undefined') {
|
||||
}
|
||||
}
|
||||
|
||||
AudioContext.prototype.createFeedbackDelay = function (wet, time, feedback) {
|
||||
BaseAudioContext.prototype.createFeedbackDelay = function (wet, time, feedback) {
|
||||
return new FeedbackDelayNode(this, wet, time, feedback);
|
||||
};
|
||||
}
|
||||
|
||||
+185
-85
@@ -1,7 +1,7 @@
|
||||
import { getAudioContext } from './audioContext.mjs';
|
||||
import { clamp, nanFallback, midiToFreq, noteToMidi } from './util.mjs';
|
||||
import { getNoiseBuffer } from './noise.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
import { getNoiseBuffer } from './noise.mjs';
|
||||
import { clamp, nanFallback, midiToFreq, noteToMidi } from './util.mjs';
|
||||
|
||||
export const noises = ['pink', 'white', 'brown', 'crackle'];
|
||||
|
||||
@@ -42,6 +42,7 @@ export const getParamADSR = (
|
||||
decay,
|
||||
sustain,
|
||||
release,
|
||||
// min = value at start of attack, max = value at end of attack; it is possible that max < min
|
||||
min,
|
||||
max,
|
||||
begin,
|
||||
@@ -59,17 +60,15 @@ export const getParamADSR = (
|
||||
max = max === 0 ? 0.001 : max;
|
||||
}
|
||||
const range = max - min;
|
||||
const peak = max;
|
||||
const sustainVal = min + sustain * range;
|
||||
const duration = end - begin;
|
||||
|
||||
const envValAtTime = (time) => {
|
||||
let val;
|
||||
if (attack > time) {
|
||||
let slope = getSlope(min, peak, 0, attack);
|
||||
val = time * slope + (min > peak ? min : 0);
|
||||
val = time * getSlope(min, max, 0, attack) + min;
|
||||
} else {
|
||||
val = (time - attack) * getSlope(peak, sustainVal, 0, decay) + peak;
|
||||
val = (time - attack) * getSlope(max, sustainVal, 0, decay) + max;
|
||||
}
|
||||
if (curve === 'exponential') {
|
||||
val = val || 0.001;
|
||||
@@ -189,10 +188,9 @@ export function applyParameterModulators(audioContext, param, start, end, envelo
|
||||
getParamADSR(param, attack, decay, sustain, release, min, max, start, holdEnd, curve);
|
||||
}
|
||||
const lfo = getParamLfo(audioContext, param, start, end, lfoValues);
|
||||
return { lfo, disconnect: () => lfo?.disconnect() };
|
||||
return lfo;
|
||||
}
|
||||
|
||||
export function createFilter(context, start, end, params, cps) {
|
||||
export function createFilter(context, start, end, params, cps, cycle) {
|
||||
let {
|
||||
frequency,
|
||||
anchor,
|
||||
@@ -202,12 +200,14 @@ export function createFilter(context, start, end, params, cps) {
|
||||
q = 1,
|
||||
drive = 0.69,
|
||||
depth,
|
||||
depthfrequency,
|
||||
dcoffset = -0.5,
|
||||
skew,
|
||||
shape,
|
||||
rate,
|
||||
sync,
|
||||
} = params;
|
||||
|
||||
let frequencyParam, filter;
|
||||
if (model === 'ladder') {
|
||||
filter = getWorklet(context, 'ladder-processor', { frequency, q, drive });
|
||||
@@ -238,9 +238,27 @@ export function createFilter(context, start, end, params, cps) {
|
||||
if (sync != null) {
|
||||
rate = cps * sync;
|
||||
}
|
||||
const lfoValues = { depth, dcoffset, skew, shape, frequency: rate };
|
||||
getParamLfo(context, frequencyParam, start, end, lfoValues);
|
||||
return filter;
|
||||
const hasLFO = [depth, depthfrequency, skew, shape, rate].some((v) => v !== undefined);
|
||||
let lfo;
|
||||
if (hasLFO) {
|
||||
depth = depth ?? 1;
|
||||
const time = cycle / cps;
|
||||
const modDepth = depthfrequency ?? (depth ?? 1) * frequency;
|
||||
const lfoValues = {
|
||||
depth: modDepth,
|
||||
dcoffset,
|
||||
skew,
|
||||
shape,
|
||||
frequency: rate ?? cps,
|
||||
min: -frequency + 30,
|
||||
max: 20000 - frequency,
|
||||
time,
|
||||
curve: 1,
|
||||
};
|
||||
lfo = getParamLfo(context, frequencyParam, start, end, lfoValues);
|
||||
}
|
||||
|
||||
return { filter, lfo };
|
||||
}
|
||||
|
||||
// stays 1 until .5, then fades out
|
||||
@@ -262,7 +280,18 @@ export function drywet(dry, wet, wetAmount = 0) {
|
||||
let mix = ac.createGain();
|
||||
dry_gain.connect(mix);
|
||||
wet_gain.connect(mix);
|
||||
return mix;
|
||||
return {
|
||||
node: mix,
|
||||
teardown: () => {
|
||||
releaseAudioNode(dry_gain);
|
||||
releaseAudioNode(wet_gain);
|
||||
// it is not the responsability of drywet
|
||||
// to call `releaseAudioNode` on
|
||||
// the 2 external args dry and wet
|
||||
dry.disconnect(dry_gain);
|
||||
wet.disconnect(wet_gain);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
let curves = ['linear', 'exponential'];
|
||||
@@ -297,6 +326,10 @@ export function getVibratoOscillator(param, value, t) {
|
||||
gain.gain.value = vibmod * 100;
|
||||
vibratoOscillator.connect(gain);
|
||||
gain.connect(param);
|
||||
onceEnded(vibratoOscillator, () => {
|
||||
releaseAudioNode(gain);
|
||||
releaseAudioNode(vibratoOscillator);
|
||||
});
|
||||
vibratoOscillator.start(t);
|
||||
return vibratoOscillator;
|
||||
}
|
||||
@@ -318,25 +351,17 @@ export function webAudioTimeout(audioContext, onComplete, startTime, stopTime) {
|
||||
constantNode.connect(zeroGain);
|
||||
|
||||
// Schedule the `onComplete` callback to occur at `stopTime`
|
||||
constantNode.onended = () => {
|
||||
// Ensure garbage collection
|
||||
try {
|
||||
zeroGain.disconnect();
|
||||
} catch {
|
||||
// pass
|
||||
}
|
||||
try {
|
||||
constantNode.disconnect();
|
||||
} catch {
|
||||
// pass
|
||||
}
|
||||
onceEnded(constantNode, () => {
|
||||
releaseAudioNode(zeroGain);
|
||||
releaseAudioNode(constantNode);
|
||||
onComplete();
|
||||
};
|
||||
});
|
||||
constantNode.start(startTime);
|
||||
constantNode.stop(stopTime);
|
||||
return constantNode;
|
||||
}
|
||||
const mod = (freq, range = 1, type = 'sine') => {
|
||||
|
||||
const mod = (freq, type = 'sine') => {
|
||||
const ctx = getAudioContext();
|
||||
let osc;
|
||||
if (noises.includes(type)) {
|
||||
@@ -348,64 +373,89 @@ const mod = (freq, range = 1, type = 'sine') => {
|
||||
osc.type = type;
|
||||
osc.frequency.value = freq;
|
||||
}
|
||||
|
||||
osc.start();
|
||||
const g = new GainNode(ctx, { gain: range });
|
||||
osc.connect(g); // -range, range
|
||||
return { node: g, stop: (t) => osc.stop(t) };
|
||||
return osc;
|
||||
};
|
||||
const fm = (frequencyparam, harmonicityRatio, modulationIndex, wave = 'sine') => {
|
||||
|
||||
const fm = (frequencyparam, harmonicityRatio, wave = 'sine') => {
|
||||
const carrfreq = frequencyparam.value;
|
||||
const modfreq = carrfreq * harmonicityRatio;
|
||||
const modgain = modfreq * modulationIndex;
|
||||
return mod(modfreq, modgain, wave);
|
||||
return { osc: mod(modfreq, wave), freq: modfreq };
|
||||
};
|
||||
|
||||
export function applyFM(param, value, begin) {
|
||||
const {
|
||||
fmh: fmHarmonicity = 1,
|
||||
fmi: fmModulationIndex,
|
||||
fmenv: fmEnvelopeType = 'exp',
|
||||
fmattack: fmAttack,
|
||||
fmdecay: fmDecay,
|
||||
fmsustain: fmSustain,
|
||||
fmrelease: fmRelease,
|
||||
fmvelocity: fmVelocity,
|
||||
fmwave: fmWaveform = 'sine',
|
||||
duration,
|
||||
} = value;
|
||||
let modulator;
|
||||
let stop = () => {};
|
||||
|
||||
if (fmModulationIndex) {
|
||||
const ac = getAudioContext();
|
||||
const envGain = ac.createGain();
|
||||
const fmmod = fm(param, fmHarmonicity, fmModulationIndex, fmWaveform);
|
||||
|
||||
modulator = fmmod.node;
|
||||
stop = fmmod.stop;
|
||||
if (![fmAttack, fmDecay, fmSustain, fmRelease, fmVelocity].some((v) => v !== undefined)) {
|
||||
// no envelope by default
|
||||
modulator.connect(param);
|
||||
} else {
|
||||
const [attack, decay, sustain, release] = getADSRValues([fmAttack, fmDecay, fmSustain, fmRelease]);
|
||||
const holdEnd = begin + duration;
|
||||
getParamADSR(
|
||||
envGain.gain,
|
||||
attack,
|
||||
decay,
|
||||
sustain,
|
||||
release,
|
||||
0,
|
||||
1,
|
||||
begin,
|
||||
holdEnd,
|
||||
fmEnvelopeType === 'exp' ? 'exponential' : 'linear',
|
||||
);
|
||||
modulator.connect(envGain);
|
||||
envGain.connect(param);
|
||||
const ac = getAudioContext();
|
||||
const toStop = []; // fm oscillators we will expose `stop` for
|
||||
const fms = {};
|
||||
// Matrix
|
||||
for (let i = 1; i <= 8; i++) {
|
||||
for (let j = 0; j <= 8; j++) {
|
||||
let control;
|
||||
if (i === j + 1) {
|
||||
// Standard fm3 -> fm2 -> fm1 -> param usage
|
||||
const iS = i === 1 ? '' : i;
|
||||
control = `fmi${iS}`;
|
||||
} else {
|
||||
control = `fmi${i}${j}`;
|
||||
}
|
||||
const amt = value[control];
|
||||
if (!amt) continue;
|
||||
let io = [];
|
||||
for (let [isMod, idx] of [
|
||||
[true, i], // source
|
||||
[false, j], // target
|
||||
]) {
|
||||
if (idx === 0) {
|
||||
io.push(param);
|
||||
continue;
|
||||
}
|
||||
if (!fms[idx]) {
|
||||
const idxS = idx === 1 ? '' : idx;
|
||||
const { osc, freq } = fm(param, value[`fmh${idxS}`] ?? 1, value[`fmwave${idxS}`] ?? 'sine');
|
||||
toStop.push(osc);
|
||||
const toCleanup = [osc]; // nodes we want to cleanup after oscillator `stop`
|
||||
const adsr = ['attack', 'decay', 'sustain', 'release'].map((s) => value[`fm${s}${idxS}`]);
|
||||
let output = osc;
|
||||
if (adsr.some((v) => v !== undefined)) {
|
||||
const envGain = ac.createGain();
|
||||
const [attack, decay, sustain, release] = getADSRValues(adsr);
|
||||
const holdEnd = begin + value.duration;
|
||||
const fmEnvelopeType = value[`fmenv${idxS}`] ?? 'exp';
|
||||
getParamADSR(
|
||||
envGain.gain,
|
||||
attack,
|
||||
decay,
|
||||
sustain,
|
||||
release,
|
||||
0,
|
||||
1,
|
||||
begin,
|
||||
holdEnd,
|
||||
fmEnvelopeType === 'exp' ? 'exponential' : 'linear',
|
||||
);
|
||||
toCleanup.push(envGain);
|
||||
output = osc.connect(envGain);
|
||||
}
|
||||
fms[idx] = { input: osc.frequency, output, freq, osc, toCleanup };
|
||||
}
|
||||
const { input, output, freq, osc, toCleanup } = fms[idx];
|
||||
const g = gainNode(amt * freq);
|
||||
io.push(isMod ? output.connect(g) : input);
|
||||
cleanupOnEnd(osc, [...toCleanup, g]);
|
||||
}
|
||||
if (!io[1]) {
|
||||
logger(
|
||||
`[superdough] control ${control} failed to connect FM ${i} to target ${j} due to missing frequency parameter (likely because fm${j} is noise)`,
|
||||
'warning',
|
||||
);
|
||||
continue;
|
||||
}
|
||||
io[0].connect(io[1]);
|
||||
}
|
||||
}
|
||||
return { stop };
|
||||
return {
|
||||
stop: (t) => toStop.forEach((m) => m?.stop(t)),
|
||||
};
|
||||
}
|
||||
|
||||
// Saturation curves
|
||||
@@ -505,7 +555,7 @@ export const getDistortion = (distort, postgain, algorithm) => {
|
||||
};
|
||||
|
||||
export const getFrequencyFromValue = (value, defaultNote = 36) => {
|
||||
let { note, freq } = value;
|
||||
let { note, freq, octave = 0 } = value;
|
||||
note = note || defaultNote;
|
||||
if (typeof note === 'string') {
|
||||
note = noteToMidi(note); // e.g. c3 => 48
|
||||
@@ -514,14 +564,64 @@ export const getFrequencyFromValue = (value, defaultNote = 36) => {
|
||||
if (!freq && typeof note === 'number') {
|
||||
freq = midiToFreq(note); // + 48);
|
||||
}
|
||||
|
||||
freq *= Math.pow(2, octave);
|
||||
return Number(freq);
|
||||
};
|
||||
|
||||
export const destroyAudioWorkletNode = (node) => {
|
||||
if (node == null) {
|
||||
return;
|
||||
}
|
||||
node.disconnect();
|
||||
node.parameters.get('end')?.setValueAtTime(0, 0);
|
||||
// This helper should be used instead of the `node.onended = callback` pattern
|
||||
// It adds a mechanism to help minimize gc retention
|
||||
export const onceEnded = (node, callback) => {
|
||||
const onended = callback;
|
||||
node.onended = function cleanup() {
|
||||
onended && onended();
|
||||
this.onended = null;
|
||||
};
|
||||
};
|
||||
|
||||
export const releaseAudioNode = (node) => {
|
||||
if (node == null) return;
|
||||
|
||||
// check we received an AudioNode
|
||||
if (!(node instanceof AudioNode)) {
|
||||
throw new Error('releaseAudioNode can only release an AudioNode');
|
||||
}
|
||||
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/AudioNode/disconnect
|
||||
node.disconnect();
|
||||
|
||||
// make sure all AudioScheduledSourceNodes are in a stopped state
|
||||
// https://developer.mozilla.org/en-US/docs/Web/API/AudioScheduledSourceNode
|
||||
if (node instanceof AudioScheduledSourceNode) {
|
||||
if (process.env.NODE_ENV === 'development' && node.onended && node.onended.name !== 'cleanup') {
|
||||
logger(
|
||||
`[superdough] Deprecation warning: it seems your code path is setting 'node.onended = callback' instead of using the onceEnded helper`,
|
||||
);
|
||||
}
|
||||
try {
|
||||
node.stop();
|
||||
} catch (e) {
|
||||
// At the stage, `start` was not called on the node
|
||||
// but an `onended` callback releasing resources may exist
|
||||
// and we want it to fire :
|
||||
// - we force a start/stop cycle so that `onended` gets called
|
||||
// - we `lock` the node so that no-one can start it
|
||||
node.start(node.context.currentTime + 5); // will never happen
|
||||
node.stop();
|
||||
}
|
||||
}
|
||||
|
||||
// https://www.w3.org/TR/webaudio-1.1/#AudioNode-actively-processing
|
||||
// An AudioWorkletNode is actively processing when its AudioWorkletProcessor's [[callable process]]
|
||||
// returns true and either its active source flag is true or
|
||||
// any AudioNode connected to one of its inputs is actively processing.
|
||||
if (node instanceof AudioWorkletNode) {
|
||||
// while `end` is not native to the web audio API, it is common practice in superdough
|
||||
// to use that param in the worklets to trigger returning false from the processor
|
||||
node.parameters.get('end')?.setValueAtTime(0, 0);
|
||||
}
|
||||
};
|
||||
|
||||
// Once the `anchor` node has ended, release all nodes in `toCleanup`
|
||||
export const cleanupOnEnd = (anchor, toCleanup) => {
|
||||
onceEnded(anchor, () => toCleanup.forEach((n) => releaseAudioNode(n)));
|
||||
};
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { drywet } from './helpers.mjs';
|
||||
import { drywet, onceEnded, releaseAudioNode } from './helpers.mjs';
|
||||
import { getAudioContext } from './audioContext.mjs';
|
||||
|
||||
let noiseCache = {};
|
||||
@@ -65,8 +65,12 @@ export function getNoiseOscillator(type = 'white', t, density = 0.02) {
|
||||
export function getNoiseMix(inputNode, wet, t) {
|
||||
const noiseOscillator = getNoiseOscillator('pink', t);
|
||||
const noiseMix = drywet(inputNode, noiseOscillator.node, wet);
|
||||
onceEnded(noiseOscillator.node, () => {
|
||||
releaseAudioNode(noiseOscillator.node);
|
||||
});
|
||||
return {
|
||||
node: noiseMix,
|
||||
node: noiseMix.node,
|
||||
stop: (time) => noiseOscillator?.stop(time),
|
||||
teardown: noiseMix.teardown,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import reverbGen from './reverbGen.mjs';
|
||||
import { clamp } from './util.mjs';
|
||||
|
||||
if (typeof AudioContext !== 'undefined') {
|
||||
AudioContext.prototype.adjustLength = function (duration, buffer, speed = 1, offsetAmount = 0) {
|
||||
BaseAudioContext.prototype.adjustLength = function (duration, buffer, speed = 1, offsetAmount = 0) {
|
||||
const sampleOffset = Math.floor(clamp(offsetAmount, 0, 1) * buffer.length);
|
||||
const newLength = buffer.sampleRate * duration;
|
||||
const newBuffer = this.createBuffer(buffer.numberOfChannels, buffer.length, buffer.sampleRate);
|
||||
@@ -23,7 +23,7 @@ if (typeof AudioContext !== 'undefined') {
|
||||
return newBuffer;
|
||||
};
|
||||
|
||||
AudioContext.prototype.createReverb = function (duration, fade, lp, dim, ir, irspeed, irbegin) {
|
||||
BaseAudioContext.prototype.createReverb = function (duration, fade, lp, dim, ir, irspeed, irbegin) {
|
||||
const convolver = this.createConvolver();
|
||||
convolver.generate = (d = 2, fade = 0.1, lp = 15000, dim = 1000, ir, irspeed, irbegin) => {
|
||||
convolver.duration = d;
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import { getCommonSampleInfo } from './util.mjs';
|
||||
import { getBaseURL, getCommonSampleInfo } from './util.mjs';
|
||||
import { registerSound, registerWaveTable } from './index.mjs';
|
||||
import { getAudioContext } from './audioContext.mjs';
|
||||
import { getADSRValues, getParamADSR, getPitchEnvelope, getVibratoOscillator } from './helpers.mjs';
|
||||
import {
|
||||
getADSRValues,
|
||||
getParamADSR,
|
||||
getPitchEnvelope,
|
||||
getVibratoOscillator,
|
||||
onceEnded,
|
||||
releaseAudioNode,
|
||||
} from './helpers.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
|
||||
const bufferCache = {}; // string: Promise<ArrayBuffer>
|
||||
@@ -211,7 +218,7 @@ export async function fetchSampleMap(url) {
|
||||
// not a browser
|
||||
return;
|
||||
}
|
||||
const base = url.split('/').slice(0, -1).join('/');
|
||||
const base = getBaseURL(url);
|
||||
if (typeof fetch === 'undefined') {
|
||||
// skip fetch when in node / testing
|
||||
return;
|
||||
@@ -236,12 +243,6 @@ export async function fetchSampleMap(url) {
|
||||
* sd: '808sd/SD0010.WAV'
|
||||
* }, 'https://raw.githubusercontent.com/tidalcycles/Dirt-Samples/master/');
|
||||
* s("[bd ~]*2, [~ hh]*2, ~ sd")
|
||||
* @example
|
||||
* samples('shabda:noise,chimp:2')
|
||||
* s("noise <chimp:0*2 chimp:1>")
|
||||
* @example
|
||||
* samples('shabda/speech/fr-FR/f:chocolat')
|
||||
* s("chocolat*4")
|
||||
*/
|
||||
|
||||
export const samples = async (sampleMap, baseUrl = sampleMap._base || '', options = {}) => {
|
||||
@@ -286,17 +287,19 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) {
|
||||
|
||||
const { bufferSource, sliceDuration, offset } = await getSampleBufferSource(value, bank, resolveUrl);
|
||||
|
||||
// asny stuff above took too long?
|
||||
if (ac.currentTime > t) {
|
||||
logger(`[sampler] still loading sound "${s}:${n}"`, 'highlight');
|
||||
// console.warn('sample still loading:', s, n);
|
||||
return;
|
||||
}
|
||||
if (!bufferSource) {
|
||||
logger(`[sampler] could not load "${s}:${n}"`, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
// async stuff above took too long?
|
||||
if (ac.currentTime > t) {
|
||||
logger(`[sampler] loading sound "${s}:${n}" took too long`, 'highlight');
|
||||
// AudioBufferSourceNode will never be used. discard it
|
||||
releaseAudioNode(bufferSource);
|
||||
return;
|
||||
}
|
||||
|
||||
// vibrato
|
||||
let vibratoOscillator = getVibratoOscillator(bufferSource.detune, value, t);
|
||||
|
||||
@@ -319,13 +322,13 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) {
|
||||
|
||||
const out = ac.createGain(); // we need a separate gain for the cutgroups because firefox...
|
||||
node.connect(out);
|
||||
bufferSource.onended = function () {
|
||||
bufferSource.disconnect();
|
||||
vibratoOscillator?.stop();
|
||||
node.disconnect();
|
||||
out.disconnect();
|
||||
onceEnded(bufferSource, function () {
|
||||
releaseAudioNode(bufferSource);
|
||||
releaseAudioNode(vibratoOscillator);
|
||||
releaseAudioNode(node);
|
||||
releaseAudioNode(out);
|
||||
onended();
|
||||
};
|
||||
});
|
||||
let envEnd = holdEnd + release + 0.01;
|
||||
bufferSource.stop(envEnd);
|
||||
const stop = (endTime) => {
|
||||
|
||||
@@ -9,23 +9,44 @@ import './reverb.mjs';
|
||||
import './vowel.mjs';
|
||||
import { nanFallback, _mod, cycleToSeconds, pickAndRename } from './util.mjs';
|
||||
import workletsUrl from './worklets.mjs?audioworklet';
|
||||
import { createFilter, gainNode, getCompressor, getDistortion, getLfo, getWorklet, effectSend } from './helpers.mjs';
|
||||
import {
|
||||
createFilter,
|
||||
gainNode,
|
||||
getCompressor,
|
||||
getDistortion,
|
||||
getLfo,
|
||||
getWorklet,
|
||||
effectSend,
|
||||
releaseAudioNode,
|
||||
} from './helpers.mjs';
|
||||
import { map } from 'nanostores';
|
||||
import { logger } from './logger.mjs';
|
||||
import { loadBuffer } from './sampler.mjs';
|
||||
import { getAudioContext } from './audioContext.mjs';
|
||||
import { getAudioContext, setAudioContext } from './audioContext.mjs';
|
||||
import { SuperdoughAudioController } from './superdoughoutput.mjs';
|
||||
import { resetSeenKeys } from './wavetable.mjs';
|
||||
|
||||
export const DEFAULT_MAX_POLYPHONY = 128;
|
||||
const DEFAULT_AUDIO_DEVICE_NAME = 'System Standard';
|
||||
|
||||
let maxPolyphony = DEFAULT_MAX_POLYPHONY;
|
||||
export let maxPolyphony = DEFAULT_MAX_POLYPHONY;
|
||||
|
||||
/**
|
||||
* Set the max polyphony. If notes are ringing out via `release` then they will
|
||||
* start to die out in first-in-first-out order once the max polyphony has been hit
|
||||
*
|
||||
* @name setMaxPolyphony
|
||||
* @param {number} Max polyphony. Defaults to 128
|
||||
* @example
|
||||
* setMaxPolyphony(4)
|
||||
* n(irand(24).seg(8)).scale("C#3:minor").room(1).release(4).gain(0.5)
|
||||
*
|
||||
*/
|
||||
export function setMaxPolyphony(polyphony) {
|
||||
maxPolyphony = parseInt(polyphony) ?? DEFAULT_MAX_POLYPHONY;
|
||||
}
|
||||
|
||||
let multiChannelOrbits = false;
|
||||
export let multiChannelOrbits = false;
|
||||
export function setMultiChannelOrbits(bool) {
|
||||
multiChannelOrbits = bool == true;
|
||||
}
|
||||
@@ -43,6 +64,17 @@ export function applyGainCurve(val) {
|
||||
return gainCurveFunc(val);
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a function to all gains provided in patterns. Can be used to rescale gain to be
|
||||
* quadratic, exponential, etc. rather than linear
|
||||
*
|
||||
* @name setGainCurve
|
||||
* @param {Function} function to apply to all gain values
|
||||
* @example
|
||||
* setGainCurve((x) => x * x) // quadratic gain
|
||||
* s("bd*4").gain(0.5) // equivalent to 0.25 gain normally
|
||||
*
|
||||
*/
|
||||
export function setGainCurve(newGainCurveFunc) {
|
||||
gainCurveFunc = newGainCurveFunc;
|
||||
}
|
||||
@@ -203,11 +235,13 @@ export function registerWorklet(url) {
|
||||
}
|
||||
|
||||
let workletsLoading;
|
||||
function loadWorklets() {
|
||||
export function loadWorklets() {
|
||||
if (!workletsLoading) {
|
||||
const audioCtx = getAudioContext();
|
||||
const allWorkletURLs = externalWorklets.concat([workletsUrl]);
|
||||
workletsLoading = Promise.all(allWorkletURLs.map((workletURL) => audioCtx.audioWorklet.addModule(workletURL)));
|
||||
workletsLoading = Promise.all(allWorkletURLs.map((workletURL) => audioCtx.audioWorklet.addModule(workletURL))).then(
|
||||
() => (workletsLoading = undefined),
|
||||
);
|
||||
}
|
||||
|
||||
return workletsLoading;
|
||||
@@ -224,6 +258,7 @@ export async function initAudio(options = {}) {
|
||||
|
||||
setMaxPolyphony(maxPolyphony);
|
||||
setMultiChannelOrbits(multiChannelOrbits);
|
||||
resetSeenKeys();
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
@@ -245,8 +280,9 @@ export async function initAudio(options = {}) {
|
||||
logger('[superdough] failed to set audio interface', 'warning');
|
||||
}
|
||||
}
|
||||
|
||||
await audioCtx.resume();
|
||||
if ((!audioCtx) instanceof OfflineAudioContext) {
|
||||
await audioCtx.resume();
|
||||
}
|
||||
if (disableWorklets) {
|
||||
logger('[superdough]: AudioWorklets disabled with disableWorklets');
|
||||
return;
|
||||
@@ -263,8 +299,8 @@ let audioReady;
|
||||
export async function initAudioOnFirstClick(options) {
|
||||
if (!audioReady) {
|
||||
audioReady = new Promise((resolve) => {
|
||||
document.addEventListener('click', async function listener() {
|
||||
document.removeEventListener('click', listener);
|
||||
document.addEventListener('mousedown', async function listener() {
|
||||
document.removeEventListener('mousedown', listener);
|
||||
await initAudio(options);
|
||||
resolve();
|
||||
});
|
||||
@@ -274,12 +310,18 @@ export async function initAudioOnFirstClick(options) {
|
||||
}
|
||||
|
||||
let controller;
|
||||
function getSuperdoughAudioController() {
|
||||
export function getSuperdoughAudioController() {
|
||||
if (controller == null) {
|
||||
controller = new SuperdoughAudioController(getAudioContext());
|
||||
}
|
||||
return controller;
|
||||
}
|
||||
|
||||
export function setSuperdoughAudioController(newController) {
|
||||
controller = newController;
|
||||
return controller;
|
||||
}
|
||||
|
||||
export function connectToDestination(input, channels) {
|
||||
const controller = getSuperdoughAudioController();
|
||||
controller.output.connectToDestination(input, channels);
|
||||
@@ -287,11 +329,11 @@ export function connectToDestination(input, channels) {
|
||||
|
||||
function getPhaser(time, end, frequency = 1, depth = 0.5, centerFrequency = 1000, sweep = 2000) {
|
||||
const ac = getAudioContext();
|
||||
const lfoGain = getLfo(ac, time, end, { frequency, depth: sweep * 2 });
|
||||
const lfo = getLfo(ac, time, end, { frequency, depth: sweep * 2 });
|
||||
|
||||
//filters
|
||||
const numStages = 2; //num of filters in series
|
||||
let fOffset = 0;
|
||||
const numStages = 1; //num of filters in series
|
||||
let fOffset = 282; //for backward compat in #1800
|
||||
const filterChain = [];
|
||||
for (let i = 0; i < numStages; i++) {
|
||||
const filter = ac.createBiquadFilter();
|
||||
@@ -300,14 +342,11 @@ function getPhaser(time, end, frequency = 1, depth = 0.5, centerFrequency = 1000
|
||||
filter.frequency.value = centerFrequency + fOffset;
|
||||
filter.Q.value = 2 - Math.min(Math.max(depth * 2, 0), 1.9);
|
||||
|
||||
lfoGain.connect(filter.detune);
|
||||
lfo.connect(filter.detune);
|
||||
fOffset += 282;
|
||||
if (i > 0) {
|
||||
filterChain[i - 1].connect(filter);
|
||||
}
|
||||
filterChain.push(filter);
|
||||
}
|
||||
return filterChain[filterChain.length - 1];
|
||||
return { filterChain, lfo };
|
||||
}
|
||||
|
||||
function getFilterType(ftype) {
|
||||
@@ -320,7 +359,7 @@ export let analysers = {},
|
||||
analysersData = {};
|
||||
|
||||
export function getAnalyserById(id, fftSize = 1024, smoothingTimeConstant = 0.5) {
|
||||
if (!analysers[id]) {
|
||||
if (!analysers[id] || analysers[id].audioContext != getAudioContext()) {
|
||||
// make sure this doesn't happen too often as it piles up garbage
|
||||
const analyserNode = getAudioContext().createAnalyser();
|
||||
analyserNode.fftSize = fftSize;
|
||||
@@ -382,7 +421,6 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
// duration is passed as value too..
|
||||
value.duration = hapDuration;
|
||||
// calculate absolute time
|
||||
|
||||
if (t < ac.currentTime) {
|
||||
console.warn(
|
||||
`[superdough]: cannot schedule sounds in the past (target: ${t.toFixed(2)}, now: ${ac.currentTime.toFixed(2)})`,
|
||||
@@ -413,7 +451,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
release = 0,
|
||||
|
||||
//phaser
|
||||
phaserrate: phaser,
|
||||
phaserrate,
|
||||
phaserdepth = getDefaultValue('phaserdepth'),
|
||||
phasersweep,
|
||||
phasercenter,
|
||||
@@ -451,6 +489,8 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
compressorKnee,
|
||||
compressorAttack,
|
||||
compressorRelease,
|
||||
transient,
|
||||
transsustain,
|
||||
} = value;
|
||||
|
||||
delaytime = delaytime ?? cycleToSeconds(delaysync, cps);
|
||||
@@ -506,7 +546,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
} else if (getSound(s)) {
|
||||
const { onTrigger } = getSound(s);
|
||||
const onEnded = () => {
|
||||
audioNodes.forEach((n) => n?.disconnect());
|
||||
audioNodes.forEach((n) => releaseAudioNode(n));
|
||||
activeSoundSources.delete(chainID);
|
||||
};
|
||||
const soundHandle = await onTrigger(t, value, onEnded, cps);
|
||||
@@ -532,6 +572,23 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
chain.push(sourceNode);
|
||||
stretch !== undefined && chain.push(getWorklet(ac, 'phase-vocoder-processor', { pitchFactor: stretch }));
|
||||
|
||||
transient !== undefined &&
|
||||
chain.push(
|
||||
getWorklet(
|
||||
ac,
|
||||
'transient-processor',
|
||||
{},
|
||||
{
|
||||
processorOptions: {
|
||||
attack: transient,
|
||||
sustain: transsustain,
|
||||
begin: t,
|
||||
end: endWithRelease,
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
// gain stage
|
||||
chain.push(gainNode(gain));
|
||||
|
||||
@@ -553,16 +610,21 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
rate: 'lprate',
|
||||
sync: 'lpsync',
|
||||
depth: 'lpdepth',
|
||||
depthfrequency: 'lpdepthfrequency',
|
||||
shape: 'lpshape',
|
||||
dcoffset: 'lpdc',
|
||||
skew: 'lpskew',
|
||||
};
|
||||
const lpParams = pickAndRename(value, lpMap);
|
||||
lpParams.type = 'lowpass';
|
||||
let lp = () => createFilter(ac, t, end, lpParams, cps);
|
||||
chain.push(lp());
|
||||
const lp = () => createFilter(ac, t, end, lpParams, cps, cycle);
|
||||
const { filter: lpf1, lfo: lfo1 } = lp();
|
||||
chain.push(lpf1);
|
||||
lfo1 && audioNodes.push(lfo1);
|
||||
if (ftype === '24db') {
|
||||
chain.push(lp());
|
||||
const { filter: lpf2, lfo: lfo2 } = lp();
|
||||
chain.push(lpf2);
|
||||
lfo2 && audioNodes.push(lfo2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -581,16 +643,21 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
rate: 'hprate',
|
||||
sync: 'hpsync',
|
||||
depth: 'hpdepth',
|
||||
depthfrequency: 'hpdepthfrequency',
|
||||
shape: 'hpshape',
|
||||
dcoffset: 'hpdc',
|
||||
skew: 'hpskew',
|
||||
};
|
||||
const hpParams = pickAndRename(value, hpMap);
|
||||
hpParams.type = 'highpass';
|
||||
let hp = () => createFilter(ac, t, end, hpParams, cps);
|
||||
chain.push(hp());
|
||||
const hp = () => createFilter(ac, t, end, hpParams, cps, cycle);
|
||||
const { filter: hpf1, lfo: lfo1 } = hp();
|
||||
chain.push(hpf1);
|
||||
lfo1 && audioNodes.push(lfo1);
|
||||
if (ftype === '24db') {
|
||||
chain.push(hp());
|
||||
const { filter: hpf2, lfo: lfo2 } = hp();
|
||||
chain.push(hpf2);
|
||||
lfo2 && audioNodes.push(lfo2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -609,16 +676,21 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
rate: 'bprate',
|
||||
sync: 'bpsync',
|
||||
depth: 'bpdepth',
|
||||
depthfrequency: 'bpdepthfrequency',
|
||||
shape: 'bpshape',
|
||||
dcoffset: 'bpdc',
|
||||
skew: 'bpskew',
|
||||
};
|
||||
const bpParams = pickAndRename(value, bpMap);
|
||||
bpParams.type = 'bandpass';
|
||||
let bp = () => createFilter(ac, t, end, bpParams, cps);
|
||||
chain.push(bp());
|
||||
const bp = () => createFilter(ac, t, end, bpParams, cps, cycle);
|
||||
const { filter: bpf1, lfo: lfo1 } = bp();
|
||||
chain.push(bpf1);
|
||||
lfo1 && audioNodes.push(lfo1);
|
||||
if (ftype === '24db') {
|
||||
chain.push(bp());
|
||||
const { filter: bpf2, lfo: lfo2 } = bp();
|
||||
chain.push(bpf2);
|
||||
lfo2 && audioNodes.push(lfo2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -665,6 +737,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
curve: 1.5,
|
||||
});
|
||||
lfo.connect(amGain.gain);
|
||||
audioNodes.push(lfo);
|
||||
chain.push(amGain);
|
||||
}
|
||||
|
||||
@@ -680,9 +753,10 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
chain.push(panner);
|
||||
}
|
||||
// phaser
|
||||
if (phaser !== undefined && phaserdepth > 0) {
|
||||
const phaserFX = getPhaser(t, endWithRelease, phaser, phaserdepth, phasercenter, phasersweep);
|
||||
chain.push(phaserFX);
|
||||
if (phaserrate !== undefined && phaserdepth > 0) {
|
||||
const { filterChain, lfo } = getPhaser(t, endWithRelease, phaserrate, phaserdepth, phasercenter, phasersweep);
|
||||
audioNodes.push(lfo);
|
||||
chain.push(...filterChain);
|
||||
}
|
||||
|
||||
// last gain
|
||||
@@ -692,7 +766,8 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
// delay
|
||||
if (delay > 0 && delaytime > 0 && delayfeedback > 0) {
|
||||
orbitBus.getDelay(delaytime, delayfeedback, t);
|
||||
orbitBus.sendDelay(post, delay);
|
||||
const send = orbitBus.sendDelay(post, delay);
|
||||
audioNodes.push(send);
|
||||
}
|
||||
// reverb
|
||||
if (room > 0) {
|
||||
@@ -717,7 +792,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
|
||||
}
|
||||
|
||||
// analyser
|
||||
if (analyze) {
|
||||
if (analyze && !(ac instanceof OfflineAudioContext)) {
|
||||
const analyserNode = getAnalyserById(analyze, 2 ** (fft + 5));
|
||||
const analyserSend = effectSend(post, analyserNode, 1);
|
||||
audioNodes.push(analyserSend);
|
||||
|
||||
@@ -82,7 +82,7 @@ export class Orbit {
|
||||
}
|
||||
|
||||
sendDelay(node, amount) {
|
||||
effectSend(node, this.delayNode, amount);
|
||||
return effectSend(node, this.delayNode, amount);
|
||||
}
|
||||
|
||||
duck(t, onsettime = 0, attacktime = 0.1, depth = 1) {
|
||||
|
||||
@@ -3,7 +3,6 @@ import { registerSound, soundMap } from './superdough.mjs';
|
||||
import { getAudioContext } from './audioContext.mjs';
|
||||
import {
|
||||
applyFM,
|
||||
destroyAudioWorkletNode,
|
||||
gainNode,
|
||||
getADSRValues,
|
||||
getFrequencyFromValue,
|
||||
@@ -13,6 +12,8 @@ import {
|
||||
getVibratoOscillator,
|
||||
getWorklet,
|
||||
noises,
|
||||
onceEnded,
|
||||
releaseAudioNode,
|
||||
webAudioTimeout,
|
||||
} from './helpers.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
@@ -48,19 +49,17 @@ export function registerSynthSounds() {
|
||||
[0.001, 0.05, 0.6, 0.01],
|
||||
);
|
||||
|
||||
let sound = getOscillator(s, t, value);
|
||||
let { node: o, stop, triggerRelease } = sound;
|
||||
|
||||
// turn down
|
||||
const g = gainNode(0.3);
|
||||
|
||||
const { duration } = value;
|
||||
|
||||
o.onended = () => {
|
||||
o.disconnect();
|
||||
g.disconnect();
|
||||
let sound = getOscillator(s, t, value, () => {
|
||||
releaseAudioNode(g);
|
||||
onended();
|
||||
};
|
||||
});
|
||||
|
||||
let { node: o, stop, triggerRelease } = sound;
|
||||
|
||||
const { duration } = value;
|
||||
|
||||
const envGain = gainNode(1);
|
||||
let node = o.connect(g).connect(envGain);
|
||||
@@ -112,15 +111,15 @@ export function registerSynthSounds() {
|
||||
|
||||
const mix = gainNode(mixGain);
|
||||
|
||||
o.onended = () => {
|
||||
o.disconnect();
|
||||
g.disconnect();
|
||||
sat.disconnect();
|
||||
noise.node.disconnect();
|
||||
noiseGain.disconnect();
|
||||
mix.disconnect();
|
||||
onceEnded(o, () => {
|
||||
releaseAudioNode(o);
|
||||
releaseAudioNode(g);
|
||||
releaseAudioNode(sat);
|
||||
releaseAudioNode(noise.node);
|
||||
releaseAudioNode(noiseGain);
|
||||
releaseAudioNode(mix);
|
||||
onended();
|
||||
};
|
||||
});
|
||||
|
||||
const node = o.connect(sat).connect(g).connect(mix);
|
||||
noise.node.connect(noiseGain).connect(mix);
|
||||
@@ -194,8 +193,7 @@ export function registerSynthSounds() {
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(o);
|
||||
envGain.disconnect();
|
||||
releaseAudioNode(o);
|
||||
onended();
|
||||
fm?.stop();
|
||||
vibratoOscillator?.stop();
|
||||
@@ -272,8 +270,7 @@ export function registerSynthSounds() {
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(o);
|
||||
envGain.disconnect();
|
||||
releaseAudioNode(o);
|
||||
onended();
|
||||
},
|
||||
begin,
|
||||
@@ -346,9 +343,8 @@ export function registerSynthSounds() {
|
||||
let timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(o);
|
||||
destroyAudioWorkletNode(lfo);
|
||||
envGain.disconnect();
|
||||
releaseAudioNode(o);
|
||||
releaseAudioNode(lfo);
|
||||
onended();
|
||||
fm?.stop();
|
||||
vibratoOscillator?.stop();
|
||||
@@ -389,11 +385,11 @@ export function registerSynthSounds() {
|
||||
|
||||
const { duration } = value;
|
||||
|
||||
o.onended = () => {
|
||||
o.disconnect();
|
||||
g.disconnect();
|
||||
onceEnded(o, () => {
|
||||
releaseAudioNode(o);
|
||||
releaseAudioNode(g);
|
||||
onended();
|
||||
};
|
||||
});
|
||||
|
||||
const envGain = gainNode(1);
|
||||
let node = o.connect(g).connect(envGain);
|
||||
@@ -460,7 +456,7 @@ export function waveformN(partials, phases, type) {
|
||||
}
|
||||
|
||||
// expects one of waveforms as s
|
||||
export function getOscillator(s, t, value) {
|
||||
export function getOscillator(s, t, value, onended) {
|
||||
const { duration, noise = 0 } = value;
|
||||
const partials = value.partials ?? value.n;
|
||||
let o;
|
||||
@@ -482,7 +478,6 @@ export function getOscillator(s, t, value) {
|
||||
}
|
||||
// set frequency
|
||||
o.frequency.value = getFrequencyFromValue(value);
|
||||
o.start(t);
|
||||
|
||||
let vibratoOscillator = getVibratoOscillator(o.detune, value, t);
|
||||
|
||||
@@ -495,6 +490,14 @@ export function getOscillator(s, t, value) {
|
||||
noiseMix = getNoiseMix(o, noise, t);
|
||||
}
|
||||
|
||||
onceEnded(o, () => {
|
||||
noiseMix?.teardown();
|
||||
releaseAudioNode(o);
|
||||
releaseAudioNode(noiseMix?.node);
|
||||
onended();
|
||||
});
|
||||
o.start(t);
|
||||
|
||||
return {
|
||||
node: noiseMix?.node || o,
|
||||
stop: (time) => {
|
||||
|
||||
@@ -114,3 +114,13 @@ export function getCommonSampleInfo(hapValue, bank) {
|
||||
export const pickAndRename = (source, map) => {
|
||||
return Object.fromEntries(Object.entries(map).map(([newKey, oldKey]) => [newKey, source[oldKey]]));
|
||||
};
|
||||
|
||||
export const getBaseURL = (url) => {
|
||||
try {
|
||||
// For real URLs
|
||||
return new URL('.', new URL(url)).href.replace(/\/$/, ''); // removes trailing slash
|
||||
} catch {
|
||||
// For pseudo URLS
|
||||
return url.split('/').slice(0, -1).join('/');
|
||||
}
|
||||
};
|
||||
|
||||
@@ -45,7 +45,8 @@ if (typeof GainNode !== 'undefined') {
|
||||
throw new Error('vowel: unknown vowel ' + letter);
|
||||
}
|
||||
const { gains, qs, freqs } = vowelFormant[letter];
|
||||
const makeupGain = ac.createGain();
|
||||
this.makeupGain = ac.createGain();
|
||||
this.audioNodes = [];
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const gain = ac.createGain();
|
||||
gain.gain.value = gains[i];
|
||||
@@ -53,17 +54,28 @@ if (typeof GainNode !== 'undefined') {
|
||||
filter.type = 'bandpass';
|
||||
filter.Q.value = qs[i];
|
||||
filter.frequency.value = freqs[i];
|
||||
this.connect(filter);
|
||||
super.connect(filter);
|
||||
filter.connect(gain);
|
||||
gain.connect(makeupGain);
|
||||
this.audioNodes.push(filter);
|
||||
gain.connect(this.makeupGain);
|
||||
this.audioNodes.push(gain);
|
||||
}
|
||||
makeupGain.gain.value = 8; // how much makeup gain to add?
|
||||
this.connect = (target) => makeupGain.connect(target);
|
||||
this.makeupGain.gain.value = 8; // how much makeup gain to add?
|
||||
return this;
|
||||
}
|
||||
connect(target) {
|
||||
this.makeupGain.connect(target);
|
||||
}
|
||||
disconnect() {
|
||||
this.makeupGain.disconnect();
|
||||
this.audioNodes.forEach((n) => n.disconnect());
|
||||
super.disconnect();
|
||||
this.makeupGain = null;
|
||||
this.audioNodes = null;
|
||||
}
|
||||
}
|
||||
|
||||
AudioContext.prototype.createVowelFilter = function (letter) {
|
||||
BaseAudioContext.prototype.createVowelFilter = function (letter) {
|
||||
return new VowelNode(this, letter);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { getAudioContext, registerSound } from './index.mjs';
|
||||
import { getCommonSampleInfo } from './util.mjs';
|
||||
import { getBaseURL, getCommonSampleInfo } from './util.mjs';
|
||||
import {
|
||||
applyFM,
|
||||
applyParameterModulators,
|
||||
destroyAudioWorkletNode,
|
||||
getADSRValues,
|
||||
getFrequencyFromValue,
|
||||
getParamADSR,
|
||||
getPitchEnvelope,
|
||||
getVibratoOscillator,
|
||||
getWorklet,
|
||||
releaseAudioNode,
|
||||
webAudioTimeout,
|
||||
} from './helpers.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
@@ -40,6 +40,11 @@ export const Warpmode = Object.freeze({
|
||||
});
|
||||
|
||||
const seenKeys = new Set();
|
||||
|
||||
export function resetSeenKeys() {
|
||||
seenKeys.clear();
|
||||
}
|
||||
|
||||
async function getPayload(url, label, frameLen = 2048) {
|
||||
const key = `${url},${frameLen}`;
|
||||
if (!seenKeys.has(key)) {
|
||||
@@ -190,6 +195,7 @@ export const tables = async (url, frameLen, json, options = {}) => {
|
||||
if (url.startsWith('local:')) {
|
||||
url = `http://localhost:5432`;
|
||||
}
|
||||
const base = getBaseURL(url);
|
||||
if (typeof fetch !== 'function') {
|
||||
// not a browser
|
||||
return;
|
||||
@@ -200,7 +206,7 @@ export const tables = async (url, frameLen, json, options = {}) => {
|
||||
}
|
||||
return fetch(url)
|
||||
.then((res) => res.json())
|
||||
.then((json) => _processTables(json, url, frameLen, options))
|
||||
.then((json) => _processTables(json, base, frameLen, options))
|
||||
.catch((error) => {
|
||||
console.error(error);
|
||||
throw new Error(`error loading "${url}"`);
|
||||
@@ -318,12 +324,11 @@ export async function onTriggerSynth(t, value, onended, tables, cps, frameLen) {
|
||||
const timeoutNode = webAudioTimeout(
|
||||
ac,
|
||||
() => {
|
||||
destroyAudioWorkletNode(source);
|
||||
vibratoOscillator?.stop();
|
||||
releaseAudioNode(source);
|
||||
releaseAudioNode(vibratoOscillator);
|
||||
fm?.stop();
|
||||
node.disconnect();
|
||||
wtPosModulators?.disconnect();
|
||||
wtWarpModulators?.disconnect();
|
||||
releaseAudioNode(wtPosModulators);
|
||||
releaseAudioNode(wtWarpModulators);
|
||||
onended();
|
||||
},
|
||||
t,
|
||||
|
||||
@@ -11,6 +11,9 @@ const PI = Math.PI;
|
||||
const TWO_PI = 2 * PI;
|
||||
const INVSR = 1 / sampleRate;
|
||||
|
||||
const timeToCoeff = (t) => 1 - Math.exp(-INVSR / t);
|
||||
const dbToLin = (db) => Math.pow(10, db / 20);
|
||||
|
||||
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
|
||||
const mod = (n, m) => ((n % m) + m) % m;
|
||||
const lerp = (a, b, n) => n * (b - a) + a;
|
||||
@@ -508,13 +511,14 @@ class SuperSawOscillatorProcessor extends AudioWorkletProcessor {
|
||||
];
|
||||
}
|
||||
process(_input, outputs, params) {
|
||||
if (currentTime <= params.begin[0]) {
|
||||
return true;
|
||||
}
|
||||
if (currentTime >= params.end[0]) {
|
||||
// this.port.postMessage({ type: 'onended' });
|
||||
// should terminate
|
||||
return false;
|
||||
}
|
||||
if (currentTime <= params.begin[0]) {
|
||||
// keep alive
|
||||
return true;
|
||||
}
|
||||
const output = outputs[0];
|
||||
const voices = params.voices[0]; // k-rate
|
||||
for (let i = 0; i < output[0].length; i++) {
|
||||
@@ -532,7 +536,7 @@ class SuperSawOscillatorProcessor extends AudioWorkletProcessor {
|
||||
const freqVoice = applySemitoneDetuneToFrequency(freq, detuner(n));
|
||||
// We must wrap this here because it is passed into sawblep below which
|
||||
// has domain [0, 1]
|
||||
const dt = ffrac(freqVoice * INVSR);
|
||||
const dt = frac(freqVoice * INVSR);
|
||||
this.phase[n] = this.phase[n] ?? Math.random();
|
||||
const v = waveshapes.sawblep(this.phase[n], dt);
|
||||
|
||||
@@ -543,8 +547,9 @@ class SuperSawOscillatorProcessor extends AudioWorkletProcessor {
|
||||
if (pn >= 1.0) pn -= 1.0;
|
||||
this.phase[n] = pn;
|
||||
// invert right and left gain
|
||||
const tmp = gainL;
|
||||
gainL = gainR;
|
||||
gainR = gainL;
|
||||
gainR = tmp;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -1338,7 +1343,7 @@ class WavetableOscillatorProcessor extends AudioWorkletProcessor {
|
||||
const tablePos = clamp(pv(parameters.position, i), 0, 1);
|
||||
const idx = tablePos * (this.numFrames - 1);
|
||||
const fIdx = idx | 0;
|
||||
const frac = idx - fIdx;
|
||||
const interpT = idx - fIdx;
|
||||
const warpAmount = clamp(pv(parameters.warp, i), 0, 1);
|
||||
const warpMode = pv(parameters.warpMode, i);
|
||||
const phaseRand = clamp(pv(parameters.phaserand, i), 0, 1);
|
||||
@@ -1368,13 +1373,13 @@ class WavetableOscillatorProcessor extends AudioWorkletProcessor {
|
||||
const ph = this._warpPhase(this.phase[n], warpAmount, warpMode);
|
||||
const s0 = this._sampleFrame(table[fIdx], ph);
|
||||
const s1 = this._sampleFrame(table[Math.min(this.numFrames - 1, fIdx + 1)], ph);
|
||||
let s = s0 + (s1 - s0) * frac;
|
||||
let s = lerp(s0, s1, interpT);
|
||||
if (warpMode === WarpMode.FLIP && this.phase[n] < warpAmount) {
|
||||
s = -s;
|
||||
}
|
||||
outL[i] += s * gainL * normalizer;
|
||||
outR[i] += s * gainR * normalizer;
|
||||
this.phase[n] = ffrac(this.phase[n] + dPhase);
|
||||
this.phase[n] = frac(this.phase[n] + dPhase);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
@@ -1382,3 +1387,82 @@ class WavetableOscillatorProcessor extends AudioWorkletProcessor {
|
||||
}
|
||||
|
||||
registerProcessor('wavetable-oscillator-processor', WavetableOscillatorProcessor);
|
||||
|
||||
class TransientProcessor extends AudioWorkletProcessor {
|
||||
static get parameterDescriptors() {
|
||||
return [];
|
||||
}
|
||||
|
||||
constructor(options) {
|
||||
super();
|
||||
this.gainCoeff = timeToCoeff(0.2);
|
||||
this.avgGain = 1;
|
||||
let {
|
||||
attackTime = 0.003,
|
||||
sustainTime = 0.08,
|
||||
attack = 0,
|
||||
sustain = 0,
|
||||
sensitivity = 0.1,
|
||||
mix = 1,
|
||||
begin = 0,
|
||||
end = 0,
|
||||
} = options.processorOptions;
|
||||
attackTime = clamp(attackTime, 0.0005, 0.05);
|
||||
sustainTime = clamp(sustainTime, 0.01, 0.5);
|
||||
this.attackCoeff = timeToCoeff(attackTime);
|
||||
this.sustainCoeff = timeToCoeff(sustainTime);
|
||||
this.attackAmt = clamp(attack, -1, 1);
|
||||
this.sustainAmt = clamp(sustain, -1, 1);
|
||||
this.scaling = 0.5 + 5 * clamp(sensitivity, 0, 1);
|
||||
this.mix = clamp(mix, 0, 1);
|
||||
this.begin = begin;
|
||||
this.end = end;
|
||||
this.attackEnv = new Float32Array(2); // assume stereo
|
||||
this.sustainEnv = new Float32Array(2);
|
||||
}
|
||||
|
||||
process(inputs, outputs, _params) {
|
||||
const input = inputs[0];
|
||||
const output = outputs[0];
|
||||
if (currentTime >= this.end) {
|
||||
return false;
|
||||
}
|
||||
if (currentTime <= this.begin) {
|
||||
return true;
|
||||
}
|
||||
const channels = input.length;
|
||||
if (channels > this.attackEnv.length) {
|
||||
this.attackEnv = new Float32Array(channels);
|
||||
this.sustainEnv = new Float32Array(channels);
|
||||
}
|
||||
let avgGain = this.avgGain;
|
||||
for (let ch = 0; ch < channels; ch++) {
|
||||
let attEnv = this.attackEnv[ch];
|
||||
let susEnv = this.sustainEnv[ch];
|
||||
for (let n = 0; n < blockSize; n++) {
|
||||
const sample = input[ch][n];
|
||||
const x = Math.abs(sample);
|
||||
attEnv = lerp(attEnv, x, this.attackCoeff);
|
||||
susEnv = lerp(susEnv, x, this.sustainCoeff);
|
||||
const peakiness = clamp((this.scaling * (attEnv - susEnv)) / (susEnv + 1e-6), -1.5, 1.5);
|
||||
const attScale = peakiness > 0 ? peakiness : 0;
|
||||
const susScale = peakiness < 0 ? -peakiness : 0;
|
||||
const attackGain = dbToLin(this.attackAmt * attScale * 18);
|
||||
const sustainGain = dbToLin(this.sustainAmt * susScale * 36);
|
||||
const gain = clamp(attackGain * sustainGain, 0, 8);
|
||||
avgGain = lerp(avgGain, gain, this.gainCoeff);
|
||||
const makeup = avgGain > 1e-3 ? 1 / avgGain : 1;
|
||||
const wet = sample * gain * makeup;
|
||||
let y = lerp(sample, wet, this.mix);
|
||||
y /= 1 + Math.abs(y); // soft clip
|
||||
output[ch][n] = y;
|
||||
}
|
||||
this.attackEnv[ch] = attEnv;
|
||||
this.sustainEnv[ch] = susEnv;
|
||||
}
|
||||
this.avgGain = avgGain;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('transient-processor', TransientProcessor);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { midiToFreq, noteToMidi } from './util.mjs';
|
||||
import { registerSound } from './superdough.mjs';
|
||||
import { getAudioContext } from './audioContext.mjs';
|
||||
import { buildSamples } from './zzfx_fork.mjs';
|
||||
import { onceEnded, releaseAudioNode } from './helpers.mjs';
|
||||
|
||||
export const getZZFX = (value, t) => {
|
||||
let {
|
||||
@@ -83,10 +84,10 @@ export function registerZZFXSounds() {
|
||||
wave,
|
||||
(t, value, onended) => {
|
||||
const { node: o } = getZZFX({ s: wave, ...value }, t);
|
||||
o.onended = () => {
|
||||
o.disconnect();
|
||||
onceEnded(o, () => {
|
||||
releaseAudioNode(o);
|
||||
onended();
|
||||
};
|
||||
});
|
||||
return {
|
||||
node: o,
|
||||
stop: () => {},
|
||||
|
||||
@@ -5,7 +5,16 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
*/
|
||||
|
||||
import { Note, Interval, Scale } from '@tonaljs/tonal';
|
||||
import { register, _mod, logger, isNote, noteToMidi, removeUndefineds, getAccidentalsOffset } from '@strudel/core';
|
||||
import {
|
||||
_mod,
|
||||
errorLogger,
|
||||
getAccidentalsOffset,
|
||||
isNote,
|
||||
logger,
|
||||
noteToMidi,
|
||||
register,
|
||||
removeUndefineds,
|
||||
} from '@strudel/core';
|
||||
import { stepInNamedScale, nearestNumberIndex } from './tonleiter.mjs';
|
||||
|
||||
const octavesInterval = (octaves) => (octaves <= 0 ? -1 : 1) + octaves * 7 + 'P';
|
||||
@@ -294,7 +303,7 @@ export const scale = register(
|
||||
}
|
||||
if (offset != 0) scaleNote = Note.transpose(scaleNote, Interval.fromSemitones(offset));
|
||||
} catch (err) {
|
||||
logger(`[tonal] ${err.message}`, 'error');
|
||||
errorLogger(err, 'tonal');
|
||||
return; // will be removed
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,10 +5,21 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
*/
|
||||
|
||||
import * as strudel from '@strudel/core';
|
||||
import { superdough, getAudioContext, setLogger, doughTrigger, registerWorklet } from 'superdough';
|
||||
import {
|
||||
superdough,
|
||||
getAudioContext,
|
||||
setLogger,
|
||||
doughTrigger,
|
||||
registerWorklet,
|
||||
setAudioContext,
|
||||
initAudio,
|
||||
setSuperdoughAudioController,
|
||||
resetGlobalEffects,
|
||||
errorLogger,
|
||||
} from 'superdough';
|
||||
import './supradough.mjs';
|
||||
import { workletUrl } from 'supradough';
|
||||
|
||||
import { SuperdoughAudioController } from 'superdough/superdoughoutput.mjs';
|
||||
registerWorklet(workletUrl);
|
||||
|
||||
const { Pattern, logger, repl } = strudel;
|
||||
@@ -26,6 +37,71 @@ export const webaudioOutput = (hap, _deadline, hapDuration, cps, t) => {
|
||||
return superdough(hap2value(hap), t, hapDuration, cps, hap.whole?.begin.valueOf());
|
||||
};
|
||||
|
||||
export async function renderPatternAudio(
|
||||
pattern,
|
||||
cps,
|
||||
begin,
|
||||
end,
|
||||
sampleRate,
|
||||
maxPolyphony,
|
||||
multiChannelOrbits,
|
||||
downloadName = undefined,
|
||||
) {
|
||||
let audioContext = getAudioContext();
|
||||
await audioContext.close();
|
||||
audioContext = new OfflineAudioContext(2, ((end - begin) / cps) * sampleRate, sampleRate);
|
||||
setAudioContext(audioContext);
|
||||
setSuperdoughAudioController(new SuperdoughAudioController(audioContext));
|
||||
await initAudio({
|
||||
maxPolyphony,
|
||||
multiChannelOrbits,
|
||||
});
|
||||
logger('[webaudio] preloading');
|
||||
|
||||
// Calling superdough(...) in ascending onset time order is important
|
||||
// for controls that depend on the audio graph state like `cut`
|
||||
let haps = pattern
|
||||
.queryArc(begin, end, { _cps: cps })
|
||||
.sort((a, b) => a.whole.begin.valueOf() - b.whole.begin.valueOf());
|
||||
for (const hap of haps) {
|
||||
if (hap.hasOnset()) {
|
||||
try {
|
||||
await superdough(
|
||||
hap2value(hap),
|
||||
(hap.whole.begin.valueOf() - begin) / cps,
|
||||
hap.duration / cps,
|
||||
cps,
|
||||
(hap.whole?.begin.valueOf() - begin) / cps,
|
||||
);
|
||||
} catch (err) {
|
||||
errorLogger(err, 'webaudio');
|
||||
}
|
||||
}
|
||||
}
|
||||
logger('[webaudio] start rendering');
|
||||
|
||||
return audioContext
|
||||
.startRendering()
|
||||
.then((renderedBuffer) => {
|
||||
const wavBuffer = audioBufferToWav(renderedBuffer);
|
||||
const blob = new Blob([wavBuffer], { type: 'audio/wav' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
downloadName = downloadName ? `${downloadName}.wav` : `${new Date().toISOString()}.wav`;
|
||||
a.download = `${downloadName}`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
URL.revokeObjectURL(url);
|
||||
})
|
||||
.finally(async () => {
|
||||
setAudioContext(null);
|
||||
setSuperdoughAudioController(null);
|
||||
resetGlobalEffects();
|
||||
});
|
||||
}
|
||||
|
||||
export function webaudioRepl(options = {}) {
|
||||
options = {
|
||||
getTime: () => getAudioContext().currentTime,
|
||||
@@ -38,3 +114,98 @@ export function webaudioRepl(options = {}) {
|
||||
Pattern.prototype.dough = function () {
|
||||
return this.onTrigger(doughTrigger, 1);
|
||||
};
|
||||
|
||||
function audioBufferToWav(buffer, opt) {
|
||||
opt = opt || {};
|
||||
|
||||
var numChannels = buffer.numberOfChannels;
|
||||
var sampleRate = buffer.sampleRate;
|
||||
var format = opt.float32 ? 3 : 1;
|
||||
var bitDepth = format === 3 ? 32 : 16;
|
||||
|
||||
var result;
|
||||
if (numChannels === 2) {
|
||||
result = interleave(buffer.getChannelData(0), buffer.getChannelData(1));
|
||||
} else {
|
||||
result = buffer.getChannelData(0);
|
||||
}
|
||||
|
||||
return encodeWAV(result, format, sampleRate, numChannels, bitDepth);
|
||||
}
|
||||
|
||||
function encodeWAV(samples, format, sampleRate, numChannels, bitDepth) {
|
||||
var bytesPerSample = bitDepth / 8;
|
||||
var blockAlign = numChannels * bytesPerSample;
|
||||
|
||||
var buffer = new ArrayBuffer(44 + samples.length * bytesPerSample);
|
||||
var view = new DataView(buffer);
|
||||
|
||||
/* RIFF identifier */
|
||||
writeString(view, 0, 'RIFF');
|
||||
/* RIFF chunk length */
|
||||
view.setUint32(4, 36 + samples.length * bytesPerSample, true);
|
||||
/* RIFF type */
|
||||
writeString(view, 8, 'WAVE');
|
||||
/* format chunk identifier */
|
||||
writeString(view, 12, 'fmt ');
|
||||
/* format chunk length */
|
||||
view.setUint32(16, 16, true);
|
||||
/* sample format (raw) */
|
||||
view.setUint16(20, format, true);
|
||||
/* channel count */
|
||||
view.setUint16(22, numChannels, true);
|
||||
/* sample rate */
|
||||
view.setUint32(24, sampleRate, true);
|
||||
/* byte rate (sample rate * block align) */
|
||||
view.setUint32(28, sampleRate * blockAlign, true);
|
||||
/* block align (channel count * bytes per sample) */
|
||||
view.setUint16(32, blockAlign, true);
|
||||
/* bits per sample */
|
||||
view.setUint16(34, bitDepth, true);
|
||||
/* data chunk identifier */
|
||||
writeString(view, 36, 'data');
|
||||
/* data chunk length */
|
||||
view.setUint32(40, samples.length * bytesPerSample, true);
|
||||
if (format === 1) {
|
||||
// Raw PCM
|
||||
floatTo16BitPCM(view, 44, samples);
|
||||
} else {
|
||||
writeFloat32(view, 44, samples);
|
||||
}
|
||||
|
||||
return buffer;
|
||||
}
|
||||
|
||||
function interleave(inputL, inputR) {
|
||||
var length = inputL.length + inputR.length;
|
||||
var result = new Float32Array(length);
|
||||
|
||||
var index = 0;
|
||||
var inputIndex = 0;
|
||||
|
||||
while (index < length) {
|
||||
result[index++] = inputL[inputIndex];
|
||||
result[index++] = inputR[inputIndex];
|
||||
inputIndex++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function writeFloat32(output, offset, input) {
|
||||
for (var i = 0; i < input.length; i++, offset += 4) {
|
||||
output.setFloat32(offset, input[i], true);
|
||||
}
|
||||
}
|
||||
|
||||
function floatTo16BitPCM(output, offset, input) {
|
||||
for (var i = 0; i < input.length; i++, offset += 2) {
|
||||
var s = Math.max(-1, Math.min(1, input[i]));
|
||||
output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7fff, true);
|
||||
}
|
||||
}
|
||||
|
||||
function writeString(view, offset, string) {
|
||||
for (var i = 0; i < string.length; i++) {
|
||||
view.setUint8(offset + i, string.charCodeAt(i));
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,5 @@
|
||||
{
|
||||
"name": "dbpatch",
|
||||
"dependencies": {
|
||||
"csv": "^6.3.11"
|
||||
},
|
||||
|
||||
@@ -16,5 +16,6 @@ export default defineConfig({
|
||||
'**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*',
|
||||
'**/shared.test.mjs',
|
||||
],
|
||||
setupFiles: './vitest.setup.mjs',
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import { afterEach } from 'vitest';
|
||||
import { useRNG } from './packages/core/signal.mjs';
|
||||
|
||||
afterEach(() => {
|
||||
// Avoid bleed between tests
|
||||
useRNG('legacy');
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
fetch('https://codeberg.org/api/v1/repos/uzu/strudel/pulls?state=closed&page=1')
|
||||
.then((res) => res.json())
|
||||
.then((pulls) => {
|
||||
const r = pulls
|
||||
.filter((pull) => pull.merged)
|
||||
.sort((a, b) => new Date(b.closed_at) - new Date(a.closed_at))
|
||||
.map((pull) => `${pull.closed_at} ${pull.title} by ${pull.user.login || '?'} in: [#${pull.number}](${pull.url}) `)
|
||||
.join('\n');
|
||||
console.log(r);
|
||||
});
|
||||
|
||||
/*
|
||||
|
||||
*/
|
||||
@@ -142,6 +142,8 @@ The "~" represents a rest, and will create silence between other events:
|
||||
|
||||
<MiniRepl client:idle tune={`note("[b4 [~ c5] d5 e5]")`} punchcard />
|
||||
|
||||
Alternatively, "-" can be used instead of "~". It means the same thing.
|
||||
|
||||
## Parallel / polyphony
|
||||
|
||||
Using commas, we can play chords.
|
||||
|
||||
@@ -0,0 +1,651 @@
|
||||
/*
|
||||
audiograph.mjs - show a svg view of the web audio API graph built during a playback
|
||||
Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/website/src/repl/audiograph.mjs>
|
||||
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// main entry point is `debugAudiograph`
|
||||
import { logger } from '@strudel/core';
|
||||
import { getAudioContext, getSuperdoughAudioController, webaudioOutput } from '@strudel/webaudio';
|
||||
|
||||
let mermaid = null;
|
||||
let svgPanZoom = null;
|
||||
|
||||
let running = false;
|
||||
let hap_count = 0;
|
||||
|
||||
let cache = new Map();
|
||||
const initCache = JSON.stringify({
|
||||
connect: [],
|
||||
where: [],
|
||||
disconnectAll: 0,
|
||||
disconnectOne: 0,
|
||||
hasStop: false,
|
||||
stopCount: 0,
|
||||
ac: null,
|
||||
creation: null,
|
||||
});
|
||||
|
||||
let toggleOrig;
|
||||
|
||||
function stackTrace() {
|
||||
var err = new Error();
|
||||
const stacktrace = err.stack;
|
||||
const lines = stacktrace.split('\n');
|
||||
let lineIndex = lines.findIndex((line) => line !== 'Error' && !line.includes('audiograph.mjs'));
|
||||
if (lines[lineIndex].includes('gainNode')) lineIndex++;
|
||||
if (lines[lineIndex].includes('getWorklet')) lineIndex++;
|
||||
const line = lines[lineIndex].replace(/\s*at\s/, '').replace('http', '@');
|
||||
let match;
|
||||
match = line.match(/([^@]*)@.*packages(\/[^:]+:\d+:\d+)/);
|
||||
if (match) {
|
||||
return match[1].replace(/[^.:/a-zA-Z0-9]/g, '') + '@' + match[2].replace(/[^.:/a-zA-Z0-9]/g, '');
|
||||
}
|
||||
return '@';
|
||||
}
|
||||
|
||||
// This captures all AudioNodes lazily
|
||||
// when an `.audioid` property is called
|
||||
// no solution was found to hook
|
||||
// AudioNode's constructor directly
|
||||
let audioid = 0;
|
||||
const lazyRegister = (o) => {
|
||||
Object.defineProperty(o.prototype, 'audioid', {
|
||||
get: function () {
|
||||
if (!this._audioid) {
|
||||
this._audioid = ++audioid;
|
||||
const s = JSON.parse(initCache);
|
||||
s.type = this.constructor.name === 'AudiographNode' ? this.constructor._parentClassName : this.constructor.name;
|
||||
// special case for subclassed AudioNodes
|
||||
// they are implemented in superdough but hard to get a reference on here
|
||||
// they are not AudioScheduledSourceNodes anyway
|
||||
if (['FeedbackDelayNode', 'VowelNode'].indexOf(s.type) === -1) {
|
||||
s.hasStop = window[s.type].prototype instanceof AudioScheduledSourceNode;
|
||||
}
|
||||
s.ac = this.context?.constructor.name || 'AudioParam';
|
||||
s.creation = s.creation || stackTrace();
|
||||
cache.set(this._audioid, s);
|
||||
}
|
||||
return this._audioid;
|
||||
},
|
||||
enumerable: false,
|
||||
configurable: true,
|
||||
});
|
||||
};
|
||||
|
||||
// extend a specific AudioNode's constructor
|
||||
// necessary when creation is done direclty by
|
||||
// calling the constructor
|
||||
// eg: new GainNode(...)
|
||||
const audioNodeHook = (node) => {
|
||||
const name = node.prototype.constructor.name;
|
||||
const PatchedNode = class AudiographNode extends node {
|
||||
constructor(...args) {
|
||||
super(...args);
|
||||
// trigger the lazy register
|
||||
this._audioid = this.audioid;
|
||||
}
|
||||
};
|
||||
PatchedNode._parentClassName = name;
|
||||
window[name] = PatchedNode;
|
||||
};
|
||||
|
||||
const drawMessage = async function (message) {
|
||||
const element = document.querySelector('.strudel-mermaid');
|
||||
let gd = '';
|
||||
gd += '---\n';
|
||||
gd += 'config:\n';
|
||||
gd += ' flowchart:\n';
|
||||
gd += ' wrappingWidth: 600\n';
|
||||
gd += '---\n';
|
||||
gd += 'flowchart LR\n';
|
||||
gd += 'id[' + message.replaceAll(' ', ' ') + ']\n';
|
||||
|
||||
let { svg } = await mermaid.render('strudelSvgId', gd);
|
||||
svg = svg.replace(/max-width:\s[0-9.]*px;/i, 'height: 100%');
|
||||
svg = svg.replaceAll('&nbsp;', ' ');
|
||||
element.innerHTML = svg;
|
||||
};
|
||||
|
||||
const drawDiagram = async function () {
|
||||
const element = document.querySelector('.strudel-mermaid');
|
||||
let code = window.strudelMirror.code;
|
||||
code = code.replace(/^await debugAudiograph.*\n?/gm, '');
|
||||
code = '// date: ' + new Date().toISOString() + '\n\n' + code;
|
||||
code = '// host: ' + document.location.hostname + '\n' + code;
|
||||
const codeLines = code.split(/(?:\n|\r\n?)/);
|
||||
const maxLineLength = codeLines.reduce((memo, line) => Math.max(memo, line.length), 0);
|
||||
|
||||
// https://mermaid.js.org/syntax/flowchart.html
|
||||
let gd = '';
|
||||
gd += '---\n';
|
||||
gd += 'config:\n';
|
||||
gd += ' flowchart:\n';
|
||||
gd += ' wrappingWidth: ' + 14 * maxLineLength + '\n';
|
||||
gd += '---\n';
|
||||
gd += 'flowchart TB\n';
|
||||
gd += '\tsubgraph AG[STRUDEL AUDIOGRAPH]\n';
|
||||
|
||||
// seed graph builder with all
|
||||
// unconnected nodes
|
||||
let lookup = [];
|
||||
cache.forEach((v, k) => {
|
||||
if (v.connect.length === 0) lookup.push(k);
|
||||
});
|
||||
const relations = [];
|
||||
let curRelations;
|
||||
const zombieCount = 0;
|
||||
const sourceLoc = (stack) => {
|
||||
if (stack === '@') return stack;
|
||||
return stack.replace('@', '\n').replace('/superdough/', '/');
|
||||
};
|
||||
const label = (s) => {
|
||||
const source = s.creation ? '\n' + sourceLoc(s.creation) : '';
|
||||
let lb = '[' + '**' + s.type + '**' + source + ']';
|
||||
if (s.ac === 'OfflineAudioContext') lb = '[' + lb + ']';
|
||||
return lb;
|
||||
};
|
||||
const isConnectLeak = (s) => {
|
||||
return (
|
||||
['AudioDestinationNode', 'AudioParam'].indexOf(s.type) === -1 &&
|
||||
s.disconnectAll === 0 &&
|
||||
s.connect.length > s.disconnectOne
|
||||
);
|
||||
};
|
||||
const isStopLeak = (s) => {
|
||||
return s.hasStop && s.stopCount === 0;
|
||||
};
|
||||
do {
|
||||
curRelations = relations.length;
|
||||
lookup.slice().forEach((n) => {
|
||||
cache.forEach((v, k) => {
|
||||
if (v.connect.indexOf(n) !== -1) {
|
||||
if (lookup.indexOf(k) === -1) lookup.push(k);
|
||||
gd += v.connect
|
||||
.map((i) => {
|
||||
if (lookup.indexOf(i) === -1) lookup.push(i);
|
||||
if (relations.indexOf(k + '-' + i) === -1) {
|
||||
relations.push(k + '-' + i);
|
||||
return (
|
||||
'\t\tnode' +
|
||||
k +
|
||||
label(v) +
|
||||
' -- ' +
|
||||
sourceLoc(v.where[0]) +
|
||||
' --> node' +
|
||||
i +
|
||||
label(cache.get(i)) +
|
||||
'\n'
|
||||
);
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
if (k === n) {
|
||||
gd += v.connect
|
||||
.map((i) => {
|
||||
if (lookup.indexOf(i) === -1) lookup.push(i);
|
||||
if (relations.indexOf(k + '-' + i) === -1) {
|
||||
relations.push(k + '-' + i);
|
||||
return (
|
||||
'\t\tnode' +
|
||||
k +
|
||||
label(v) +
|
||||
' -- ' +
|
||||
sourceLoc(v.where[0]) +
|
||||
' --> node' +
|
||||
i +
|
||||
label(cache.get(i)) +
|
||||
'\n'
|
||||
);
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
}
|
||||
});
|
||||
});
|
||||
} while (relations.length > curRelations /*&& lookup.length < 100*/);
|
||||
// add orphan nodes
|
||||
const inRelation = '-' + relations.join('-') + '-';
|
||||
cache.forEach((v, k) => {
|
||||
if (!inRelation.includes('-' + k + '-')) {
|
||||
gd += '\t\tnode' + k + label(v) + '\n';
|
||||
}
|
||||
});
|
||||
|
||||
const codePlaceholder = 'm'.repeat(maxLineLength);
|
||||
gd += '\tsubgraph LEGEND\n';
|
||||
gd += '\t\tlegend1[in AudioContext]\n';
|
||||
gd += '\t\tlegend2[[in OfflineAudioContext]]\n';
|
||||
gd += '\t\tlegend3[not disconnected]\n';
|
||||
gd += '\t\tlegend4[AudioParam]\n';
|
||||
gd += '\t\tlegend5[AudioDestinationNode]\n';
|
||||
gd += '\t\tlegend6[not stopped]\n';
|
||||
gd += '\tend\n';
|
||||
gd += '\tsubgraph CODE[Strudel Code]\n';
|
||||
// we use a codePlaceholder to
|
||||
// - avoid problems with special chars
|
||||
// - stop mermaid to split lines on space with multiple tspans
|
||||
// - force mermaid to prepare a sufficiently sized zone
|
||||
gd += '\ncode[' + (codePlaceholder + '<br>').repeat(codeLines.length) + ']\n';
|
||||
gd += '\tend\n';
|
||||
gd += '\tend\n';
|
||||
gd += '\tclassDef audioparam fill:#6f6;\n';
|
||||
gd += '\tclassDef destination fill:#99f;\n';
|
||||
gd += '\tclassDef connectleak fill:#f96,stroke:#f00,stroke-width:2px;\n';
|
||||
gd += '\tclassDef stopleak fill:#f55,stroke:#f00,stroke-width:2px;\n';
|
||||
gd += '\tclass legend3 connectleak;\n';
|
||||
gd += '\tclass legend4 audioparam;\n';
|
||||
gd += '\tclass legend5 destination;\n';
|
||||
gd += '\tclass legend6 stopleak;\n';
|
||||
cache.forEach((v, k) => {
|
||||
if (isConnectLeak(v)) {
|
||||
gd += '\tclass node' + k + ' connectleak;\n';
|
||||
} else if (isStopLeak(v)) {
|
||||
gd += '\tclass node' + k + ' stopleak;\n';
|
||||
}
|
||||
if (v.type === 'AudioParam') {
|
||||
gd += '\tclass node' + k + ' audioparam;\n';
|
||||
}
|
||||
if (v.type === 'AudioDestinationNode') {
|
||||
gd += '\tclass node' + k + ' destination;\n';
|
||||
}
|
||||
});
|
||||
let { svg } = await mermaid.render('strudelSvgId', gd);
|
||||
|
||||
// put real code in code zone
|
||||
let idx = 0;
|
||||
const escapeHtml = (unsafe) => {
|
||||
return unsafe
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
};
|
||||
svg = svg.replaceAll(codePlaceholder, () => escapeHtml(codeLines[idx++]));
|
||||
|
||||
// improve sizing on web page
|
||||
svg = svg.replace(/max-width:\s[0-9.]*px;/i, 'height: 100%');
|
||||
element.innerHTML = svg;
|
||||
|
||||
// align the code lines
|
||||
let svgText = document.querySelector('[id^=flowchart-code] text');
|
||||
svgText.setAttributeNS(null, 'style', 'text-anchor: start;');
|
||||
const svgElement = document.querySelector('svg');
|
||||
const svgLabel = document.querySelector('svg [id^=flowchart-code] .label');
|
||||
const transformList = svgLabel.transform.baseVal;
|
||||
const svgTransform = svgElement.createSVGTransform();
|
||||
const tspans = Array.from(document.querySelectorAll('[id^=flowchart-code] tspan.text-inner-tspan'));
|
||||
let tspansMaxLength = tspans.reduce((memo, tspan) => Math.max(memo, tspan.getComputedTextLength()), 0);
|
||||
svgTransform.setTranslate(-tspansMaxLength / 2, 0);
|
||||
transformList.appendItem(svgTransform);
|
||||
|
||||
let doPan = false;
|
||||
let eventsHandler;
|
||||
let panZoom;
|
||||
let mousepos;
|
||||
|
||||
eventsHandler = {
|
||||
haltEventListeners: ['mousedown', 'mousemove', 'mouseup'],
|
||||
mouseDownHandler: function (ev) {
|
||||
if (event.target.className == '[object SVGAnimatedString]') {
|
||||
doPan = true;
|
||||
mousepos = {
|
||||
x: ev.clientX,
|
||||
y: ev.clientY,
|
||||
};
|
||||
}
|
||||
},
|
||||
mouseMoveHandler: function (ev) {
|
||||
if (doPan) {
|
||||
panZoom.panBy({
|
||||
x: ev.clientX - mousepos.x,
|
||||
y: ev.clientY - mousepos.y,
|
||||
});
|
||||
mousepos = {
|
||||
x: ev.clientX,
|
||||
y: ev.clientY,
|
||||
};
|
||||
window.getSelection().removeAllRanges();
|
||||
}
|
||||
},
|
||||
mouseUpHandler: function (ev) {
|
||||
doPan = false;
|
||||
},
|
||||
init: function (options) {
|
||||
options.svgElement.addEventListener('mousedown', this.mouseDownHandler, false);
|
||||
options.svgElement.addEventListener('mousemove', this.mouseMoveHandler, false);
|
||||
options.svgElement.addEventListener('mouseup', this.mouseUpHandler, false);
|
||||
},
|
||||
destroy: function (options) {
|
||||
options.svgElement.removeEventListener('mousedown', this.mouseDownHandler, false);
|
||||
options.svgElement.removeEventListener('mousemove', this.mouseMoveHandler, false);
|
||||
options.svgElement.removeEventListener('mouseup', this.mouseUpHandler, false);
|
||||
},
|
||||
};
|
||||
panZoom = svgPanZoom('#strudelSvgId', {
|
||||
zoomEnabled: true,
|
||||
controlIconsEnabled: true,
|
||||
fit: 1,
|
||||
center: 1,
|
||||
zoomScaleSensitivity: 0.4,
|
||||
customEventsHandler: eventsHandler,
|
||||
});
|
||||
};
|
||||
|
||||
const svgExport = async () => {
|
||||
const a = document.createElement('a');
|
||||
document.body.appendChild(a);
|
||||
a.style = 'display: none';
|
||||
|
||||
const selector = '.strudel-mermaid';
|
||||
const bbox = document.querySelector('svg g').getBBox();
|
||||
let transform, style;
|
||||
// clean pan-zoom viewport
|
||||
const pzViewport = document.querySelector('.svg-pan-zoom_viewport');
|
||||
if (pzViewport) {
|
||||
transform = pzViewport.transform;
|
||||
style = pzViewport.style;
|
||||
pzViewport.setAttribute('transform', '');
|
||||
pzViewport.style = '';
|
||||
}
|
||||
|
||||
const spzMin = await fetch('https://cdn.jsdelivr.net/npm/svg-pan-zoom@3.6.2/dist/svg-pan-zoom.min.js').then((res) =>
|
||||
res.text(),
|
||||
);
|
||||
|
||||
const scriptContent = '<![CDATA[' + spzMin + ';svgPanZoom("svg");]]>';
|
||||
// prepare svg
|
||||
const content = document
|
||||
.querySelector(selector)
|
||||
.innerHTML.replaceAll('<br>', '<br/>')
|
||||
// remove useless tags
|
||||
.replace(/<g id="svg-pan-zoom.*<\/g>/, '<script>' + scriptContent + '</script>')
|
||||
.replace(/<defs>.*<\/defs>/, '')
|
||||
// give inkscape true sizes
|
||||
.replace('width="100%"', 'width="' + bbox.width + '" height="' + bbox.height + '"');
|
||||
|
||||
// restore pan-zoom viewport
|
||||
if (pzViewport) {
|
||||
pzViewport.setAttribute('transform', transform);
|
||||
pzViewport.style = style;
|
||||
}
|
||||
|
||||
// trigger download
|
||||
var blob = new Blob([content], { type: 'image/svg+xml' }),
|
||||
url = window.URL.createObjectURL(blob);
|
||||
a.href = url;
|
||||
a.download = 'audiograph.svg';
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
const resetAudioOutput = function (audioid) {
|
||||
// calling reset on SuperdoughAudioController
|
||||
// will discard output nodes AND recreate them
|
||||
// so we keep the same `cache` to handle the
|
||||
// `disconnects` knowing that new nodes will be
|
||||
// stricly after the current audioid.
|
||||
// then we purge the old nodes from the `cache`
|
||||
// to have a clean state
|
||||
|
||||
// make sure destination will be recreated in the
|
||||
// cache
|
||||
const destination = getAudioContext().destination;
|
||||
if (destination._audioid) delete destination._audioid;
|
||||
|
||||
const sac = getSuperdoughAudioController();
|
||||
sac.reset();
|
||||
Array.from(cache.keys()).map((k) => {
|
||||
if (k <= audioid) cache.delete(k);
|
||||
});
|
||||
};
|
||||
|
||||
const postProcessing = async function () {
|
||||
hap_count = 0;
|
||||
await drawDiagram();
|
||||
|
||||
resetAudioOutput(audioid);
|
||||
};
|
||||
|
||||
const defaultOptions = {
|
||||
StopAfterHapCount: 10,
|
||||
hapsBatch: 0,
|
||||
maxEdges: 10000,
|
||||
maxTextSize: 200000,
|
||||
audioAPIBreathingRoomSec: 5,
|
||||
};
|
||||
|
||||
// `StopAfterHapCount` :
|
||||
// The player will auto-stop after hap count have
|
||||
// been played. when StopAfterHapCount = 0, it will
|
||||
// continue playing until 'stop' is clicked
|
||||
// `audioAPIBreathingRoomSec` :
|
||||
// how much time should we wait after 'stop' to let
|
||||
// the audioAPI finish its tail of ondended calls
|
||||
// `hapsBatch` :
|
||||
// the AudioGraph will be displayed every hapsBatch haps
|
||||
// when hapsBatch = 0, AudioGraph will only be displayed
|
||||
// after and auto-stop or after 'stop' is clicked
|
||||
// In hapsBatch mode you will probably see a trailing of
|
||||
// non disconnected notes on the graph because the audio
|
||||
// API may have some lag disconnecting them
|
||||
// cf also audioAPIBreathingRoomSec
|
||||
// `maxEdges`
|
||||
// This is a mermaid.js config that forces a hard limit
|
||||
// on the maximum number of Edges of a graph
|
||||
// needs a reload to be taken into account
|
||||
// `maxTextSize`
|
||||
// This is a mermaid.js config that forces a hard limit
|
||||
// on the maximum text size of a graph definition
|
||||
// needs a reload to be taken into account
|
||||
|
||||
export const debugAudiograph = async (argOptions = {}) => {
|
||||
const options = Object.assign({}, defaultOptions, argOptions);
|
||||
const { StopAfterHapCount, hapsBatch, maxEdges, maxTextSize, audioAPIBreathingRoomSec } = options;
|
||||
const sm = window.strudelMirror;
|
||||
const code = sm.code;
|
||||
if (!code.match(/await\s+debugAudiograph/)) {
|
||||
throw new Error('you need to call `await debugAudiograph()` for audiograph to work');
|
||||
}
|
||||
const emptyOptions = /await\s+debugAudiograph\(\)/.exec(code);
|
||||
if (emptyOptions) {
|
||||
const cutCode = emptyOptions.index + emptyOptions[0].length - 1;
|
||||
const codeOptions = JSON.stringify({ StopAfterHapCount: StopAfterHapCount }).replaceAll('"', '');
|
||||
sm.setCode(code.slice(0, cutCode) + codeOptions + code.slice(cutCode));
|
||||
}
|
||||
|
||||
if (window.audiograph === undefined) {
|
||||
const ag = (window.audiograph = {});
|
||||
|
||||
toggleOrig = sm.toggle;
|
||||
|
||||
////////////////////////////////////////
|
||||
// step 1: web audio api instrumentation
|
||||
////////////////////////////////////////
|
||||
|
||||
// path AudioNode & AudioParam
|
||||
// to give them lazy ids
|
||||
// this captures both `ac.createGain`
|
||||
// and `new GainNode(..)` patterns
|
||||
lazyRegister(AudioNode);
|
||||
lazyRegister(AudioParam);
|
||||
lazyRegister(PeriodicWave);
|
||||
|
||||
const audioNodes = [
|
||||
AudioBufferSourceNode,
|
||||
AudioWorkletNode,
|
||||
AnalyserNode,
|
||||
BiquadFilterNode,
|
||||
ChannelMergerNode,
|
||||
ChannelSplitterNode,
|
||||
ConstantSourceNode,
|
||||
ConvolverNode,
|
||||
DelayNode,
|
||||
DynamicsCompressorNode,
|
||||
GainNode,
|
||||
IIRFilterNode,
|
||||
OscillatorNode,
|
||||
PannerNode,
|
||||
StereoPannerNode,
|
||||
WaveShaperNode,
|
||||
];
|
||||
audioNodes.map((n) => {
|
||||
if (n.prototype instanceof AudioScheduledSourceNode) {
|
||||
const stopOrig = n.prototype.stop;
|
||||
n.prototype.stop = function (...args) {
|
||||
// stop called
|
||||
const result = stopOrig.call(this, ...args);
|
||||
const s = cache.get(this.audioid);
|
||||
s.stopCount++;
|
||||
return result;
|
||||
};
|
||||
}
|
||||
audioNodeHook(n);
|
||||
});
|
||||
|
||||
// patch BaseAudioContext factory methods
|
||||
// to capture the source reference
|
||||
Object.getOwnPropertyNames(BaseAudioContext.prototype)
|
||||
.filter((n) => n.startsWith('create') && ['createBuffer'].indexOf(n) === -1)
|
||||
.map((name) => {
|
||||
const orig = BaseAudioContext.prototype[name];
|
||||
BaseAudioContext.prototype[name] = function (...args) {
|
||||
const result = orig.call(this, ...args);
|
||||
const s = cache.get(result.audioid);
|
||||
s.creation = stackTrace();
|
||||
return result;
|
||||
};
|
||||
});
|
||||
|
||||
const connectOrig = AudioNode.prototype.connect;
|
||||
AudioNode.prototype.connect = function (destination, ...args) {
|
||||
const result = connectOrig.call(this, destination, ...args);
|
||||
const s = cache.get(this.audioid);
|
||||
s.connect.push(destination.audioid);
|
||||
s.where.push(stackTrace());
|
||||
return result;
|
||||
};
|
||||
|
||||
const disconnectOrig = AudioNode.prototype.disconnect;
|
||||
AudioNode.prototype.disconnect = function (destination, ...args) {
|
||||
const result = disconnectOrig.call(this, destination, ...args);
|
||||
const s = cache.get(this.audioid);
|
||||
if (s.connect.length) {
|
||||
if (destination) {
|
||||
s.disconnectOne++;
|
||||
} else {
|
||||
s.disconnectAll++;
|
||||
}
|
||||
} else {
|
||||
logger('WEIRD: node ' + this.audioid + 'called disconnect before any call to connect !');
|
||||
//logger(new Error().stack);
|
||||
console.log(cache);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// call reset 2 times to handle reload + 'play'
|
||||
// the first reset's disconnect adds audioid tags on previous outputs
|
||||
// that were not tagged (wrong cutoff)
|
||||
resetAudioOutput(audioid);
|
||||
// the second reset has the correct audioid cutoff
|
||||
resetAudioOutput(audioid);
|
||||
|
||||
////////////////////////////////////////
|
||||
// step 2: Load external modules
|
||||
////////////////////////////////////////
|
||||
|
||||
const { default: mermaidModule } = await import(
|
||||
'https://cdn.jsdelivr.net/npm/mermaid@11.12.1/dist/mermaid.esm.mjs'
|
||||
);
|
||||
mermaid = mermaidModule;
|
||||
|
||||
mermaid.initialize({
|
||||
startOnLoad: false,
|
||||
themeCSS: '.flowchart { height: 100%; }',
|
||||
maxEdges: maxEdges,
|
||||
maxTextSize: maxTextSize,
|
||||
htmlLabels: false,
|
||||
flowchart: {
|
||||
htmlLabels: false,
|
||||
},
|
||||
});
|
||||
|
||||
const { default: svgPanZoomModule } = await import('https://esm.sh/svg-pan-zoom');
|
||||
svgPanZoom = svgPanZoomModule;
|
||||
|
||||
//////////////////////////////////////////
|
||||
// step 3: UI modifications
|
||||
//////////////////////////////////////////
|
||||
|
||||
// add audiograph panel
|
||||
if (!document.querySelector('.strudel-mermaid')) {
|
||||
const mermaidDiv = document.createElement('div');
|
||||
mermaidDiv.className = 'strudel-mermaid';
|
||||
mermaidDiv.style = 'min-height: 600px; width: 60%';
|
||||
const referenceNode = document.querySelector('#code');
|
||||
referenceNode.parentNode.insertBefore(mermaidDiv, referenceNode.nextSibling);
|
||||
}
|
||||
|
||||
// add svg export button
|
||||
if (!document.querySelector('button[title=svg]')) {
|
||||
const exportButton = document.createElement('button');
|
||||
exportButton.innerHTML = '<span>ExportDiagram</span>';
|
||||
exportButton.title = 'svg';
|
||||
exportButton.onclick = svgExport;
|
||||
const updateButton = document.querySelector('button[title=update]');
|
||||
updateButton.parentNode.insertBefore(exportButton, updateButton);
|
||||
}
|
||||
}
|
||||
|
||||
if (!running) {
|
||||
running = true;
|
||||
}
|
||||
|
||||
if (hapsBatch === 0 || hap_count < hapsBatch) {
|
||||
let msg = '';
|
||||
msg += 'Recording activity...';
|
||||
msg += '\npress stop to build diagram';
|
||||
if (StopAfterHapCount) {
|
||||
msg += '\nwill stop automatically in ' + Math.max(StopAfterHapCount - hap_count, 0) + ' haps';
|
||||
}
|
||||
await drawMessage(msg);
|
||||
}
|
||||
|
||||
sm.toggle = async () => {
|
||||
running = false;
|
||||
sm.toggle = toggleOrig;
|
||||
// schedule `toggle` on the js main loop
|
||||
// to avoid interfering with any on-flight onTick
|
||||
// not doing this can lead to a phase > 0 which will
|
||||
// break the next start
|
||||
setTimeout(sm.toggle.bind(sm), 0);
|
||||
await drawMessage('please wait ' + audioAPIBreathingRoomSec + ' seconds\n' + 'the audio API is finishing its work');
|
||||
setTimeout(postProcessing, audioAPIBreathingRoomSec * 1000);
|
||||
};
|
||||
|
||||
/*global all*/
|
||||
all((pat) =>
|
||||
pat.onTrigger(async (hap, duration, cps, t) => {
|
||||
hap_count++;
|
||||
const key = Object.entries(hap.value)
|
||||
.map((param) => param.join('/'))
|
||||
.join('/');
|
||||
|
||||
// if we reached StopAfterHapCount, click 'stop'
|
||||
if (StopAfterHapCount && hap_count > StopAfterHapCount) {
|
||||
if (running) {
|
||||
await sm.toggle();
|
||||
}
|
||||
// stop sending haps to superdough(...)
|
||||
return;
|
||||
}
|
||||
|
||||
await webaudioOutput(hap, t, hap.duration / cps, cps, t);
|
||||
|
||||
if (hapsBatch && hap_count % hapsBatch === 0) drawDiagram();
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -8,3 +8,34 @@ export function ActionButton({ children, label, labelIsHidden, className, ...but
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
export function SpecialActionButton(props) {
|
||||
const { className, ...buttonProps } = props;
|
||||
|
||||
return (
|
||||
<ActionButton
|
||||
{...buttonProps}
|
||||
className={cx('bg-background p-2 max-w-[300px] rounded-md hover:opacity-50', className)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ActionInput({ label, className, ...props }) {
|
||||
return (
|
||||
<label className={cx('inline-flex items-center cursor-pointer', className)}>
|
||||
<input {...props} className="sr-only peer" />
|
||||
|
||||
<span className="inline-flex items-center peer-hover:opacity-50">{label}</span>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
export function SpecialActionInput({ className, ...props }) {
|
||||
return (
|
||||
<ActionInput
|
||||
{...props}
|
||||
className={className}
|
||||
label={<span className="bg-background p-2 max-w-[300px] rounded-md">{props.label}</span>}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
import PlayCircleIcon from '@heroicons/react/20/solid/PlayCircleIcon';
|
||||
import cx from '@src/cx.mjs';
|
||||
import NumberInput from '@src/repl/components/NumberInput';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Textbox } from '../textbox/Textbox';
|
||||
import { getAudioContext } from '@strudel/webaudio';
|
||||
import XMarkIcon from '@heroicons/react/24/outline/XMarkIcon';
|
||||
|
||||
function Checkbox({ label, value, onChange, disabled = false }) {
|
||||
return (
|
||||
<label className={cx(disabled && 'opacity-50')}>
|
||||
<input disabled={disabled} type="checkbox" checked={value} onChange={onChange} />
|
||||
{' ' + label}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function FormItem({ label, children, disabled }) {
|
||||
return (
|
||||
<div className="grid gap-2 w-full">
|
||||
<label className={cx(disabled && 'opacity-50')}>{label}</label>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function ExportTab(Props) {
|
||||
const { handleExport } = Props;
|
||||
|
||||
const [downloadName, setDownloadName] = useState('');
|
||||
const [startCycle, setStartCycle] = useState(0);
|
||||
const [endCycle, setEndCycle] = useState(1);
|
||||
const [sampleRate, setSampleRate] = useState(48000);
|
||||
const [multiChannelOrbits, setMultiChannelOrbits] = useState(true);
|
||||
const [maxPolyphony, setMaxPolyphony] = useState(1024);
|
||||
const [exporting, setExporting] = useState(false);
|
||||
const [progress, setProgress] = useState(0);
|
||||
const [length, setLength] = useState(1);
|
||||
|
||||
const refreshProgress = () => {
|
||||
const audioContext = getAudioContext();
|
||||
if (audioContext instanceof OfflineAudioContext) {
|
||||
setProgress(audioContext.currentTime);
|
||||
setLength(audioContext.length / sampleRate);
|
||||
setTimeout(refreshProgress, 100);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="text-foreground w-full p-4 space-y-4">
|
||||
<FormItem label="File name" disabled={exporting}>
|
||||
<Textbox
|
||||
onBlur={(e) => {
|
||||
setDownloadName(e.target.value);
|
||||
}}
|
||||
onChange={(v) => {
|
||||
setDownloadName(v);
|
||||
}}
|
||||
disabled={exporting}
|
||||
placeholder="Leave empty to use current date"
|
||||
className={cx('placeholder:opacity-50', exporting && 'opacity-50 border-opacity-50')}
|
||||
value={downloadName ?? ''}
|
||||
/>
|
||||
</FormItem>
|
||||
<div className="flex flex-row gap-4 w-full">
|
||||
<FormItem label="Start cycle" disabled={exporting}>
|
||||
<Textbox
|
||||
min={1}
|
||||
max={Infinity}
|
||||
onBlur={(e) => {
|
||||
let v = parseInt(e.target.value);
|
||||
v = isNaN(v) ? 0 : Math.max(0, v);
|
||||
setStartCycle(v);
|
||||
}}
|
||||
onChange={(v) => {
|
||||
v = parseInt(v);
|
||||
setStartCycle(v);
|
||||
}}
|
||||
type="number"
|
||||
placeholder=""
|
||||
disabled={exporting}
|
||||
className={cx(exporting && 'opacity-50 border-opacity-50', 'w-full')}
|
||||
value={startCycle ?? ''}
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem label="End cycle" disabled={exporting}>
|
||||
<Textbox
|
||||
min={1}
|
||||
max={Infinity}
|
||||
onBlur={(e) => {
|
||||
let v = parseInt(e.target.value);
|
||||
v = isNaN(v) ? Math.max(startCycle + 1, parseInt(v)) : v;
|
||||
setEndCycle(v);
|
||||
}}
|
||||
onChange={(v) => {
|
||||
v = parseInt(v);
|
||||
setEndCycle(v);
|
||||
}}
|
||||
type="number"
|
||||
placeholder=""
|
||||
disabled={exporting}
|
||||
className={cx(exporting && 'opacity-50 border-opacity-50', 'w-full')}
|
||||
value={endCycle ?? ''}
|
||||
/>
|
||||
</FormItem>
|
||||
</div>
|
||||
<div className="flex flex-row gap-4">
|
||||
<FormItem label="Sample rate" disabled={exporting}>
|
||||
<Textbox
|
||||
min={1}
|
||||
max={Infinity}
|
||||
onBlur={(e) => {
|
||||
let v = parseInt(e.target.value);
|
||||
v = isNaN(v) ? 1 : Math.max(1, v);
|
||||
setSampleRate(v);
|
||||
}}
|
||||
onChange={(v) => {
|
||||
v = parseInt(v);
|
||||
setSampleRate(v);
|
||||
}}
|
||||
type="number"
|
||||
placeholder=""
|
||||
disabled={exporting}
|
||||
className={cx(exporting && 'opacity-50 border-opacity-50')}
|
||||
value={sampleRate ?? ''}
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem label="Maximum polyphony" disabled={exporting}>
|
||||
<Textbox
|
||||
min={1}
|
||||
max={Infinity}
|
||||
onBlur={(e) => {
|
||||
let v = parseInt(e.target.value);
|
||||
v = isNaN(v) ? Math.max(1, parseInt(v)) : v;
|
||||
setMaxPolyphony(v);
|
||||
}}
|
||||
onChange={(v) => {
|
||||
v = Math.max(1, parseInt(v));
|
||||
setMaxPolyphony(v);
|
||||
}}
|
||||
type="number"
|
||||
placeholder=""
|
||||
disabled={exporting}
|
||||
className={cx(exporting && 'opacity-50 border-opacity-50')}
|
||||
value={maxPolyphony ?? ''}
|
||||
/>
|
||||
</FormItem>
|
||||
</div>
|
||||
<div>
|
||||
<Checkbox
|
||||
label="Multi Channel Orbits"
|
||||
onChange={(cbEvent) => {
|
||||
const val = cbEvent.target.checked;
|
||||
setMultiChannelOrbits(val);
|
||||
}}
|
||||
disabled={exporting}
|
||||
value={multiChannelOrbits}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
className={cx('bg-background p-2 w-full rounded-md hover:opacity-75 relative', exporting && 'opacity-50')}
|
||||
disabled={exporting}
|
||||
onClick={async () => {
|
||||
setExporting(true);
|
||||
setTimeout(refreshProgress, 2000);
|
||||
const modal = document.getElementById('exportProgressModal');
|
||||
modal.showModal();
|
||||
await handleExport(startCycle, endCycle, sampleRate, maxPolyphony, multiChannelOrbits, downloadName)
|
||||
.then(() => {
|
||||
const modal = document.getElementById('exportProgressModal');
|
||||
modal.close();
|
||||
})
|
||||
.finally(() => {
|
||||
setExporting(false);
|
||||
setProgress(0);
|
||||
setLength(1);
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="absolute top-0 left-0 right-0 bottom-0 backdrop-invert"
|
||||
style={{
|
||||
width: `${(exporting ? 1 : 0) + (progress / length) * 99}%`,
|
||||
}}
|
||||
/>
|
||||
<span className="text-foreground">{exporting ? 'Exporting...' : 'Export to WAV'}</span>
|
||||
</button>
|
||||
</div>
|
||||
<dialog
|
||||
closedby={exporting ? 'none' : 'closerequest'}
|
||||
id="exportProgressModal"
|
||||
className="text-md bg-background text-foreground rounded-lg backdrop:bg-background backdrop:opacity-25"
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { errorLogger } from '@strudel/core';
|
||||
import { useSettings, storePrebakeScript } from '../../../settings.mjs';
|
||||
import { SpecialActionInput } from '../button/action-button';
|
||||
|
||||
async function importScript(script) {
|
||||
const reader = new FileReader();
|
||||
reader.readAsText(script);
|
||||
|
||||
reader.onload = () => {
|
||||
const text = reader.result;
|
||||
storePrebakeScript(text);
|
||||
};
|
||||
|
||||
reader.onerror = () => {
|
||||
errorLogger(new Error('failed to import prebake script'), 'importScript');
|
||||
};
|
||||
}
|
||||
export function ImportPrebakeScriptButton() {
|
||||
const settings = useSettings();
|
||||
|
||||
return (
|
||||
<SpecialActionInput
|
||||
type="file"
|
||||
label="import prebake script"
|
||||
accept=".strudel"
|
||||
onChange={(e) => importScript(e.target.files[0])}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { useLogger } from '../useLogger';
|
||||
import { WelcomeTab } from './WelcomeTab';
|
||||
import { PatternsTab } from './PatternsTab';
|
||||
import { ChevronLeftIcon, XMarkIcon } from '@heroicons/react/16/solid';
|
||||
import ExportTab from './ExportTab';
|
||||
|
||||
const TAURI = typeof window !== 'undefined' && window.__TAURI__;
|
||||
|
||||
@@ -80,6 +81,7 @@ const tabNames = {
|
||||
patterns: 'patterns',
|
||||
sounds: 'sounds',
|
||||
reference: 'reference',
|
||||
export: 'export',
|
||||
console: 'console',
|
||||
settings: 'settings',
|
||||
};
|
||||
@@ -126,6 +128,8 @@ function PanelContent({ context, tab }) {
|
||||
return <SoundsTab />;
|
||||
case tabNames.reference:
|
||||
return <Reference />;
|
||||
case tabNames.export:
|
||||
return <ExportTab handleExport={context.handleExport} />;
|
||||
case tabNames.settings:
|
||||
return <SettingsTab started={context.started} />;
|
||||
case tabNames.files:
|
||||
|
||||
@@ -7,6 +7,8 @@ import { AudioDeviceSelector } from './AudioDeviceSelector.jsx';
|
||||
import { AudioEngineTargetSelector } from './AudioEngineTargetSelector.jsx';
|
||||
import { confirmDialog } from '../../util.mjs';
|
||||
import { DEFAULT_MAX_POLYPHONY, setMaxPolyphony, setMultiChannelOrbits } from '@strudel/webaudio';
|
||||
import { ActionButton, SpecialActionButton } from '../button/action-button.jsx';
|
||||
import { ImportPrebakeScriptButton } from './ImportPrebakeScriptButton.jsx';
|
||||
|
||||
function Checkbox({ label, value, onChange, disabled = false }) {
|
||||
return (
|
||||
@@ -113,6 +115,7 @@ export function SettingsTab({ started }) {
|
||||
isTabIndentationEnabled,
|
||||
isMultiCursorEnabled,
|
||||
patternAutoStart,
|
||||
includePrebakeScriptInShare,
|
||||
} = useSettings();
|
||||
const shouldAlwaysSync = isUdels();
|
||||
const canChangeAudioDevice = AudioContext.prototype.setSinkId != null;
|
||||
@@ -204,6 +207,15 @@ export function SettingsTab({ started }) {
|
||||
/>
|
||||
</FormItem>
|
||||
</div>
|
||||
<FormItem label="Prebake">
|
||||
<ImportPrebakeScriptButton />
|
||||
<Checkbox
|
||||
label="Include prebake script in share"
|
||||
onChange={(cbEvent) => settingsMap.setKey('includePrebakeScriptInShare', cbEvent.target.checked)}
|
||||
value={includePrebakeScriptInShare}
|
||||
/>
|
||||
</FormItem>
|
||||
|
||||
<FormItem label="Keybindings">
|
||||
<ButtonGroup
|
||||
value={keybindings}
|
||||
@@ -313,8 +325,7 @@ export function SettingsTab({ started }) {
|
||||
</FormItem>
|
||||
<FormItem label="Zen Mode">Try clicking the logo in the top left!</FormItem>
|
||||
<FormItem label="Reset Settings">
|
||||
<button
|
||||
className="bg-background p-2 max-w-[300px] rounded-md hover:opacity-50"
|
||||
<SpecialActionButton
|
||||
onClick={() => {
|
||||
confirmDialog('Sure?').then((r) => {
|
||||
if (r) {
|
||||
@@ -325,7 +336,7 @@ export function SettingsTab({ started }) {
|
||||
}}
|
||||
>
|
||||
restore default settings
|
||||
</button>
|
||||
</SpecialActionButton>
|
||||
</FormItem>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -14,6 +14,10 @@ import { prebake } from '@src/repl/prebake.mjs';
|
||||
const getSamples = (samples) =>
|
||||
Array.isArray(samples) ? samples.length : typeof samples === 'object' ? Object.values(samples).length : 1;
|
||||
|
||||
function wait(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export function SoundsTab() {
|
||||
const sounds = useStore(soundMap);
|
||||
|
||||
@@ -56,9 +60,7 @@ export function SoundsTab() {
|
||||
|
||||
// holds mutable ref to current triggered sound
|
||||
const trigRef = useRef();
|
||||
|
||||
// Used to cycle through sound previews on banks with multiple sounds
|
||||
let soundPreviewIdx = 0;
|
||||
const numRef = useRef(0);
|
||||
|
||||
// stop current sound on mouseup
|
||||
useEvent('mouseup', () => {
|
||||
@@ -66,6 +68,14 @@ export function SoundsTab() {
|
||||
trigRef.current = undefined;
|
||||
ref?.stop?.(getAudioContext().currentTime + 0.01);
|
||||
});
|
||||
useEvent('keydown', (e) => {
|
||||
if (!isNaN(Number(e.key))) {
|
||||
numRef.current = Number(e.key);
|
||||
}
|
||||
});
|
||||
useEvent('keyup', (e) => {
|
||||
numRef.current = 0;
|
||||
});
|
||||
return (
|
||||
<div id="sounds-tab" className="px-4 flex gap-2 flex-col w-full h-full text-foreground">
|
||||
<Textbox placeholder="Search" value={search} onChange={(v) => setSearch(v)} />
|
||||
@@ -115,25 +125,34 @@ export function SoundsTab() {
|
||||
const params = {
|
||||
note: ['synth', 'soundfont'].includes(data.type) ? 'a3' : undefined,
|
||||
s: name,
|
||||
n: soundPreviewIdx,
|
||||
n: numRef.current,
|
||||
clip: 1,
|
||||
release: 0.5,
|
||||
sustain: 1,
|
||||
duration: 0.5,
|
||||
};
|
||||
soundPreviewIdx++;
|
||||
const onended = () => trigRef.current?.node?.disconnect();
|
||||
try {
|
||||
// Pre-load the sample by calling onTrigger with a future time
|
||||
// This triggers the loading but schedules playback for later
|
||||
const time = ctx.currentTime + 0.5; // Give 500ms for loading
|
||||
const ref = await onTrigger(time, params, onended);
|
||||
trigRef.current = ref;
|
||||
if (ref?.node) {
|
||||
connectToDestination(ref.node);
|
||||
// Attempt to play the sample and retry every 200ms until 10 attempts have been reached
|
||||
let errMsg;
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
try {
|
||||
// Pre-load the sample by calling onTrigger with a future time
|
||||
// This triggers the loading but schedules playback for later
|
||||
const time = ctx.currentTime + 0.05; // Give 50ms for loading
|
||||
const ref = await onTrigger(time, params, onended);
|
||||
trigRef.current = ref;
|
||||
if (ref?.node) {
|
||||
connectToDestination(ref.node);
|
||||
break;
|
||||
}
|
||||
} catch (err) {
|
||||
errMsg = err;
|
||||
}
|
||||
if (attempt == 9) {
|
||||
console.warn('Failed to trigger sound after 10 attempts' + (errMsg ? `: ${errMsg}` : ''));
|
||||
} else {
|
||||
await wait(200);
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed to trigger sound:', err);
|
||||
}
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -3,6 +3,8 @@ import { aliasBank, registerSynthSounds, registerZZFXSounds, samples } from '@st
|
||||
import { registerSamplesFromDB } from './idbutils.mjs';
|
||||
import './piano.mjs';
|
||||
import './files.mjs';
|
||||
import { settingsMap } from '@src/settings.mjs';
|
||||
import { evaluate } from '@strudel/transpiler';
|
||||
|
||||
const { BASE_URL } = import.meta.env;
|
||||
const baseNoTrailing = BASE_URL.endsWith('/') ? BASE_URL.slice(0, -1) : BASE_URL;
|
||||
|
||||
@@ -393,6 +393,8 @@ samples({
|
||||
bass: { d2: 'https://cdn.freesound.org/previews/608/608286_13074022-lq.mp3' }
|
||||
})
|
||||
|
||||
useRNG('legacy')
|
||||
|
||||
stack(
|
||||
// bells
|
||||
n("0").euclidLegato(3,8)
|
||||
@@ -430,6 +432,7 @@ export const festivalOfFingers3 = `// "Festival of fingers 3"
|
||||
// @by Felix Roos
|
||||
|
||||
setcps(1)
|
||||
useRNG('legacy')
|
||||
|
||||
n("[-7*3],0,2,6,[8 7]")
|
||||
.echoWith(
|
||||
@@ -454,6 +457,8 @@ export const meltingsubmarine = `// "Melting submarine"
|
||||
// @by Felix Roos
|
||||
|
||||
samples('github:tidalcycles/dirt-samples')
|
||||
useRNG('legacy')
|
||||
|
||||
stack(
|
||||
s("bd:5,[~ <sd:1!3 sd:1(3,4,3)>],hh27(3,4,1)") // drums
|
||||
.speed(perlin.range(.7,.9)) // random sample speed variation
|
||||
@@ -602,6 +607,9 @@ export const belldub = `// "Belldub"
|
||||
|
||||
samples({ bell: {b4:'https://cdn.freesound.org/previews/339/339809_5121236-lq.mp3'}})
|
||||
// "Hand Bells, B, Single.wav" by InspectorJ (www.jshaw.co.uk) of Freesound.org
|
||||
|
||||
useRNG('legacy')
|
||||
|
||||
stack(
|
||||
// bass
|
||||
note("[0 ~] [2 [0 2]] [4 4*2] [[4 ~] [2 ~] 0@2]".scale('g1 dorian').superimpose(x=>x.add(.02)))
|
||||
@@ -638,6 +646,7 @@ export const dinofunk = `// "Dinofunk"
|
||||
// @by Felix Roos
|
||||
|
||||
setcps(1)
|
||||
useRNG('legacy')
|
||||
|
||||
samples({bass:'https://cdn.freesound.org/previews/614/614637_2434927-hq.mp3',
|
||||
dino:{b4:'https://cdn.freesound.org/previews/316/316403_5123851-hq.mp3'}})
|
||||
@@ -666,6 +675,8 @@ export const sampleDemo = `// "Sample demo"
|
||||
// @license CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
// @by Felix Roos
|
||||
|
||||
useRNG('legacy')
|
||||
|
||||
stack(
|
||||
// percussion
|
||||
s("[woodblock:1 woodblock:2*2] snare_rim:0,gong/8,brakedrum:1(3,8),~@3 cowbell:3")
|
||||
@@ -684,6 +695,8 @@ export const holyflute = `// "Holy flute"
|
||||
// @license CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
// @by Felix Roos
|
||||
|
||||
useRNG('legacy')
|
||||
|
||||
"c3 eb3(3,8) c4/2 g3*2"
|
||||
.superimpose(
|
||||
x=>x.slow(2).add(12),
|
||||
@@ -699,6 +712,8 @@ export const flatrave = `// "Flatrave"
|
||||
// @license CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
// @by Felix Roos
|
||||
|
||||
useRNG('legacy')
|
||||
|
||||
stack(
|
||||
s("bd*2,~ [cp,sd]").bank('RolandTR909'),
|
||||
|
||||
@@ -727,6 +742,8 @@ export const amensister = `// "Amensister"
|
||||
|
||||
samples('github:tidalcycles/dirt-samples')
|
||||
|
||||
useRNG('legacy')
|
||||
|
||||
stack(
|
||||
// amen
|
||||
n("0 1 2 3 4 5 6 7")
|
||||
@@ -834,6 +851,8 @@ export const arpoon = `// "Arpoon"
|
||||
// @license CC BY-NC-SA 4.0 https://creativecommons.org/licenses/by-nc-sa/4.0/
|
||||
// @by Felix Roos
|
||||
|
||||
useRNG('legacy')
|
||||
|
||||
samples('github:tidalcycles/dirt-samples')
|
||||
|
||||
n("[0,3] 2 [1,3] 2".fast(3).lastOf(4, fast(2))).clip(2)
|
||||
|
||||
@@ -6,14 +6,16 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
|
||||
import { code2hash, getPerformanceTimeSeconds, logger, silence } from '@strudel/core';
|
||||
import { getDrawContext } from '@strudel/draw';
|
||||
import { transpiler } from '@strudel/transpiler';
|
||||
import { evaluate, transpiler } from '@strudel/transpiler';
|
||||
import {
|
||||
getAudioContextCurrentTime,
|
||||
renderPatternAudio,
|
||||
webaudioOutput,
|
||||
resetGlobalEffects,
|
||||
resetLoadedSounds,
|
||||
initAudioOnFirstClick,
|
||||
resetDefaults,
|
||||
initAudio,
|
||||
} from '@strudel/webaudio';
|
||||
import { setVersionDefaultsFrom } from './util.mjs';
|
||||
import { StrudelMirror, defaultSettings } from '@strudel/codemirror';
|
||||
@@ -36,6 +38,7 @@ import { getRandomTune, initCode, loadModules, shareCode } from './util.mjs';
|
||||
import './Repl.css';
|
||||
import { setInterval, clearInterval } from 'worker-timers';
|
||||
import { getMetadata } from '../metadata_parser';
|
||||
import { debugAudiograph } from './audiograph';
|
||||
|
||||
const { latestCode, maxPolyphony, audioDeviceName, multiChannelOrbits } = settingsMap.get();
|
||||
let modulesLoading, presets, drawContext, clearCanvas, audioReady;
|
||||
@@ -63,11 +66,10 @@ async function getModule(name) {
|
||||
const initialCode = `// LOADING`;
|
||||
|
||||
export function useReplContext() {
|
||||
const { isSyncEnabled, audioEngineTarget } = useSettings();
|
||||
const { isSyncEnabled, audioEngineTarget, prebakeScript, includePrebakeScriptInShare } = useSettings();
|
||||
const shouldUseWebaudio = audioEngineTarget !== audioEngineTargets.osc;
|
||||
const defaultOutput = shouldUseWebaudio ? webaudioOutput : superdirtOutput;
|
||||
const getTime = shouldUseWebaudio ? getAudioContextCurrentTime : getPerformanceTimeSeconds;
|
||||
|
||||
const init = useCallback(() => {
|
||||
const drawTime = [-2, 2];
|
||||
const drawContext = getDrawContext();
|
||||
@@ -84,7 +86,12 @@ export function useReplContext() {
|
||||
pattern: silence,
|
||||
drawTime,
|
||||
drawContext,
|
||||
prebake: async () => Promise.all([modulesLoading, presets]),
|
||||
prebake: async () =>
|
||||
Promise.all([modulesLoading, presets]).then(() => {
|
||||
if (prebakeScript?.length) {
|
||||
return evaluate(prebakeScript ?? '');
|
||||
}
|
||||
}),
|
||||
onUpdateState: (state) => {
|
||||
setReplState({ ...state });
|
||||
},
|
||||
@@ -125,6 +132,7 @@ export function useReplContext() {
|
||||
bgFill: false,
|
||||
});
|
||||
window.strudelMirror = editor;
|
||||
window.debugAudiograph = debugAudiograph;
|
||||
|
||||
// init settings
|
||||
initCode().then(async (decoded) => {
|
||||
@@ -203,6 +211,30 @@ export function useReplContext() {
|
||||
const handleEvaluate = () => {
|
||||
editorRef.current.evaluate();
|
||||
};
|
||||
|
||||
const handleExport = async (begin, end, sampleRate, maxPolyphony, multiChannelOrbits, downloadName = undefined) => {
|
||||
await editorRef.current.evaluate(false);
|
||||
editorRef.current.repl.scheduler.stop();
|
||||
await renderPatternAudio(
|
||||
editorRef.current.repl.state.pattern,
|
||||
editorRef.current.repl.scheduler.cps,
|
||||
begin,
|
||||
end,
|
||||
sampleRate,
|
||||
maxPolyphony,
|
||||
multiChannelOrbits,
|
||||
downloadName,
|
||||
).finally(async () => {
|
||||
const { latestCode, maxPolyphony, audioDeviceName, multiChannelOrbits } = settingsMap.get();
|
||||
await initAudio({
|
||||
latestCode,
|
||||
maxPolyphony,
|
||||
audioDeviceName,
|
||||
multiChannelOrbits,
|
||||
});
|
||||
editorRef.current.repl.scheduler.stop();
|
||||
});
|
||||
};
|
||||
const handleShuffle = async () => {
|
||||
const patternData = await getRandomTune();
|
||||
const code = patternData.code;
|
||||
@@ -214,7 +246,13 @@ export function useReplContext() {
|
||||
editorRef.current.repl.evaluate(code);
|
||||
};
|
||||
|
||||
const handleShare = async () => shareCode(replState.code);
|
||||
const handleShare = async () => {
|
||||
let code = replState.code;
|
||||
if (includePrebakeScriptInShare) {
|
||||
code = prebakeScript + '\n' + code;
|
||||
}
|
||||
shareCode(code);
|
||||
};
|
||||
const context = {
|
||||
started,
|
||||
pending,
|
||||
@@ -225,6 +263,7 @@ export function useReplContext() {
|
||||
handleShuffle,
|
||||
handleShare,
|
||||
handleEvaluate,
|
||||
handleExport,
|
||||
init,
|
||||
error,
|
||||
editorRef,
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { evalScope, hash2code, logger } from '@strudel/core';
|
||||
import { code2hash, evalScope, hash2code, logger } from '@strudel/core';
|
||||
import { settingPatterns } from '../settings.mjs';
|
||||
import { setVersionDefaults } from '@strudel/webaudio';
|
||||
import { getMetadata } from '../metadata_parser';
|
||||
import { isTauri } from '../tauri.mjs';
|
||||
import './Repl.css';
|
||||
import { createClient } from '@supabase/supabase-js';
|
||||
import { nanoid } from 'nanoid';
|
||||
import { writeText } from '@tauri-apps/plugin-clipboard-manager';
|
||||
import { $featuredPatterns /* , loadDBPatterns */ } from '@src/user_pattern_utils.mjs';
|
||||
|
||||
@@ -109,9 +108,8 @@ export function confirmDialog(msg) {
|
||||
});
|
||||
}
|
||||
|
||||
let lastShared;
|
||||
|
||||
//RIP due to SPAM
|
||||
// let lastShared;
|
||||
// export async function shareCode(codeToShare) {
|
||||
// // const codeToShare = activeCode || code;
|
||||
// if (lastShared === codeToShare) {
|
||||
@@ -146,9 +144,10 @@ let lastShared;
|
||||
// });
|
||||
// }
|
||||
|
||||
export async function shareCode() {
|
||||
export async function shareCode(codeToShare) {
|
||||
try {
|
||||
const shareUrl = window.location.href;
|
||||
const hash = '#' + code2hash(codeToShare);
|
||||
const shareUrl = window.location.origin + window.location.pathname + hash;
|
||||
if (isTauri()) {
|
||||
await writeText(shareUrl);
|
||||
} else {
|
||||
|
||||
@@ -45,11 +45,13 @@ export const defaultSettings = {
|
||||
isPanelOpen: true,
|
||||
togglePanelTrigger: 'click', //click | hover
|
||||
userPatterns: '{}',
|
||||
prebakeScript: '',
|
||||
audioEngineTarget: audioEngineTargets.webaudio,
|
||||
isButtonRowHidden: false,
|
||||
isCSSAnimationDisabled: false,
|
||||
maxPolyphony: 128,
|
||||
multiChannelOrbits: false,
|
||||
includePrebakeScriptInShare: true,
|
||||
};
|
||||
|
||||
let search = null;
|
||||
@@ -96,6 +98,7 @@ export function useSettings() {
|
||||
isPanelOpen: parseBoolean(state.isPanelOpen),
|
||||
userPatterns: userPatterns,
|
||||
multiChannelOrbits: parseBoolean(state.multiChannelOrbits),
|
||||
includePrebakeScriptInShare: parseBoolean(state.includePrebakeScriptInShare),
|
||||
patternAutoStart: isUdels()
|
||||
? false
|
||||
: state.patternAutoStart === undefined
|
||||
@@ -108,6 +111,8 @@ export const setActiveFooter = (tab) => settingsMap.setKey('activeFooter', tab);
|
||||
export const setPanelPinned = (bool) => settingsMap.setKey('isPanelPinned', bool);
|
||||
export const setIsPanelOpened = (bool) => settingsMap.setKey('isPanelOpen', bool);
|
||||
|
||||
export const storePrebakeScript = (script) => settingsMap.setKey('prebakeScript', script);
|
||||
|
||||
export const setIsZen = (active) => settingsMap.setKey('isZen', !!active);
|
||||
|
||||
const patternSetting = (key) =>
|
||||
|
||||
Reference in New Issue
Block a user