tonal

package
v1.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 25, 2025 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnalyzeKeyTransition

func AnalyzeKeyTransition(fromKey int, fromMode KeyMode, toKey int, toMode KeyMode) map[string]interface{}

AnalyzeKeyTransition analyzes the transition between two keys

func ClassifyHarmonicRatio

func ClassifyHarmonicRatio(harmonicRatio float64) string

ClassifyHarmonicRatio classifies harmonic ratio into categories

func ClassifyInharmonicity

func ClassifyInharmonicity(inharmonicity float64) string

ClassifyInharmonicity classifies inharmonicity level

func EstimateInstrumentType

func EstimateInstrumentType(inharmonicity float64, f0 float64) string

EstimateInstrumentType estimates instrument type from inharmonicity

func EstimateVoicingQuality

func EstimateVoicingQuality(harmonicRatio float64) float64

EstimateVoicingQuality estimates voicing quality from harmonic ratio

func GetChordQualityName

func GetChordQualityName(quality ChordQuality) string

GetChordQualityName returns the human-readable name for a chord quality

func GetKeyName

func GetKeyName(key int, mode KeyMode) string

GetKeyName returns human-readable key name

func GetPitchDetectionMethodName

func GetPitchDetectionMethodName(method PitchDetectionMethod) string

GetPitchDetectionMethodName returns the name of the detection method

func GetSupportedChordQualities

func GetSupportedChordQualities() []string

GetSupportedChordQualities returns a list of supported chord qualities

func GetSupportedDetectionMethods

func GetSupportedDetectionMethods() []string

GetSupportedDetectionMethods returns a list of supported detection methods

func GetSupportedHarmonicRatioMethods

func GetSupportedHarmonicRatioMethods() []string

GetSupportedMethods returns list of supported harmonic ratio methods

func GetSupportedInharmonicityMethods

func GetSupportedInharmonicityMethods() []string

GetSupportedMethods returns list of supported inharmonicity methods

func GetSupportedInharmonicityModels

func GetSupportedInharmonicityModels() []string

GetSupportedModels returns list of supported physical models

func GetSupportedMethods

func GetSupportedMethods() []string

GetSupportedMethods returns list of supported estimation methods

func GetSupportedProfiles

func GetSupportedProfiles() []string

GetSupportedProfiles returns list of supported key profiles

func IsKeyCompatible

func IsKeyCompatible(key1 int, mode1 KeyMode, key2 int, mode2 KeyMode) bool

IsKeyCompatible checks if two keys are compatible/related

Types

type ChordCandidate

type ChordCandidate struct {
	Root       int            `json:"root"`       // Root note (0=C, 1=C#, ..., 11=B)
	Quality    ChordQuality   `json:"quality"`    // Chord quality/type
	Inversion  ChordInversion `json:"inversion"`  // Chord inversion
	RootName   string         `json:"root_name"`  // Human-readable root name
	ChordName  string         `json:"chord_name"` // Full chord name
	Confidence float64        `json:"confidence"` // Detection confidence (0-1)
	Strength   float64        `json:"strength"`   // Chord strength measure
	Salience   float64        `json:"salience"`   // Perceptual salience
	Method     string         `json:"method"`     // Detection method used
}

ChordCandidate represents a possible chord detection

type ChordDetectionMethod

type ChordDetectionMethod int

ChordDetectionMethod specifies the algorithm for chord detection

const (
	ChordTemplateMatching ChordDetectionMethod = iota
	ChordHarmonicAnalysis
	ChordCQTBased
	ChordStatistical
	ChordMLBased
	ChordHybrid
)

type ChordDetectionParams

type ChordDetectionParams struct {
	Method          ChordDetectionMethod `json:"method"`
	ChromaSize      int                  `json:"chroma_size"`      // Size of chroma vector (12, 24, 36)
	UseHarmonics    bool                 `json:"use_harmonics"`    // Consider harmonic content
	WeightHarmonics bool                 `json:"weight_harmonics"` // Weight harmonics differently

	// Template matching parameters
	NormalizeTemplates bool    `json:"normalize_templates"` // Normalize chord templates
	TemplateStrength   float64 `json:"template_strength"`   // Template weighting strength
	UseInversions      bool    `json:"use_inversions"`      // Detect chord inversions

	// Quality thresholds
	MinConfidence    float64 `json:"min_confidence"`     // Minimum confidence threshold
	MaxCandidates    int     `json:"max_candidates"`     // Maximum candidates to return
	MinChordStrength float64 `json:"min_chord_strength"` // Minimum chord strength

	// Bass detection
	UseBassDetection bool       `json:"use_bass_detection"` // Enable bass note detection
	BassFreqRange    [2]float64 `json:"bass_freq_range"`    // Bass frequency range [min, max]
	BassWeight       float64    `json:"bass_weight"`        // Weight for bass in detection

	// Extended harmony
	DetectExtensions  bool `json:"detect_extensions"`  // Detect 7ths, 9ths, etc.
	DetectAlterations bool `json:"detect_alterations"` // Detect altered chords
	MaxExtension      int  `json:"max_extension"`      // Maximum extension to detect (7, 9, 11, 13)

	// Temporal analysis
	UseTemporalSmoothing bool `json:"use_temporal_smoothing"` // Enable temporal smoothing
	TemporalWindow       int  `json:"temporal_window"`        // Frames for temporal analysis

	// Advanced options
	UseFunctionalAnalysis bool    `json:"use_functional_analysis"` // Analyze functional harmony
	UseVoiceLeading       bool    `json:"use_voice_leading"`       // Analyze voice leading
	ContextWeight         float64 `json:"context_weight"`          // Weight for harmonic context

	// Machine learning parameters
	ModelPath       string    `json:"model_path"`       // Path to ML model (if available)
	UseEnsemble     bool      `json:"use_ensemble"`     // Use ensemble of methods
	EnsembleWeights []float64 `json:"ensemble_weights"` // Weights for ensemble methods
}

ChordDetectionParams contains parameters for chord detection

type ChordDetectionResult

type ChordDetectionResult struct {
	// Primary chord information
	Root       int            `json:"root"`       // Best root estimate (0-11)
	Quality    ChordQuality   `json:"quality"`    // Best chord quality
	Inversion  ChordInversion `json:"inversion"`  // Best inversion
	RootName   string         `json:"root_name"`  // Human-readable root name
	ChordName  string         `json:"chord_name"` // Full chord name
	Confidence float64        `json:"confidence"` // Overall confidence (0-1)
	Strength   float64        `json:"strength"`   // Chord strength measure

	// Multiple chord candidates
	Candidates []ChordCandidate `json:"candidates"`

	// Harmonic analysis
	ChromaVector    []float64 `json:"chroma_vector"`    // Input chroma profile
	HarmonicProfile []float64 `json:"harmonic_profile"` // Harmonic content analysis
	BassNote        int       `json:"bass_note"`        // Bass note (for inversions)
	BassConfidence  float64   `json:"bass_confidence"`  // Bass note confidence

	// Quality metrics
	Clarity    float64 `json:"clarity"`    // Chord clarity measure
	Ambiguity  float64 `json:"ambiguity"`  // Chord ambiguity measure
	Consonance float64 `json:"consonance"` // Consonance/dissonance measure
	Tension    float64 `json:"tension"`    // Harmonic tension
	Stability  float64 `json:"stability"`  // Temporal stability

	// Template matching scores
	TemplateScores []float64 `json:"template_scores"` // Scores for each chord template

	// Statistical analysis
	ChordProbability float64            `json:"chord_probability"` // Probability this is a chord
	KeyCompatibility map[string]float64 `json:"key_compatibility"` // Compatibility with keys
	FunctionalRole   string             `json:"functional_role"`   // Tonic, subdominant, dominant, etc.

	// Extended harmony analysis
	Extensions   []int `json:"extensions"`    // Additional notes (9, 11, 13, etc.)
	Alterations  []int `json:"alterations"`   // Altered notes (b5, #11, etc.)
	AddedNotes   []int `json:"added_notes"`   // Added notes (add9, add11, etc.)
	OmittedNotes []int `json:"omitted_notes"` // Missing chord tones

	// Voice leading analysis
	VoiceLeading []float64 `json:"voice_leading"` // Voice leading smoothness
	ChordSpacing string    `json:"chord_spacing"` // Close, open, spread
	Doubling     []int     `json:"doubling"`      // Doubled notes

	// Computational details
	Method         string  `json:"method"`          // Detection method used
	ProcessTime    float64 `json:"process_time"`    // Processing time in ms
	ChromaSize     int     `json:"chroma_size"`     // Chroma vector size used
	AnalysisFrames int     `json:"analysis_frames"` // Number of frames analyzed
}

ChordDetectionResult contains the output of chord detection analysis

type ChordDetector

type ChordDetector struct {
	// contains filtered or unexported fields
}

ChordDetector performs chord detection analysis

func NewChordDetector

func NewChordDetector(sampleRate int) *ChordDetector

NewChordDetector creates a new chord detector with default parameters

func NewChordDetectorWithParams

func NewChordDetectorWithParams(sampleRate int, params ChordDetectionParams) *ChordDetector

NewChordDetectorWithParams creates a new chord detector with custom parameters

func (*ChordDetector) DetectChord

func (cd *ChordDetector) DetectChord(audioData []float64) (*ChordDetectionResult, error)

DetectChord performs chord detection on audio data

type ChordInversion

type ChordInversion int

ChordInversion represents the inversion of a chord

const (
	ChordRoot ChordInversion = iota
	ChordFirst
	ChordSecond
	ChordThird
	ChordFourth
)

type ChordProgressionAnalyzer

type ChordProgressionAnalyzer struct {
	// contains filtered or unexported fields
}

ChordProgressionAnalyzer analyzes sequences of chords

func NewChordProgressionAnalyzer

func NewChordProgressionAnalyzer(sampleRate int) *ChordProgressionAnalyzer

NewChordProgressionAnalyzer creates a new chord progression analyzer

func (*ChordProgressionAnalyzer) AddChord

func (cpa *ChordProgressionAnalyzer) AddChord(result ChordDetectionResult)

AddChord adds a chord detection result to the progression

func (*ChordProgressionAnalyzer) AnalyzeProgression

func (cpa *ChordProgressionAnalyzer) AnalyzeProgression() map[string]interface{}

AnalyzeProgression analyzes the chord progression

type ChordQuality

type ChordQuality int

ChordQuality represents the quality/type of a chord

const (
	ChordMajor ChordQuality = iota
	ChordMinor
	ChordDiminished
	ChordAugmented
	ChordSus2
	ChordSus4
	ChordMaj7
	ChordMin7
	ChordDom7
	ChordMinMaj7
	ChordAug7
	ChordDim7
	ChordHalfDim7
	ChordAdd9
	ChordMaj9
	ChordMin9
	ChordDom9
	ChordMaj11
	ChordMin11
	ChordDom11
	ChordMaj13
	ChordMin13
	ChordDom13
	ChordPowerChord // 🤘
	ChordUnknown
)

type ChordTemplate

type ChordTemplate struct {
	Quality    ChordQuality `json:"quality"`
	Pattern    []float64    `json:"pattern"`    // Chroma pattern for the chord
	Name       string       `json:"name"`       // Chord name
	Intervals  []int        `json:"intervals"`  // Intervals from root
	Extensions []int        `json:"extensions"` // Possible extensions
	Inversions [][]float64  `json:"inversions"` // Inversion patterns
	Weight     float64      `json:"weight"`     // Template importance weight
	Consonance float64      `json:"consonance"` // Consonance rating
}

ChordTemplate represents a chord template for matching

type HarmonicData

type HarmonicData struct {
	// contains filtered or unexported fields
}

HarmonicData represents analyzed harmonic structure

type HarmonicRatioAnalyzer

type HarmonicRatioAnalyzer struct {
	// contains filtered or unexported fields
}

HarmonicRatioAnalyzer implements harmonic-to-noise ratio analysis

func NewHarmonicRatioAnalyzer

func NewHarmonicRatioAnalyzer(sampleRate int) *HarmonicRatioAnalyzer

NewHarmonicRatioAnalyzer creates a new harmonic ratio analyzer

func NewHarmonicRatioAnalyzerWithParams

func NewHarmonicRatioAnalyzerWithParams(params HarmonicRatioParams) *HarmonicRatioAnalyzer

NewHarmonicRatioAnalyzerWithParams creates analyzer with custom parameters

func (*HarmonicRatioAnalyzer) AnalyzeFrame

func (hra *HarmonicRatioAnalyzer) AnalyzeFrame(audioFrame []float64) (HarmonicRatioResult, error)

AnalyzeFrame analyzes harmonic ratio for a single audio frame

func (*HarmonicRatioAnalyzer) AnalyzeSequence

func (hra *HarmonicRatioAnalyzer) AnalyzeSequence(audioFrames [][]float64) ([]HarmonicRatioResult, error)

AnalyzeSequence analyzes harmonic ratio for a sequence of audio frames

func (*HarmonicRatioAnalyzer) GetAverageHarmonicRatio

func (hra *HarmonicRatioAnalyzer) GetAverageHarmonicRatio(results []HarmonicRatioResult) float64

GetAverageHarmonicRatio computes average harmonic ratio from sequence

func (*HarmonicRatioAnalyzer) GetF0History

func (hra *HarmonicRatioAnalyzer) GetF0History() []float64

GetF0History returns the F0 history

func (*HarmonicRatioAnalyzer) GetHistory

func (hra *HarmonicRatioAnalyzer) GetHistory() []float64

GetHistory returns the harmonic ratio history

func (*HarmonicRatioAnalyzer) GetParameters

func (hra *HarmonicRatioAnalyzer) GetParameters() HarmonicRatioParams

GetParameters returns current parameters

func (*HarmonicRatioAnalyzer) Initialize

func (hra *HarmonicRatioAnalyzer) Initialize()

Initialize sets up the analyzer

func (*HarmonicRatioAnalyzer) Reset

func (hra *HarmonicRatioAnalyzer) Reset()

Reset resets the analyzer state

func (*HarmonicRatioAnalyzer) SetParameters

func (hra *HarmonicRatioAnalyzer) SetParameters(params HarmonicRatioParams)

SetParameters updates parameters

type HarmonicRatioMethod

type HarmonicRatioMethod int

HarmonicRatioMethod defines different methods for computing harmonic ratio

const (
	HarmonicRatioHNR      HarmonicRatioMethod = iota // Harmonic-to-Noise Ratio
	HarmonicRatioACF                                 // Autocorrelation-based
	HarmonicRatioHPS                                 // Harmonic Product Spectrum
	HarmonicRatioComb                                // Comb filtering
	HarmonicRatioSpectral                            // Spectral peak analysis
	HarmonicRatioYin                                 // YIN-based periodicity
)

type HarmonicRatioParams

type HarmonicRatioParams struct {
	Method     HarmonicRatioMethod `json:"method"`
	SampleRate int                 `json:"sample_rate"`
	WindowSize int                 `json:"window_size"`
	HopSize    int                 `json:"hop_size"`

	// Frequency analysis parameters
	MinFreq           float64 `json:"min_freq"`           // Minimum frequency to analyze
	MaxFreq           float64 `json:"max_freq"`           // Maximum frequency to analyze
	MaxHarmonics      int     `json:"max_harmonics"`      // Maximum number of harmonics
	HarmonicTolerance float64 `json:"harmonic_tolerance"` // Tolerance for harmonic detection

	// Spectral analysis parameters
	MinPeakHeight        float64 `json:"min_peak_height"`        // Minimum peak height threshold
	PeakDetectionWidth   int     `json:"peak_detection_width"`   // Width for peak detection
	SpectralSmoothingLen int     `json:"spectral_smoothing_len"` // Spectral smoothing length

	// Noise floor estimation
	NoiseFloorMethod       string  `json:"noise_floor_method"`        // "median", "percentile", "minimum"
	NoiseFloorPercentile   float64 `json:"noise_floor_percentile"`    // Percentile for noise floor
	NoiseFloorSmoothingLen int     `json:"noise_floor_smoothing_len"` // Smoothing length

	// Temporal analysis
	UseTemporalSmoothing bool `json:"use_temporal_smoothing"` // Enable temporal smoothing
	TemporalSmoothingLen int  `json:"temporal_smoothing_len"` // Temporal smoothing length

	// Advanced parameters
	UseFreqWeighting      bool `json:"use_freq_weighting"`      // Weight by frequency importance
	UsePsychoacousticMask bool `json:"use_psychoacoustic_mask"` // Apply psychoacoustic masking
	AdaptiveThreshold     bool `json:"adaptive_threshold"`      // Use adaptive thresholding
}

HarmonicRatioParams contains parameters for harmonic ratio computation

type HarmonicRatioResult

type HarmonicRatioResult struct {
	// Primary measures
	HarmonicRatio  float64 `json:"harmonic_ratio"`  // Overall harmonic-to-noise ratio (dB)
	HarmonicEnergy float64 `json:"harmonic_energy"` // Total harmonic energy
	NoiseEnergy    float64 `json:"noise_energy"`    // Total noise energy
	TotalEnergy    float64 `json:"total_energy"`    // Total signal energy

	// Detailed harmonic analysis
	HarmonicFrequencies []float64 `json:"harmonic_frequencies"` // Detected harmonic frequencies
	HarmonicAmplitudes  []float64 `json:"harmonic_amplitudes"`  // Harmonic amplitudes
	HarmonicPhases      []float64 `json:"harmonic_phases"`      // Harmonic phases
	HarmonicRatios      []float64 `json:"harmonic_ratios"`      // Individual harmonic ratios

	// Fundamental frequency analysis
	F0Frequency  float64 `json:"f0_frequency"`  // Fundamental frequency
	F0Confidence float64 `json:"f0_confidence"` // F0 detection confidence
	F0Strength   float64 `json:"f0_strength"`   // F0 strength measure

	// Spectral analysis
	SpectralPeaks      []harmonic.SpectralPeak `json:"spectral_peaks"`        // Detected spectral peaks
	NoiseFloor         []float64               `json:"noise_floor"`           // Estimated noise floor
	SignalToNoiseRatio float64                 `json:"signal_to_noise_ratio"` // Overall SNR

	// Quality metrics
	Periodicity float64 `json:"periodicity"` // Periodicity measure
	Harmonicity float64 `json:"harmonicity"` // Harmonicity measure
	Voicing     float64 `json:"voicing"`     // Voicing probability
	Roughness   float64 `json:"roughness"`   // Spectral roughness

	// Temporal analysis
	TemporalStability float64 `json:"temporal_stability"` // Temporal stability
	TemporalCoherence float64 `json:"temporal_coherence"` // Temporal coherence

	// Analysis metadata
	Method            string     `json:"method"`              // Method used
	ProcessingTime    float64    `json:"processing_time"`     // Processing time (ms)
	NumHarmonics      int        `json:"num_harmonics"`       // Number of harmonics found
	AnalysisFreqRange [2]float64 `json:"analysis_freq_range"` // Frequency range analyzed
}

HarmonicRatioResult contains comprehensive harmonic ratio analysis results

type InharmonicityAnalyzer

type InharmonicityAnalyzer struct {
	// contains filtered or unexported fields
}

InharmonicityAnalyzer implements inharmonicity analysis

func NewInharmonicityAnalyzer

func NewInharmonicityAnalyzer(sampleRate int) *InharmonicityAnalyzer

NewInharmonicityAnalyzer creates a new inharmonicity analyzer

func NewInharmonicityAnalyzerWithParams

func NewInharmonicityAnalyzerWithParams(params InharmonicityParams) *InharmonicityAnalyzer

NewInharmonicityAnalyzerWithParams creates analyzer with custom parameters

func (*InharmonicityAnalyzer) AnalyzeFrame

func (ia *InharmonicityAnalyzer) AnalyzeFrame(audioFrame []float64) (InharmonicityResult, error)

AnalyzeFrame analyzes inharmonicity for a single audio frame

func (*InharmonicityAnalyzer) AnalyzeSequence

func (ia *InharmonicityAnalyzer) AnalyzeSequence(audioFrames [][]float64) ([]InharmonicityResult, error)

AnalyzeSequence analyzes inharmonicity for a sequence of audio frames

func (*InharmonicityAnalyzer) GetAverageInharmonicity

func (ia *InharmonicityAnalyzer) GetAverageInharmonicity(results []InharmonicityResult) float64

GetAverageInharmonicity computes average inharmonicity from sequence

func (*InharmonicityAnalyzer) GetF0History

func (ia *InharmonicityAnalyzer) GetF0History() []float64

GetF0History returns the F0 history

func (*InharmonicityAnalyzer) GetHistory

func (ia *InharmonicityAnalyzer) GetHistory() []float64

GetHistory returns the inharmonicity history

func (*InharmonicityAnalyzer) GetParameters

func (ia *InharmonicityAnalyzer) GetParameters() InharmonicityParams

GetParameters returns current parameters

func (*InharmonicityAnalyzer) Initialize

func (ia *InharmonicityAnalyzer) Initialize()

Initialize sets up the analyzer

func (*InharmonicityAnalyzer) Reset

func (ia *InharmonicityAnalyzer) Reset()

Reset resets the analyzer state

func (*InharmonicityAnalyzer) SetParameters

func (ia *InharmonicityAnalyzer) SetParameters(params InharmonicityParams)

SetParameters updates parameters

type InharmonicityMethod

type InharmonicityMethod int

InharmonicityMethod defines different methods for computing inharmonicity

const (
	InharmonicityRailsback         InharmonicityMethod = iota // Railsback curve fitting
	InharmonicityFletcherMunson                               // Fletcher-Munson based
	InharmonicitySpectralDeviation                            // Spectral deviation from harmonics
	InharmonicityPartialTracking                              // Partial tracking method
	InharmonicityBeatPattern                                  // Beat pattern analysis
	InharmonicityStatistical                                  // Statistical deviation
)

type InharmonicityModel

type InharmonicityModel int

InharmonicityModel represents different physical models

const (
	ModelString   InharmonicityModel = iota // String instrument model
	ModelPipe                               // Pipe/wind instrument model
	ModelMembrane                           // Membrane/percussion model
	ModelGeneral                            // General inharmonicity model
)

type InharmonicityParams

type InharmonicityParams struct {
	Method     InharmonicityMethod `json:"method"`
	Model      InharmonicityModel  `json:"model"`
	SampleRate int                 `json:"sample_rate"`
	WindowSize int                 `json:"window_size"`

	// Harmonic analysis parameters
	MaxHarmonics        int     `json:"max_harmonics"`         // Maximum harmonics to analyze
	MinHarmonics        int     `json:"min_harmonics"`         // Minimum harmonics required
	HarmonicTolerance   float64 `json:"harmonic_tolerance"`    // Tolerance for harmonic detection
	MinHarmonicStrength float64 `json:"min_harmonic_strength"` // Minimum harmonic strength

	// Frequency analysis
	MinFreq        float64 `json:"min_freq"`        // Minimum fundamental frequency
	MaxFreq        float64 `json:"max_freq"`        // Maximum fundamental frequency
	FreqResolution float64 `json:"freq_resolution"` // Frequency resolution requirement

	// Inharmonicity calculation
	ReferenceHarmonic int  `json:"reference_harmonic"`  // Reference harmonic (usually 1)
	WeightByAmplitude bool `json:"weight_by_amplitude"` // Weight by harmonic amplitude
	UseLogFrequency   bool `json:"use_log_frequency"`   // Use logarithmic frequency scale

	// Physical model parameters
	StringTension   float64 `json:"string_tension"`   // String tension (for string model)
	StringLength    float64 `json:"string_length"`    // String length
	StringStiffness float64 `json:"string_stiffness"` // String stiffness parameter

	// Statistical parameters
	OutlierThreshold    float64 `json:"outlier_threshold"`     // Threshold for outlier removal
	ConfidenceLevel     float64 `json:"confidence_level"`      // Confidence level for statistics
	UseRobustEstimation bool    `json:"use_robust_estimation"` // Use robust statistical methods

	// Temporal analysis
	UseTemporalTracking bool `json:"use_temporal_tracking"` // Track inharmonicity over time
	TemporalWindow      int  `json:"temporal_window"`       // Window for temporal analysis
}

InharmonicityParams contains parameters for inharmonicity analysis

type InharmonicityResult

type InharmonicityResult struct {
	// Primary inharmonicity measures
	Inharmonicity           float64 `json:"inharmonicity"`            // Overall inharmonicity coefficient
	InharmonicityStdDev     float64 `json:"inharmonicity_std_dev"`    // Standard deviation
	InharmonicityConfidence float64 `json:"inharmonicity_confidence"` // Confidence in measurement

	// Detailed harmonic analysis
	HarmonicDeviations  []float64 `json:"harmonic_deviations"`  // Deviation for each harmonic
	HarmonicFrequencies []float64 `json:"harmonic_frequencies"` // Measured harmonic frequencies
	IdealFrequencies    []float64 `json:"ideal_frequencies"`    // Ideal harmonic frequencies
	HarmonicAmplitudes  []float64 `json:"harmonic_amplitudes"`  // Harmonic amplitudes
	HarmonicNumbers     []int     `json:"harmonic_numbers"`     // Harmonic numbers

	// Fundamental frequency analysis
	F0Frequency  float64 `json:"f0_frequency"`  // Fundamental frequency
	F0Confidence float64 `json:"f0_confidence"` // F0 detection confidence
	F0Stability  float64 `json:"f0_stability"`  // F0 stability measure

	// Physical model parameters
	EstimatedStiffness float64            `json:"estimated_stiffness"` // Estimated string stiffness
	ModelFitQuality    float64            `json:"model_fit_quality"`   // Quality of model fit
	ModelParameters    map[string]float64 `json:"model_parameters"`    // Model-specific parameters

	// Quality metrics
	HarmonicClarity  float64 `json:"harmonic_clarity"`  // Clarity of harmonic structure
	SpectralPurity   float64 `json:"spectral_purity"`   // Spectral purity measure
	PartialCoherence float64 `json:"partial_coherence"` // Coherence of partials

	// Statistical measures
	RSquared   float64 `json:"r_squared"`   // Coefficient of determination
	ChiSquared float64 `json:"chi_squared"` // Chi-squared goodness of fit
	PValue     float64 `json:"p_value"`     // Statistical significance

	// Temporal analysis
	TemporalStability  float64 `json:"temporal_stability"`  // Temporal stability
	InharmonicityTrend float64 `json:"inharmonicity_trend"` // Trend over time

	// Analysis metadata
	Method          string  `json:"method"`           // Method used
	Model           string  `json:"model"`            // Physical model used
	NumHarmonics    int     `json:"num_harmonics"`    // Number of harmonics analyzed
	ProcessingTime  float64 `json:"processing_time"`  // Processing time (ms)
	AnalysisQuality string  `json:"analysis_quality"` // Quality assessment
}

InharmonicityResult contains comprehensive inharmonicity analysis results

type KeyCandidate

type KeyCandidate struct {
	Key        int     `json:"key"`        // Key number (0=C, 1=C#, ..., 11=B)
	Mode       KeyMode `json:"mode"`       // Major or Minor
	KeyName    string  `json:"key_name"`   // Human-readable key name
	Confidence float64 `json:"confidence"` // Confidence score (0-1)
	Strength   float64 `json:"strength"`   // Key strength measure
	Profile    string  `json:"profile"`    // Profile used for detection
}

KeyCandidate represents a potential key with confidence

type KeyEstimationBatch

type KeyEstimationBatch struct {
	// contains filtered or unexported fields
}

KeyEstimationBatch processes multiple chroma vectors for batch key estimation

func NewKeyEstimationBatch

func NewKeyEstimationBatch(sampleRate int) *KeyEstimationBatch

NewKeyEstimationBatch creates a new batch processor

func (*KeyEstimationBatch) GetGlobalKey

func (keb *KeyEstimationBatch) GetGlobalKey() KeyEstimationResult

GetGlobalKey estimates the global key from batch results

func (*KeyEstimationBatch) GetKeyProgression

func (keb *KeyEstimationBatch) GetKeyProgression() []KeyTransition

GetKeyProgression analyzes the key progression through the batch

func (*KeyEstimationBatch) ProcessBatch

func (keb *KeyEstimationBatch) ProcessBatch(chromaSequence []chroma.ChromaVector) []KeyEstimationResult

ProcessBatch processes a batch of chroma vectors

type KeyEstimationMethod

type KeyEstimationMethod int

KeyEstimationMethod defines different key estimation approaches

const (
	KeyMethodProfile KeyEstimationMethod = iota
	KeyMethodCorrelation
	KeyMethodBayesian
	KeyMethodHMM
	KeyMethodDeepLearning
)

type KeyEstimationParams

type KeyEstimationParams struct {
	Method          KeyEstimationMethod `json:"method"`
	Profile         KeyProfile          `json:"profile"`
	HPCPSize        int                 `json:"hpcp_size"`        // Size of HPCP vector (12, 24, 36)
	UseHarmonics    bool                `json:"use_harmonics"`    // Consider harmonic content
	WeightHarmonics bool                `json:"weight_harmonics"` // Weight harmonics differently

	// Preprocessing
	NormalizeChroma bool `json:"normalize_chroma"` // Normalize input chroma
	RemoveMean      bool `json:"remove_mean"`      // Remove mean from chroma
	UsePolyphony    bool `json:"use_polyphony"`    // Consider polyphonic content

	// Analysis parameters
	MinConfidence   float64 `json:"min_confidence"`   // Minimum confidence threshold
	MaxCandidates   int     `json:"max_candidates"`   // Maximum candidates to return
	ProfileStrength float64 `json:"profile_strength"` // Profile weighting strength

	// Temporal analysis
	UseTemporalSmoothing bool `json:"use_temporal_smoothing"` // Enable temporal smoothing
	TemporalWindow       int  `json:"temporal_window"`        // Frames for temporal analysis

	// Advanced options
	UseDetuningCorrection  bool `json:"use_detuning_correction"` // Correct for detuning
	TranspositionInvariant bool `json:"transposition_invariant"` // Find best transposition
	BinaryMode             bool `json:"binary_mode"`             // Use binary chroma vectors
}

KeyEstimationParams contains parameters for key estimation

type KeyEstimationResult

type KeyEstimationResult struct {
	// Primary key information
	Key        int     `json:"key"`        // Best key estimate (0-11)
	Mode       KeyMode `json:"mode"`       // Major or Minor
	KeyName    string  `json:"key_name"`   // Human-readable name (e.g., "C major")
	Confidence float64 `json:"confidence"` // Overall confidence (0-1)
	Strength   float64 `json:"strength"`   // Key strength measure

	// Multiple key candidates
	Candidates []KeyCandidate `json:"candidates"`

	// Analysis details
	ChromaVector      []float64 `json:"chroma_vector"`      // Input chroma profile
	KeyProfile        string    `json:"key_profile"`        // Profile type used
	Method            string    `json:"method"`             // Estimation method
	CorrelationScores []float64 `json:"correlation_scores"` // Correlation with each key

	// Quality metrics
	Clarity   float64 `json:"clarity"`   // Key clarity measure
	Ambiguity float64 `json:"ambiguity"` // Key ambiguity measure
	Stability float64 `json:"stability"` // Temporal stability

	// Additional analysis
	RelatedKeys []KeyCandidate `json:"related_keys"` // Closely related keys
	Modulations []int          `json:"modulations"`  // Detected modulation points
	Tonality    float64        `json:"tonality"`     // Overall tonality strength

	// Computational details
	ProcessTime float64 `json:"process_time"` // Processing time in ms
	HPCPSize    int     `json:"hpcp_size"`    // HPCP vector size used
}

KeyEstimationResult contains comprehensive key estimation results

type KeyEstimator

type KeyEstimator struct {
	// contains filtered or unexported fields
}

KeyEstimator implements musical key estimation algorithms

func NewKeyEstimator

func NewKeyEstimator(sampleRate int) *KeyEstimator

NewKeyEstimator creates a new key estimator with default parameters

func NewKeyEstimatorWithParams

func NewKeyEstimatorWithParams(sampleRate int, params KeyEstimationParams) *KeyEstimator

NewKeyEstimatorWithParams creates a key estimator with custom parameters

func (*KeyEstimator) EstimateKey

func (ke *KeyEstimator) EstimateKey(chromaVector chroma.ChromaVector) KeyEstimationResult

EstimateKey estimates musical key from chroma vector

func (*KeyEstimator) EstimateKeyFromHPCP

func (ke *KeyEstimator) EstimateKeyFromHPCP(hpcpResult chroma.HPCPResult) KeyEstimationResult

EstimateKeyFromHPCP estimates key directly from HPCP result

func (*KeyEstimator) EstimateKeySequence

func (ke *KeyEstimator) EstimateKeySequence(chromaSequence []chroma.ChromaVector) KeyEstimationResult

EstimateKeySequence estimates key from a sequence of chroma vectors

func (*KeyEstimator) GetKeyHistory

func (ke *KeyEstimator) GetKeyHistory() []KeyCandidate

GetKeyHistory returns the key estimation history

func (*KeyEstimator) GetParameters

func (ke *KeyEstimator) GetParameters() KeyEstimationParams

GetParameters returns current parameters

func (*KeyEstimator) Initialize

func (ke *KeyEstimator) Initialize()

Initialize sets up the key estimator

func (*KeyEstimator) Reset

func (ke *KeyEstimator) Reset()

Reset resets the estimator state

func (*KeyEstimator) SetParameters

func (ke *KeyEstimator) SetParameters(params KeyEstimationParams)

SetParameters updates parameters

type KeyMode

type KeyMode int

KeyMode represents major or minor mode

const (
	KeyModeMajor KeyMode = iota
	KeyModeMinor
)

func GetDominantKey

func GetDominantKey(key int, mode KeyMode) (int, KeyMode)

GetDominantKey returns the dominant key (5th above)

func GetParallelKey

func GetParallelKey(key int, mode KeyMode) (int, KeyMode)

GetParallelKey returns the parallel major/minor key

func GetRelativeKey

func GetRelativeKey(key int, mode KeyMode) (int, KeyMode)

GetRelativeKey returns the relative major/minor key

func GetSubdominantKey

func GetSubdominantKey(key int, mode KeyMode) (int, KeyMode)

GetSubdominantKey returns the subdominant key (5th below)

type KeyProfile

type KeyProfile int

KeyProfile represents different key detection profiles

const (
	KeyProfileKrumhansl KeyProfile = iota
	KeyProfileTemperley
	KeyProfileShaath
	KeyProfileEDMA
	KeyProfileBgate
	KeyProfileDiatonic
	KeyProfileTonicTriad
)

type KeyProfileTemplate

type KeyProfileTemplate struct {
	MajorProfile []float64 `json:"major_profile"`
	MinorProfile []float64 `json:"minor_profile"`
	Name         string    `json:"name"`
	Description  string    `json:"description"`
}

KeyProfileTemplate contains template for key profile

type KeyTransition

type KeyTransition struct {
	FromKey        int     `json:"from_key"`
	FromMode       KeyMode `json:"from_mode"`
	ToKey          int     `json:"to_key"`
	ToMode         KeyMode `json:"to_mode"`
	Frame          int     `json:"frame"`
	Confidence     float64 `json:"confidence"`
	TransitionType string  `json:"transition_type"`
}

KeyTransition represents a key transition in the progression

type PitchCandidate

type PitchCandidate struct {
	Frequency  float64 `json:"frequency"`  // Frequency in Hz
	Confidence float64 `json:"confidence"` // Confidence score (0-1)
	Salience   float64 `json:"salience"`   // Perceptual salience
	Harmonic   int     `json:"harmonic"`   // Harmonic number (1=fundamental)
	Method     string  `json:"method"`     // Detection method used
}

PitchCandidate represents a potential pitch with confidence

type PitchDetectionMethod

type PitchDetectionMethod int

PitchDetectionMethod represents different pitch detection algorithms

const (
	// Autocorrelation-based methods
	AutocorrelationYin PitchDetectionMethod = iota
	AutocorrelationACF
	AutocorrelationNSDF

	// Frequency domain methods
	FrequencyDomainHPS // Harmonic Product Spectrum
	FrequencyDomainCepstrum
	FrequencyDomainPeaks

	// Time domain methods
	TimeDomainZeroCrossing
	TimeDomainPeakPicking

	// Hybrid methods
	HybridYinFFT
	HybridMPM    // McLeod Pitch Method
	HybridPRAATT // PRAAT-style algorithm
)

type PitchDetectionParams

type PitchDetectionParams struct {
	Method     PitchDetectionMethod `json:"method"`
	SampleRate int                  `json:"sample_rate"`
	WindowSize int                  `json:"window_size"`
	HopSize    int                  `json:"hop_size"`

	// Frequency range constraints
	MinFreq float64 `json:"min_freq"` // Minimum frequency (Hz)
	MaxFreq float64 `json:"max_freq"` // Maximum frequency (Hz)

	// Algorithm-specific parameters
	YinThreshold      float64 `json:"yin_threshold"` // YIN threshold (0.1-0.5)
	AutocorrThreshold float64 `json:"autocorr_threshold"`
	CepstralThreshold float64 `json:"cepstral_threshold"`

	// Quality thresholds
	MinConfidence    float64 `json:"min_confidence"`    // Minimum confidence threshold
	MinSalience      float64 `json:"min_salience"`      // Minimum salience threshold
	VoicingThreshold float64 `json:"voicing_threshold"` // Voicing threshold

	// Harmonic analysis
	MaxHarmonics      int     `json:"max_harmonics"`      // Maximum harmonics to analyze
	HarmonicTolerance float64 `json:"harmonic_tolerance"` // Harmonic frequency tolerance

	// Preprocessing options
	PreEmphasis    bool   `json:"pre_emphasis"`    // Apply pre-emphasis
	WindowFunction string `json:"window_function"` // Window function type
	ZeroPadding    int    `json:"zero_padding"`    // Zero padding factor

	// Post-processing options
	MedianFilter      int  `json:"median_filter"` // Median filter length
	TemporalSmoothing bool `json:"temporal_smoothing"`
	OctaveCorrection  bool `json:"octave_correction"`
}

PitchDetectionParams contains parameters for pitch detection

type PitchDetectionResult

type PitchDetectionResult struct {
	// Primary pitch information
	Pitch      float64 `json:"pitch"`      // Best pitch estimate (Hz)
	Confidence float64 `json:"confidence"` // Overall confidence (0-1)
	Salience   float64 `json:"salience"`   // Perceptual salience
	Voicing    float64 `json:"voicing"`    // Voicing probability (0-1)

	// Multiple pitch candidates
	Candidates []PitchCandidate `json:"candidates"`

	// Pitch stability measures
	Stability   float64 `json:"stability"`   // Pitch stability over time
	Periodicity float64 `json:"periodicity"` // Periodicity strength

	// Harmonic analysis
	Harmonics  []PitchCandidate `json:"harmonics"`   // Detected harmonics
	F0Multiple float64          `json:"f0_multiple"` // F0 multiple factor

	// Quality metrics
	SNR      float64 `json:"snr"`      // Signal-to-noise ratio
	Clarity  float64 `json:"clarity"`  // Pitch clarity measure
	Strength float64 `json:"strength"` // Pitch strength

	// Algorithm-specific data
	YinThreshold  float64   `json:"yin_threshold"`  // YIN threshold used
	AutocorrPeaks []float64 `json:"autocorr_peaks"` // Autocorrelation peaks
	CepstralPeak  float64   `json:"cepstral_peak"`  // Cepstral peak location
	HarmonicRatio float64   `json:"harmonic_ratio"` // Harmonic-to-noise ratio

	// Computational details
	Method      PitchDetectionMethod `json:"method"`
	SampleRate  int                  `json:"sample_rate"`
	WindowSize  int                  `json:"window_size"`
	ProcessTime float64              `json:"process_time"` // Processing time in ms
}

PitchDetectionResult contains comprehensive pitch detection results

type PitchDetector

type PitchDetector struct {
	// contains filtered or unexported fields
}

PitchDetector implements comprehensive pitch detection algorithms

References: - de Cheveigné, A., Kawahara, H. (2002). "YIN, a fundamental frequency estimator for speech and music" - Boersma, P. (1993). "Accurate short-term analysis of the fundamental frequency" - McLeod, P., Wyvill, G. (2005). "A smarter way to find pitch" - Rabiner, L.R. (1977). "On the use of autocorrelation analysis for pitch detection" - Noll, A.M. (1967). "Cepstrum pitch determination" - Schroeder, M.R. (1968). "Period histogram and product spectrum" - Talkin, D. (1995). "A robust algorithm for pitch tracking (RAPT)"

Pitch detection is fundamental for: - Music transcription and analysis - Audio synthesis and processing - Speech analysis and recognition - Audio effects and processing - Music information retrieval

func NewPitchDetector

func NewPitchDetector(sampleRate int) *PitchDetector

NewPitchDetector creates a new pitch detector with default parameters

func NewPitchDetectorWithParams

func NewPitchDetectorWithParams(params PitchDetectionParams) *PitchDetector

NewPitchDetectorWithParams creates a pitch detector with custom parameters

func (*PitchDetector) AnalyzePitchStability

func (pd *PitchDetector) AnalyzePitchStability(pitchSequence []float64) map[string]float64

AnalyzePitchStability analyzes pitch stability over time

func (*PitchDetector) DetectPitch

func (pd *PitchDetector) DetectPitch(audioFrame []float64) (*PitchDetectionResult, error)

DetectPitch detects pitch in a single audio frame

func (*PitchDetector) GetConfidenceHistory

func (pd *PitchDetector) GetConfidenceHistory() []float64

GetConfidenceHistory returns the confidence history

func (*PitchDetector) GetParameters

func (pd *PitchDetector) GetParameters() PitchDetectionParams

GetParameters returns the current parameters

func (*PitchDetector) GetPitchHistory

func (pd *PitchDetector) GetPitchHistory() []float64

GetPitchHistory returns the pitch history

func (*PitchDetector) ProcessAudioStream

func (pd *PitchDetector) ProcessAudioStream(audioFrames [][]float64) ([]*PitchDetectionResult, error)

ProcessAudioStream processes a stream of audio frames

func (*PitchDetector) Reset

func (pd *PitchDetector) Reset()

Reset resets the pitch detector state

func (*PitchDetector) SetParameters

func (pd *PitchDetector) SetParameters(params PitchDetectionParams)

SetParameters updates the detector parameters

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL