# Euterpe Domain

> **Euterpe** - Music Theory, Audio Production, and Generative Music

Library-only domain providing a comprehensive music technology platform covering
music primitives (notes, intervals, scales, chords, rhythm, keys, form,
dynamics, MIDI), advanced music theory (harmony, counterpoint, melody, set
theory, orchestration), AI-powered generative music, a DAW (Digital Audio
Workstation) engine, audio mastering, spatial audio (Dolby Atmos, ambisonics,
binaural), and voice technology (cloning, TTS, singing synthesis). Named after
the Greek muse of music and lyric poetry.

---

## Overview

The Euterpe domain implements a complete music technology stack spanning from
fundamental pitch and rhythm representation through to AI-powered composition,
professional audio production, and immersive spatial sound. The platform is
built on a rigorous music theory foundation that supports not only Western tonal
music but also microtonal systems, Indian ragas, Arabic maqamat, Byzantine
neumes, and other global traditions. Multiple tuning systems are first-class
citizens: standard A440, A432, Baroque A415, scientific pitch, just intonation,
and Pythagorean tuning. The theory engine goes beyond simple scale and chord
lookup to provide deep harmonic analysis, species counterpoint, melody
generation, chord progression analysis, groove quantization, pitch class set
theory, and orchestration guidance. The generative layer uses state-of-the-art
AI models for text-to-music generation, stem separation, voice generation,
melody generation, arrangement, audio inpainting, style transfer, and
conditional generation. The studio layer provides a complete DAW engine with
timeline, clip editing, MIDI editing, mixer, effects processing, virtual
instruments, automation, and project management. Audio mastering provides
professional mastering chains, mix analysis, stem mastering, format conversion,
and AI-assisted mix engineering. The spatial audio module implements Dolby Atmos
authoring, binaural rendering, higher-order ambisonics, VR/AR audio
spatialization, and AI-powered spatial upmixing. Voice technology covers voice
cloning, voice conversion, text-to-speech, text-to- singing synthesis, vocal
processing, choir simulation, and voice analysis.

---

## Architecture

```
                    @euterpe/studio
                    (DAW engine, timeline, mixer,
                     effects, instruments, automation)
                         |
         +---------------+---------------+
         |               |               |
    @euterpe/master  @euterpe/spatial  @euterpe/voice
    (mastering       (Atmos, binaural, (cloning,
     chain, mix      ambisonics,        conversion,
     analysis,       VR audio,          TTS, singing,
     stem master,    spatial upmix)     choir, analysis)
     format)              |               |
         |               |               |
         +-------+-------+-------+-------+
                         |
                  @euterpe/genesis
                  (text-to-music, stems,
                   melody gen, arrangement,
                   inpainting, style transfer,
                   conditional, quality)
                         |
                  @euterpe/theory
                  (harmony, counterpoint,
                   melody, progressions,
                   groove, set theory,
                   orchestration, genre,
                   ear training, notation)
                         |
                  @euterpe/core
                  (notes, intervals, scales,
                   chords, rhythm, keys, form,
                   dynamics, audio, MIDI)
```

### Layer Summary

1. **Core** - Music primitives: pitch classes, notes, tuning systems, intervals,
   scales (including ragas and maqamat), chords and voicings, rhythm and time
   signatures, keys and tonality, musical form, dynamics and expression, audio
   buffer/format handling, and MIDI protocol implementation
2. **Theory** - Music intelligence: harmonic analysis, species counterpoint,
   melody analysis and generation, chord progression patterns, groove
   quantization, pitch class set theory, orchestration, genre classification,
   ear training, and notation
3. **Generation** - AI music creation: text-to-music, stem separation, voice
   generation, melody generation, arrangement, inpainting, style transfer,
   conditional generation, quality assessment, and training infrastructure
4. **Production** - DAW engine with timeline, clip/MIDI editing, mixer, effects,
   instruments, automation, project management, and AI-assisted features;
   mastering chain with mix analysis, stem mastering, and format conversion;
   spatial audio with Dolby Atmos, ambisonics, binaural, and VR audio; voice
   technology with cloning, TTS, and singing synthesis

---

## Libraries (7)

### `@euterpe/core` - Core Music Primitives and Foundations

Comprehensive music theory and audio primitives library providing the
foundational building blocks for the entire platform. Ten sub-modules cover all
fundamental music concepts.

**Notes and pitch** implements pitch classes and notes with full accidental
support, enharmonic equivalence, and frequency calculation. Supports multiple
tuning systems as first-class constructs: `STANDARD_TUNING` (A440),
`A432_TUNING`, `BAROQUE_TUNING` (A415), `SCIENTIFIC_PITCH_TUNING`,
`JUST_INTONATION_TUNING`, and `PYTHAGOREAN_TUNING`. MIDI-to-frequency and
frequency-to-MIDI conversion with cent-level precision. Note creation from MIDI
numbers, scientific notation (e.g., "C4"), and raw frequencies. Microtonal note
support with arbitrary cent offsets. Multiple notation formats: scientific
pitch, Helmholtz, solfege, Nashville number system, Indian sargam syllables, and
Byzantine neumes.

**Intervals** provides interval construction, inversion, quality classification
(major, minor, perfect, augmented, diminished), semitone distance calculation,
and compound interval handling.

**Scales and modes** implements Western scales (major, minor, harmonic minor,
melodic minor, chromatic, whole-tone, pentatonic, blues) plus world scales
including Indian ragas and Arabic maqamat. Mode rotation and scale degree
naming.

**Chords and voicings** covers chord construction from root and quality, chord
inversion, voicing generation, chord symbol parsing, and extended chords (7ths,
9ths, 11ths, 13ths, altered dominants, polychords).

**Rhythm and time** defines time signatures (simple, compound, complex,
additive), note durations, dotted and tuplet divisions, tempo with BPM, and
rhythmic pattern representation.

**Keys and tonality** provides key signature management, relative/parallel key
relationships, key detection from note collections, and modulation path finding.

**Musical form** defines structural units (phrase, period, section, movement)
and common formal templates (sonata, rondo, binary, ternary, strophic,
through-composed).

**Dynamics and expression** represents dynamic markings (ppp through fff),
hairpins (crescendo, diminuendo), articulations (staccato, legato, accent,
tenuto, marcato), and tempo modifiers (ritardando, accelerando, fermata).

**Audio** handles audio buffer creation and manipulation, sample rate
conversion, format detection, and waveform representation.

**MIDI** implements MIDI message types (note on/off, control change, program
change, pitch bend, system exclusive), channel management, and MIDI file
parsing/generation.

**Dependencies:** none (zero runtime dependencies)

### `@euterpe/theory` - Music Theory Intelligence Engine

Deep music understanding and analysis with ten sub-modules.

**Harmony** provides harmonic analysis including Roman numeral analysis, chord
function identification (tonic, dominant, subdominant, pre-dominant), secondary
dominants, borrowed chords, Neapolitan and augmented sixth chords, pivot chord
modulation detection, and harmonic rhythm analysis.

**Counterpoint** implements species counterpoint rules (first through fifth
species), voice leading validation, parallel fifths/octaves detection, proper
dissonance treatment, melodic interval constraints, and cantus firmus
generation.

**Melody** analyzes melodic contour, range, intervallic content, climax
identification, motivic patterns, sequence detection, and conjunct/disjunct
motion. Generates melodies constrained by harmonic context.

**Progressions** catalogs common chord progression patterns by genre and style,
provides progression generation with voice leading optimization, and analyzes
existing progressions for functional harmony.

**Groove** handles rhythmic quantization (straight, swing, shuffle), groove
template application, humanization algorithms that add natural timing variation,
and groove extraction from performance data.

**Set theory** implements pitch class set operations (prime form, normal order,
Forte number, interval vector, Z-relation), set-class catalog, and
transformational theory (transposition, inversion, multiplication).

**Orchestration** provides instrument range and transposition data, scoring
guidelines, instrument combination suggestions, orchestral balance analysis, and
arrangement voicing distribution.

**Genre** classifies musical characteristics by genre with stylistic feature
extraction and genre-appropriate compositional suggestions.

**Ear training** generates interval, chord, scale, and progression recognition
exercises with difficulty progression and performance tracking.

**Notation** handles music notation rendering data, clef assignment, beam
grouping, tie and slur logic, and notation export preparation.

**Peer dependencies:** `@euterpe/core`

### `@euterpe/genesis` - AI Music Generation Engine

State-of-the-art generative AI for music creation with ten sub-modules.

**Text-to-music** generates audio from natural language descriptions using
diffusion-based or transformer-based models with prompt engineering for musical
style, instrumentation, mood, and structure control.

**Stems** provides audio stem separation (vocals, drums, bass, other) using deep
neural networks, enabling remix workflows and selective regeneration.

**Voice** generates vocal content including singing voice synthesis from lyrics
and melody, vocal style transfer, and voice-conditioned generation.

**Melody generation** creates melodic lines constrained by harmonic context,
style parameters, and structural requirements using both rule-based and neural
approaches.

**Arrangement** automates arrangement creation from lead sheets or simple
inputs, distributing musical ideas across instruments with appropriate voicings,
rhythms, and dynamics.

**Inpainting** fills in missing or selected regions of existing audio with
contextually appropriate generated content, enabling seamless editing and
extension.

**Style transfer** transforms the style of existing musical content while
preserving structural and melodic identity, enabling cross-genre adaptation.

**Conditional** generates music conditioned on multiple simultaneous constraints
(chord progression, melody, rhythm pattern, instrumentation, energy curve).

**Quality** assesses generated audio quality using perceptual metrics, musical
coherence scoring, and artifact detection.

**Infrastructure** manages model loading, inference optimization, GPU/CPU
dispatch, batching, caching, and model versioning for the generation pipeline.

**Peer dependencies:** `@euterpe/core`, `@euterpe/theory`

### `@euterpe/studio` - DAW Engine

Complete Digital Audio Workstation engine with ten sub-modules.

**DAW engine** provides the core audio processing graph, real-time audio
rendering, buffer management, latency compensation, and transport controls
(play, pause, stop, record, loop).

**Timeline** manages the arrangement timeline with track lanes, regions,
markers, tempo maps, time signature changes, and timeline zoom/scroll
navigation.

**Clip editing** handles audio clip manipulation including cut, copy, paste,
trim, fade in/out, crossfade, time stretch, and pitch shift with non-
destructive editing.

**MIDI editing** provides piano roll editing, step sequencing, MIDI
quantization, velocity editing, controller lane editing, and MIDI transformation
tools.

**Mixer** implements a channel strip architecture with gain staging, pan,
mute/solo, send/return routing, bus grouping, and master output with metering.

**Effects** provides audio effect processors including EQ (parametric, graphic,
shelving), dynamics (compressor, limiter, gate, expander), time-based effects
(reverb, delay, chorus, flanger, phaser), and distortion/saturation.

**Instruments** implements virtual instruments including synthesizers
(subtractive, FM, wavetable, granular), samplers, drum machines, and instrument
preset management.

**Automation** enables parameter automation with breakpoint editing, automation
curves (linear, bezier, step), automation lanes per track, and automation
recording from controller input.

**Project management** handles session save/load, project file format, audio
file reference management, undo/redo history, and project export.

**AI features** integrates AI-assisted tools including auto-mixing, intelligent
EQ suggestions, mastering assistance, and AI-powered audio repair.

**Peer dependencies:** `@euterpe/core`, `@euterpe/theory`, `@euterpe/genesis`

### `@euterpe/master` - Audio Mastering

Professional audio mastering pipeline with five sub-modules.

**Mastering chain** implements the mastering signal processing chain including
multiband compression, stereo enhancement, harmonic excitation, limiting, and
loudness normalization (LUFS targeting per streaming platform specifications).

**Mix analysis** provides spectral analysis, dynamic range measurement, stereo
field visualization, loudness metering (integrated, short-term, momentary LUFS),
true peak detection, and crest factor analysis.

**Stem mastering** enables mastering from individual stems (drums, bass, vocals,
instruments) with per-stem processing before final limiting, providing more
control than stereo mastering.

**Format masters** handles final format conversion including sample rate
conversion, bit depth dithering, codec encoding (WAV, FLAC, AAC, MP3, Opus), and
format-specific metadata embedding.

**Mix assistant** provides AI-powered mix improvement suggestions based on
spectral balance analysis, dynamic range assessment, and reference track
comparison.

**Peer dependencies:** `@euterpe/core`, `@euterpe/theory`

### `@euterpe/spatial` - Immersive Audio and Spatial Sound

Spatial audio processing platform with five sub-modules.

**Atmos** implements Dolby Atmos authoring tools including object-based audio
positioning, bed channel management, metadata generation, renderer integration,
and Atmos ADM (Audio Definition Model) file creation for immersive music
production.

**Binaural** provides binaural audio rendering using HRTF (Head-Related Transfer
Function) processing for headphone-based 3D audio. Includes HRTF database
management, personalized HRTF estimation, and head tracking integration.

**Ambisonics** implements higher-order ambisonics (HOA) encoding, decoding, and
transformation. Supports B-format and higher-order spherical harmonics with
rotation, beamforming, and speaker-array decoding.

**VR audio** provides spatial audio for virtual reality and augmented reality
applications including room acoustics simulation, distance attenuation modeling,
occlusion, and real-time source positioning tied to 3D scene state.

**Spatial upmix** uses AI models to convert stereo or multichannel audio to
immersive spatial formats, analyzing the source material to intelligently
distribute elements across the spatial field while preserving artistic intent.

**Peer dependencies:** `@euterpe/core`

### `@euterpe/voice` - Voice Technology

Voice and singing technology with seven sub-modules.

**Voice cloning** creates synthetic voice models from reference audio samples,
enabling voice reproduction for narration, singing, and content creation with
speaker verification and consent management.

**Voice conversion** transforms one speaker's voice to sound like another while
preserving linguistic content, supporting real-time and offline processing with
multiple conversion approaches (encoder-decoder, GAN-based, diffusion-based).

**TTS (Text-to-Speech)** generates natural speech from text with support for
multiple languages, speaking styles, emotion control, SSML markup, and prosody
adjustment.

**Text-to-singing** synthesizes singing vocals from lyrics and melody input,
supporting multiple vocal styles, vibrato control, breath simulation, and
expression parameters.

**Vocal processing** provides vocal-specific audio processing including pitch
correction (auto-tune style and transparent), formant shifting, vocal doubling,
harmonizer effects, de-essing, and breath removal.

**Choir** simulates choir and ensemble vocals from single voice inputs,
generating multiple virtual singers with natural variation in timing, pitch, and
timbre to create realistic choral textures.

**Voice analysis** extracts vocal characteristics including pitch tracking,
formant analysis, voice quality assessment, singing technique evaluation, and
vocal range detection.

**Peer dependencies:** `@euterpe/core`, `@euterpe/theory`

---

## Technology Stack

| Component | Technology                                    |
| --------- | --------------------------------------------- |
| Language  | TypeScript (ESM)                              |
| Runtime   | Node.js                                       |
| Build     | Nx with `@nx/js:tsc`                          |
| Testing   | Vitest                                        |
| Audio     | Web Audio API compatible, custom DSP          |
| Spatial   | Dolby Atmos, Ambisonics, HRTF binaural        |
| MIDI      | Full MIDI 1.0 protocol                        |
| AI/ML     | Diffusion, transformer, GAN-based generation  |
| Notation  | Scientific, Helmholtz, solfege, sargam, neume |
| Tuning    | A440, A432, Baroque, Just, Pythagorean        |

---

## Development

```bash
# Test a specific library
pnpm nx test @euterpe/core

# Build all Euterpe libraries
pnpm nx run-many --target=build --projects=tag:scope:euterpe

# Lint a library
pnpm nx lint @euterpe/theory

# Run all domain tests
pnpm nx run-many --target=test --projects=tag:scope:euterpe
```

### Configuration

- **Project tags:** `["scope:euterpe", "layer:domain", "type:lib"]`
- **Build executor:** `@nx/js:tsc`
- All libraries use ESM (`"type": "module"`)
- Core has zero runtime dependencies
- Libraries use workspace peer dependencies for inter-library references

### Dependency Graph

```
@euterpe/core (standalone, zero deps)
  |
  +-- @euterpe/theory (peer: core)
  |     |
  |     +-- @euterpe/genesis (peer: core, theory)
  |     |     |
  |     |     +-- @euterpe/studio (peer: core, theory, genesis)
  |     |
  |     +-- @euterpe/master (peer: core, theory)
  |     |
  |     +-- @euterpe/voice (peer: core, theory)
  |
  +-- @euterpe/spatial (peer: core)
```

The dependency chain reflects the layered architecture: `core` provides music
primitives, `theory` adds analytical intelligence, and the production libraries
(`genesis`, `studio`, `master`, `voice`) build on both. `spatial` depends only
on `core` since spatial audio processing operates on audio buffers independently
of music theory. `studio` has the deepest dependency chain, requiring `genesis`
for its AI-assisted production features.
