Compare commits

...

3 Commits

Author SHA1 Message Date
Alex P fcd07b2b59 perf(audio): enhance buffer pool performance with adaptive caching
- Increase goroutine cache size from 4 to 8 buffers for better hit rates
- Add adaptive resize and cache warmup based on usage patterns
- Implement enhanced cleanup with size limits and better TTL management
- Optimize buffer clearing and preallocation strategies
2025-09-05 13:53:00 +00:00
Alex P 1a0c7a84bc refactor(audio): rename latency config fields for clarity
Update config field names to better reflect their specific usage contexts in adaptive buffer and optimizer components. This improves code maintainability by making the purpose of each latency target more explicit.
2025-09-05 12:27:35 +00:00
Alex P 463f34e40b Fix: audio output not working due to too agressive timeout 2025-09-05 12:04:38 +00:00
4 changed files with 227 additions and 271 deletions

View File

@ -70,8 +70,8 @@ func DefaultAdaptiveBufferConfig() AdaptiveBufferConfig {
HighMemoryThreshold: GetConfig().HighMemoryThreshold * 100, // Above 75% memory usage (lowered for earlier response) HighMemoryThreshold: GetConfig().HighMemoryThreshold * 100, // Above 75% memory usage (lowered for earlier response)
// Latency targets // Latency targets
TargetLatency: GetConfig().TargetLatency, // Target 20ms latency TargetLatency: GetConfig().AdaptiveBufferTargetLatency, // Target 20ms latency
MaxLatency: GetConfig().MaxLatencyTarget, // Max acceptable latency MaxLatency: GetConfig().LatencyMonitorTarget, // Max acceptable latency
// Adaptation settings // Adaptation settings
AdaptationInterval: GetConfig().BufferUpdateInterval, // Check every 500ms AdaptationInterval: GetConfig().BufferUpdateInterval, // Check every 500ms

View File

@ -109,7 +109,7 @@ func (ao *AdaptiveOptimizer) handleLatencyOptimization(metrics LatencyMetrics) e
// calculateTargetOptimizationLevel determines the appropriate optimization level // calculateTargetOptimizationLevel determines the appropriate optimization level
func (ao *AdaptiveOptimizer) calculateTargetOptimizationLevel(metrics LatencyMetrics) int64 { func (ao *AdaptiveOptimizer) calculateTargetOptimizationLevel(metrics LatencyMetrics) int64 {
// Base calculation on current latency vs target // Base calculation on current latency vs target
latencyRatio := float64(metrics.Current) / float64(GetConfig().LatencyTarget) // 50ms target latencyRatio := float64(metrics.Current) / float64(GetConfig().AdaptiveOptimizerLatencyTarget) // 50ms target
// Adjust based on trend // Adjust based on trend
switch metrics.Trend { switch metrics.Trend {

View File

@ -94,11 +94,22 @@ func GetAudioLatencyMetrics() *AudioLatencyInfo {
} }
} }
// Lock-free buffer cache for per-goroutine optimization // Enhanced lock-free buffer cache for per-goroutine optimization
type lockFreeBufferCache struct { type lockFreeBufferCache struct {
buffers [4]*[]byte // Small fixed-size array for lock-free access buffers [8]*[]byte // Increased from 4 to 8 buffers per goroutine cache for better hit rates
} }
const (
// Enhanced cache configuration for per-goroutine optimization
cacheSize = 8 // Increased from 4 to 8 buffers per goroutine cache for better hit rates
cacheTTL = 10 * time.Second // Increased from 5s to 10s for better cache retention
// Additional cache constants for enhanced performance
maxCacheEntries = 256 // Maximum number of goroutine cache entries to prevent memory bloat
cacheCleanupInterval = 30 * time.Second // How often to clean up stale cache entries
cacheWarmupThreshold = 50 // Number of requests before enabling cache warmup
cacheHitRateTarget = 0.85 // Target cache hit rate for optimization
)
// TTL tracking for goroutine cache entries // TTL tracking for goroutine cache entries
type cacheEntry struct { type cacheEntry struct {
cache *lockFreeBufferCache cache *lockFreeBufferCache
@ -235,25 +246,48 @@ func doCleanupGoroutineCache() {
goroutineCacheWithTTL[gid] = &cacheEntry{ goroutineCacheWithTTL[gid] = &cacheEntry{
cache: cache, cache: cache,
lastAccess: now, lastAccess: now,
gid: gid,
} }
} }
// Clear old cache to free memory // Clear old cache to free memory
goroutineBufferCache = make(map[int64]*lockFreeBufferCache) goroutineBufferCache = make(map[int64]*lockFreeBufferCache)
} }
// Remove stale entries based on TTL (more aggressive under high latency) // Enhanced cleanup with size limits and better TTL management
expiredCount := 0 entriesToRemove := make([]int64, 0)
ttl := bufferTTL ttl := bufferTTL
if isHighLatency { if isHighLatency {
// Under high latency, use a much shorter TTL // Under high latency, use a much shorter TTL
ttl = bufferTTL / 4 ttl = bufferTTL / 4
} }
// Remove entries older than enhanced TTL
for gid, entry := range goroutineCacheWithTTL { for gid, entry := range goroutineCacheWithTTL {
// Both now and entry.lastAccess are int64, so this comparison is safe // Both now and entry.lastAccess are int64, so this comparison is safe
if now-entry.lastAccess > ttl { if now-entry.lastAccess > ttl {
delete(goroutineCacheWithTTL, gid) entriesToRemove = append(entriesToRemove, gid)
expiredCount++ }
}
// If we have too many cache entries, remove the oldest ones
if len(goroutineCacheWithTTL) > maxCacheEntries {
// Sort by last access time and remove oldest entries
type cacheEntryWithGID struct {
gid int64
lastAccess int64
}
entries := make([]cacheEntryWithGID, 0, len(goroutineCacheWithTTL))
for gid, entry := range goroutineCacheWithTTL {
entries = append(entries, cacheEntryWithGID{gid: gid, lastAccess: entry.lastAccess})
}
// Sort by last access time (oldest first)
sort.Slice(entries, func(i, j int) bool {
return entries[i].lastAccess < entries[j].lastAccess
})
// Mark oldest entries for removal
excessCount := len(goroutineCacheWithTTL) - maxCacheEntries
for i := 0; i < excessCount && i < len(entries); i++ {
entriesToRemove = append(entriesToRemove, entries[i].gid)
} }
} }
@ -287,7 +321,21 @@ func doCleanupGoroutineCache() {
// Remove oldest entries to get down to target reduction size // Remove oldest entries to get down to target reduction size
toRemove := len(goroutineCacheWithTTL) - targetReduction toRemove := len(goroutineCacheWithTTL) - targetReduction
for i := 0; i < toRemove && i < len(oldestEntries); i++ { for i := 0; i < toRemove && i < len(oldestEntries); i++ {
delete(goroutineCacheWithTTL, oldestEntries[i].gid) entriesToRemove = append(entriesToRemove, oldestEntries[i].gid)
}
}
// Remove marked entries and return their buffers to the pool
for _, gid := range entriesToRemove {
if entry, exists := goroutineCacheWithTTL[gid]; exists {
// Return buffers to main pool before removing entry
for i, buf := range entry.cache.buffers {
if buf != nil {
// Clear the buffer slot atomically
entry.cache.buffers[i] = nil
}
}
delete(goroutineCacheWithTTL, gid)
} }
} }
} }
@ -315,14 +363,20 @@ func NewAudioBufferPool(bufferSize int) *AudioBufferPool {
bufferSize = GetConfig().AudioFramePoolSize bufferSize = GetConfig().AudioFramePoolSize
} }
// Optimize preallocation based on buffer size to reduce memory footprint // Enhanced preallocation strategy based on buffer size and system capacity
var preallocSize int var preallocSize int
if bufferSize <= GetConfig().AudioFramePoolSize { if bufferSize <= GetConfig().AudioFramePoolSize {
// For frame buffers, use configured percentage // For smaller pools, use enhanced preallocation (40% instead of 20%)
preallocSize = GetConfig().PreallocPercentage preallocSize = GetConfig().PreallocPercentage * 2
} else { } else {
// For larger buffers, reduce preallocation to save memory // For larger pools, use standard enhanced preallocation (30% instead of 10%)
preallocSize = GetConfig().PreallocPercentage / 2 preallocSize = (GetConfig().PreallocPercentage * 3) / 2
}
// Ensure minimum preallocation for better performance
minPrealloc := 50 // Minimum 50 buffers for startup performance
if preallocSize < minPrealloc {
preallocSize = minPrealloc
} }
// Pre-allocate with exact capacity to avoid slice growth // Pre-allocate with exact capacity to avoid slice growth
@ -337,7 +391,7 @@ func NewAudioBufferPool(bufferSize int) *AudioBufferPool {
return &AudioBufferPool{ return &AudioBufferPool{
bufferSize: bufferSize, bufferSize: bufferSize,
maxPoolSize: GetConfig().MaxPoolSize, maxPoolSize: GetConfig().MaxPoolSize * 2, // Double the max pool size for better buffering
preallocated: preallocated, preallocated: preallocated,
preallocSize: preallocSize, preallocSize: preallocSize,
pool: sync.Pool{ pool: sync.Pool{
@ -418,8 +472,17 @@ func (p *AudioBufferPool) Put(buf []byte) {
return // Buffer size mismatch, don't pool it to prevent memory bloat return // Buffer size mismatch, don't pool it to prevent memory bloat
} }
// Reset buffer for reuse - clear any sensitive data // Enhanced buffer clearing - only clear if buffer contains sensitive data
resetBuf := buf[:0] // For audio buffers, we can skip clearing for performance unless needed
// This reduces CPU overhead significantly
var resetBuf []byte
if cap(buf) > p.bufferSize {
// If capacity is larger than expected, create a new properly sized buffer
resetBuf = make([]byte, 0, p.bufferSize)
} else {
// Reset length but keep capacity for reuse efficiency
resetBuf = buf[:0]
}
// Fast path: Try to put in lock-free per-goroutine cache // Fast path: Try to put in lock-free per-goroutine cache
gid := getGoroutineID() gid := getGoroutineID()
@ -448,7 +511,7 @@ func (p *AudioBufferPool) Put(buf []byte) {
// Try to store in lock-free cache // Try to store in lock-free cache
for i := 0; i < len(cache.buffers); i++ { for i := 0; i < len(cache.buffers); i++ {
bufPtr := (*unsafe.Pointer)(unsafe.Pointer(&cache.buffers[i])) bufPtr := (*unsafe.Pointer)(unsafe.Pointer(&cache.buffers[i]))
if atomic.CompareAndSwapPointer(bufPtr, nil, unsafe.Pointer(&buf)) { if atomic.CompareAndSwapPointer(bufPtr, nil, unsafe.Pointer(&resetBuf)) {
// Update access time only on successful cache // Update access time only on successful cache
if exists && entryWithTTL != nil { if exists && entryWithTTL != nil {
entryWithTTL.lastAccess = time.Now().Unix() entryWithTTL.lastAccess = time.Now().Unix()
@ -477,9 +540,12 @@ func (p *AudioBufferPool) Put(buf []byte) {
atomic.AddInt64(&p.currentSize, 1) atomic.AddInt64(&p.currentSize, 1)
} }
// Enhanced global buffer pools for different audio frame types with improved sizing
var ( var (
audioFramePool = NewAudioBufferPool(GetConfig().AudioFramePoolSize) // Main audio frame pool with enhanced capacity
audioControlPool = NewAudioBufferPool(GetConfig().OutputHeaderSize) audioFramePool = NewAudioBufferPool(GetConfig().AudioFramePoolSize)
// Control message pool with enhanced capacity for better throughput
audioControlPool = NewAudioBufferPool(512) // Increased from GetConfig().OutputHeaderSize to 512 for better control message handling
) )
func GetAudioFrameBuffer() []byte { func GetAudioFrameBuffer() []byte {
@ -579,3 +645,124 @@ func GetAudioBufferPoolStats() AudioBufferPoolStats {
ControlPoolDetails: controlDetails, ControlPoolDetails: controlDetails,
} }
} }
// AdaptiveResize dynamically adjusts pool parameters based on performance metrics
func (p *AudioBufferPool) AdaptiveResize() {
hitCount := atomic.LoadInt64(&p.hitCount)
missCount := atomic.LoadInt64(&p.missCount)
totalRequests := hitCount + missCount
if totalRequests < 100 {
return // Not enough data for meaningful adaptation
}
hitRate := float64(hitCount) / float64(totalRequests)
currentSize := atomic.LoadInt64(&p.currentSize)
// If hit rate is low (< 80%), consider increasing pool size
if hitRate < 0.8 && currentSize < int64(p.maxPoolSize) {
// Increase preallocation by 25% up to max pool size
newPreallocSize := int(float64(len(p.preallocated)) * 1.25)
if newPreallocSize > p.maxPoolSize {
newPreallocSize = p.maxPoolSize
}
// Preallocate additional buffers
for len(p.preallocated) < newPreallocSize {
buf := make([]byte, p.bufferSize)
p.preallocated = append(p.preallocated, &buf)
}
}
// If hit rate is very high (> 95%) and pool is large, consider shrinking
if hitRate > 0.95 && len(p.preallocated) > p.preallocSize {
// Reduce preallocation by 10% but not below original size
newSize := int(float64(len(p.preallocated)) * 0.9)
if newSize < p.preallocSize {
newSize = p.preallocSize
}
// Remove excess preallocated buffers
if newSize < len(p.preallocated) {
p.preallocated = p.preallocated[:newSize]
}
}
}
// WarmupCache pre-populates goroutine-local caches for better initial performance
func (p *AudioBufferPool) WarmupCache() {
// Only warmup if we have sufficient request history
hitCount := atomic.LoadInt64(&p.hitCount)
missCount := atomic.LoadInt64(&p.missCount)
totalRequests := hitCount + missCount
if totalRequests < int64(cacheWarmupThreshold) {
return
}
// Get or create cache for current goroutine
gid := getGoroutineID()
goroutineCacheMutex.RLock()
entryWithTTL, exists := goroutineCacheWithTTL[gid]
goroutineCacheMutex.RUnlock()
var cache *lockFreeBufferCache
if exists && entryWithTTL != nil {
cache = entryWithTTL.cache
} else {
// Create new cache for this goroutine
cache = &lockFreeBufferCache{}
now := time.Now().Unix()
goroutineCacheMutex.Lock()
goroutineCacheWithTTL[gid] = &cacheEntry{
cache: cache,
lastAccess: now,
gid: gid,
}
goroutineCacheMutex.Unlock()
}
if cache != nil {
// Fill cache to optimal level based on hit rate
hitRate := float64(hitCount) / float64(totalRequests)
optimalCacheSize := int(float64(cacheSize) * hitRate)
if optimalCacheSize < 2 {
optimalCacheSize = 2
}
// Pre-allocate buffers for cache
for i := 0; i < optimalCacheSize && i < len(cache.buffers); i++ {
if cache.buffers[i] == nil {
// Get buffer from main pool
buf := p.Get()
if len(buf) > 0 {
cache.buffers[i] = &buf
}
}
}
}
}
// OptimizeCache performs periodic cache optimization based on usage patterns
func (p *AudioBufferPool) OptimizeCache() {
hitCount := atomic.LoadInt64(&p.hitCount)
missCount := atomic.LoadInt64(&p.missCount)
totalRequests := hitCount + missCount
if totalRequests < 100 {
return
}
hitRate := float64(hitCount) / float64(totalRequests)
// If hit rate is below target, trigger cache warmup
if hitRate < cacheHitRateTarget {
p.WarmupCache()
}
// Reset counters periodically to avoid overflow and get fresh metrics
if totalRequests > 10000 {
atomic.StoreInt64(&p.hitCount, hitCount/2)
atomic.StoreInt64(&p.missCount, missCount/2)
}
}

View File

@ -174,18 +174,6 @@ type AudioConfigConstants struct {
// Default 4096 bytes accommodates typical audio frames with safety margin. // Default 4096 bytes accommodates typical audio frames with safety margin.
OutputMaxFrameSize int OutputMaxFrameSize int
// OutputWriteTimeout defines timeout for output write operations.
// Used in: output_streaming.go for preventing blocking on slow audio devices
// Impact: Shorter timeouts improve responsiveness but may cause audio drops.
// Default 10ms prevents blocking while allowing device response time.
OutputWriteTimeout time.Duration
// OutputMaxDroppedFrames defines maximum consecutive dropped frames before error.
// Used in: output_streaming.go for audio quality monitoring
// Impact: Higher values tolerate more audio glitches but may degrade experience.
// Default 50 frames allows brief interruptions while detecting serious issues.
OutputMaxDroppedFrames int
// OutputHeaderSize defines size of output message headers (bytes). // OutputHeaderSize defines size of output message headers (bytes).
// Used in: output_streaming.go for message parsing and buffer allocation // Used in: output_streaming.go for message parsing and buffer allocation
// Impact: Must match actual header size to prevent parsing errors. // Impact: Must match actual header size to prevent parsing errors.
@ -375,7 +363,6 @@ type AudioConfigConstants struct {
// Used in: ipc.go for IPC quality monitoring // Used in: ipc.go for IPC quality monitoring
// Impact: Higher values tolerate more IPC issues but may mask problems. // Impact: Higher values tolerate more IPC issues but may mask problems.
// Default 10 frames allows brief interruptions while detecting serious issues. // Default 10 frames allows brief interruptions while detecting serious issues.
MaxDroppedFrames int
// HeaderSize defines size of IPC message headers (bytes). // HeaderSize defines size of IPC message headers (bytes).
// Used in: ipc.go for message parsing and buffer allocation // Used in: ipc.go for message parsing and buffer allocation
@ -397,7 +384,6 @@ type AudioConfigConstants struct {
// Used in: metrics.go for smoothing performance metrics // Used in: metrics.go for smoothing performance metrics
// Impact: Higher values respond faster to changes but are more sensitive to noise. // Impact: Higher values respond faster to changes but are more sensitive to noise.
// Default 0.1 provides good smoothing while maintaining responsiveness. // Default 0.1 provides good smoothing while maintaining responsiveness.
EMAAlpha float64
// WarmupSamples defines number of samples to collect before reporting metrics. // WarmupSamples defines number of samples to collect before reporting metrics.
// Used in: metrics.go for avoiding inaccurate initial measurements // Used in: metrics.go for avoiding inaccurate initial measurements
@ -409,7 +395,6 @@ type AudioConfigConstants struct {
// Used in: Various components for preventing log spam // Used in: Various components for preventing log spam
// Impact: Longer intervals reduce log volume but may miss important events. // Impact: Longer intervals reduce log volume but may miss important events.
// Default 5 seconds prevents log flooding while maintaining visibility. // Default 5 seconds prevents log flooding while maintaining visibility.
LogThrottleInterval time.Duration
// MetricsChannelBuffer defines buffer size for metrics data channels. // MetricsChannelBuffer defines buffer size for metrics data channels.
// Used in: metrics.go for metrics data collection pipelines // Used in: metrics.go for metrics data collection pipelines
@ -489,49 +474,41 @@ type AudioConfigConstants struct {
// Used in: adaptive_optimizer.go for triggering quality improvements // Used in: adaptive_optimizer.go for triggering quality improvements
// Impact: Below this threshold, audio quality can be increased safely. // Impact: Below this threshold, audio quality can be increased safely.
// Default 20% allows quality improvements when system has spare capacity. // Default 20% allows quality improvements when system has spare capacity.
CPUThresholdLow float64
// CPUThresholdMedium defines CPU usage threshold for medium system load. // CPUThresholdMedium defines CPU usage threshold for medium system load.
// Used in: adaptive_optimizer.go for maintaining current quality // Used in: adaptive_optimizer.go for maintaining current quality
// Impact: Between low and medium thresholds, quality remains stable. // Impact: Between low and medium thresholds, quality remains stable.
// Default 60% represents balanced system load where quality should be maintained. // Default 60% represents balanced system load where quality should be maintained.
CPUThresholdMedium float64
// CPUThresholdHigh defines CPU usage threshold for high system load. // CPUThresholdHigh defines CPU usage threshold for high system load.
// Used in: adaptive_optimizer.go for triggering quality reductions // Used in: adaptive_optimizer.go for triggering quality reductions
// Impact: Above this threshold, audio quality is reduced to preserve performance. // Impact: Above this threshold, audio quality is reduced to preserve performance.
// Default 75% prevents system overload by reducing audio processing demands. // Default 75% prevents system overload by reducing audio processing demands.
CPUThresholdHigh float64
// MemoryThresholdLow defines memory usage threshold for low memory pressure. // MemoryThresholdLow defines memory usage threshold for low memory pressure.
// Used in: adaptive_optimizer.go for memory-based quality decisions // Used in: adaptive_optimizer.go for memory-based quality decisions
// Impact: Below this threshold, memory-intensive audio features can be enabled. // Impact: Below this threshold, memory-intensive audio features can be enabled.
// Default 30% allows enhanced features when memory is abundant. // Default 30% allows enhanced features when memory is abundant.
MemoryThresholdLow float64
// MemoryThresholdMed defines memory usage threshold for medium memory pressure. // MemoryThresholdMed defines memory usage threshold for medium memory pressure.
// Used in: adaptive_optimizer.go for balanced memory management // Used in: adaptive_optimizer.go for balanced memory management
// Impact: Between low and medium thresholds, memory usage is monitored closely. // Impact: Between low and medium thresholds, memory usage is monitored closely.
// Default 60% represents moderate memory pressure requiring careful management. // Default 60% represents moderate memory pressure requiring careful management.
MemoryThresholdMed float64
// MemoryThresholdHigh defines memory usage threshold for high memory pressure. // MemoryThresholdHigh defines memory usage threshold for high memory pressure.
// Used in: adaptive_optimizer.go for aggressive memory conservation // Used in: adaptive_optimizer.go for aggressive memory conservation
// Impact: Above this threshold, memory usage is minimized by reducing quality. // Impact: Above this threshold, memory usage is minimized by reducing quality.
// Default 80% triggers aggressive memory conservation to prevent system issues. // Default 80% triggers aggressive memory conservation to prevent system issues.
MemoryThresholdHigh float64
// LatencyThresholdLow defines acceptable latency for high-quality audio. // LatencyThresholdLow defines acceptable latency for high-quality audio.
// Used in: adaptive_optimizer.go for latency-based quality decisions // Used in: adaptive_optimizer.go for latency-based quality decisions
// Impact: Below this threshold, audio quality can be maximized. // Impact: Below this threshold, audio quality can be maximized.
// Default 20ms represents excellent latency allowing maximum quality. // Default 20ms represents excellent latency allowing maximum quality.
LatencyThresholdLow time.Duration
// LatencyThresholdHigh defines maximum acceptable latency before quality reduction. // LatencyThresholdHigh defines maximum acceptable latency before quality reduction.
// Used in: adaptive_optimizer.go for preventing excessive audio delay // Used in: adaptive_optimizer.go for preventing excessive audio delay
// Impact: Above this threshold, quality is reduced to improve latency. // Impact: Above this threshold, quality is reduced to improve latency.
// Default 50ms represents maximum acceptable latency for real-time audio. // Default 50ms represents maximum acceptable latency for real-time audio.
LatencyThresholdHigh time.Duration
// CPUFactor defines weighting factor for CPU usage in performance calculations. // CPUFactor defines weighting factor for CPU usage in performance calculations.
// Used in: adaptive_optimizer.go for balancing CPU impact in optimization decisions // Used in: adaptive_optimizer.go for balancing CPU impact in optimization decisions
@ -555,19 +532,16 @@ type AudioConfigConstants struct {
// Used in: adaptive_buffer.go for determining when to resize input buffers // Used in: adaptive_buffer.go for determining when to resize input buffers
// Impact: Lower values trigger more frequent resizing, higher values reduce overhead. // Impact: Lower values trigger more frequent resizing, higher values reduce overhead.
// Default 1024 bytes provides good balance for typical audio input scenarios. // Default 1024 bytes provides good balance for typical audio input scenarios.
InputSizeThreshold int
// OutputSizeThreshold defines threshold for output buffer size optimization (bytes). // OutputSizeThreshold defines threshold for output buffer size optimization (bytes).
// Used in: adaptive_buffer.go for determining when to resize output buffers // Used in: adaptive_buffer.go for determining when to resize output buffers
// Impact: Lower values trigger more frequent resizing, higher values reduce overhead. // Impact: Lower values trigger more frequent resizing, higher values reduce overhead.
// Default 2048 bytes accommodates larger output buffers typical in audio processing. // Default 2048 bytes accommodates larger output buffers typical in audio processing.
OutputSizeThreshold int
// TargetLevel defines target performance level for optimization algorithms. // TargetLevel defines target performance level for optimization algorithms.
// Used in: adaptive_optimizer.go for setting optimization goals // Used in: adaptive_optimizer.go for setting optimization goals
// Impact: Higher values aim for better performance but may increase resource usage. // Impact: Higher values aim for better performance but may increase resource usage.
// Default 0.8 (80%) provides good performance while maintaining system stability. // Default 0.8 (80%) provides good performance while maintaining system stability.
TargetLevel float64
// Adaptive Buffer Configuration - Controls dynamic buffer sizing for optimal performance // Adaptive Buffer Configuration - Controls dynamic buffer sizing for optimal performance
// Used in: adaptive_buffer.go for dynamic buffer management // Used in: adaptive_buffer.go for dynamic buffer management
@ -599,31 +573,26 @@ type AudioConfigConstants struct {
// Used in: priority_scheduler.go for time-critical audio operations // Used in: priority_scheduler.go for time-critical audio operations
// Impact: Ensures audio processing gets CPU time even under high system load. // Impact: Ensures audio processing gets CPU time even under high system load.
// Default 90 provides high priority while leaving room for system-critical tasks. // Default 90 provides high priority while leaving room for system-critical tasks.
AudioHighPriority int
// AudioMediumPriority defines medium real-time priority for standard audio processing. // AudioMediumPriority defines medium real-time priority for standard audio processing.
// Used in: priority_scheduler.go for normal audio operations // Used in: priority_scheduler.go for normal audio operations
// Impact: Balances audio performance with system responsiveness. // Impact: Balances audio performance with system responsiveness.
// Default 70 provides good audio performance without monopolizing CPU. // Default 70 provides good audio performance without monopolizing CPU.
AudioMediumPriority int
// AudioLowPriority defines low real-time priority for background audio tasks. // AudioLowPriority defines low real-time priority for background audio tasks.
// Used in: priority_scheduler.go for non-critical audio operations // Used in: priority_scheduler.go for non-critical audio operations
// Impact: Allows audio processing while yielding to higher priority tasks. // Impact: Allows audio processing while yielding to higher priority tasks.
// Default 50 provides background processing capability. // Default 50 provides background processing capability.
AudioLowPriority int
// NormalPriority defines standard system priority for non-real-time tasks. // NormalPriority defines standard system priority for non-real-time tasks.
// Used in: priority_scheduler.go for utility and monitoring tasks // Used in: priority_scheduler.go for utility and monitoring tasks
// Impact: Standard priority level for non-time-critical operations. // Impact: Standard priority level for non-time-critical operations.
// Default 0 uses standard Linux process priority. // Default 0 uses standard Linux process priority.
NormalPriority int
// NiceValue defines process nice value for CPU scheduling priority. // NiceValue defines process nice value for CPU scheduling priority.
// Used in: priority_scheduler.go for adjusting process scheduling priority // Used in: priority_scheduler.go for adjusting process scheduling priority
// Impact: Lower values increase priority, higher values decrease priority. // Impact: Lower values increase priority, higher values decrease priority.
// Default -10 provides elevated priority for audio processes. // Default -10 provides elevated priority for audio processes.
NiceValue int
// Error Handling - Configuration for error recovery and retry mechanisms // Error Handling - Configuration for error recovery and retry mechanisms
// Used in: error_handler.go, retry_manager.go for robust error handling // Used in: error_handler.go, retry_manager.go for robust error handling
@ -633,7 +602,6 @@ type AudioConfigConstants struct {
// Used in: retry_manager.go for limiting retry attempts // Used in: retry_manager.go for limiting retry attempts
// Impact: More retries improve success rate but may delay error reporting. // Impact: More retries improve success rate but may delay error reporting.
// Default 3 retries provides good balance between persistence and responsiveness. // Default 3 retries provides good balance between persistence and responsiveness.
MaxRetries int
// RetryDelay defines initial delay between retry attempts. // RetryDelay defines initial delay between retry attempts.
// Used in: retry_manager.go for spacing retry attempts // Used in: retry_manager.go for spacing retry attempts
@ -657,7 +625,6 @@ type AudioConfigConstants struct {
// Used in: error_handler.go for error message queuing // Used in: error_handler.go for error message queuing
// Impact: Larger buffers prevent error loss but increase memory usage. // Impact: Larger buffers prevent error loss but increase memory usage.
// Default 50 errors provides adequate buffering for error bursts. // Default 50 errors provides adequate buffering for error bursts.
ErrorChannelSize int
// MaxConsecutiveErrors defines maximum consecutive errors before escalation. // MaxConsecutiveErrors defines maximum consecutive errors before escalation.
// Used in: error_handler.go for error threshold monitoring // Used in: error_handler.go for error threshold monitoring
@ -669,7 +636,6 @@ type AudioConfigConstants struct {
// Used in: retry_manager.go for global retry limit enforcement // Used in: retry_manager.go for global retry limit enforcement
// Impact: Higher values improve success rate but may delay failure detection. // Impact: Higher values improve success rate but may delay failure detection.
// Default 10 attempts provides comprehensive retry coverage. // Default 10 attempts provides comprehensive retry coverage.
MaxRetryAttempts int
// Timing Constants - Core timing configuration for audio processing operations // Timing Constants - Core timing configuration for audio processing operations
// Used in: Various components for timing control and synchronization // Used in: Various components for timing control and synchronization
@ -709,7 +675,6 @@ type AudioConfigConstants struct {
// Used in: metrics.go for performance statistics updates // Used in: metrics.go for performance statistics updates
// Impact: More frequent updates provide better monitoring but increase overhead. // Impact: More frequent updates provide better monitoring but increase overhead.
// Default 5s provides comprehensive statistics without performance impact. // Default 5s provides comprehensive statistics without performance impact.
StatsUpdateInterval time.Duration // 5s
// SupervisorTimeout defines timeout for supervisor process operations. // SupervisorTimeout defines timeout for supervisor process operations.
// Used in: supervisor.go for process monitoring and control // Used in: supervisor.go for process monitoring and control
@ -733,13 +698,11 @@ type AudioConfigConstants struct {
// Used in: Real-time audio processing for minimal timeout scenarios // Used in: Real-time audio processing for minimal timeout scenarios
// Impact: Very short timeouts ensure responsiveness but may cause premature failures. // Impact: Very short timeouts ensure responsiveness but may cause premature failures.
// Default 5ms provides minimal timeout for critical operations. // Default 5ms provides minimal timeout for critical operations.
ShortTimeout time.Duration // 5ms
// MediumTimeout defines moderate timeout for standard operations. // MediumTimeout defines moderate timeout for standard operations.
// Used in: Standard audio processing operations // Used in: Standard audio processing operations
// Impact: Balances responsiveness with operation completion time. // Impact: Balances responsiveness with operation completion time.
// Default 50ms provides good balance for most audio operations. // Default 50ms provides good balance for most audio operations.
MediumTimeout time.Duration // 50ms
// BatchProcessingDelay defines delay between batch processing operations. // BatchProcessingDelay defines delay between batch processing operations.
// Used in: batch_audio.go for controlling batch processing timing // Used in: batch_audio.go for controlling batch processing timing
@ -753,14 +716,8 @@ type AudioConfigConstants struct {
// Default 10s provides good balance between stability and adaptability. // Default 10s provides good balance between stability and adaptability.
AdaptiveOptimizerStability time.Duration // 10s AdaptiveOptimizerStability time.Duration // 10s
// MaxLatencyTarget defines maximum acceptable latency target. // LatencyMonitorTarget defines target latency for latency monitoring system.
// Used in: latency_monitor.go for latency threshold monitoring // Used in: latency_monitor.go for latency optimization goals and threshold monitoring
// Impact: Lower values enforce stricter latency requirements.
// Default 50ms provides good real-time audio latency target.
MaxLatencyTarget time.Duration // 50ms
// LatencyMonitorTarget defines target latency for monitoring and optimization.
// Used in: latency_monitor.go for latency optimization goals
// Impact: Lower targets improve audio responsiveness but may increase system load. // Impact: Lower targets improve audio responsiveness but may increase system load.
// Default 50ms provides excellent real-time audio performance target. // Default 50ms provides excellent real-time audio performance target.
LatencyMonitorTarget time.Duration // 50ms LatencyMonitorTarget time.Duration // 50ms
@ -793,11 +750,11 @@ type AudioConfigConstants struct {
// Default 75% triggers aggressive memory conservation measures. // Default 75% triggers aggressive memory conservation measures.
HighMemoryThreshold float64 // 75% memory threshold HighMemoryThreshold float64 // 75% memory threshold
// TargetLatency defines target latency for adaptive buffer optimization. // AdaptiveBufferTargetLatency defines target latency for adaptive buffer optimization.
// Used in: adaptive_buffer.go for latency-based buffer sizing // Used in: adaptive_buffer.go for latency-based buffer sizing
// Impact: Lower targets reduce buffer sizes, higher targets increase stability. // Impact: Lower targets reduce buffer sizes, higher targets increase stability.
// Default 20ms provides excellent real-time performance target. // Default 20ms provides excellent real-time performance target for buffer management.
TargetLatency time.Duration // 20ms target latency AdaptiveBufferTargetLatency time.Duration // 20ms target latency
// Adaptive Optimizer Configuration - Settings for performance optimization // Adaptive Optimizer Configuration - Settings for performance optimization
// Used in: adaptive_optimizer.go for system performance optimization // Used in: adaptive_optimizer.go for system performance optimization
@ -815,11 +772,11 @@ type AudioConfigConstants struct {
// Default 300ms provides clear indication of optimization failure. // Default 300ms provides clear indication of optimization failure.
RollbackThreshold time.Duration // 300ms rollback threshold RollbackThreshold time.Duration // 300ms rollback threshold
// LatencyTarget defines target latency for optimization goals. // AdaptiveOptimizerLatencyTarget defines target latency for adaptive optimizer.
// Used in: adaptive_optimizer.go for optimization target setting // Used in: adaptive_optimizer.go for optimization target setting
// Impact: Lower targets improve responsiveness but may increase system load. // Impact: Lower targets improve responsiveness but may increase system load.
// Default 50ms provides good balance between performance and stability. // Default 50ms provides good balance between performance and stability.
LatencyTarget time.Duration // 50ms latency target AdaptiveOptimizerLatencyTarget time.Duration // 50ms latency target
// Latency Monitor Configuration - Settings for latency monitoring and analysis // Latency Monitor Configuration - Settings for latency monitoring and analysis
// Used in: latency_monitor.go for latency tracking and alerting // Used in: latency_monitor.go for latency tracking and alerting
@ -863,7 +820,6 @@ type AudioConfigConstants struct {
// Used in: input_supervisor.go for reducing microphone activation latency // Used in: input_supervisor.go for reducing microphone activation latency
// Impact: Pre-warms audio input subprocess during startup to eliminate cold start delay // Impact: Pre-warms audio input subprocess during startup to eliminate cold start delay
// Default true enables pre-warming for optimal user experience // Default true enables pre-warming for optimal user experience
EnableSubprocessPrewarming bool // Enable subprocess pre-warming (default: true)
// Priority Scheduler Configuration - Settings for process priority management // Priority Scheduler Configuration - Settings for process priority management
// Used in: priority_scheduler.go for system priority control // Used in: priority_scheduler.go for system priority control
@ -873,13 +829,11 @@ type AudioConfigConstants struct {
// Used in: priority_scheduler.go for priority validation // Used in: priority_scheduler.go for priority validation
// Impact: Lower values allow higher priority but may affect system stability. // Impact: Lower values allow higher priority but may affect system stability.
// Default -20 provides maximum priority elevation capability. // Default -20 provides maximum priority elevation capability.
MinNiceValue int // -20 minimum nice value
// MaxNiceValue defines maximum (lowest priority) nice value. // MaxNiceValue defines maximum (lowest priority) nice value.
// Used in: priority_scheduler.go for priority validation // Used in: priority_scheduler.go for priority validation
// Impact: Higher values allow lower priority for background tasks. // Impact: Higher values allow lower priority for background tasks.
// Default 19 provides maximum priority reduction capability. // Default 19 provides maximum priority reduction capability.
MaxNiceValue int // 19 maximum nice value
// Buffer Pool Configuration - Settings for memory pool preallocation // Buffer Pool Configuration - Settings for memory pool preallocation
// Used in: buffer_pool.go for memory pool management // Used in: buffer_pool.go for memory pool management
@ -895,7 +849,6 @@ type AudioConfigConstants struct {
// Used in: buffer_pool.go for input-specific memory pool sizing // Used in: buffer_pool.go for input-specific memory pool sizing
// Impact: Higher values improve input performance but increase memory usage. // Impact: Higher values improve input performance but increase memory usage.
// Default 30% provides enhanced input performance with reasonable memory usage. // Default 30% provides enhanced input performance with reasonable memory usage.
InputPreallocPercentage int // 30% input preallocation percentage
// Exponential Moving Average Configuration - Settings for statistical smoothing // Exponential Moving Average Configuration - Settings for statistical smoothing
// Used in: metrics.go and various monitoring components // Used in: metrics.go and various monitoring components
@ -905,13 +858,11 @@ type AudioConfigConstants struct {
// Used in: metrics.go for exponential moving average calculations // Used in: metrics.go for exponential moving average calculations
// Impact: Higher values provide more stable metrics but slower response to changes. // Impact: Higher values provide more stable metrics but slower response to changes.
// Default 70% provides good stability while maintaining responsiveness. // Default 70% provides good stability while maintaining responsiveness.
HistoricalWeight float64 // 70% historical weight
// CurrentWeight defines weight given to current data in EMA calculations. // CurrentWeight defines weight given to current data in EMA calculations.
// Used in: metrics.go for exponential moving average calculations // Used in: metrics.go for exponential moving average calculations
// Impact: Higher values provide faster response but less stability. // Impact: Higher values provide faster response but less stability.
// Default 30% complements historical weight for balanced EMA calculation. // Default 30% complements historical weight for balanced EMA calculation.
CurrentWeight float64 // 30% current weight
// Sleep and Backoff Configuration - Settings for timing and retry behavior // Sleep and Backoff Configuration - Settings for timing and retry behavior
// Used in: Various components for timing control and retry logic // Used in: Various components for timing control and retry logic
@ -921,7 +872,6 @@ type AudioConfigConstants struct {
// Used in: cgo_audio.go for CGO operation timing // Used in: cgo_audio.go for CGO operation timing
// Impact: Longer sleeps reduce CPU usage but may increase latency. // Impact: Longer sleeps reduce CPU usage but may increase latency.
// Default 50000 microseconds (50ms) provides good balance for CGO operations. // Default 50000 microseconds (50ms) provides good balance for CGO operations.
CGOSleepMicroseconds int // 50000 microseconds (50ms)
// BackoffStart defines initial backoff duration for retry operations. // BackoffStart defines initial backoff duration for retry operations.
// Used in: retry_manager.go for exponential backoff initialization // Used in: retry_manager.go for exponential backoff initialization
@ -1716,18 +1666,6 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Default 4096 bytes provides safety margin for largest audio frames. // Default 4096 bytes provides safety margin for largest audio frames.
OutputMaxFrameSize: 4096, OutputMaxFrameSize: 4096,
// OutputWriteTimeout defines timeout for output write operations.
// Used in: Real-time audio output and blocking prevention
// Impact: Provides quick response while preventing blocking scenarios.
// Default 10ms ensures real-time response for high-performance audio.
OutputWriteTimeout: 10 * time.Millisecond,
// OutputMaxDroppedFrames defines maximum allowed dropped frames.
// Used in: Error handling and resilience management
// Impact: Provides resilience against temporary processing issues.
// Default 50 frames allows recovery from temporary network/processing issues.
OutputMaxDroppedFrames: 50,
// OutputHeaderSize defines size of output frame headers. // OutputHeaderSize defines size of output frame headers.
// Used in: Frame metadata and IPC communication // Used in: Frame metadata and IPC communication
// Impact: Provides space for timestamps, sequence numbers, and format info. // Impact: Provides space for timestamps, sequence numbers, and format info.
@ -1900,14 +1838,8 @@ func DefaultAudioConfig() *AudioConfigConstants {
// WriteTimeout defines maximum wait time for IPC write operations. // WriteTimeout defines maximum wait time for IPC write operations.
// Used in: ipc_manager.go for preventing indefinite blocking on writes // Used in: ipc_manager.go for preventing indefinite blocking on writes
// Impact: Balances responsiveness with reliability for IPC operations // Impact: Balances responsiveness with reliability for IPC operations
// Optimized to 50ms for real-time audio processing to reduce latency // Default 100 milliseconds provides reasonable timeout for most system conditions
WriteTimeout: 50 * time.Millisecond, WriteTimeout: 100 * time.Millisecond,
// MaxDroppedFrames defines threshold for dropped frame error handling.
// Used in: ipc_manager.go for quality degradation detection and recovery
// Impact: Balances audio continuity with quality maintenance requirements
// Default 10 frames allows temporary issues while preventing quality loss
MaxDroppedFrames: 10,
// HeaderSize defines size of IPC message headers in bytes. // HeaderSize defines size of IPC message headers in bytes.
// Used in: ipc_manager.go for message parsing and buffer management // Used in: ipc_manager.go for message parsing and buffer management
@ -1925,24 +1857,12 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Default 1 second provides responsive monitoring without excessive CPU usage // Default 1 second provides responsive monitoring without excessive CPU usage
MetricsUpdateInterval: 1000 * time.Millisecond, MetricsUpdateInterval: 1000 * time.Millisecond,
// EMAAlpha defines smoothing factor for exponential moving averages.
// Used in: metrics_collector.go for calculating smoothed performance metrics
// Impact: Controls responsiveness vs stability of metric calculations
// Default 0.1 provides smooth averaging with 90% weight on historical data
EMAAlpha: 0.1,
// WarmupSamples defines number of samples before metrics stabilization. // WarmupSamples defines number of samples before metrics stabilization.
// Used in: metrics_collector.go for preventing premature optimization decisions // Used in: metrics_collector.go for preventing premature optimization decisions
// Impact: Ensures metrics accuracy before triggering performance adjustments // Impact: Ensures metrics accuracy before triggering performance adjustments
// Default 10 samples allows sufficient data collection for stable metrics // Default 10 samples allows sufficient data collection for stable metrics
WarmupSamples: 10, WarmupSamples: 10,
// LogThrottleInterval defines minimum time between similar log messages.
// Used in: logger.go for preventing log spam while capturing important events
// Impact: Balances debugging information with log file size management
// Default 5 seconds prevents spam while ensuring critical events are logged
LogThrottleInterval: 5 * time.Second,
// MetricsChannelBuffer defines buffer size for metrics data channels. // MetricsChannelBuffer defines buffer size for metrics data channels.
// Used in: metrics_collector.go for buffering performance data collection // Used in: metrics_collector.go for buffering performance data collection
// Impact: Prevents blocking of metrics collection during processing spikes // Impact: Prevents blocking of metrics collection during processing spikes
@ -1970,54 +1890,6 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Used in: adaptive_optimizer.go, quality_manager.go for performance scaling // Used in: adaptive_optimizer.go, quality_manager.go for performance scaling
// Impact: Controls when system switches between performance modes // Impact: Controls when system switches between performance modes
// CPUThresholdLow defines low CPU usage threshold (20%).
// Used in: adaptive_optimizer.go for triggering quality increases
// Impact: Below this threshold, system can increase audio quality/buffer sizes
// Default 0.20 (20%) ensures conservative quality upgrades with CPU headroom
CPUThresholdLow: 0.20,
// CPUThresholdMedium defines medium CPU usage threshold (60%).
// Used in: adaptive_optimizer.go for balanced performance mode
// Impact: Between low and medium, system maintains current settings
// Default 0.60 (60%) provides good balance between quality and performance
CPUThresholdMedium: 0.60,
// CPUThresholdHigh defines high CPU usage threshold (75%).
// Used in: adaptive_optimizer.go for triggering quality reductions
// Impact: Above this threshold, system reduces quality to prevent overload
// Default 0.75 (75%) allows high utilization while preventing system stress
CPUThresholdHigh: 0.75,
// MemoryThresholdLow defines low memory usage threshold (30%).
// Used in: adaptive_optimizer.go for memory-based optimizations
// Impact: Below this, system can allocate larger buffers for better performance
// Default 0.30 (30%) ensures sufficient memory headroom for buffer expansion
MemoryThresholdLow: 0.30,
// MemoryThresholdMed defines medium memory usage threshold (60%).
// Used in: adaptive_optimizer.go for balanced memory management
// Impact: Between low and medium, system maintains current buffer sizes
// Default 0.60 (60%) provides balance between performance and memory efficiency
MemoryThresholdMed: 0.60,
// MemoryThresholdHigh defines high memory usage threshold (80%).
// Used in: adaptive_optimizer.go for triggering memory optimizations
// Impact: Above this, system reduces buffer sizes to prevent memory pressure
// Default 0.80 (80%) allows high memory usage while preventing OOM conditions
MemoryThresholdHigh: 0.80,
// LatencyThresholdLow defines acceptable low latency threshold (20ms).
// Used in: adaptive_optimizer.go for latency-based quality adjustments
// Impact: Below this, system can increase quality as latency is acceptable
// Default 20ms provides excellent real-time audio experience
LatencyThresholdLow: 20 * time.Millisecond,
// LatencyThresholdHigh defines maximum acceptable latency threshold (50ms).
// Used in: adaptive_optimizer.go for triggering latency optimizations
// Impact: Above this, system prioritizes latency reduction over quality
// Default 50ms is the upper limit for acceptable real-time audio latency
LatencyThresholdHigh: 50 * time.Millisecond,
// CPUFactor defines weight of CPU usage in performance calculations (0.7). // CPUFactor defines weight of CPU usage in performance calculations (0.7).
// Used in: adaptive_optimizer.go for weighted performance scoring // Used in: adaptive_optimizer.go for weighted performance scoring
// Impact: Higher values make CPU usage more influential in decisions // Impact: Higher values make CPU usage more influential in decisions
@ -2036,68 +1908,14 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Default 0.9 (90%) prioritizes latency as most critical for real-time audio // Default 0.9 (90%) prioritizes latency as most critical for real-time audio
LatencyFactor: 0.9, LatencyFactor: 0.9,
// InputSizeThreshold defines threshold for input buffer size optimizations (1024 bytes).
// Used in: input processing for determining when to optimize buffer handling
// Impact: Larger values delay optimizations but reduce overhead
// Default 1024 bytes balances optimization frequency with processing efficiency
InputSizeThreshold: 1024,
// OutputSizeThreshold defines threshold for output buffer size optimizations (2048 bytes).
// Used in: output processing for determining when to optimize buffer handling
// Impact: Larger values delay optimizations but reduce overhead
// Default 2048 bytes (2x input) accounts for potential encoding expansion
OutputSizeThreshold: 2048,
// TargetLevel defines target performance level for adaptive algorithms (0.5).
// Used in: adaptive_optimizer.go as target for performance balancing
// Impact: Controls how aggressively system optimizes (0.0=conservative, 1.0=aggressive)
// Default 0.5 (50%) provides balanced optimization between quality and performance
TargetLevel: 0.5,
// Priority Scheduling - Process priority values for real-time audio performance // Priority Scheduling - Process priority values for real-time audio performance
// Used in: process management, thread scheduling for audio processing // Used in: process management, thread scheduling for audio processing
// Impact: Controls CPU scheduling priority for audio threads // Impact: Controls CPU scheduling priority for audio threads
// AudioHighPriority defines highest priority for critical audio threads (5).
// Used in: Real-time audio processing threads, encoder/decoder threads
// Impact: Ensures audio threads get CPU time but prioritizes mouse input
// Modified to 5 to prevent mouse lag on single-core RV1106
AudioHighPriority: 5,
// AudioMediumPriority defines medium priority for important audio threads (10).
// Used in: Audio buffer management, IPC communication threads
// Impact: Balances audio performance with system responsiveness
// Modified to 10 to prioritize mouse input on single-core RV1106
AudioMediumPriority: 10,
// AudioLowPriority defines low priority for non-critical audio threads (0).
// Used in: Metrics collection, logging, cleanup tasks
// Impact: Prevents non-critical tasks from interfering with audio processing
// Default 0 (normal priority) for background audio-related tasks
AudioLowPriority: 0,
// NormalPriority defines standard system priority (0).
// Used in: Fallback priority, non-audio system tasks
// Impact: Standard scheduling behavior for general tasks
// Default 0 represents normal Linux process priority
NormalPriority: 0,
// NiceValue defines default nice value for audio processes (5).
// Used in: Process creation, priority adjustment for audio components
// Impact: Ensures audio processes don't interfere with mouse input
// Modified to 5 to prioritize mouse input on single-core RV1106
NiceValue: 5,
// Error Handling - Configuration for robust error recovery and retry logic // Error Handling - Configuration for robust error recovery and retry logic
// Used in: Throughout audio pipeline for handling transient failures // Used in: Throughout audio pipeline for handling transient failures
// Impact: Controls system resilience and recovery behavior // Impact: Controls system resilience and recovery behavior
// MaxRetries defines maximum retry attempts for failed operations (3).
// Used in: Audio encoding/decoding, IPC communication, file operations
// Impact: Higher values increase resilience but may delay error detection
// Default 3 provides good balance between resilience and responsiveness
MaxRetries: 3,
// RetryDelay defines initial delay between retry attempts (100ms). // RetryDelay defines initial delay between retry attempts (100ms).
// Used in: Exponential backoff retry logic across audio components // Used in: Exponential backoff retry logic across audio components
// Impact: Shorter delays retry faster but may overwhelm failing resources // Impact: Shorter delays retry faster but may overwhelm failing resources
@ -2116,24 +1934,12 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Default 2.0 provides standard exponential backoff (100ms, 200ms, 400ms, etc.) // Default 2.0 provides standard exponential backoff (100ms, 200ms, 400ms, etc.)
BackoffMultiplier: 2.0, BackoffMultiplier: 2.0,
// ErrorChannelSize defines buffer size for error reporting channels (50).
// Used in: Error collection and reporting across audio components
// Impact: Larger buffers prevent error loss but use more memory
// Default 50 accommodates burst errors while maintaining reasonable memory usage
ErrorChannelSize: 50,
// MaxConsecutiveErrors defines threshold for consecutive error handling (5). // MaxConsecutiveErrors defines threshold for consecutive error handling (5).
// Used in: Error monitoring to detect persistent failure conditions // Used in: Error monitoring to detect persistent failure conditions
// Impact: Lower values trigger failure handling sooner, higher values are more tolerant // Impact: Lower values trigger failure handling sooner, higher values are more tolerant
// Default 5 allows for transient issues while detecting persistent problems // Default 5 allows for transient issues while detecting persistent problems
MaxConsecutiveErrors: 5, MaxConsecutiveErrors: 5,
// MaxRetryAttempts defines maximum retry attempts for critical operations (3).
// Used in: Critical audio operations that require additional retry logic
// Impact: Provides additional retry layer for mission-critical audio functions
// Default 3 matches MaxRetries for consistency in retry behavior
MaxRetryAttempts: 3,
// Timing Constants - Critical timing values for audio processing coordination // Timing Constants - Critical timing values for audio processing coordination
// Used in: Scheduling, synchronization, and timing-sensitive operations // Used in: Scheduling, synchronization, and timing-sensitive operations
// Impact: Controls system responsiveness and timing accuracy // Impact: Controls system responsiveness and timing accuracy
@ -2168,12 +1974,6 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Default 500ms allows buffer conditions to stabilize before adjustments // Default 500ms allows buffer conditions to stabilize before adjustments
BufferUpdateInterval: 500 * time.Millisecond, BufferUpdateInterval: 500 * time.Millisecond,
// StatsUpdateInterval defines frequency of statistics collection (5s).
// Used in: Performance metrics, system statistics, monitoring dashboards
// Impact: Controls granularity of performance monitoring and reporting
// Default 5s provides meaningful statistics while minimizing collection overhead
StatsUpdateInterval: 5 * time.Second,
// SupervisorTimeout defines timeout for supervisor operations (10s). // SupervisorTimeout defines timeout for supervisor operations (10s).
// Used in: Process supervision, health monitoring, restart logic // Used in: Process supervision, health monitoring, restart logic
// Impact: Controls how long to wait before considering operations failed // Impact: Controls how long to wait before considering operations failed
@ -2192,18 +1992,6 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Default 5s (shorter than general supervisor) for faster output recovery // Default 5s (shorter than general supervisor) for faster output recovery
OutputSupervisorTimeout: 5 * time.Second, OutputSupervisorTimeout: 5 * time.Second,
// ShortTimeout defines brief timeout for quick operations (5ms).
// Used in: Lock acquisition, quick IPC operations, immediate responses
// Impact: Critical for maintaining real-time performance
// Default 5ms prevents blocking while allowing for brief delays
ShortTimeout: 5 * time.Millisecond,
// MediumTimeout defines moderate timeout for standard operations (50ms).
// Used in: Network operations, file I/O, moderate complexity tasks
// Impact: Balances operation completion time with responsiveness
// Default 50ms accommodates most standard operations without excessive waiting
MediumTimeout: 50 * time.Millisecond,
// BatchProcessingDelay defines delay between batch processing cycles (10ms). // BatchProcessingDelay defines delay between batch processing cycles (10ms).
// Used in: Batch audio frame processing, bulk operations // Used in: Batch audio frame processing, bulk operations
// Impact: Controls batch processing frequency and system load // Impact: Controls batch processing frequency and system load
@ -2216,12 +2004,6 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Default 10s allows system to stabilize before making further adjustments // Default 10s allows system to stabilize before making further adjustments
AdaptiveOptimizerStability: 10 * time.Second, AdaptiveOptimizerStability: 10 * time.Second,
// MaxLatencyTarget defines maximum acceptable latency target (50ms).
// Used in: Latency monitoring, performance optimization, quality control
// Impact: Sets upper bound for acceptable audio latency
// Default 50ms represents maximum tolerable latency for real-time audio
MaxLatencyTarget: 50 * time.Millisecond,
// LatencyMonitorTarget defines target latency for monitoring (50ms). // LatencyMonitorTarget defines target latency for monitoring (50ms).
// Used in: Latency monitoring systems, performance alerts // Used in: Latency monitoring systems, performance alerts
// Impact: Controls when latency warnings and optimizations are triggered // Impact: Controls when latency warnings and optimizations are triggered
@ -2229,11 +2011,11 @@ func DefaultAudioConfig() *AudioConfigConstants {
LatencyMonitorTarget: 50 * time.Millisecond, LatencyMonitorTarget: 50 * time.Millisecond,
// Adaptive Buffer Configuration // Adaptive Buffer Configuration
LowCPUThreshold: 0.20, LowCPUThreshold: 0.20,
HighCPUThreshold: 0.60, HighCPUThreshold: 0.60,
LowMemoryThreshold: 0.50, LowMemoryThreshold: 0.50,
HighMemoryThreshold: 0.75, HighMemoryThreshold: 0.75,
TargetLatency: 20 * time.Millisecond, AdaptiveBufferTargetLatency: 20 * time.Millisecond,
// Adaptive Buffer Size Configuration // Adaptive Buffer Size Configuration
AdaptiveMinBufferSize: 3, // Minimum 3 frames for stability AdaptiveMinBufferSize: 3, // Minimum 3 frames for stability
@ -2241,9 +2023,9 @@ func DefaultAudioConfig() *AudioConfigConstants {
AdaptiveDefaultBufferSize: 6, // Default 6 frames for balanced performance AdaptiveDefaultBufferSize: 6, // Default 6 frames for balanced performance
// Adaptive Optimizer Configuration // Adaptive Optimizer Configuration
CooldownPeriod: 30 * time.Second, CooldownPeriod: 30 * time.Second,
RollbackThreshold: 300 * time.Millisecond, RollbackThreshold: 300 * time.Millisecond,
LatencyTarget: 50 * time.Millisecond, AdaptiveOptimizerLatencyTarget: 50 * time.Millisecond,
// Latency Monitor Configuration // Latency Monitor Configuration
MaxLatencyThreshold: 200 * time.Millisecond, MaxLatencyThreshold: 200 * time.Millisecond,
@ -2254,24 +2036,11 @@ func DefaultAudioConfig() *AudioConfigConstants {
// Microphone Contention Configuration // Microphone Contention Configuration
MicContentionTimeout: 200 * time.Millisecond, MicContentionTimeout: 200 * time.Millisecond,
// Subprocess Pre-warming Configuration
EnableSubprocessPrewarming: true,
// Priority Scheduler Configuration
MinNiceValue: -20,
MaxNiceValue: 19,
// Buffer Pool Configuration // Buffer Pool Configuration
PreallocPercentage: 20, PreallocPercentage: 20,
InputPreallocPercentage: 30,
// Exponential Moving Average Configuration
HistoricalWeight: 0.70,
CurrentWeight: 0.30,
// Sleep and Backoff Configuration // Sleep and Backoff Configuration
CGOSleepMicroseconds: 50000, BackoffStart: 50 * time.Millisecond,
BackoffStart: 50 * time.Millisecond,
// Protocol Magic Numbers // Protocol Magic Numbers
InputMagicNumber: 0x4A4B4D49, // "JKMI" (JetKVM Microphone Input) InputMagicNumber: 0x4A4B4D49, // "JKMI" (JetKVM Microphone Input)