@dsebastien/music-notation 0.19.2 → 0.21.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.
package/dist/index.js CHANGED
@@ -5426,9 +5426,11 @@ var ICONS = {
5426
5426
  loop: "M3 8a5 5 0 0 1 8.5-3.5L13 6V2.5M13 8a5 5 0 0 1-8.5 3.5L3 10v3.5",
5427
5427
  count: "M5.5 14h5L9 2.5H7zM8 11.5l4.5-7",
5428
5428
  click: "M3 5v6M8 5v6M13 5v6",
5429
- copy: "M2.5 3.5h11v9h-11zM2.5 11l3.5-3.5 3 3 2-2 2.5 2.5M10.5 6.5h.01"
5429
+ copy: "M2.5 3.5h11v9h-11zM2.5 11l3.5-3.5 3 3 2-2 2.5 2.5M10.5 6.5h.01",
5430
+ full: "M2.5 6V2.5H6M10 2.5h3.5V6M13.5 10v3.5H10M6 13.5H2.5V10",
5431
+ exit: "M6 2.5V6H2.5M13.5 6H10V2.5M10 13.5V10h3.5M2.5 10H6v3.5"
5430
5432
  };
5431
- var STROKED = new Set(["loop", "count", "click", "copy"]);
5433
+ var STROKED = new Set(["loop", "count", "click", "copy", "full", "exit"]);
5432
5434
  function icon(doc, name) {
5433
5435
  const root = svg(doc, "svg", {
5434
5436
  class: `mn-play-icon mn-play-icon-${name}${STROKED.has(name) ? " mn-play-icon-line" : ""}`,
@@ -6133,6 +6135,242 @@ async function toPng(el, options = {}) {
6133
6135
  return new Promise((resolve, reject) => canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error("The image could not be made")), "image/png"));
6134
6136
  }
6135
6137
 
6138
+ // src/playback/full-screen.ts
6139
+ var SCROLL_KEYS = new Set(["PageUp", "PageDown", "Home", "End", "ArrowUp", "ArrowDown"]);
6140
+ function backgroundBehind(el) {
6141
+ const win = el.ownerDocument.defaultView;
6142
+ if (!win)
6143
+ return "";
6144
+ for (let node = el.parentElement;node; node = node.parentElement) {
6145
+ const color = win.getComputedStyle(node).backgroundColor;
6146
+ if (color && color !== "transparent" && !/^rgba\(.*,\s*0\)$/.test(color))
6147
+ return color;
6148
+ }
6149
+ return "";
6150
+ }
6151
+ function fullScreenControl(doc, block, surface, follow = () => {}, options = {}) {
6152
+ const redraws = options.redraws !== false;
6153
+ const win = doc.defaultView;
6154
+ const button = iconButton(doc, "mn-tab-full", "Full screen", "full");
6155
+ button.classList.add("mn-play-full");
6156
+ let on = false;
6157
+ let browser = false;
6158
+ let following = false;
6159
+ let before = null;
6160
+ let place = null;
6161
+ let held = false;
6162
+ let ownMinHeight = "";
6163
+ const setFollow = (yes) => {
6164
+ if (following === yes)
6165
+ return;
6166
+ following = yes;
6167
+ follow(yes);
6168
+ };
6169
+ const show = () => {
6170
+ block.classList.toggle("mn-fullscreen", on);
6171
+ button.classList.toggle("mn-on", on);
6172
+ button.setAttribute("aria-pressed", String(on));
6173
+ button.title = on ? "Exit full screen" : "Full screen";
6174
+ button.replaceChildren(icon(doc, on ? "exit" : "full"));
6175
+ };
6176
+ const enter = () => {
6177
+ if (on)
6178
+ return;
6179
+ on = true;
6180
+ before = {
6181
+ x: win?.scrollX ?? 0,
6182
+ y: win?.scrollY ?? 0,
6183
+ background: block.style.backgroundColor
6184
+ };
6185
+ if (!held)
6186
+ ownMinHeight = block.style.minHeight;
6187
+ held = false;
6188
+ place = doc.createElement("div");
6189
+ place.className = "mn-fullscreen-place";
6190
+ place.style.height = `${block.offsetHeight}px`;
6191
+ const margins = win?.getComputedStyle(block);
6192
+ if (margins) {
6193
+ place.style.marginTop = margins.marginTop;
6194
+ place.style.marginBottom = margins.marginBottom;
6195
+ }
6196
+ block.before(place);
6197
+ const background = backgroundBehind(block);
6198
+ if (background)
6199
+ block.style.backgroundColor = background;
6200
+ show();
6201
+ surface.tabIndex = 0;
6202
+ surface.focus({ preventScroll: true });
6203
+ setFollow(true);
6204
+ options.changed?.(true);
6205
+ try {
6206
+ block.requestFullscreen?.().catch(() => {});
6207
+ } catch {}
6208
+ };
6209
+ const leave = (focus = true) => {
6210
+ if (!on)
6211
+ return;
6212
+ on = false;
6213
+ setFollow(false);
6214
+ show();
6215
+ block.style.backgroundColor = before?.background ?? "";
6216
+ if (place) {
6217
+ if (redraws) {
6218
+ block.style.minHeight = place.style.height;
6219
+ held = true;
6220
+ }
6221
+ place.remove();
6222
+ place = null;
6223
+ }
6224
+ surface.removeAttribute("tabindex");
6225
+ surface.scrollTop = 0;
6226
+ if (browser && doc.fullscreenElement === block)
6227
+ doc.exitFullscreen?.().catch(() => {});
6228
+ browser = false;
6229
+ if (before && win)
6230
+ win.scrollTo(before.x, before.y);
6231
+ before = null;
6232
+ options.changed?.(false);
6233
+ if (focus)
6234
+ button.focus({ preventScroll: true });
6235
+ };
6236
+ button.addEventListener("click", () => on ? leave() : enter());
6237
+ block.addEventListener("keydown", (event) => {
6238
+ if (!on || event.key !== "Escape")
6239
+ return;
6240
+ event.stopPropagation();
6241
+ event.preventDefault();
6242
+ leave();
6243
+ });
6244
+ const byHand = () => {
6245
+ if (on)
6246
+ setFollow(false);
6247
+ };
6248
+ surface.addEventListener("wheel", byHand, { passive: true });
6249
+ surface.addEventListener("touchmove", byHand, { passive: true });
6250
+ surface.addEventListener("keydown", (event) => {
6251
+ if (SCROLL_KEYS.has(event.key))
6252
+ byHand();
6253
+ });
6254
+ const space = (event) => {
6255
+ if (!on || event.key !== " " || event.ctrlKey || event.metaKey || event.altKey)
6256
+ return;
6257
+ if (!block.isConnected) {
6258
+ leave(false);
6259
+ return;
6260
+ }
6261
+ const target = event.target;
6262
+ if (target?.closest("input:not([type=range]), textarea, select, [contenteditable=true]"))
6263
+ return;
6264
+ event.preventDefault();
6265
+ event.stopPropagation();
6266
+ if (event.type !== "keydown" || event.repeat)
6267
+ return;
6268
+ block.querySelector(".mn-play .mn-play-toggle")?.click();
6269
+ };
6270
+ doc.addEventListener("keydown", space, true);
6271
+ doc.addEventListener("keyup", space, true);
6272
+ const changed = () => {
6273
+ if (doc.fullscreenElement === block)
6274
+ browser = true;
6275
+ else if (browser)
6276
+ leave();
6277
+ };
6278
+ doc.addEventListener("fullscreenchange", changed);
6279
+ show();
6280
+ return {
6281
+ button,
6282
+ active: () => on,
6283
+ playing: () => {
6284
+ if (on)
6285
+ setFollow(true);
6286
+ },
6287
+ drawn: () => {
6288
+ if (on || !held)
6289
+ return;
6290
+ held = false;
6291
+ block.style.minHeight = ownMinHeight;
6292
+ },
6293
+ destroy: () => {
6294
+ leave(false);
6295
+ doc.removeEventListener("fullscreenchange", changed);
6296
+ doc.removeEventListener("keydown", space, true);
6297
+ doc.removeEventListener("keyup", space, true);
6298
+ }
6299
+ };
6300
+ }
6301
+ var ZOOMS = [4, 3.5, 3, 2.5, 2.25, 2, 1.75, 1.5, 1.25, 1];
6302
+ var TALL_ZOOM = 1.5;
6303
+ function chooseZoom(fits) {
6304
+ const wide = [];
6305
+ for (const zoom of ZOOMS) {
6306
+ const fit = fits(zoom);
6307
+ if (fit.width && fit.height)
6308
+ return zoom;
6309
+ if (fit.width)
6310
+ wide.push(zoom);
6311
+ }
6312
+ return wide.find((zoom) => zoom <= TALL_ZOOM) ?? 1;
6313
+ }
6314
+ function blockFullScreen(doc, block) {
6315
+ const win = doc.defaultView;
6316
+ let frame = 0;
6317
+ const fit = () => {
6318
+ frame = 0;
6319
+ if (!block.classList.contains("mn-fullscreen"))
6320
+ return;
6321
+ const zoom = chooseZoom((z) => {
6322
+ block.style.setProperty("--mn-zoom", String(z));
6323
+ return {
6324
+ width: block.scrollWidth <= block.clientWidth + 1,
6325
+ height: block.scrollHeight <= block.clientHeight + 1
6326
+ };
6327
+ });
6328
+ block.style.setProperty("--mn-zoom", String(zoom));
6329
+ for (const bar of nested())
6330
+ bar.style.setProperty("zoom", String(1 / zoom));
6331
+ };
6332
+ const nested = () => [
6333
+ ...block.querySelectorAll(":scope > :not(.mn-play) .mn-play")
6334
+ ];
6335
+ const later = () => {
6336
+ if (!win || frame)
6337
+ return;
6338
+ frame = win.requestAnimationFrame(fit);
6339
+ };
6340
+ const control = fullScreenControl(doc, block, block, undefined, {
6341
+ redraws: false,
6342
+ changed: (on) => {
6343
+ block.classList.toggle("mn-fullscreen-fit", on);
6344
+ if (on) {
6345
+ fit();
6346
+ later();
6347
+ win?.addEventListener("resize", later);
6348
+ } else {
6349
+ win?.removeEventListener("resize", later);
6350
+ block.style.removeProperty("--mn-zoom");
6351
+ for (const bar of nested())
6352
+ bar.style.removeProperty("zoom");
6353
+ }
6354
+ }
6355
+ });
6356
+ return {
6357
+ ...control,
6358
+ destroy: () => {
6359
+ control.destroy();
6360
+ win?.removeEventListener("resize", later);
6361
+ if (frame)
6362
+ win?.cancelAnimationFrame(frame);
6363
+ }
6364
+ };
6365
+ }
6366
+ function addFullScreen(doc, bar, block, on = true) {
6367
+ if (!on || !block || block.querySelector(".mn-play-full"))
6368
+ return () => {};
6369
+ const full = blockFullScreen(doc, block);
6370
+ bar.appendChild(full.button);
6371
+ return () => full.destroy();
6372
+ }
6373
+
6136
6374
  // src/playback/copy-image.ts
6137
6375
  var COPY_SAID = {
6138
6376
  copied: "Copied",
@@ -6190,13 +6428,16 @@ function copyImageButton(doc, win, target, make = (el) => toPng(el)) {
6190
6428
  return [button, said];
6191
6429
  }
6192
6430
  var NOT_DRAWN_HERE = ".mn-tab, .mn-tab-holder, .mn-tab-surface, .mn-exercise-tab";
6193
- function attachCopy(el, make) {
6431
+ function attachCopy(el, make, options = {}) {
6194
6432
  const doc = el.ownerDocument;
6195
6433
  const win = doc.defaultView;
6196
6434
  if (!win)
6197
6435
  return () => {};
6198
6436
  const blocks = el.classList.contains("mn-block") ? [el] : [...el.querySelectorAll(".mn-block")];
6199
6437
  const bars = [];
6438
+ const frees = [];
6439
+ if (options.copy === false && options.fullScreen === false)
6440
+ return () => {};
6200
6441
  for (const block of blocks) {
6201
6442
  if (block.querySelector(".mn-play"))
6202
6443
  continue;
@@ -6205,7 +6446,9 @@ function attachCopy(el, make) {
6205
6446
  if (!drawings.length && !timed)
6206
6447
  continue;
6207
6448
  const bar = playBar(doc, "mn-copy-bar", "Image");
6208
- bar.append(...copyImageButton(doc, win, () => block, make));
6449
+ if (options.copy !== false)
6450
+ bar.append(...copyImageButton(doc, win, () => block, make));
6451
+ frees.push(addFullScreen(doc, bar, block, options.fullScreen));
6209
6452
  if (timed)
6210
6453
  block.appendChild(bar);
6211
6454
  else
@@ -6213,6 +6456,8 @@ function attachCopy(el, make) {
6213
6456
  bars.push(bar);
6214
6457
  }
6215
6458
  return () => {
6459
+ for (const free of frees)
6460
+ free();
6216
6461
  for (const bar of bars)
6217
6462
  bar.remove();
6218
6463
  };
@@ -6369,6 +6614,7 @@ function timedBarFor(doc, win, drawing, options, piece) {
6369
6614
  bar.appendChild(choice(doc, "mn-play-sound", "Sound", ["guitar", "piano"], settings.sound, { guitar: "Guitar", piano: "Piano" }, (value) => settings.sound = value === "piano" ? "piano" : "guitar"));
6370
6615
  if (options.copy !== false)
6371
6616
  bar.append(...copyImageButton(doc, win, () => wrap.closest(".mn-block") ?? wrap));
6617
+ const freeFull = addFullScreen(doc, bar, wrap.closest(".mn-block"), options.fullScreen);
6372
6618
  const app = handToApp(options, bar, {
6373
6619
  kind: piece.kind,
6374
6620
  drawing,
@@ -6377,6 +6623,7 @@ function timedBarFor(doc, win, drawing, options, piece) {
6377
6623
  });
6378
6624
  return () => {
6379
6625
  stop();
6626
+ freeFull();
6380
6627
  app.free();
6381
6628
  };
6382
6629
  }
@@ -6527,6 +6774,7 @@ function progressionBarFor(doc, win, drawing, options, diagrams = null) {
6527
6774
  }));
6528
6775
  if (options.copy !== false)
6529
6776
  bar.append(...copyImageButton(doc, win, () => drawing.closest(".mn-block") ?? drawing));
6777
+ const freeFull = addFullScreen(doc, bar, drawing.closest(".mn-block"), options.fullScreen);
6530
6778
  const app = handToApp(options, bar, {
6531
6779
  kind: drawing.classList.contains("mn-chart") ? "chart" : "progression",
6532
6780
  drawing,
@@ -6535,6 +6783,7 @@ function progressionBarFor(doc, win, drawing, options, diagrams = null) {
6535
6783
  });
6536
6784
  return () => {
6537
6785
  stop();
6786
+ freeFull();
6538
6787
  if (diagrams?.onPlay === stop) {
6539
6788
  diagrams.onPlay = null;
6540
6789
  diagrams.stopOthers = null;
@@ -7430,6 +7679,7 @@ function blockBarFor(doc, win, block, diagrams, options) {
7430
7679
  bar.appendChild(sound);
7431
7680
  if (options.copy !== false)
7432
7681
  bar.append(...copyImageButton(doc, win, (whole) => whole || !several ? block : diagramImage(made.selected.wrap)));
7682
+ const freeFull = addFullScreen(doc, bar, block, options.fullScreen);
7433
7683
  bind({
7434
7684
  changed() {
7435
7685
  const busy = made.busy;
@@ -7450,7 +7700,10 @@ function blockBarFor(doc, win, block, diagrams, options) {
7450
7700
  sound.value = made.sound;
7451
7701
  }
7452
7702
  });
7453
- return () => group.destroy();
7703
+ return () => {
7704
+ freeFull();
7705
+ group.destroy();
7706
+ };
7454
7707
  }
7455
7708
 
7456
7709
  // src/playback/controls.ts
@@ -12490,11 +12743,13 @@ function renderBlock(language, source, host, given = {}) {
12490
12743
  }
12491
12744
  const picks = options.pick ? [...el.querySelectorAll("svg[data-mn-pick]")].map((svg) => attachPick(svg, pickOptions(options))) : [];
12492
12745
  const copy = options.copy !== false;
12746
+ const fullScreen = options.fullScreen !== false;
12493
12747
  const stopPlayback = options.play ? attachPlayback(el, {
12494
12748
  hand: options.hand,
12495
12749
  ...typeof options.play === "object" ? options.play : {},
12496
- copy
12497
- }) : copy ? attachCopy(el) : null;
12750
+ copy,
12751
+ fullScreen
12752
+ }) : copy || fullScreen ? attachCopy(el, undefined, { copy, fullScreen }) : null;
12498
12753
  return {
12499
12754
  ok: error === null,
12500
12755
  el,
@@ -13539,7 +13794,7 @@ var styles_default = `/* Music notation. Colors follow Obsidian's theme variable
13539
13794
  .mn-play input[type='range'] {
13540
13795
  all: unset;
13541
13796
  appearance: none;
13542
- width: 44px;
13797
+ width: 36px;
13543
13798
  /* As tall as the thumb, so no host or browser has to center it: the visible 3px track is a
13544
13799
  centered line drawn by the background. */
13545
13800
  height: 9px;
@@ -14461,6 +14716,90 @@ var styles_default = `/* Music notation. Colors follow Obsidian's theme variable
14461
14716
  align-items: center;
14462
14717
  gap: 2px 6px;
14463
14718
  }
14719
+
14720
+ /* Full screen for a tab or a score (#113): the block fills the screen (the browser's full screen,
14721
+ or the window when the browser refuses it), the score in a scroll area of its own at the
14722
+ screen's width, the bar at the bottom. The background is the page's, set by the control. */
14723
+ .mn-tab.mn-fullscreen {
14724
+ position: fixed;
14725
+ inset: 0;
14726
+ z-index: 9999;
14727
+ display: flex;
14728
+ flex-direction: column;
14729
+ box-sizing: border-box;
14730
+ width: auto;
14731
+ max-width: none;
14732
+ height: auto;
14733
+ margin: 0;
14734
+ /* Room on the sides, more on a wide screen. */
14735
+ padding: 12px max(24px, 3vw) 8px;
14736
+ overflow: hidden;
14737
+ background: Canvas;
14738
+ }
14739
+
14740
+ .mn-tab.mn-fullscreen .mn-tab-surface {
14741
+ flex: 1 1 auto;
14742
+ min-height: 0;
14743
+ overflow: auto;
14744
+ overscroll-behavior: contain;
14745
+ /* The scroll bar has its room from the start: the score is drawn once, at the width left. */
14746
+ scrollbar-gutter: stable;
14747
+ outline: none;
14748
+ }
14749
+
14750
+ .mn-tab.mn-fullscreen .mn-play.mn-play-static.mn-tab-bar {
14751
+ position: static;
14752
+ flex: none;
14753
+ margin-top: 8px;
14754
+ }
14755
+
14756
+ /* Full screen for the other blocks (#113): diagrams, charts, patterns, progressions, the circle of
14757
+ fifths. What the block holds is zoomed to the largest size that fits the screen (the control
14758
+ sets --mn-zoom), centered; a block that can't fit scrolls. The bar keeps its size, at the
14759
+ bottom. */
14760
+ .mn-block.mn-fullscreen-fit {
14761
+ position: fixed;
14762
+ inset: 0;
14763
+ z-index: 9999;
14764
+ display: flex;
14765
+ flex-direction: column;
14766
+ align-items: center;
14767
+ box-sizing: border-box;
14768
+ width: auto;
14769
+ max-width: none;
14770
+ height: auto;
14771
+ margin: 0;
14772
+ padding: 16px max(32px, 4vw) 0;
14773
+ overflow: auto;
14774
+ overscroll-behavior: contain;
14775
+ background: Canvas;
14776
+ outline: none;
14777
+ }
14778
+
14779
+ .mn-block.mn-fullscreen-fit > :not(.mn-play) {
14780
+ zoom: var(--mn-zoom, 1);
14781
+ flex: none;
14782
+ }
14783
+
14784
+ /* A row of diagrams is centered on the screen. */
14785
+ .mn-block.mn-fullscreen-fit .mn-row {
14786
+ justify-content: center;
14787
+ }
14788
+
14789
+ /* Centered while it fits; from the top when it scrolls. */
14790
+ .mn-block.mn-fullscreen-fit > :first-child {
14791
+ margin-top: auto;
14792
+ }
14793
+
14794
+ .mn-block.mn-fullscreen-fit > .mn-play {
14795
+ position: sticky;
14796
+ bottom: 0;
14797
+ flex: none;
14798
+ align-self: stretch;
14799
+ margin-top: auto;
14800
+ padding: 6px 0 8px;
14801
+ background: inherit;
14802
+ }
14464
14803
  `;
14465
14804
 
14466
14805
  // src/styles.ts
@@ -14474,6 +14813,522 @@ function injectStyles(doc) {
14474
14813
  style.textContent = STYLES;
14475
14814
  doc.head.appendChild(style);
14476
14815
  }
14816
+ // src/tab/instruments.ts
14817
+ function pageInstruments(options) {
14818
+ if (!options || typeof options !== "object" || !("play" in options))
14819
+ return;
14820
+ const play = options.play;
14821
+ if (!play || typeof play !== "object" || !("instruments" in play))
14822
+ return;
14823
+ const folder = play.instruments;
14824
+ return typeof folder === "string" && folder.trim() ? folder.trim() : undefined;
14825
+ }
14826
+ function soundsOfScore(score) {
14827
+ const programs = new Set;
14828
+ let drums = false;
14829
+ for (const track of score.tracks) {
14830
+ if (track.isPercussion)
14831
+ drums = true;
14832
+ else
14833
+ programs.add(track.playbackInfo.program);
14834
+ }
14835
+ return { programs: [...programs].sort((a, b) => a - b), drums };
14836
+ }
14837
+ function filesOf(index, sounds) {
14838
+ const files = [];
14839
+ for (const program of sounds.programs) {
14840
+ const entry = index.programs[String(program)];
14841
+ if (!entry?.file)
14842
+ return null;
14843
+ files.push(entry.file);
14844
+ }
14845
+ if (sounds.drums) {
14846
+ if (!index.drums?.file)
14847
+ return null;
14848
+ files.push(index.drums.file);
14849
+ } else if (index.click?.file && sounds.click !== false)
14850
+ files.push(index.click.file);
14851
+ return files.length ? files : null;
14852
+ }
14853
+ var soundCaches = new WeakMap;
14854
+ var isIndex = (value) => typeof value === "object" && value !== null && ("programs" in value) && typeof value.programs === "object" && value.programs !== null;
14855
+ async function instrumentSounds(source, sounds, win) {
14856
+ let perWindow = soundCaches.get(win);
14857
+ if (!perWindow)
14858
+ soundCaches.set(win, perWindow = new Map);
14859
+ let cache = perWindow.get(source);
14860
+ if (!cache)
14861
+ perWindow.set(source, cache = { index: null, files: new Map });
14862
+ const read = async (file) => {
14863
+ try {
14864
+ if (typeof source === "function")
14865
+ return await source(file);
14866
+ const response = await win.fetch(`${source.replace(/\/+$/, "")}/${file}`);
14867
+ return response.ok ? new Uint8Array(await response.arrayBuffer()) : null;
14868
+ } catch {
14869
+ return null;
14870
+ }
14871
+ };
14872
+ const fileOf = (file) => {
14873
+ let bytes = cache.files.get(file);
14874
+ if (!bytes) {
14875
+ bytes = read(file);
14876
+ cache.files.set(file, bytes);
14877
+ bytes.then((b) => {
14878
+ if (!b)
14879
+ cache.files.delete(file);
14880
+ });
14881
+ }
14882
+ return bytes;
14883
+ };
14884
+ cache.index ??= read("index.json").then((bytes) => {
14885
+ if (!bytes)
14886
+ return null;
14887
+ try {
14888
+ const value = JSON.parse(new TextDecoder().decode(bytes));
14889
+ return isIndex(value) ? value : null;
14890
+ } catch {
14891
+ return null;
14892
+ }
14893
+ });
14894
+ const index = await cache.index;
14895
+ if (!index) {
14896
+ cache.index = null;
14897
+ return null;
14898
+ }
14899
+ const files = filesOf(index, sounds);
14900
+ if (!files)
14901
+ return null;
14902
+ const all = await Promise.all(files.map(fileOf));
14903
+ return all.every((b) => b !== null) ? all : null;
14904
+ }
14905
+
14906
+ // src/playback/soundfont.ts
14907
+ var GEN = {
14908
+ filter: 8,
14909
+ filterQ: 9,
14910
+ filterAmount: 11,
14911
+ modAttack: 26,
14912
+ modHold: 27,
14913
+ modDecay: 28,
14914
+ modSustain: 29,
14915
+ attack: 34,
14916
+ hold: 35,
14917
+ decay: 36,
14918
+ sustain: 37,
14919
+ release: 38,
14920
+ instrument: 41,
14921
+ keyRange: 43,
14922
+ velRange: 44,
14923
+ attenuation: 48,
14924
+ coarse: 51,
14925
+ fine: 52,
14926
+ sample: 53,
14927
+ modes: 54,
14928
+ scale: 56,
14929
+ rootKey: 58
14930
+ };
14931
+ var DEFAULTS = {
14932
+ [GEN.filter]: 13500,
14933
+ [GEN.filterQ]: 0,
14934
+ [GEN.filterAmount]: 0,
14935
+ [GEN.modAttack]: -12000,
14936
+ [GEN.modHold]: -12000,
14937
+ [GEN.modDecay]: -12000,
14938
+ [GEN.modSustain]: 0,
14939
+ [GEN.attack]: -12000,
14940
+ [GEN.hold]: -12000,
14941
+ [GEN.decay]: -12000,
14942
+ [GEN.sustain]: 0,
14943
+ [GEN.release]: -12000,
14944
+ [GEN.attenuation]: 0,
14945
+ [GEN.coarse]: 0,
14946
+ [GEN.fine]: 0,
14947
+ [GEN.modes]: 0,
14948
+ [GEN.scale]: 100,
14949
+ [GEN.rootKey]: -1
14950
+ };
14951
+ var text2 = (bytes, start, length) => {
14952
+ let end = start;
14953
+ while (end < start + length && bytes[end] !== 0)
14954
+ end++;
14955
+ return new TextDecoder("latin1").decode(bytes.subarray(start, end));
14956
+ };
14957
+ var view = (bytes) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
14958
+ var signed = (n) => n > 32767 ? n - 65536 : n;
14959
+ var seconds = (timecents) => timecents <= -11950 ? 0 : Math.pow(2, timecents / 1200);
14960
+ function chunks(bytes) {
14961
+ const out = [];
14962
+ const v = view(bytes);
14963
+ let at = 0;
14964
+ while (at + 8 <= bytes.length) {
14965
+ const size = v.getUint32(at + 4, true);
14966
+ out.push([text2(bytes, at, 4), bytes.subarray(at + 8, at + 8 + size)]);
14967
+ at += 8 + size + size % 2;
14968
+ }
14969
+ return out;
14970
+ }
14971
+ function zones(bags, gens, from, to) {
14972
+ const b = view(bags);
14973
+ const g = view(gens);
14974
+ const out = [];
14975
+ for (let z = from;z < to; z++) {
14976
+ const zone = new Map;
14977
+ const end = b.getUint16((z + 1) * 4, true);
14978
+ for (let i = b.getUint16(z * 4, true);i < end; i++)
14979
+ zone.set(g.getUint16(i * 4, true), g.getUint16(i * 4 + 2, true));
14980
+ out.push(zone);
14981
+ }
14982
+ return out;
14983
+ }
14984
+ function readSoundfont(bytes) {
14985
+ if (text2(bytes, 0, 4) !== "RIFF" || text2(bytes, 8, 4) !== "sfbk")
14986
+ throw new Error("Not a soundfont");
14987
+ const t = {};
14988
+ let data = null;
14989
+ for (const [id, body] of chunks(bytes.subarray(12))) {
14990
+ if (id !== "LIST")
14991
+ continue;
14992
+ const kind = text2(body, 0, 4);
14993
+ for (const [sub, part] of chunks(body.subarray(4))) {
14994
+ if (kind === "sdta" && sub === "smpl")
14995
+ data = part;
14996
+ else if (kind === "pdta")
14997
+ t[sub] = part;
14998
+ }
14999
+ }
15000
+ const names = ["phdr", "pbag", "pgen", "inst", "ibag", "igen", "shdr"];
15001
+ if (!data || names.some((n) => !t[n]))
15002
+ throw new Error("Not a complete soundfont");
15003
+ const [phdr, pbag, pgen, inst, ibag, igen, shdr] = names.map((n) => t[n]);
15004
+ const sv = view(shdr);
15005
+ const samples = [];
15006
+ for (let i = 0;i < shdr.length / 46 - 1; i++) {
15007
+ const at = i * 46;
15008
+ const start = sv.getUint32(at + 20, true);
15009
+ const compressed = (sv.getUint16(at + 44, true) & 16) !== 0;
15010
+ const key = sv.getUint8(at + 40);
15011
+ samples.push({
15012
+ name: text2(shdr, at, 20),
15013
+ start,
15014
+ end: sv.getUint32(at + 24, true),
15015
+ loopStart: sv.getUint32(at + 28, true) - (compressed ? 0 : start),
15016
+ loopEnd: sv.getUint32(at + 32, true) - (compressed ? 0 : start),
15017
+ rate: sv.getUint32(at + 36, true),
15018
+ key: key > 127 ? 60 : key,
15019
+ correction: sv.getInt8(at + 41),
15020
+ compressed
15021
+ });
15022
+ }
15023
+ const pv = view(phdr);
15024
+ const iv = view(inst);
15025
+ const presets = [];
15026
+ for (let p = 0;p < phdr.length / 38 - 1; p++) {
15027
+ const regions = [];
15028
+ const presetZones = zones(pbag, pgen, pv.getUint16(p * 38 + 24, true), pv.getUint16((p + 1) * 38 + 24, true));
15029
+ const presetGlobal = presetZones[0] && !presetZones[0].has(GEN.instrument) ? presetZones[0] : null;
15030
+ for (const presetZone of presetZones) {
15031
+ const instrument = presetZone.get(GEN.instrument);
15032
+ if (instrument === undefined || instrument >= inst.length / 22 - 1)
15033
+ continue;
15034
+ const instrumentZones = zones(ibag, igen, iv.getUint16(instrument * 22 + 20, true), iv.getUint16((instrument + 1) * 22 + 20, true));
15035
+ const global = instrumentZones[0] && !instrumentZones[0].has(GEN.sample) ? instrumentZones[0] : null;
15036
+ const added = (gen) => signed(presetZone.get(gen) ?? presetGlobal?.get(gen) ?? 0);
15037
+ const range = (zone, gen) => {
15038
+ const amount = zone.get(gen);
15039
+ return amount === undefined ? [0, 127] : [amount & 255, amount >> 8];
15040
+ };
15041
+ const [pLoKey, pHiKey] = range(presetZone, GEN.keyRange);
15042
+ const [pLoVel, pHiVel] = range(presetZone, GEN.velRange);
15043
+ for (const zone of instrumentZones) {
15044
+ const sample = zone.get(GEN.sample);
15045
+ if (sample === undefined || !samples[sample])
15046
+ continue;
15047
+ const own = (gen) => signed(zone.get(gen) ?? global?.get(gen) ?? (DEFAULTS[gen] ?? 0) & 65535);
15048
+ const value = (gen) => own(gen) + added(gen);
15049
+ const keys = range(zone.has(GEN.keyRange) ? zone : global ?? zone, GEN.keyRange);
15050
+ const vels = range(zone.has(GEN.velRange) ? zone : global ?? zone, GEN.velRange);
15051
+ const loKey = Math.max(keys[0], pLoKey);
15052
+ const hiKey = Math.min(keys[1], pHiKey);
15053
+ const loVel = Math.max(vels[0], pLoVel);
15054
+ const hiVel = Math.min(vels[1], pHiVel);
15055
+ if (loKey > hiKey || loVel > hiVel)
15056
+ continue;
15057
+ const info = samples[sample];
15058
+ const root = own(GEN.rootKey);
15059
+ const cutoff = value(GEN.filter);
15060
+ const amount = value(GEN.filterAmount);
15061
+ regions.push({
15062
+ loKey,
15063
+ hiKey,
15064
+ loVel,
15065
+ hiVel,
15066
+ sample,
15067
+ rootKey: root >= 0 && root <= 127 ? root : info.key,
15068
+ tune: value(GEN.coarse) * 100 + value(GEN.fine) + info.correction,
15069
+ scale: own(GEN.scale),
15070
+ attenuation: value(GEN.attenuation) / 10,
15071
+ loop: (own(GEN.modes) & 1) === 1 && info.loopEnd > info.loopStart,
15072
+ attack: seconds(value(GEN.attack)),
15073
+ hold: seconds(value(GEN.hold)),
15074
+ decay: seconds(value(GEN.decay)),
15075
+ sustain: Math.max(0, value(GEN.sustain)) / 10,
15076
+ release: seconds(value(GEN.release)),
15077
+ filter: cutoff >= 13500 && amount <= 0 ? null : 8.176 * Math.pow(2, cutoff / 1200),
15078
+ filterQ: Math.max(0, value(GEN.filterQ)) / 10,
15079
+ filterEnvelope: {
15080
+ amount,
15081
+ attack: seconds(value(GEN.modAttack)),
15082
+ hold: seconds(value(GEN.modHold)),
15083
+ decay: seconds(value(GEN.modDecay)),
15084
+ sustain: 1 - Math.min(1000, Math.max(0, value(GEN.modSustain))) / 1000
15085
+ }
15086
+ });
15087
+ }
15088
+ }
15089
+ presets.push({
15090
+ name: text2(phdr, p * 38, 20),
15091
+ program: pv.getUint16(p * 38 + 20, true),
15092
+ bank: pv.getUint16(p * 38 + 22, true),
15093
+ regions
15094
+ });
15095
+ }
15096
+ return { presets, samples, data };
15097
+ }
15098
+ function regionsFor(preset, key, velocity) {
15099
+ return preset.regions.filter((r) => key >= r.loKey && key <= r.hiKey && velocity >= r.loVel && velocity <= r.hiVel);
15100
+ }
15101
+
15102
+ // src/playback/sampled.ts
15103
+ var PROGRAMS = { guitar: 25, piano: 0 };
15104
+ var MUTED = 28;
15105
+ var CLICK_KEY = 33;
15106
+ var LONGEST_RELEASE = 2.5;
15107
+ var SILENCE = 0.00001;
15108
+ function loopWithin(loop, duration) {
15109
+ if (!loop || !(loop.end > loop.start))
15110
+ return null;
15111
+ if (loop.end <= duration)
15112
+ return loop;
15113
+ const back = loop.end - duration;
15114
+ if (loop.start - back < 0)
15115
+ return null;
15116
+ return { start: loop.start - back, end: duration };
15117
+ }
15118
+ function sampledPlayer(win, source, fallback, options = {}) {
15119
+ const voices = new Map;
15120
+ const contextOf = () => options.context?.() ?? contextFor(win);
15121
+ const load = async (kind, ctx) => {
15122
+ const sounds = kind === "click" ? { programs: [], drums: false } : {
15123
+ programs: [kind === "muted" ? MUTED : PROGRAMS[kind]],
15124
+ drums: false,
15125
+ click: false
15126
+ };
15127
+ const files = await instrumentSounds(source, sounds, win);
15128
+ const bytes = files?.[0];
15129
+ if (!bytes)
15130
+ return null;
15131
+ try {
15132
+ const font = readSoundfont(bytes);
15133
+ const preset = font.presets[0];
15134
+ if (!preset?.regions.length)
15135
+ return null;
15136
+ const buffers = new Map;
15137
+ const loops = new Map;
15138
+ await Promise.all([...new Set(preset.regions.map((r) => r.sample))].map(async (index) => {
15139
+ const sample = font.samples[index];
15140
+ loops.set(index, {
15141
+ start: sample.loopStart / sample.rate,
15142
+ end: sample.loopEnd / sample.rate
15143
+ });
15144
+ if (sample.compressed) {
15145
+ const ogg = font.data.slice(sample.start, sample.end);
15146
+ buffers.set(index, await ctx.decodeAudioData(ogg.buffer));
15147
+ return;
15148
+ }
15149
+ const points = sample.end - sample.start;
15150
+ const buffer = ctx.createBuffer(1, Math.max(1, points), sample.rate);
15151
+ const out = buffer.getChannelData(0);
15152
+ const data = new DataView(font.data.buffer, font.data.byteOffset + sample.start * 2, points * 2);
15153
+ for (let i = 0;i < points; i++)
15154
+ out[i] = data.getInt16(i * 2, true) / 32768;
15155
+ buffers.set(index, buffer);
15156
+ }));
15157
+ return { preset, buffers, loops };
15158
+ } catch {
15159
+ return null;
15160
+ }
15161
+ };
15162
+ const voiceOf = (kind, ctx) => {
15163
+ let voice = voices.get(kind);
15164
+ if (!voice) {
15165
+ voice = load(kind, ctx);
15166
+ voices.set(kind, voice);
15167
+ voice.then((v) => {
15168
+ if (!v)
15169
+ voices.delete(kind);
15170
+ });
15171
+ }
15172
+ return voice;
15173
+ };
15174
+ const kindOf = (e, sound) => e.kind === "click" ? "click" : e.kind === "muted" && sound === "guitar" ? "muted" : sound;
15175
+ const sound = (ctx, out, voice, region, key, level, at, end) => {
15176
+ const buffer = voice.buffers.get(region.sample);
15177
+ if (!buffer)
15178
+ return null;
15179
+ const source = ctx.createBufferSource();
15180
+ source.buffer = buffer;
15181
+ source.playbackRate.value = Math.pow(2, ((key - region.rootKey) * region.scale + region.tune) / 1200);
15182
+ const loop = region.loop ? loopWithin(voice.loops.get(region.sample), buffer.duration) : null;
15183
+ if (loop) {
15184
+ source.loop = true;
15185
+ source.loopStart = loop.start;
15186
+ source.loopEnd = loop.end;
15187
+ }
15188
+ const peak = level * Math.pow(10, -region.attenuation / 20) * Math.SQRT1_2;
15189
+ const env = ctx.createGain();
15190
+ const gain = env.gain;
15191
+ const held = at + region.attack + region.hold;
15192
+ if (region.attack > 0.002) {
15193
+ gain.setValueAtTime(0, at);
15194
+ gain.linearRampToValueAtTime(peak, at + region.attack);
15195
+ } else
15196
+ gain.setValueAtTime(peak, at);
15197
+ gain.setValueAtTime(peak, held);
15198
+ const release = Math.min(Math.max(region.release, 0.02), LONGEST_RELEASE);
15199
+ const off = Math.max(end, at + 0.006);
15200
+ if (region.decay > 0 && region.sustain > 0 && off > held) {
15201
+ const floor = Math.min(region.sustain, 100);
15202
+ const reached = held + region.decay * floor / 100;
15203
+ const down = reached <= off ? floor : 100 * (off - held) / region.decay;
15204
+ gain.exponentialRampToValueAtTime(Math.max(peak * Math.pow(10, -down / 20), peak * SILENCE), Math.min(reached, off));
15205
+ }
15206
+ gain.setTargetAtTime(0, off, release / 11.5);
15207
+ let node = source;
15208
+ if (region.filter !== null) {
15209
+ const filter = ctx.createBiquadFilter();
15210
+ filter.type = "lowpass";
15211
+ filter.frequency.value = Math.min(region.filter, ctx.sampleRate / 2 - 1);
15212
+ filter.Q.value = region.filterQ;
15213
+ const { amount, attack, hold, decay, sustain: stays } = region.filterEnvelope;
15214
+ if (amount) {
15215
+ const start = at + attack;
15216
+ if (attack > 0.002) {
15217
+ filter.detune.setValueAtTime(0, at);
15218
+ filter.detune.linearRampToValueAtTime(amount, start);
15219
+ } else
15220
+ filter.detune.setValueAtTime(amount, at);
15221
+ filter.detune.setValueAtTime(amount, start + hold);
15222
+ if (decay > 0 && stays < 1)
15223
+ filter.detune.linearRampToValueAtTime(amount * stays, start + hold + decay * (1 - stays));
15224
+ }
15225
+ source.connect(filter);
15226
+ node = filter;
15227
+ }
15228
+ node.connect(env);
15229
+ env.connect(out);
15230
+ source.start(at);
15231
+ const over = off + release;
15232
+ source.stop(over);
15233
+ return { source, over };
15234
+ };
15235
+ return {
15236
+ reportsStart: true,
15237
+ play(events, { sound: instrument, volume, onEnd, onStart }) {
15238
+ const ctx = contextOf();
15239
+ if (!ctx)
15240
+ return fallback.play(events, { sound: instrument, volume, onEnd, onStart });
15241
+ let stopped = false;
15242
+ let handle = null;
15243
+ let level = Number.isFinite(volume) ? Math.min(1, Math.max(0, volume)) : 0.8;
15244
+ const resumed = "resume" in ctx ? ctx.resume() : Promise.resolve();
15245
+ const kinds = [...new Set(events.map((e) => kindOf(e, instrument)))];
15246
+ Promise.all(kinds.map((kind) => voiceOf(kind, ctx))).then((loaded) => {
15247
+ if (stopped)
15248
+ return;
15249
+ if (loaded.some((v) => !v)) {
15250
+ handle = fallback.play(events, {
15251
+ sound: instrument,
15252
+ volume: level,
15253
+ ...onEnd ? { onEnd } : {},
15254
+ ...onStart ? { onStart } : {}
15255
+ });
15256
+ if (!fallback.reportsStart)
15257
+ onStart?.();
15258
+ return;
15259
+ }
15260
+ const byKind = new Map(kinds.map((kind, i) => [kind, loaded[i]]));
15261
+ const master = ctx.createGain();
15262
+ master.gain.value = level;
15263
+ master.connect(ctx.destination);
15264
+ const start = ctx.currentTime + 0.05;
15265
+ const sources = [];
15266
+ let tail = 0;
15267
+ for (const e of events) {
15268
+ const kind = kindOf(e, instrument);
15269
+ const voice = byKind.get(kind);
15270
+ const velocity = e.velocity === undefined || !Number.isFinite(e.velocity) ? 100 : Math.round(Math.min(127, Math.max(1, e.velocity)));
15271
+ const key = kind === "click" ? CLICK_KEY : e.midi;
15272
+ const at = start + e.time;
15273
+ for (const region of regionsFor(voice.preset, key, velocity)) {
15274
+ const made = sound(ctx, master, voice, region, key, velocity / 127, at, at + e.duration);
15275
+ if (!made)
15276
+ continue;
15277
+ sources.push(made.source);
15278
+ tail = Math.max(tail, made.over - start);
15279
+ }
15280
+ }
15281
+ const finish = () => master.disconnect();
15282
+ let heard;
15283
+ const announce = () => {
15284
+ if (stopped || !onStart)
15285
+ return;
15286
+ const latency = "outputLatency" in ctx && Number.isFinite(ctx.outputLatency) ? ctx.outputLatency : 0;
15287
+ heard = win.setTimeout(() => {
15288
+ if (!stopped)
15289
+ onStart();
15290
+ }, Math.max(0, start - ctx.currentTime + latency) * 1000);
15291
+ };
15292
+ if (onStart)
15293
+ Promise.resolve(resumed).then(announce, announce);
15294
+ const timer = win.setTimeout(() => onEnd?.(), (lengthOf(events) + 0.15) * 1000);
15295
+ let cleanup = win.setTimeout(finish, (tail + 0.15) * 1000);
15296
+ handle = {
15297
+ stop() {
15298
+ win.clearTimeout(timer);
15299
+ win.clearTimeout(heard);
15300
+ win.clearTimeout(cleanup);
15301
+ const now = ctx.currentTime;
15302
+ master.gain.setTargetAtTime(0, now, 0.01);
15303
+ for (const s of sources) {
15304
+ try {
15305
+ s.stop(now + 0.05);
15306
+ } catch {}
15307
+ }
15308
+ cleanup = win.setTimeout(finish, 80);
15309
+ },
15310
+ setVolume(next) {
15311
+ master.gain.setTargetAtTime(next, ctx.currentTime, 0.015);
15312
+ }
15313
+ };
15314
+ });
15315
+ return {
15316
+ stop() {
15317
+ if (stopped)
15318
+ return;
15319
+ stopped = true;
15320
+ handle?.stop();
15321
+ },
15322
+ setVolume(next) {
15323
+ if (stopped || !Number.isFinite(next))
15324
+ return;
15325
+ level = Math.min(1, Math.max(0, next));
15326
+ handle?.setVolume?.(level);
15327
+ }
15328
+ };
15329
+ }
15330
+ };
15331
+ }
14477
15332
  // src/convert/text-tab.ts
14478
15333
  var STRING_PREFIX = /^\s*([A-Ga-g][#b]?|[1-8](?=\s*[|:]))?\s*[|:]?/;
14479
15334
  var STRING_BODY = /^[-0-9xX|:hpbrsvt/\\~^().*<>\s]*$/;
@@ -15470,6 +16325,7 @@ export {
15470
16325
  noteOf,
15471
16326
  noteTargets,
15472
16327
  numeralOf,
16328
+ pageInstruments,
15473
16329
  parentMajor,
15474
16330
  parseCapo,
15475
16331
  parseChord,
@@ -15527,6 +16383,7 @@ export {
15527
16383
  rootMarkOf,
15528
16384
  runPasses,
15529
16385
  runProgression,
16386
+ sampledPlayer,
15530
16387
  scaleFingers,
15531
16388
  scaleFormula,
15532
16389
  scaleName,
@@ -15569,5 +16426,5 @@ export {
15569
16426
  withTonicizations
15570
16427
  };
15571
16428
 
15572
- //# debugId=C140B6C3DE3C556464756E2164756E21
16429
+ //# debugId=39249053506929F764756E2164756E21
15573
16430
  //# sourceMappingURL=index.js.map