soundroo 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (217) hide show
  1. package/AGENTS.md +3 -1
  2. package/README.md +11 -3
  3. package/THIRD_PARTY_NOTICES.md +1 -1
  4. package/assets/reverb/hall.wav +0 -0
  5. package/assets/samples/SOURCES.md +233 -333
  6. package/assets/samples/samples.json +51856 -363
  7. package/bin/soundroo.js +25 -3
  8. package/docs/composing.md +24 -7
  9. package/docs/headless.md +19 -6
  10. package/package.json +1 -1
  11. package/src/arrangement.js +2 -1
  12. package/src/audio/convolution.js +121 -0
  13. package/src/audio/library.js +194 -0
  14. package/src/audio/midi-import.js +174 -0
  15. package/src/audio/midi.js +27 -4
  16. package/src/audio/sampler.js +208 -52
  17. package/src/audio/synth.js +129 -6
  18. package/src/catalog.js +6 -6
  19. package/src/cloud/payload.js +2 -1
  20. package/src/headless.js +37 -9
  21. package/src/identity.js +14 -4
  22. package/src/project.js +20 -7
  23. package/src/render.js +121 -46
  24. package/src/samples-install.js +103 -0
  25. package/src/score.js +72 -15
  26. package/src/timeline.js +50 -0
  27. package/src/version.js +1 -1
  28. package/assets/samples/brass/39-1-1.wav +0 -0
  29. package/assets/samples/brass/41-1-1.wav +0 -0
  30. package/assets/samples/brass/45-1-1.wav +0 -0
  31. package/assets/samples/brass/46-1-1.wav +0 -0
  32. package/assets/samples/brass/50-1-1.wav +0 -0
  33. package/assets/samples/brass/53-1-1.wav +0 -0
  34. package/assets/samples/brass/57-1-1.wav +0 -0
  35. package/assets/samples/brass/60-1-1.wav +0 -0
  36. package/assets/samples/brass/63-1-1.wav +0 -0
  37. package/assets/samples/brass/67-1-1.wav +0 -0
  38. package/assets/samples/brass/70-1-1.wav +0 -0
  39. package/assets/samples/brass/74-1-1.wav +0 -0
  40. package/assets/samples/brass/77-1-1.wav +0 -0
  41. package/assets/samples/brass/81-1-1.wav +0 -0
  42. package/assets/samples/closed-hat/42-1-1.wav +0 -0
  43. package/assets/samples/closed-hat/42-1-2.wav +0 -0
  44. package/assets/samples/closed-hat/42-2-1.wav +0 -0
  45. package/assets/samples/closed-hat/42-2-2.wav +0 -0
  46. package/assets/samples/closed-hat/42-3-1.wav +0 -0
  47. package/assets/samples/closed-hat/42-3-2.wav +0 -0
  48. package/assets/samples/crash/49-1-1.wav +0 -0
  49. package/assets/samples/crash/49-2-1.wav +0 -0
  50. package/assets/samples/electric-bass/24-1-1.wav +0 -0
  51. package/assets/samples/electric-bass/24-2-1.wav +0 -0
  52. package/assets/samples/electric-bass/26-1-1.wav +0 -0
  53. package/assets/samples/electric-bass/26-2-1.wav +0 -0
  54. package/assets/samples/electric-bass/29-1-1.wav +0 -0
  55. package/assets/samples/electric-bass/29-2-1.wav +0 -0
  56. package/assets/samples/electric-bass/32-1-1.wav +0 -0
  57. package/assets/samples/electric-bass/32-2-1.wav +0 -0
  58. package/assets/samples/electric-bass/35-1-1.wav +0 -0
  59. package/assets/samples/electric-bass/35-2-1.wav +0 -0
  60. package/assets/samples/electric-bass/38-1-1.wav +0 -0
  61. package/assets/samples/electric-bass/38-2-1.wav +0 -0
  62. package/assets/samples/electric-bass/41-1-1.wav +0 -0
  63. package/assets/samples/electric-bass/41-2-1.wav +0 -0
  64. package/assets/samples/electric-bass/44-1-1.wav +0 -0
  65. package/assets/samples/electric-bass/44-2-1.wav +0 -0
  66. package/assets/samples/electric-bass/47-1-1.wav +0 -0
  67. package/assets/samples/electric-bass/47-2-1.wav +0 -0
  68. package/assets/samples/electric-bass/50-1-1.wav +0 -0
  69. package/assets/samples/electric-bass/50-2-1.wav +0 -0
  70. package/assets/samples/electric-bass/53-1-1.wav +0 -0
  71. package/assets/samples/electric-bass/53-2-1.wav +0 -0
  72. package/assets/samples/electric-bass/56-1-1.wav +0 -0
  73. package/assets/samples/electric-bass/56-2-1.wav +0 -0
  74. package/assets/samples/electric-bass/59-1-1.wav +0 -0
  75. package/assets/samples/electric-bass/59-2-1.wav +0 -0
  76. package/assets/samples/electric-bass/62-1-1.wav +0 -0
  77. package/assets/samples/electric-bass/62-2-1.wav +0 -0
  78. package/assets/samples/guitar-clean/40-1-1.wav +0 -0
  79. package/assets/samples/guitar-clean/41-1-1.wav +0 -0
  80. package/assets/samples/guitar-clean/45-1-1.wav +0 -0
  81. package/assets/samples/guitar-clean/48-1-1.wav +0 -0
  82. package/assets/samples/guitar-clean/50-1-1.wav +0 -0
  83. package/assets/samples/guitar-clean/52-1-1.wav +0 -0
  84. package/assets/samples/guitar-clean/55-1-1.wav +0 -0
  85. package/assets/samples/guitar-clean/59-1-1.wav +0 -0
  86. package/assets/samples/guitar-clean/61-1-1.wav +0 -0
  87. package/assets/samples/guitar-clean/64-1-1.wav +0 -0
  88. package/assets/samples/guitar-clean/67-1-1.wav +0 -0
  89. package/assets/samples/guitar-clean/71-1-1.wav +0 -0
  90. package/assets/samples/guitar-clean/72-1-1.wav +0 -0
  91. package/assets/samples/guitar-clean/74-1-1.wav +0 -0
  92. package/assets/samples/guitar-clean/77-1-1.wav +0 -0
  93. package/assets/samples/guitar-clean/80-1-1.wav +0 -0
  94. package/assets/samples/guitar-clean/82-1-1.wav +0 -0
  95. package/assets/samples/guitar-clean/85-1-1.wav +0 -0
  96. package/assets/samples/guitar-crunch/40-1-1.wav +0 -0
  97. package/assets/samples/guitar-crunch/41-1-1.wav +0 -0
  98. package/assets/samples/guitar-crunch/45-1-1.wav +0 -0
  99. package/assets/samples/guitar-crunch/48-1-1.wav +0 -0
  100. package/assets/samples/guitar-crunch/50-1-1.wav +0 -0
  101. package/assets/samples/guitar-crunch/52-1-1.wav +0 -0
  102. package/assets/samples/guitar-crunch/55-1-1.wav +0 -0
  103. package/assets/samples/guitar-crunch/59-1-1.wav +0 -0
  104. package/assets/samples/guitar-crunch/61-1-1.wav +0 -0
  105. package/assets/samples/guitar-crunch/64-1-1.wav +0 -0
  106. package/assets/samples/guitar-crunch/67-1-1.wav +0 -0
  107. package/assets/samples/guitar-crunch/71-1-1.wav +0 -0
  108. package/assets/samples/guitar-crunch/72-1-1.wav +0 -0
  109. package/assets/samples/guitar-crunch/74-1-1.wav +0 -0
  110. package/assets/samples/guitar-crunch/77-1-1.wav +0 -0
  111. package/assets/samples/guitar-crunch/80-1-1.wav +0 -0
  112. package/assets/samples/guitar-crunch/82-1-1.wav +0 -0
  113. package/assets/samples/guitar-crunch/85-1-1.wav +0 -0
  114. package/assets/samples/open-hat/46-1-1.wav +0 -0
  115. package/assets/samples/open-hat/46-2-1.wav +0 -0
  116. package/assets/samples/piano/102-1-1.wav +0 -0
  117. package/assets/samples/piano/102-2-1.wav +0 -0
  118. package/assets/samples/piano/105-1-1.wav +0 -0
  119. package/assets/samples/piano/105-2-1.wav +0 -0
  120. package/assets/samples/piano/108-1-1.wav +0 -0
  121. package/assets/samples/piano/108-2-1.wav +0 -0
  122. package/assets/samples/piano/21-1-1.wav +0 -0
  123. package/assets/samples/piano/21-2-1.wav +0 -0
  124. package/assets/samples/piano/24-1-1.wav +0 -0
  125. package/assets/samples/piano/24-2-1.wav +0 -0
  126. package/assets/samples/piano/27-1-1.wav +0 -0
  127. package/assets/samples/piano/27-2-1.wav +0 -0
  128. package/assets/samples/piano/30-1-1.wav +0 -0
  129. package/assets/samples/piano/30-2-1.wav +0 -0
  130. package/assets/samples/piano/33-1-1.wav +0 -0
  131. package/assets/samples/piano/33-2-1.wav +0 -0
  132. package/assets/samples/piano/36-1-1.wav +0 -0
  133. package/assets/samples/piano/36-2-1.wav +0 -0
  134. package/assets/samples/piano/39-1-1.wav +0 -0
  135. package/assets/samples/piano/39-2-1.wav +0 -0
  136. package/assets/samples/piano/42-1-1.wav +0 -0
  137. package/assets/samples/piano/42-2-1.wav +0 -0
  138. package/assets/samples/piano/45-1-1.wav +0 -0
  139. package/assets/samples/piano/45-2-1.wav +0 -0
  140. package/assets/samples/piano/48-1-1.wav +0 -0
  141. package/assets/samples/piano/48-2-1.wav +0 -0
  142. package/assets/samples/piano/51-1-1.wav +0 -0
  143. package/assets/samples/piano/51-2-1.wav +0 -0
  144. package/assets/samples/piano/54-1-1.wav +0 -0
  145. package/assets/samples/piano/54-2-1.wav +0 -0
  146. package/assets/samples/piano/57-1-1.wav +0 -0
  147. package/assets/samples/piano/57-2-1.wav +0 -0
  148. package/assets/samples/piano/60-1-1.wav +0 -0
  149. package/assets/samples/piano/60-2-1.wav +0 -0
  150. package/assets/samples/piano/63-1-1.wav +0 -0
  151. package/assets/samples/piano/63-2-1.wav +0 -0
  152. package/assets/samples/piano/66-1-1.wav +0 -0
  153. package/assets/samples/piano/66-2-1.wav +0 -0
  154. package/assets/samples/piano/69-1-1.wav +0 -0
  155. package/assets/samples/piano/69-2-1.wav +0 -0
  156. package/assets/samples/piano/72-1-1.wav +0 -0
  157. package/assets/samples/piano/72-2-1.wav +0 -0
  158. package/assets/samples/piano/75-1-1.wav +0 -0
  159. package/assets/samples/piano/75-2-1.wav +0 -0
  160. package/assets/samples/piano/78-1-1.wav +0 -0
  161. package/assets/samples/piano/78-2-1.wav +0 -0
  162. package/assets/samples/piano/81-1-1.wav +0 -0
  163. package/assets/samples/piano/81-2-1.wav +0 -0
  164. package/assets/samples/piano/84-1-1.wav +0 -0
  165. package/assets/samples/piano/84-2-1.wav +0 -0
  166. package/assets/samples/piano/87-1-1.wav +0 -0
  167. package/assets/samples/piano/87-2-1.wav +0 -0
  168. package/assets/samples/piano/90-1-1.wav +0 -0
  169. package/assets/samples/piano/90-2-1.wav +0 -0
  170. package/assets/samples/piano/93-1-1.wav +0 -0
  171. package/assets/samples/piano/93-2-1.wav +0 -0
  172. package/assets/samples/piano/96-1-1.wav +0 -0
  173. package/assets/samples/piano/96-2-1.wav +0 -0
  174. package/assets/samples/piano/99-1-1.wav +0 -0
  175. package/assets/samples/piano/99-2-1.wav +0 -0
  176. package/assets/samples/ride/51-1-1.wav +0 -0
  177. package/assets/samples/ride/51-2-1.wav +0 -0
  178. package/assets/samples/rock-kick/36-1-1.wav +0 -0
  179. package/assets/samples/rock-kick/36-1-2.wav +0 -0
  180. package/assets/samples/rock-kick/36-2-1.wav +0 -0
  181. package/assets/samples/rock-kick/36-2-2.wav +0 -0
  182. package/assets/samples/rock-kick/36-3-1.wav +0 -0
  183. package/assets/samples/rock-kick/36-3-2.wav +0 -0
  184. package/assets/samples/rock-kick/36-4-1.wav +0 -0
  185. package/assets/samples/rock-kick/36-4-2.wav +0 -0
  186. package/assets/samples/rock-snare/38-1-1.wav +0 -0
  187. package/assets/samples/rock-snare/38-1-2.wav +0 -0
  188. package/assets/samples/rock-snare/38-2-1.wav +0 -0
  189. package/assets/samples/rock-snare/38-2-2.wav +0 -0
  190. package/assets/samples/rock-snare/38-3-1.wav +0 -0
  191. package/assets/samples/rock-snare/38-3-2.wav +0 -0
  192. package/assets/samples/rock-snare/38-4-1.wav +0 -0
  193. package/assets/samples/rock-snare/38-4-2.wav +0 -0
  194. package/assets/samples/strings/36-1-1.wav +0 -0
  195. package/assets/samples/strings/40-1-1.wav +0 -0
  196. package/assets/samples/strings/43-1-1.wav +0 -0
  197. package/assets/samples/strings/47-1-1.wav +0 -0
  198. package/assets/samples/strings/50-1-1.wav +0 -0
  199. package/assets/samples/strings/53-1-1.wav +0 -0
  200. package/assets/samples/strings/55-1-1.wav +0 -0
  201. package/assets/samples/strings/59-1-1.wav +0 -0
  202. package/assets/samples/strings/62-1-1.wav +0 -0
  203. package/assets/samples/strings/65-1-1.wav +0 -0
  204. package/assets/samples/strings/69-1-1.wav +0 -0
  205. package/assets/samples/strings/72-1-1.wav +0 -0
  206. package/assets/samples/strings/76-1-1.wav +0 -0
  207. package/assets/samples/strings/79-1-1.wav +0 -0
  208. package/assets/samples/strings/83-1-1.wav +0 -0
  209. package/assets/samples/strings/86-1-1.wav +0 -0
  210. package/assets/samples/tom/41-1-1.wav +0 -0
  211. package/assets/samples/tom/41-2-1.wav +0 -0
  212. package/assets/samples/tom/45-1-1.wav +0 -0
  213. package/assets/samples/tom/45-2-1.wav +0 -0
  214. package/assets/samples/tom/48-1-1.wav +0 -0
  215. package/assets/samples/tom/48-2-1.wav +0 -0
  216. package/assets/samples/tom/50-1-1.wav +0 -0
  217. package/assets/samples/tom/50-2-1.wav +0 -0
package/bin/soundroo.js CHANGED
@@ -8,7 +8,7 @@ import { createSpeech, transformSpeech } from '../src/voice.js';
8
8
  const args = process.argv.slice(2);
9
9
  const command = args.shift() ?? 'start';
10
10
  const options = {}, positional = [];
11
- const boolean = new Set(['json', 'examples', 'all', 'replace', 'stems', 'help', 'version', 'no-render', 'dry-run', 'rights-accepted', 'no-wait', 'force', 'confirm', 'start', 'wait', 'local-only', 'refresh', 'no-guest']);
11
+ const boolean = new Set(['json', 'examples', 'all', 'replace', 'stems', 'help', 'version', 'no-render', 'dry-run', 'rights-accepted', 'no-wait', 'force', 'confirm', 'start', 'wait', 'local-only', 'refresh', 'no-guest', 'add']);
12
12
  // Optional network sharing; its code loads only for these commands.
13
13
  const network = new Set(['share', 'publish', 'login', 'logout', 'whoami', 'claim', 'claim-link', 'import', 'cloud']);
14
14
  try {
@@ -31,7 +31,9 @@ const directory = libraryPath(options.library ?? (['init', 'start', 'demo', 'lis
31
31
  const number = (key, fallback) => options[key] == null ? fallback : Number(options[key]);
32
32
  const exampleSeed = () => number('seed', (options.collection ?? 'variety') === 'variety' ? 21 : 1);
33
33
  function help() {
34
- print(`Soundroo ${VERSION} — music made with your coding agent\n\nUse Node 22 or newer. No installation is needed for instrumental music.\n\n node bin/soundroo.js start [library] Open the local listening studio; first start loads ten examples\n node bin/soundroo.js init [library] Create an empty personal collection\n node bin/soundroo.js demo [library] Create and render the original example collection\n node bin/soundroo.js add score.json Add an editable composition (--replace revises it)\n node bin/soundroo.js validate score.json Check a composition before rendering\n node bin/soundroo.js render [track-id] Render a track, or --all; --stems exports its parts; --sound synthesized\n node bin/soundroo.js inspect [track-id] Inspect saved music and audio reports\n node bin/soundroo.js list [library] List the collection\n node bin/soundroo.js catalog Discover instruments and tone controls\n node bin/soundroo.js example [id] List the example tracks by genre, or print one to learn from\n node bin/soundroo.js requests Read pending musical briefs from the studio\n node bin/soundroo.js doctor Check the local runtime\n node bin/soundroo.js version Show the toolkit version and engine hash\n node bin/soundroo.js voice create "words" --out library/assets/voice.wav\n node bin/soundroo.js voice process voice.wav --effect vocoder --out processed.wav\n\nOptional sharing on soundroo.com (only these commands use the network; see docs/sharing.md):\n node bin/soundroo.js share --dry-run Preview what would be uploaded; nothing is sent or saved\n node bin/soundroo.js share --rights-accepted Publish the library and print its links\n node bin/soundroo.js share status Show this library's shared links\n node bin/soundroo.js import LINK Add an open track to the library as a remix\n node bin/soundroo.js claim --email ADDRESS Email a link that keeps your guest artist page\n node bin/soundroo.js login | logout | whoami | claim-link\n\nOptions: --library PATH, --json, --port NUMBER, --seed NUMBER, --title TEXT, --collection variety|open-window, --service URL.\nSpeech creation is optional and needs Kokoro; speech effects and bundled voice examples work with Node alone.\nThe studio creates no hidden model calls. Your existing coding agent composes and revises the music.`);
34
+ print(`Soundroo ${VERSION} — music made with your coding agent\n\nUse Node 22 or newer. No installation is needed: the recorded instruments download once, the first time a track uses them.\n\n node bin/soundroo.js start [library] Open the local listening studio; first start loads ten examples\n node bin/soundroo.js init [library] Create an empty personal collection\n node bin/soundroo.js demo [library] Create and render the original example collection\n node bin/soundroo.js add score.json Add an editable composition (--replace revises it)\n node bin/soundroo.js validate score.json Check a composition before rendering\n node bin/soundroo.js render [track-id] Render a track, or --all; --stems exports its parts; --sound synthesized\n node bin/soundroo.js inspect [track-id] Inspect saved music and audio reports\n node bin/soundroo.js list [library] List the collection\n node bin/soundroo.js catalog Discover instruments and tone controls\n node bin/soundroo.js example [id] List the example tracks by genre, or print one to learn from\n node bin/soundroo.js requests Read pending musical briefs from the studio\n node bin/soundroo.js import-midi piece.mid Turn a MIDI file into a score (--add puts it in the library)
35
+ node bin/soundroo.js samples [--all] The recorded instruments: status, or download them now
36
+ node bin/soundroo.js doctor Check the local runtime\n node bin/soundroo.js version Show the toolkit version and engine hash\n node bin/soundroo.js voice create "words" --out library/assets/voice.wav\n node bin/soundroo.js voice process voice.wav --effect vocoder --out processed.wav\n\nOptional sharing on soundroo.com (apart from that one download, only these commands use the network; see docs/sharing.md):\n node bin/soundroo.js share --dry-run Preview what would be uploaded; nothing is sent or saved\n node bin/soundroo.js share --rights-accepted Publish the library and print its links\n node bin/soundroo.js share status Show this library's shared links\n node bin/soundroo.js import LINK Add an open track to the library as a remix\n node bin/soundroo.js claim --email ADDRESS Email a link that keeps your guest artist page\n node bin/soundroo.js login | logout | whoami | claim-link\n\nOptions: --library PATH, --json, --port NUMBER, --seed NUMBER, --title TEXT, --collection variety|open-window, --service URL.\nSpeech creation is optional and needs Kokoro; speech effects and bundled voice examples work with Node alone.\nThe studio creates no hidden model calls. Your existing coding agent composes and revises the music.`);
35
37
  }
36
38
 
37
39
  try {
@@ -40,8 +42,16 @@ try {
40
42
  else if (command === 'doctor') {
41
43
  const major = Number(process.versions.node.split('.')[0]);
42
44
  const checks = [{ name: 'Node 22+', ok: major >= 22, version: process.version }, { name: 'Studio files', ok: fs.existsSync(new URL('../web/index.html', import.meta.url)) }, { name: 'Score renderer', ok: fs.existsSync(new URL('../src/render.js', import.meta.url)) }];
43
- print({ ready: checks.every(c => c.ok), checks, requiredMusicTools: [], optionalSpeech: 'Install Kokoro only for creating new spoken phrases.' });
45
+ const { samples } = await import('../src/headless.js');
46
+ const packs = samples();
47
+ print({ ready: checks.every(c => c.ok), checks, requiredMusicTools: [], recordedInstruments: { installed: packs.filter(p => p.installed).map(p => p.name), missing: packs.filter(p => !p.installed).map(p => p.name), note: 'Missing recordings download by themselves the first time a track needs them (node bin/soundroo.js samples --all gets them all).' }, optionalSpeech: 'Install Kokoro only for creating new spoken phrases.' });
44
48
  if (checks.some(c => !c.ok)) process.exitCode = 1;
49
+ } else if (command === 'samples') {
50
+ // The recorded instruments: their status, or download them (all, or the named packs).
51
+ const { samples, installSamples } = await import('../src/headless.js');
52
+ const names = positional.length ? positional : options.all ? undefined : null;
53
+ const packs = names === null ? samples() : await installSamples(names, { log });
54
+ print(options.json ? { packs } : packs.map(p => `${p.installed ? 'installed' : 'missing '} ${p.name.padEnd(14)} ${(p.size / 1e6).toFixed(0).padStart(5)} MB ${p.instruments.join(', ')}`).join('\n') + (names === null && packs.some(p => !p.installed) ? '\n\nThey download by themselves the first time a track needs them. To get them all now: node bin/soundroo.js samples --all' : ''));
45
55
  } else if (command === 'init') {
46
56
  const collection = await initLibrary(directory, { examples: Boolean(options.examples), exampleSet: options.collection ?? 'variety', seed: exampleSeed(), title: options.title ?? 'Your music', description: options.description ?? '' });
47
57
  print({ directory, collection });
@@ -67,6 +77,18 @@ try {
67
77
  } else if (command === 'add') {
68
78
  if (!positional[0]) throw new Error('Choose a JSON score file to add.');
69
79
  print({ id: await addTrack(directory, positional[0], { replace: Boolean(options.replace) }), directory });
80
+ } else if (command === 'import-midi') {
81
+ // A MIDI file as an editable version 3 score; --add puts it in the library too.
82
+ if (!positional[0]) throw new Error('Choose a .mid file to import.');
83
+ const { midiToScore } = await import('../src/audio/midi-import.js');
84
+ const { validateScore } = await import('../src/score.js');
85
+ const { score, skipped } = midiToScore(fs.readFileSync(positional[0]), { title: options.title, id: options.id ?? path.basename(positional[0]).replace(/\.midi?$/i, '') });
86
+ const { valid, issues } = validateScore(score);
87
+ if (!valid) throw new Error(`The imported score is not valid: ${issues.slice(0, 5).map(i => `${i.path}: ${i.message}`).join('; ')}`);
88
+ const out = options.out ?? path.join(path.dirname(positional[0]), `${score.id}.json`);
89
+ fs.writeFileSync(out, JSON.stringify(score, null, 2) + '\n');
90
+ const added = options.add ? await addTrack(directory, out, { replace: Boolean(options.replace) }) : null;
91
+ print({ file: out, id: score.id, parts: score.parts.map(p => ({ id: p.id, instrument: p.instrument, notes: p.notes.length, pedal: p.pedal?.length ?? 0 })), tempoChanges: score.tempo?.length ?? 0, skippedDrumNotes: skipped, ...(added ? { added, directory } : {}) });
70
92
  } else if (command === 'validate') {
71
93
  if (!positional[0]) throw new Error('Choose a JSON score file to validate.');
72
94
  const { validateScore } = await import('../src/score.js'); const result = validateScore(JSON.parse(fs.readFileSync(positional[0], 'utf8'))); print(result); if (!result.valid) process.exitCode = 2;
package/docs/composing.md CHANGED
@@ -31,22 +31,39 @@ For a revision, change the score or its script, use `add --replace`, then render
31
31
 
32
32
  ## Score format
33
33
 
34
- Every score uses `version: 1`, or `version: 2` for the compact pattern strings below, a lowercase slug `id`, a title, `bpm`, the total length in quarter-note `beats`, and an array of instrument `parts`. Useful metadata includes `description`, `genre`, `mood`, `key`, an integer `seed`, and named `sections`.
34
+ Every score uses `version: 1`, `version: 2` for the compact pattern strings below, or `version: 3` for those plus tempo changes and the sustain pedal, a lowercase slug `id`, a title, `bpm`, the total length in quarter-note `beats`, and an array of instrument `parts`. Useful metadata includes `description`, `genre`, `mood`, `key`, an integer `seed`, and named `sections`.
35
35
 
36
36
  | Field | Meaning |
37
37
  | --- | --- |
38
- | `bpm` | Tempo from 20 to 400 beats per minute. |
38
+ | `bpm` | Tempo from 20 to 400 beats per minute at beat 0. |
39
+ | `tempo` | Version 3: tempo changes `{beat, bpm, ramp}` after beat 0. `ramp: true` glides from the tempo before it and arrives at `bpm` on that beat (a ritardando or accelerando). |
39
40
  | `beats` | Total score length in quarter-note beats. Leave space for musical release and the ending. |
40
41
  | `sections` | `{id, name, beat, beats}`; section starts and lengths use beats. |
41
42
  | `master` | `{volume, reverb}`; volume 0–2, reverb 0–1. |
42
- | `parts` | `{id, name, instrument, volume, pan, color, tone, notes, patterns, clips, sample}`. |
43
+ | `parts` | `{id, name, instrument, volume, pan, color, tone, notes, patterns, clips, sample, pedal}`. |
44
+ | `pedal` | Version 3: sustain pedal spans `{beat, beats}` in which the pedal is down. A note released inside a span rings until the pedal comes up. Spans that touch are a pedal change: the dampers fall between them. Patterns can carry `pedal` too; clips repeat it. |
43
45
  | `notes` | `{pitch, beat, duration, velocity}`. Pitch is a MIDI integer or scientific pitch such as `F#4`; velocity is greater than 0 and at most 1. |
44
46
  | `patterns` | Named blocks `{name: {beats, notes}}` with timing relative to the block. Version 2 adds `line`, `steps` and `pitch`. |
45
47
  | `clips` | `{pattern, beat, repeat, transpose, velocity}`; repeat and transpose a named pattern at a score position. |
46
48
  | `tone` | Instrument-specific controls. Discover names and supported ranges with `catalog`. |
47
49
  | `artwork` | Optional sleeve metadata: `{style, colors: [background, ink, accent], seed}`. Colors use six-digit hex. |
48
50
 
49
- The renderer validates timing, identities, ranges, supported controls and expansion limits. Scores support up to ten minutes, 64 parts and 100,000 expanded note events.
51
+ The renderer validates timing, identities, ranges, supported controls and expansion limits. Scores support up to ten minutes (counted with their tempo changes), 64 parts and 100,000 expanded note events.
52
+
53
+ ### Expressive timing and the pedal (version 3)
54
+
55
+ Piano music lives on the sustain pedal and on timing that breathes. Pedal once per harmony: a span from where the chord starts to just before the next one, so the next span begins where this one ends and the dampers clear the old harmony. Without a pedal, a piano note stops when its `duration` ends. The highest notes (from F#6 up) have no dampers and ring on whatever the pedal does, as on a real piano.
56
+
57
+ ```json
58
+ "tempo": [{"beat": 56, "bpm": 112}, {"beat": 64, "bpm": 72, "ramp": true}],
59
+ "parts": [{"id": "piano", "instrument": "piano", "notes": [], "pedal": [{"beat": 0, "beats": 2}, {"beat": 2, "beats": 2}]}]
60
+ ```
61
+
62
+ Use tempo changes for the large shape (a slower bridge, a ritardando into the last chord) and fractional beats and velocities for the small one: a melody note placed a little late, an inner voice softer than the tune.
63
+
64
+ ### Importing MIDI
65
+
66
+ Any program that writes standard MIDI files can compose for Soundroo. `node bin/soundroo.js import-midi piece.mid --title "Piece" --add --library library/my-music` turns a MIDI file into a version 3 score and adds it to the library: notes keep their exact timing, velocity and length; tempo changes, the sustain pedal (controller 64) and markers (as sections) come along. General MIDI programs choose the closest Soundroo instrument (pianos, guitars, basses, strings, brass, organ, pads, leads), and drums on channel 10 become the acoustic kit. Without `--add` the score is only written next to the MIDI file, to edit first. A script can write the MIDI with any library, or write the score JSON directly.
50
67
 
51
68
  ## Compact notation (version 2)
52
69
 
@@ -74,7 +91,7 @@ Part volume defaults to 1 and master volume to 0.8. The mix controls use the sam
74
91
 
75
92
  Run `node bin/soundroo.js catalog --json` for the authoritative instrument names and controls. Instruments include `piano`, `electric-piano`, `organ`, `strings`, `brass`, `pad`, `pluck`, `bass`, `electric-bass`, `bell`, `marimba`, `analog-lead`, `fm-lead`, `acid-bass`, `guitar-clean`, `guitar-crunch`, two drum kits, `noise`, and `sample`.
76
93
 
77
- The piano, strings, brass, guitars, electric bass and the acoustic drum kit play recordings of real instruments (see `assets/samples/SOURCES.md`); the rest are synthesized. Recorded notes sound most natural inside the instrument's real range: piano A0 to C8, bass E1 to C4, guitar E2 to C6, strings C2 to D6, brass E♭2 to A5.
94
+ The piano, strings, brass, guitars, electric bass and the acoustic drum kit play full recordings of real instruments in stereo (see `assets/samples/SOURCES.md`); the rest are synthesized. The grand piano has sixteen recorded loudness layers per note, its natural decay, and the sounds of its dampers, hammers and pedal. Drums, bass and guitars choose among several recorded takes, so repeated notes never sound copied. The recordings are about 4 GB; the toolkit downloads the ones a track needs the first time it renders it (or all of them with `node bin/soundroo.js samples --all`) and keeps them in your cache folder. Recorded notes sound most natural inside the instrument's real range: piano A0 to C8, bass E1 to C4, guitar E2 to C6, strings C2 to D6, brass E♭2 to A5.
78
95
 
79
96
  For guitar-led music, use `guitar-clean`, `guitar-crunch` and `electric-bass`. Crunch guitar runs a recorded guitar through overdrive and cabinet filtering before its mix fader; power chords (root, fifth and octave) sound biggest. `brightness`, `release`, `palmMute` and, for crunch, `drive` shape the articulation. Use short palm-muted notes for riffs and alternating bass; release the mute for sustained choruses. Strum chord notes a few milliseconds apart. Guitar notes typically sit between E2 and E6; bass generally sits an octave lower. Keep riffs and lead hooks out of each other's way. Crunch overdrive compresses velocity accents; use clean guitar or part balance for more pronounced dynamics.
80
97
 
@@ -82,7 +99,7 @@ There are two drum kits. The acoustic kit is recorded: `rock-kick`, `rock-snare`
82
99
 
83
100
  For video game music, `chip-lead` is a pulse wave like the sound chips in 8-bit consoles. Its `duty` sets the pulse width: 0.125 is thin and nasal, 0.25 the classic lead, 0.5 a hollow square. `chip-bass` is a triangle bass. Use them with `kick`, `snare` and `hi-hat`, fast sixteenth-note arpeggios and little reverb. [`examples/pixel-grand-prix.json`](../examples/pixel-grand-prix.json) is a complete 8-bit racing theme.
84
101
 
85
- Velocity picks the recorded layer: soft notes sound softer, not just quieter. Strings and brass hold long notes steadily; their `detune` doubles the section with a second take, and `attack` adds a slower swell. Electronic timbres, mallets, textures and processed speech are synthesized.
102
+ Velocity picks the recorded layer: soft notes sound softer, not just quieter. Strings and brass hold long notes steadily; their `detune` doubles the section with a second take, and `attack` adds a slower swell. Cymbals ring out in full; a new hit on the same cymbal takes over from its oldest ringing. The recorded instruments play unfiltered; `brightness` darkens them only when set below 20000. Electronic timbres, mallets, textures and processed speech are synthesized.
86
103
 
87
104
  Every score can also play with all instruments synthesized: `node bin/soundroo.js render <track> --sound synthesized` saves that version beside the recorded one. soundroo.com renders both, and listeners switch between them in the player. Write for the recorded instruments; the synthesized version follows the same notes.
88
105
 
@@ -128,7 +145,7 @@ The studio's player volume changes listening only. Saved mixer values change the
128
145
 
129
146
  ## Check and listen
130
147
 
131
- Use validation before rendering. Every render is mastered: a high-pass below 30 Hz, the same loudness for every track (about -14 LUFS, the level streaming services play at; the report's `loudness`) and a limiter that keeps peaks at -1 dBFS. Part volumes set the balance between parts. A master volume below the default 0.8 makes the whole track quieter; a higher one changes nothing. `limitedFraction` is the share of the track the limiter turns down by more than 3 dB; a track with sharp peaks is first played a little quieter, and if that is not enough the report warns that loud moments sound squashed. Lower the loudest parts then, usually drums or bass.
148
+ Use validation before rendering. The master reverb is a concert hall (`master.reverb` sets how much of it you hear). Music with drums gets a gentle glue compressor; music without drums keeps its full dynamics. Every render is mastered: a high-pass below 30 Hz, the same loudness for every track (about -14 LUFS, the level streaming services play at; the report's `loudness`) and a limiter that keeps peaks at -1 dBFS. Part volumes set the balance between parts. A master volume below the default 0.8 makes the whole track quieter; a higher one changes nothing. `limitedFraction` is the share of the track the limiter turns down by more than 3 dB; a track with sharp peaks is first played a little quieter, and if that is not enough the report warns that loud moments sound squashed. Lower the loudest parts then, usually drums or bass.
132
149
 
133
150
  The report's `suggestions` point at arrangement problems listeners notice: drums and bass that only come in after bar eight, the same four bars repeated unchanged for 24 bars or more, sections that all use the same parts, and a long silent ending. Fix them unless the person asked for exactly that.
134
151
 
package/docs/headless.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Headless engine
2
2
 
3
- `src/headless.js` is Soundroo's engine without the music library, studio or CLI. A server, worker or test passes score JSON and receives validation issues, WAV bytes and render reports, MIDI, record sleeves and identities. It needs Node 22 or newer and no npm packages. Only speech recipes load the optional local Kokoro runtime.
3
+ `src/headless.js` is Soundroo's engine without the music library, studio or CLI. A server, worker or test passes score JSON and receives validation issues, WAV bytes and render reports, MIDI, record sleeves and identities. It needs Node 22 or newer and no npm packages. Only speech recipes load the optional local Kokoro runtime. The recorded instruments play from sample packs that are installed once (see [Recorded instruments](#recorded-instruments)); renders never download.
4
4
 
5
5
  The CLI and studio render through the same functions, so a headless render of a library score and mix produces the same WAV bytes, report and revision as `render` writes into `tracks/<id>/renders/`.
6
6
 
@@ -9,8 +9,9 @@ import * as soundroo from './src/headless.js';
9
9
 
10
10
  const check = soundroo.validate(score);
11
11
  if (!check.valid) return { error: check.issues }; // [{path, message}]
12
+ await soundroo.prepareSamples(score, { samplesDir }); // downloads missing instrument packs once
12
13
  await soundroo.prepareSpeech(score, { cacheDir }); // only scores with speech recipes
13
- const { wav, report, revision } = await soundroo.render(score, { mix, speech: { cacheDir, synthesize: false } });
14
+ const { wav, report, revision } = await soundroo.render(score, { mix, samplesDir, speech: { cacheDir, synthesize: false } });
14
15
  const midi = soundroo.midi(score); // Buffer
15
16
  const svg = soundroo.sleeve(score, { index: 0, artwork }); // string
16
17
  const fingerprint = soundroo.fingerprint(score); // 'fp1:…'
@@ -34,8 +35,13 @@ const fingerprint = soundroo.fingerprint(score); // 'fp1:…'
34
35
  | `validateArtwork(artwork)` | `{valid, issues}` for `{style, colors, seed}`. |
35
36
  | `speechRecipes(score, {cacheDir})` | `[{key, text, voice, file, cached}]` for each distinct recipe. |
36
37
  | `prepareSpeech(score, options)` | Speaks uncached recipes and returns them with `synthesized`. |
38
+ | `samples({samplesDir})` | `[{name, file, size, installed, instruments}]` for every sample pack. |
39
+ | `samplePacks(score)` | The names of the packs a score's recorded instruments play from. |
40
+ | `prepareSamples(score, options)` | Downloads the packs a score needs that are missing, and checks them. |
41
+ | `installSamples(names, options)` | Downloads the named packs (all when `names` is omitted). |
42
+ | `defaultSamplesDir()` | `SOUNDROO_SAMPLES_DIR`, else `soundroo/samples` in the user's cache folder. |
37
43
 
38
- `compile` returns version 1 shaped JSON for both score versions: defaults filled, clips and pattern strings expanded into sorted notes, patterns and clips removed. A version 2 score without speech therefore compiles into a score older engines can also render.
44
+ `compile` returns the expanded score for every version: defaults filled, clips and pattern strings expanded into sorted notes and pedal spans, patterns and clips removed, `tempo` and each part's `pedal` as lists. It says `version: 1` unless it uses tempo changes or the pedal, then `version: 3`. A version 2 score without speech therefore compiles into a score older engines can also render.
39
45
 
40
46
  ## Rendering
41
47
 
@@ -50,6 +56,7 @@ const fingerprint = soundroo.fingerprint(score); // 'fp1:…'
50
56
  | `sound` | `recorded` (default) or `synthesized`: every instrument synthesized, as engines before 0.6.0 played them. Same timeline and mastering; the revision stays the same. |
51
57
  | `projectDir` | Library folder for `assets/` WAVs. Network scores should not use local WAVs. |
52
58
  | `speech` | `{cacheDir, synthesize, modelDir, offline, log}` for speech recipes. |
59
+ | `samplesDir` | Folder of the installed sample packs. Default `defaultSamplesDir()`. |
53
60
  | `progress`, `signal` | Progress callback and AbortSignal, as in `renderScore`. |
54
61
 
55
62
  `wav` is a 16-bit stereo PCM WAV `Buffer`. The report contains duration, sample rate, peak and RMS (linear and dBFS), clipped and non-finite sample counts, silent fraction, a 360-point peak waveform, section times, `loudness` (integrated LUFS after mastering), `loudnessGainDb`, `limitedFraction` (share of the track the limiter turns down by more than 3 dB), warnings, arrangement `suggestions`, `revision` and `source`. Signal measurements diagnose problems; they do not judge music.
@@ -61,14 +68,19 @@ Errors:
61
68
  - Cancellation through `signal` or a `false` progress result throws `AbortError`.
62
69
  - Audio with non-finite or full-scale samples throws an error carrying `.report`.
63
70
  - A speech recipe missing from the cache with `synthesize: false` throws, naming the words and voice.
71
+ - A recorded instrument whose pack is not installed throws `MissingSamplesError` (`code: 'samples_missing'`, `packs`).
64
72
 
65
73
  ## Identities
66
74
 
67
- **Engine hash.** SHA-256 over a manifest of `src/identity.js`, `src/score.js`, `src/notation.js`, `src/render.js`, `src/catalog.js`, `src/speech.js`, `src/headless.js`, every `src/audio/*.js` and the built-in `assets/voices/*.wav`. Each JavaScript file is read with LF line endings. The toolkit version, CLI, studio, library, sleeve, network and documentation files do not count, so a release that changes only those keeps its engine hash. `engineManifest()` lists the files to compare when a server copies an engine release.
75
+ **Engine hash.** SHA-256 over a manifest of `src/identity.js`, `src/score.js`, `src/notation.js`, `src/render.js`, `src/timeline.js`, `src/catalog.js`, `src/speech.js`, `src/headless.js`, every `src/audio/*.js`, the built-in `assets/voices/*.wav`, the hall impulse response `assets/reverb/hall.wav` and the sample manifest `assets/samples/samples.json`, which records the size and SHA-256 of every sample pack. Each JavaScript file is read with LF line endings. The toolkit version, CLI, studio, library, sleeve, network and documentation files do not count, so a release that changes only those keeps its engine hash. `engineManifest()` lists the files to compare when a server copies an engine release.
68
76
 
69
77
  **Revision.** The first 24 hex characters of SHA-256 over canonical JSON of `{engine, mix, sampleRate, score}`, plus the bytes of any referenced `assets/` WAV. Canonical JSON sorts object keys at every level, so key order and whitespace do not matter, but every value does. The score's title, `origin` or a saved mix all change the revision. Built-in phrases count through the engine hash. A speech recipe counts by its words and voice, not by its synthesized samples, so a server computes the same revision as the computer that rendered locally. Pass scores and mixes as parsed JSON objects; an empty object must stay `{}`, not become `[]`.
70
78
 
71
- **Fingerprint.** `fp1:` and SHA-256 of the compiled music: tempo, and for each sounding part its instrument, effective tone controls including defaults, sample treatment and sorted note events rounded to a millionth. It ignores metadata, ids, names, colors, sections, seed, score length, part order, part volume and pan, master volume and reverb, artwork and the mix. Parts at zero volume or without notes are left out. It also ignores values the instrument never reads: drum and sample pitch, tom pitch beyond its 35–60 range, duration on struck and plucked sounds, and sample settings an effect does not use. A score written in version 2 notation shares its fingerprint with the same notes in version 1. Fingerprints identify exact musical copies only; any changed note produces a different fingerprint. The `fp1` prefix changes if the definition ever does.
79
+ **Fingerprint.** `fp1:` and SHA-256 of the compiled music: tempo and tempo changes, and for each sounding part its sustain pedal spans, its instrument, effective tone controls including defaults, sample treatment and sorted note events rounded to a millionth. It ignores metadata, ids, names, colors, sections, seed, score length, part order, part volume and pan, master volume and reverb, artwork and the mix. Parts at zero volume or without notes are left out. It also ignores values the instrument never reads: drum and sample pitch, tom pitch beyond its 35–60 range, duration on struck and plucked sounds, and sample settings an effect does not use. A score written in version 2 notation shares its fingerprint with the same notes in version 1. Fingerprints identify exact musical copies only; any changed note produces a different fingerprint. The `fp1` prefix changes if the definition ever does.
80
+
81
+ ## Recorded instruments
82
+
83
+ The piano, strings, brass, guitars, electric bass and acoustic drum kit play full recordings from seven sample packs, about 4 GB together (`assets/samples/SOURCES.md`). A pack is one file of WAV recordings; `assets/samples/samples.json` maps notes to recordings, gives each recording's place in its pack and the pack's size, SHA-256 and download address (a release of the toolkit repository on GitHub). `prepareSamples(score)` downloads the packs a score needs into `samplesDir`, resumes interrupted downloads and keeps a pack only when its size and SHA-256 match; `SOUNDROO_SAMPLES_URL` points it at a mirror with the same file names, and `SOUNDROO_OFFLINE=1` stops it from downloading. A render reads each recording from its pack while the note plays, so memory stays small.
72
84
 
73
85
  ## Speech recipes
74
86
 
@@ -82,7 +94,8 @@ A server can list `speechRecipes(score)` to check the words, call `prepareSpeech
82
94
 
83
95
  | Limit | Value |
84
96
  | --- | --- |
85
- | Score length | 600 seconds |
97
+ | Score length | 600 seconds, counted with tempo changes |
98
+ | Tempo changes / pedal spans per part | 1,024 / 4,096 |
86
99
  | Parts | 64 |
87
100
  | Expanded note events | 100,000, and the same for source notes including pattern definitions |
88
101
  | Patterns per part / clips per part | 128 / 4,096 |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "soundroo",
3
- "version": "0.7.0",
3
+ "version": "0.8.0",
4
4
  "description": "Original music made with your coding agent. A local composition toolkit and listening studio.",
5
5
  "homepage": "https://www.soundroo.com",
6
6
  "type": "module",
@@ -3,6 +3,7 @@
3
3
  // that all sound the same, a silent ending). They are hints, not errors: a
4
4
  // slow intro or a steady loop is fine when the person asked for it.
5
5
  import { getCatalog } from './catalog.js';
6
+ import { makeTimeline } from './timeline.js';
6
7
 
7
8
  const DRUMS = new Set(getCatalog().instruments.filter(preset => preset.drums).map(preset => preset.id));
8
9
  const BASSES = new Set(['bass', 'acid-bass', 'electric-bass', 'chip-bass']);
@@ -53,7 +54,7 @@ function silentEnd(score) {
53
54
  const notes = score.parts.flatMap(part => part.notes);
54
55
  if (!notes.length) return null;
55
56
  const end = Math.max(...notes.map(note => note.beat + note.duration));
56
- const silence = (score.beats - end) * 60 / score.bpm;
57
+ const timeline = makeTimeline(score), silence = timeline.duration - timeline.seconds(end);
57
58
  if (silence < SILENT_END_SECONDS) return null;
58
59
  return { code: 'silent_end', message: `The last ${Math.round(silence)} seconds are silent. Set beats to where the music ends, plus a short tail.` };
59
60
  }
@@ -0,0 +1,121 @@
1
+ // The master reverb: the reverb send convolved with the stereo impulse
2
+ // response of a concert hall (assets/reverb/hall.wav, generated by
3
+ // scripts/reverb/hall.py). Renders are offline, so the whole send is
4
+ // convolved at once with uniformly partitioned FFT convolution.
5
+ import { readFileSync } from 'node:fs';
6
+ import { parseWav, resample } from './pcm.js';
7
+
8
+ const HALL = new URL('../../assets/reverb/hall.wav', import.meta.url);
9
+ const BLOCK = 16384, SIZE = BLOCK * 2;
10
+
11
+ // --- radix-2 complex FFT, in place ------------------------------------------------------------
12
+
13
+ const tables = new Map();
14
+ function table(n) {
15
+ if (!tables.has(n)) {
16
+ const bits = Math.log2(n), reverse = new Uint32Array(n), cos = new Float64Array(n / 2), sin = new Float64Array(n / 2);
17
+ for (let i = 0; i < n; i++) {
18
+ let r = 0;
19
+ for (let b = 0; b < bits; b++) r = (r << 1) | ((i >>> b) & 1);
20
+ reverse[i] = r;
21
+ }
22
+ for (let i = 0; i < n / 2; i++) { cos[i] = Math.cos(2 * Math.PI * i / n); sin[i] = Math.sin(2 * Math.PI * i / n); }
23
+ tables.set(n, { reverse, cos, sin });
24
+ }
25
+ return tables.get(n);
26
+ }
27
+
28
+ /** In-place FFT of (re, im); inverse = true computes the unscaled inverse. */
29
+ export function fft(re, im, inverse = false) {
30
+ const n = re.length, { reverse, cos, sin } = table(n), sign = inverse ? 1 : -1;
31
+ for (let i = 0; i < n; i++) {
32
+ const j = reverse[i];
33
+ if (j > i) {
34
+ let t = re[i]; re[i] = re[j]; re[j] = t;
35
+ t = im[i]; im[i] = im[j]; im[j] = t;
36
+ }
37
+ }
38
+ for (let size = 2; size <= n; size <<= 1) {
39
+ const half = size >> 1, step = n / size;
40
+ for (let start = 0; start < n; start += size) {
41
+ for (let k = 0, w = 0; k < half; k++, w += step) {
42
+ const a = start + k, b = a + half;
43
+ const wr = cos[w], wi = sign * sin[w];
44
+ const xr = re[b] * wr - im[b] * wi, xi = re[b] * wi + im[b] * wr;
45
+ re[b] = re[a] - xr; im[b] = im[a] - xi;
46
+ re[a] += xr; im[a] += xi;
47
+ }
48
+ }
49
+ }
50
+ }
51
+
52
+ // --- the hall ---------------------------------------------------------------------------------
53
+
54
+ const halls = new Map();
55
+ // The impulse response at a render's sample rate, split into blocks and
56
+ // transformed once: [{re, im}] per block, left channel in the real part of
57
+ // the inverse and right in the imaginary part (see convolveHall).
58
+ function hall(sampleRate) {
59
+ if (!halls.has(sampleRate)) {
60
+ const bytes = readFileSync(HALL);
61
+ const wav = parseWav(bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));
62
+ const [left, right] = wav.channels.map(channel => wav.sampleRate === sampleRate ? channel : resample(channel, wav.sampleRate, sampleRate));
63
+ const parts = Math.ceil(left.length / BLOCK), spectra = [];
64
+ for (let p = 0; p < parts; p++) {
65
+ // H = HL + i·HR: the transforms of two real responses in one complex one.
66
+ const re = new Float64Array(SIZE), im = new Float64Array(SIZE);
67
+ for (let i = 0; i < BLOCK && p * BLOCK + i < left.length; i++) { re[i] = left[p * BLOCK + i]; im[i] = right[p * BLOCK + i]; }
68
+ fft(re, im);
69
+ spectra.push({ re, im });
70
+ }
71
+ halls.set(sampleRate, spectra);
72
+ }
73
+ return halls.get(sampleRate);
74
+ }
75
+
76
+ /** Adds the hall's response to the mono `send` (times `gain`) into the stereo
77
+ * channels. The tail stops at the end of the channels. */
78
+ export function convolveHall(send, channels, sampleRate, gain) {
79
+ if (!(gain > 0)) return;
80
+ const spectra = hall(sampleRate), parts = spectra.length, n = send.length;
81
+ // Transforms of the latest input blocks, newest first.
82
+ const history = [];
83
+ const outRe = new Float64Array(SIZE), outIm = new Float64Array(SIZE);
84
+ const carryL = new Float64Array(BLOCK), carryR = new Float64Array(BLOCK);
85
+ const [left, right] = channels;
86
+ const scale = gain / SIZE;
87
+ for (let start = 0; start < n + parts * BLOCK; start += BLOCK) {
88
+ if (start >= n && history.every(h => h === null)) break;
89
+ let input = null;
90
+ if (start < n) {
91
+ const re = new Float64Array(SIZE), im = new Float64Array(SIZE);
92
+ let any = false;
93
+ for (let i = 0; i < BLOCK && start + i < n; i++) { const v = send[start + i]; re[i] = v; if (v !== 0) any = true; }
94
+ if (any) { fft(re, im); input = { re, im }; }
95
+ }
96
+ history.unshift(input);
97
+ if (history.length > parts) history.pop();
98
+ // Y = Σ X_k · H_k. X is the transform of a real block, so each product
99
+ // keeps HL and HR apart: the inverse gives left in re and right in im.
100
+ outRe.fill(0); outIm.fill(0);
101
+ let any = false;
102
+ for (let k = 0; k < history.length; k++) {
103
+ const x = history[k];
104
+ if (!x) continue;
105
+ any = true;
106
+ const h = spectra[k], xr = x.re, xi = x.im, hr = h.re, hi = h.im;
107
+ for (let i = 0; i < SIZE; i++) {
108
+ outRe[i] += xr[i] * hr[i] - xi[i] * hi[i];
109
+ outIm[i] += xr[i] * hi[i] + xi[i] * hr[i];
110
+ }
111
+ }
112
+ if (any) fft(outRe, outIm, true);
113
+ for (let i = 0; i < BLOCK; i++) {
114
+ const frame = start + i;
115
+ const l = (any ? outRe[i] * scale : 0) + carryL[i], r = (any ? outIm[i] * scale : 0) + carryR[i];
116
+ if (frame < left.length) { left[frame] += l; right[frame] += r; }
117
+ carryL[i] = any ? outRe[BLOCK + i] * scale : 0;
118
+ carryR[i] = any ? outIm[BLOCK + i] * scale : 0;
119
+ }
120
+ }
121
+ }
@@ -0,0 +1,194 @@
1
+ // Recorded instruments come from sample packs: one file per instrument with
2
+ // its recordings as ordinary WAVs one after another (assets/samples/SOURCES.md).
3
+ // assets/samples/samples.json maps notes to recordings and records where each
4
+ // recording's audio starts in its pack, with the pack's size and SHA-256.
5
+ //
6
+ // The packs are large (the piano alone is about 2 GB), so they are not part of
7
+ // the repository. prepareSamples (samples-install.js) downloads the packs a
8
+ // score needs into a samples folder once and checks them; renders read the
9
+ // recordings from there while they play, so a render holds only the stretch of
10
+ // each note it is playing in memory.
11
+ import fs from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
14
+
15
+ const MANIFEST = new URL('../../assets/samples/samples.json', import.meta.url);
16
+ let manifest;
17
+
18
+ export function sampleManifest() {
19
+ manifest ??= JSON.parse(fs.readFileSync(MANIFEST, 'utf8'));
20
+ return manifest;
21
+ }
22
+
23
+ /** Where packs are kept unless a render names a folder: SOUNDROO_SAMPLES_DIR,
24
+ * then the user's cache folder. */
25
+ export function defaultSamplesDir(env = process.env) {
26
+ if (env.SOUNDROO_SAMPLES_DIR) return path.resolve(env.SOUNDROO_SAMPLES_DIR);
27
+ const cache = process.platform === 'win32' ? (env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'))
28
+ : process.platform === 'darwin' ? path.join(os.homedir(), 'Library', 'Caches')
29
+ : (env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache'));
30
+ return path.join(cache, 'soundroo', 'samples');
31
+ }
32
+
33
+ /** The file name of a pack: its name and the start of its SHA-256, so packs of
34
+ * different engine versions sit side by side. */
35
+ export function packFileName(name) {
36
+ const pack = sampleManifest().packs[name];
37
+ if (!pack) throw new Error(`Unknown sample pack ${name}.`);
38
+ return `${name}-${pack.sha256.slice(0, 16)}.pack`;
39
+ }
40
+
41
+ /** The packs an instrument plays from. */
42
+ export function instrumentPacks(instrument) {
43
+ const spec = sampleManifest().instruments[instrument];
44
+ return spec ? [spec.pack] : [];
45
+ }
46
+
47
+ export class MissingSamplesError extends Error {
48
+ constructor(packs, dir) {
49
+ super(`The recordings for ${packs.join(', ')} are not installed in ${dir}. Run "node bin/soundroo.js samples --all" once to download them, or render with --sound synthesized.`);
50
+ this.name = 'MissingSamplesError';
51
+ this.code = 'samples_missing';
52
+ this.packs = packs;
53
+ }
54
+ }
55
+
56
+ // Short recordings (drum hits, release noises) are read whole once and kept;
57
+ // longer ones are read in windows while they play.
58
+ const WHOLE_FRAMES = 96000;
59
+ const WINDOW_FRAMES = 16384;
60
+ const kept = new Map();
61
+ let keptValues = 0;
62
+ const KEPT_LIMIT = 32_000_000;
63
+
64
+ // PCM bytes into per-channel Float32Arrays, written at `at` in `out` (new arrays when out is omitted).
65
+ function decode(buffer, frames, channels, bits, out = Array.from({ length: channels }, () => new Float32Array(frames)), at = 0) {
66
+ if (bits === 24) {
67
+ for (let c = 0; c < channels; c++) {
68
+ const target = out[c];
69
+ for (let i = 0, p = c * 3; i < frames; i++, p += channels * 3) target[at + i] = (((buffer[p] | (buffer[p + 1] << 8) | (buffer[p + 2] << 16)) << 8) >> 8) * (1 / 8388608);
70
+ }
71
+ } else if (bits === 16) {
72
+ for (let c = 0; c < channels; c++) {
73
+ const target = out[c];
74
+ for (let i = 0, p = c * 2; i < frames; i++, p += channels * 2) target[at + i] = ((buffer[p] | (buffer[p + 1] << 8)) << 16 >> 16) * (1 / 32768);
75
+ }
76
+ } else throw new Error(`Unsupported sample depth ${bits}.`);
77
+ return out;
78
+ }
79
+
80
+ /** The recordings of one samples folder. Open packs stay open for the render. */
81
+ export class SampleLibrary {
82
+ constructor(dir = defaultSamplesDir()) {
83
+ this.dir = dir;
84
+ this.files = new Map();
85
+ }
86
+
87
+ instrument(id) {
88
+ const spec = sampleManifest().instruments[id];
89
+ if (!spec) throw new Error(`No recorded samples for ${id}.`);
90
+ return spec;
91
+ }
92
+
93
+ missing(packs) {
94
+ return [...new Set(packs)].sort().filter(name => {
95
+ const file = path.join(this.dir, packFileName(name));
96
+ try { return fs.statSync(file).size !== sampleManifest().packs[name].size; } catch { return true; }
97
+ });
98
+ }
99
+
100
+ fd(pack) {
101
+ if (!this.files.has(pack)) {
102
+ const file = path.join(this.dir, packFileName(pack));
103
+ const missing = this.missing([pack]);
104
+ if (missing.length) throw new MissingSamplesError(missing, this.dir);
105
+ this.files.set(pack, fs.openSync(file, 'r'));
106
+ }
107
+ return this.files.get(pack);
108
+ }
109
+
110
+ /** A playable recording: {frames, channels, rate, read(start, count)}. read
111
+ * returns per-channel Float32Arrays for frames [start, start + count). */
112
+ recording(packName, name) {
113
+ const info = sampleManifest().packs[packName].samples[name];
114
+ if (!info) throw new Error(`The ${packName} pack has no recording ${name}.`);
115
+ const fd = this.fd(packName), width = info.bits / 8 * info.channels;
116
+ const read = (start, count, out, at) => {
117
+ const buffer = Buffer.allocUnsafe(count * width);
118
+ const got = fs.readSync(fd, buffer, 0, buffer.length, info.offset + start * width);
119
+ if (got !== buffer.length) throw new Error(`The ${packName} pack is shorter than expected; install it again.`);
120
+ return decode(buffer, count, info.channels, info.bits, out, at);
121
+ };
122
+ // Keyed by the pack's content, so recordings kept in memory always belong to this pack.
123
+ return { ...info, key: `${packFileName(packName)}/${name}`, read };
124
+ }
125
+
126
+ close() {
127
+ for (const fd of this.files.values()) fs.closeSync(fd);
128
+ this.files.clear();
129
+ }
130
+ }
131
+
132
+ // Interpolation reads up to half its longest kernel (64 frames) on either side
133
+ // of the playback position; outside the recording they are silence.
134
+ const PAD = 64;
135
+
136
+ // Frames [from, from + count) of a recording, silent outside it.
137
+ function framesAround(recording, from, count) {
138
+ const start = Math.max(0, from), stop = Math.min(recording.frames, from + count);
139
+ const out = Array.from({ length: recording.channels }, () => new Float32Array(count));
140
+ if (stop > start) recording.read(start, stop - start, out, start - from);
141
+ return out;
142
+ }
143
+
144
+ /** Frames of a recording as a voice plays it. Nothing is read until the voice
145
+ * starts (ensure), and release() lets go of it when the voice ends. Short
146
+ * recordings and looped ones are read whole once (a looped note never plays
147
+ * past its loop, so only that far) and shared; long ones are read through a
148
+ * window that moves forward with the playback position. data[channel][frame -
149
+ * base] holds the frames; reads may reach PAD frames outside the recording. */
150
+ export class SampleStream {
151
+ constructor(recording) {
152
+ this.recording = recording;
153
+ this.frames = recording.frames;
154
+ this.channels = recording.channels;
155
+ this.base = 0;
156
+ this.data = null;
157
+ this.whole = recording.frames <= WHOLE_FRAMES || !!recording.loop;
158
+ }
159
+
160
+ /** Makes frames [from, to) available in this.data (offset by this.base). */
161
+ ensure(from, to) {
162
+ if (this.whole) {
163
+ if (!this.data) {
164
+ const length = this.recording.loop ? Math.min(this.frames, this.recording.loop[1] + PAD) : this.frames;
165
+ const key = `${this.recording.key}:${length}`;
166
+ let whole = kept.get(key);
167
+ if (whole) {
168
+ // Most recently used last, so the oldest goes first when the cache is full.
169
+ kept.delete(key);
170
+ } else {
171
+ whole = framesAround(this.recording, -PAD, length + 2 * PAD);
172
+ keptValues += length * this.channels;
173
+ }
174
+ kept.set(key, whole);
175
+ for (const [oldKey, oldData] of kept) {
176
+ if (keptValues <= KEPT_LIMIT || oldKey === key) break;
177
+ kept.delete(oldKey);
178
+ keptValues -= (oldData[0].length - 2 * PAD) * oldData.length;
179
+ }
180
+ this.data = whole;
181
+ this.base = -PAD;
182
+ }
183
+ return;
184
+ }
185
+ if (this.data && from >= this.base && to <= this.base + this.data[0].length) return;
186
+ const count = Math.max(WINDOW_FRAMES, to - from);
187
+ this.base = from;
188
+ this.data = framesAround(this.recording, from, count);
189
+ }
190
+
191
+ release() {
192
+ this.data = null;
193
+ }
194
+ }