Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ OpenStand is an **early but usable** practice tool. What works today:
- **A real-looking lead sheet.** Chord symbols in a handwritten jazz hand (Petaluma), rehearsal marks, repeat signs, endings, segno and coda, correct flat/sharp spelling in every key, and the current bar marked with a highlighter stroke as it plays.
- **Practice controls:** tempo (40–300 BPM, changes instantly), transpose to any key while playing, number of choruses, and a count-in in the tune's meter (4/4 "1 . 2 . 1 2 3 4", 6/8 two pulses then six eighths). Keyboard shortcuts: <kbd>Space</kbd> to play/stop, <kbd>↑</kbd>/<kbd>↓</kbd> for ±5 BPM, <kbd>→</kbd>/<kbd>←</kbd> to transpose by a half step, and <kbd>L</kbd> to clear the loop. Shortcuts are inactive while editing a chart or focusing a form control.
- **Practice modes:** loop any bars or a rehearsal section, go round all 12 keys (or step up a half or whole tone each chorus), and speed up a few BPM every chorus.
- **Chord and scale helper:** keyboard, guitar diagrams and fitting scales for any chord.
- **Style lab:** change a style's drums (a main groove, a variation the band switches to, and a fill for the end of the form), bass line and chord rhythm on a grid (each with an optional second pattern the band switches to) and hear it while the band plays. Save your styles and pick them from the style menu, share one as a link, or send it to the project as a new style.
- **Mixer** with per-instrument volume and mute, a master volume and an output level meter.
- **Light and dark themes** that follow your system setting, and a layout that works on phones.
Expand Down Expand Up @@ -147,7 +148,7 @@ Positions are in beats from the start of the bar or chord. Off-beat eighths are
- [x] Chart editor, and export back to iReal Pro
- [x] Practice modes: tempo ramp per chorus, loop a section, cycle through all 12 keys
- [ ] Export to ChordPro and MusicXML
- [ ] Chord helper: piano keyboard, guitar diagrams, scale suggestions
- [x] Chord helper: piano keyboard, guitar diagrams, scale suggestions
- [ ] Export to WAV / MIDI / PDF
- [ ] Engine published as a standalone package

Expand Down
59 changes: 58 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ import { chartFromHash, labFromHash, shareUrl, styleShareUrl } from './formats/s
import { addTunes, loadTunes, removePlaylist, removeTune, saveTune } from './library/db'
import { loadMyStyles, myStyleId, removeMyStyle, saveMyStyle } from './library/myStyles'
import type { Chart as ChartData } from './music/chart'
import { keyPrefersFlats, noteName } from './music/chords'
import { keyPrefersFlats, noteName, parseChord, transposeChord, type Chord } from './music/chords'
import { emptyChart } from './music/edit'
import { EXAMPLES, type Tune } from './music/songs'
import { getStyle, STYLES, type StyleDefinition } from './styles'
import { labFromStyle, styleFromLab, styleSource, labId, STEPS_PER_BEAT, type LabStyle } from './styles/lab'
import { Chart } from './ui/Chart'
import { ChordHelper } from './ui/ChordHelper'
import { Editor, EditorHeader } from './ui/Editor'
import { ImportDialog, type ImportResult } from './ui/ImportDialog'
import { Library } from './ui/Library'
Expand Down Expand Up @@ -81,6 +82,39 @@ const noteNameFor = (pc: number) => noteName(pc, keyPrefersFlats(pc)).replace('b

const compLabel = (program: number) => (program >= 24 && program <= 31 ? 'Guitar' : 'Piano')

function firstChord(chart: ChartData, transpose: number): Chord {
for (const bar of chart.bars) {
for (const c of bar.chords) {
const parsed = c.symbol ? parseChord(c.symbol) : null
if (parsed) return transposeChord(parsed, transpose)
}
}
return transposeChord(parseChord('C')!, transpose)
}

function playingChord(chart: ChartData, position: Position | null, transpose: number): Chord | null {
if (!position || position.countIn > 0) return null
if (position.ending) return firstChord(chart, transpose)
const bar = chart.bars[position.measure]
if (!bar) return null
if (bar.chords.length > 0) {
let at = 0
for (const c of bar.chords) {
at += c.beats
if (position.beatInBar < at || c === bar.chords[bar.chords.length - 1]) {
const parsed = c.symbol ? parseChord(c.symbol) : null
return parsed ? transposeChord(parsed, transpose) : null
}
}
}
const held = chart.bars
.slice(0, position.measure)
.flatMap((b) => b.chords)
.findLast((c) => c.symbol)?.symbol
const parsed = held ? parseChord(held) : null
return parsed ? transposeChord(parsed, transpose) : null
}

function positionAt(timeline: Timeline, beat: number): Position | null {
if (beat < timeline.countIn) {
const barBeats = timeline.countIn
Expand Down Expand Up @@ -158,6 +192,8 @@ export default function App() {
const outputLevel = useCallback(() => playerRef.current?.level() ?? { peak: -100, rms: -100 }, [])
const [practice, setPractice] = useState<PracticeSettings>(NO_PRACTICE)
const [picking, setPicking] = useState<null | 'first' | { from: number }>(null)
const [selectedChord, setSelectedChord] = useState<Chord | null>(null)
const [chordsOpen, setChordsOpen] = useState(false)
const [draft, setDraft] = useState<Draft | null>(null)
const [editBar, setEditBar] = useState(0)
const [irealState, setIrealState] = useState<'idle' | 'copied' | 'failed'>('idle')
Expand All @@ -178,7 +214,11 @@ export default function App() {
// During practice the chorus decides the key on the stand and the tempo
const chorus = position ? Math.min(position.chorus, choruses - 1) : 0
const shownTranspose = playing ? chorusTranspose(transpose, practice.keyStep, chorus) : transpose
const shownKeyPc = (chart.key + shownTranspose + 12) % 12
const liveBpm = clampBpm(bpm + practice.ramp * (playing ? chorus : 0))
const shownChord = selectedChord
? transposeChord(selectedChord, shownTranspose)
: (playing ? playingChord(chart, position, shownTranspose) : null) ?? firstChord(chart, shownTranspose)

useEffect(() => {
// The effect may run twice (StrictMode); a discarded player must not update the UI
Expand Down Expand Up @@ -336,6 +376,7 @@ export default function App() {
setBpm(next.chart.bpm)
setPractice((p) => ({ ...p, loop: null }))
setPicking(null)
setSelectedChord(null)
setLibraryOpen(false)
try {
localStorage.setItem(LAST_TUNE, next.id)
Expand Down Expand Up @@ -656,6 +697,14 @@ export default function App() {
range={picking && picking !== 'first' ? [picking.from, picking.from] : draft ? null : practice.loop}
selectedBar={draft ? editBar : null}
onBarClick={draft ? setEditBar : picking ? pickBar : undefined}
onChordClick={
!draft && !picking
? (c) => {
setSelectedChord(transposeChord(c, -shownTranspose))
setChordsOpen(true)
}
: undefined
}
header={draft ? <EditorHeader chart={draft.chart} onChange={(c) => setDraft({ ...draft, chart: c })} /> : undefined}
/>
</main>
Expand Down Expand Up @@ -739,6 +788,14 @@ export default function App() {
onChoruses={(n) => changeArrangement({ choruses: n })}
>
<Practice chart={chart} settings={practice} onChange={changePractice} onPickLoop={() => setPicking('first')} />
<ChordHelper
chord={shownChord}
keyPc={shownKeyPc}
following={selectedChord === null}
onFollowChange={(follow) => setSelectedChord(follow ? null : transposeChord(shownChord, -shownTranspose))}
open={chordsOpen}
onOpenChange={setChordsOpen}
/>
<Mixer
labels={{ bass: 'Bass', comp: compLabel(style.comp.program), drums: 'Drums' }}
volumes={volumes}
Expand Down
152 changes: 152 additions & 0 deletions src/music/fretboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import { closeVoicingTones, type Chord } from './chords'

// Standard guitar tuning (E2 A2 D3 G3 B3 E4) as pitch classes and MIDI note numbers
export const TUNING = [4, 9, 2, 7, 11, 4] as const
const MIDI = [40, 45, 50, 55, 59, 64] as const

export interface FretShape {
frets: (number | null)[] // 6 strings from low E (0) to high E (5); null = muted (x)
baseFret: number
}

interface Candidate extends FretShape {
bassString: number
bassFret: number
coverage: number
score: number
}

function isErgonomic(frets: (number | null)[], minFret: number): boolean {
const fretted = frets.filter((f): f is number => f !== null && f > 0)
if (fretted.length <= 4) return true
// 5 or 6 fretted strings need an index-finger barre at minFret and at most 3 other fingers
const firstBarred = frets.findIndex((f) => f === minFret)
const lastPlayed = frets.findLastIndex((f) => f !== null)
for (let s = firstBarred; s <= lastPlayed; s++) {
if (frets[s] === null || frets[s]! < minFret) return false
}
return fretted.filter((f) => f > minFret).length <= 3
}

function isContiguousOrShell(played: number[]): boolean {
const span = played[played.length - 1] - played[0] + 1
if (span === played.length) return true
// Jazz shell / drop-3 with bass on 6th string and 5th string muted
return played[0] === 0 && played[1] === 2 && played[played.length - 1] - 2 + 1 === played.length - 1
}

export function guitarShapes(chord: Chord): [FretShape, FretShape] {
const tones = closeVoicingTones(chord)
const tonePcs = new Set(tones.map((t) => (chord.root + t) % 12))
const required = new Set<number>([
chord.root,
(chord.root + tones[1]) % 12,
...(tones.length > 3 ? [(chord.root + tones[3]) % 12] : []),
...(tones[2] !== 7 ? [(chord.root + tones[2]) % 12] : []),
])

const byKey = new Map<string, Candidate>()

for (let bassString = 0; bassString <= 2; bassString++) {
for (let bassFret = 0; bassFret <= 11; bassFret++) {
if ((TUNING[bassString] + bassFret) % 12 !== chord.bass) continue

const winStarts: number[] = []
if (bassFret <= 4) winStarts.push(1)
if (bassFret > 0) {
for (let w = Math.max(1, bassFret - 3); w <= Math.min(11, bassFret); w++) {
if (!winStarts.includes(w)) winStarts.push(w)
}
}

for (const win of winStarts) {
const choices: (number | null)[][] = Array.from({ length: 6 }, (_, s) => {
if (s < bassString) return [null]
if (s === bassString) return [bassFret]
const opts: (number | null)[] = [null]
if (win === 1 && tonePcs.has(TUNING[s])) opts.push(0)
for (let f = win; f <= win + 3; f++) {
if (tonePcs.has((TUNING[s] + f) % 12)) opts.push(f)
}
return opts
})

const cur: (number | null)[] = [null, null, null, null, null, null]
const search = (s: number) => {
if (s === 6) {
const played: number[] = []
for (let i = 0; i < 6; i++) if (cur[i] !== null) played.push(i)
if (played.length < 4 || !isContiguousOrShell(played)) return

for (let i = 1; i < played.length; i++) {
if (MIDI[played[i]] + cur[played[i]]! <= MIDI[played[i - 1]] + cur[played[i - 1]]!) return
}

const fretted = played.map((i) => cur[i]!).filter((f) => f > 0)
const minFret = fretted.length ? Math.min(...fretted) : 0
const maxFret = fretted.length ? Math.max(...fretted) : 0
if (fretted.length && maxFret - minFret > 3) return
if (played.some((i) => cur[i] === 0) && maxFret > 4) return
if (fretted.length && !isErgonomic(cur, minFret)) return

const pcs = new Set(played.map((i) => (TUNING[i] + cur[i]!) % 12))
let reqHits = 0
for (const r of required) if (pcs.has(r)) reqHits++
const coverage = reqHits * 30 + pcs.size * 12

const contiguous = played[played.length - 1] - played[0] + 1 === played.length
const openCount = played.filter((i) => cur[i] === 0).length
const span = fretted.length ? maxFret - minFret : 0
const baseFret = maxFret <= 4 ? 1 : minFret
const score =
coverage +
(contiguous ? 16 : 0) +
played.length * 4 +
openCount * 2 -
span * 3 -
baseFret * 1.5 -
bassFret * 0.5

const key = cur.map((f) => f ?? 'x').join(',')
const prev = byKey.get(key)
if (!prev || score > prev.score) {
byKey.set(key, { frets: [...cur], baseFret, bassString, bassFret, coverage, score })
}
return
}
for (const f of choices[s]) {
cur[s] = f
search(s + 1)
}
}
search(0)
}
}
}

const all = [...byKey.values()]
const maxCoverage = Math.max(0, ...all.map((c) => c.coverage))
const strong = all.filter((c) => c.coverage >= maxCoverage - 12)
const pool = strong.length >= 2 ? strong : all

pool.sort((a, b) => a.baseFret - b.baseFret || a.bassFret - b.bassFret || b.score - a.score)
const firstPos = pool[0]?.baseFret ?? 1
const first =
pool.filter((c) => c.baseFret === firstPos).sort((a, b) => b.score - a.score)[0] ??
({ frets: [null, null, 0, 0, 0, 0], baseFret: 1, bassString: 2, bassFret: 0, coverage: 0, score: 0 } as Candidate)

const higher = pool.filter(
(c) => c.baseFret >= first.baseFret + 2 || (c.bassString !== first.bassString && c.bassFret >= first.bassFret + 2),
)
const secondPool = higher.length ? higher : pool.filter((c) => c !== first)
const nextPos = secondPool[0]?.baseFret ?? first.baseFret
const second =
secondPool.filter((c) => c.baseFret <= nextPos + 1).sort((a, b) => b.score - a.score)[0] ??
secondPool[0] ??
first

return [
{ frets: first.frets, baseFret: first.baseFret },
{ frets: second.frets, baseFret: second.baseFret },
]
}
Loading
Loading