oxyde 0.1.10

AI Agent SDK for Game NPCs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use crate::oxyde_game::emotion::EmotionalState;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;

/// Audio cache management module.
pub mod audio_cache;
/// Emotion modeling module.
pub mod emotion;
/// TTS providers module.
pub mod providers;
/// Voice profiles module.
pub mod voice_profiles;

pub use audio_cache::*;
// pub use emotion::EmotionalState;
pub use providers::*;
pub use voice_profiles::*;

/// Represents audio data generated by TTS synthesis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AudioData {
    /// The format of the audio (e.g., MP3, WAV).
    pub format: AudioFormat,
    /// Raw audio bytes.
    pub data: Vec<u8>,
    /// Sample rate of the audio in Hz.
    pub sample_rate: u32,
    /// Number of audio channels.
    pub channels: u8,
    /// Duration of the audio in milliseconds.
    pub duration_ms: u32,
}

impl AudioData {
    /// Returns the size of the audio data in bytes.
    pub fn size_bytes(&self) -> usize {
        self.data.len()
    }
}

/// Represents the settings for voice synthesis.
#[derive(Debug, Clone)]
pub struct TTSService {
    /// The TTS provider being used (ElevenLabs).
    provider: TTSProvider,
    /// Shared audio cache for storing synthesized audio.
    pub cache: Arc<RwLock<AudioCache>>,
    /// Shared voice profiles for NPCs.
    voice_profiles: Arc<RwLock<HashMap<String, VoiceProfile>>>,
    /// Configuration for the TTS service.
    config: TTSConfig,
}

/// Represents the TTS provider to use.
/// Currently, only ElevenLabs is supported.
/// This enum can be extended in the future to support more providers.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum TTSProvider {
    /// ElevenLabs TTS provider.
    ElevenLabs,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
/// Configuration for the TTS service.
/// This struct defines the settings for the TTS service, including the default provider,
pub struct TTSConfig {
    /// The default TTS provider to use.
    /// This can be set to ElevenLabs or any other supported provider in the future.
    pub default_provider: TTSProvider,

    /// Whether to enable caching of audio data.
    /// Caching can improve performance by avoiding repeated synthesis of the same text.
    pub cache_enabled: bool,

    /// Maximum size of the audio cache in megabytes.
    /// This limits the amount of audio data that can be cached to prevent excessive memory usage.
    pub cache_max_size_mb: usize,

    /// Default voice settings for TTS synthesis.
    /// These settings define the characteristics of the voice used for synthesis.
    pub voice_speed: f32,

    /// Default voice volume for TTS synthesis.
    pub voice_pitch: f32,

    /// Default voice volume for TTS synthesis.
    pub enable_ssml: bool,

    /// The output audio format for TTS synthesis.
    pub output_format: AudioFormat,
}

#[derive(Debug, Clone, Serialize, Deserialize)]

/// Represents the audio format used in TTS synthesis.
/// Currently, only MP3 is supported. can update this to support more formats in the future.
pub enum AudioFormat {
    /// MP3 audio format.
    MP3,
}

impl TTSService {
    /// Create a new TTS service instance with the specified provider and configuration.
    /// This initializes the TTS service with the given provider and configuration settings.
    pub fn new(provider: TTSProvider, config: TTSConfig) -> Self {
        Self {
            provider,
            cache: Arc::new(RwLock::new(AudioCache::new(config.cache_max_size_mb))),
            voice_profiles: Arc::new(RwLock::new(HashMap::new())),
            config,
        }
    }

    /// Main method: Convert NPC dialogue to speech with emotional context
    pub async fn synthesize_npc_speech(
        &self,
        npc_name: &str,
        text: &str,
        emotional_state: &EmotionalState, // Use the main SDK's EmotionalState
        urgency: f32,
    ) -> Result<AudioData, TTSError> {
        // Check cache first
        let cache_key = self.generate_cache_key(npc_name, text, emotional_state);
        if self.config.cache_enabled {
            let mut cache = self.cache.write().await;
            if let Some(cached_audio) = cache.get(&cache_key) {
                return Ok(cached_audio);
            }
        }

        // Get voice profile for this NPC
        let voice_profile = self.get_voice_profile(npc_name).await;

        // Apply emotional modulation to voice settings
        let voice_settings =
            self.modulate_voice_for_emotion(&voice_profile, emotional_state, urgency);

        // Enhance text with SSML for emotional expression
        let enhanced_text = if self.config.enable_ssml {
            self.add_emotional_ssml(text, emotional_state, urgency)
        } else {
            text.to_string()
        };

        // Generate speech with ElevenLabs
        let audio_data = match self.provider {
            TTSProvider::ElevenLabs => {
                self.elevenlabs_synthesize(&enhanced_text, &voice_settings)
                    .await?
            }
        };

        // Cache the result
        if self.config.cache_enabled {
            let mut cache = self.cache.write().await;
            cache.insert(cache_key, audio_data.clone());
        }

        Ok(audio_data)
    }

    /// Simplified voice profile creation
    pub async fn create_voice_profile_for_npc(
        &self,
        npc_name: &str,
        personality: &str,
    ) -> VoiceProfile {
        let voice_profile = VoiceProfile {
            npc_name: npc_name.to_string(),
            base_voice: BaseVoice {
                voice_id: "default".to_string(),
                base_pitch: 0.5,
                base_rate: 0.5,
                base_volume: 0.7,
            },
            emotional_range: EmotionalVoiceRange::from_personality(personality),
        };

        // Store the profile
        let mut profiles = self.voice_profiles.write().await;
        profiles.insert(npc_name.to_string(), voice_profile.clone());

        voice_profile
    }

    // Simplified emotional modulation (only using basic VoiceSettings)
    fn modulate_voice_for_emotion(
        &self,
        base_profile: &VoiceProfile,
        e: &EmotionalState,
        _urgency: f32, // Unused for now
    ) -> VoiceSettings {
        let mut settings = VoiceSettings::from_profile(base_profile);

        let joy = (e.joy + 1.0) * 0.5;
        let anger = (e.anger + 1.0) * 0.5;
        let fear = (e.fear + 1.0) * 0.5;
        let trust = (e.trust + 1.0) * 0.5;
        let surprise = (e.surprise + 1.0) * 0.5;
        let sadness = (e.sadness + 1.0) * 0.5;
        let disgust = (e.disgust + 1.0) * 0.5;
        let anticipation = (e.anticipation + 1.0) * 0.5;

        settings.style_exaggeration += 0.25 * joy;
        settings.stability += 0.05 * joy;

        settings.stability -= 0.3 * anger;
        settings.style_exaggeration += 0.1 * anger;

        settings.stability -= 0.2 * fear;
        settings.similarity_boost -= 0.1 * fear;

        settings.stability += 0.2 * sadness;
        settings.style_exaggeration -= 0.1 * sadness;

        settings.style_exaggeration += 0.2 * surprise;

        settings.stability -= 0.15 * disgust;

        settings.style_exaggeration += 0.1 * anticipation;

        settings
    }

    // Add SSML markup for emotional expression
    fn add_emotional_ssml(
        &self,
        text: &str,
        emotions: &EmotionalState, // Use the main SDK's EmotionalState
        urgency: f32,
    ) -> String {
        let mut ssml = String::from("<speak>");

        // Add prosody based on emotions
        let mut prosody_attrs = Vec::new();

        if emotions.joy > 0.6 {
            prosody_attrs.push(format!("rate=\"{:.0}%\"", 100.0 + (emotions.joy * 20.0)));
            prosody_attrs.push(format!("pitch=\"+{:.0}Hz\"", emotions.joy * 30.0));
        }

        if emotions.anger > 0.5 {
            prosody_attrs.push(format!("rate=\"{:.0}%\"", 100.0 + (emotions.anger * 25.0)));
            prosody_attrs.push(format!(
                "volume=\"{:.0}%\"",
                100.0 + (emotions.anger * 15.0)
            ));
        }

        if emotions.fear > 0.5 {
            prosody_attrs.push(format!("pitch=\"+{:.0}Hz\"", emotions.fear * 40.0));
            prosody_attrs.push(format!("rate=\"{:.0}%\"", 100.0 - (emotions.fear * 10.0)));
        }

        if urgency > 0.5 {
            prosody_attrs.push(format!("rate=\"{:.0}%\"", 100.0 + (urgency * 30.0)));
        }

        if !prosody_attrs.is_empty() {
            ssml.push_str(&format!("<prosody {}>", prosody_attrs.join(" ")));
            ssml.push_str(text);
            ssml.push_str("</prosody>");
        } else {
            ssml.push_str(text);
        }

        ssml.push_str("</speak>");
        ssml
    }

    async fn elevenlabs_synthesize(
        &self,
        text: &str,
        settings: &VoiceSettings,
    ) -> Result<AudioData, TTSError> {
        let client = reqwest::Client::new();
        let api_key = std::env::var("ELEVENLABS_API_KEY")
            .map_err(|_| TTSError::MissingApiKey("ElevenLabs"))?;

        // Use a valid ElevenLabs voice ID
        let voice_id = if settings.voice_id == "default" {
            "21m00Tcm4TlvDq8ikWAM" // Rachel - a real ElevenLabs voice ID
        } else {
            &settings.voice_id
        };

        let request_body = serde_json::json!({
            "text": text,
            "model_id": "eleven_monolingual_v1",
            "voice_settings": {
                "stability": settings.stability,
                "similarity_boost": settings.similarity_boost,
                "style": settings.style_exaggeration,
                "use_speaker_boost": true
            }
        });

        let url = format!("https://api.elevenlabs.io/v1/text-to-speech/{}", voice_id);

        let response = client
            .post(&url)
            .header("Accept", "audio/mpeg")
            .header("xi-api-key", api_key)
            .header("Content-Type", "application/json")
            .json(&request_body)
            .send()
            .await
            .map_err(|e| TTSError::Network(e))?;

        let status = response.status();
        let headers = response.headers().clone();
        let audio_bytes = response.bytes().await.map_err(|e| TTSError::Network(e))?;

        if !status.is_success() {
            let error_text = String::from_utf8_lossy(&audio_bytes);
            return Err(TTSError::ApiError(format!(
                "ElevenLabs API error ({}): {}",
                status, error_text
            )));
        }

        if let Some(content_type) = headers.get("content-type") {
            let content_type_str = content_type.to_str().unwrap_or("");
            if !content_type_str.starts_with("audio/") {
                let error_text = String::from_utf8_lossy(&audio_bytes);
                return Err(TTSError::ApiError(format!(
                    "Expected audio content but received '{}': {}",
                    content_type_str, error_text
                )));
            }
        }

        if audio_bytes.len() < 100 {
            let text_content = String::from_utf8_lossy(&audio_bytes);
            return Err(TTSError::ApiError(format!(
                "Response too small ({} bytes), likely an error: {}",
                audio_bytes.len(),
                text_content
            )));
        }

        if audio_bytes.len() >= 3 {
            let has_id3 = &audio_bytes[0..3] == b"ID3";
            let has_mp3_sync = audio_bytes.len() >= 2
                && (audio_bytes[0] == 0xFF && (audio_bytes[1] & 0xE0) == 0xE0);

            if !has_id3 && !has_mp3_sync {
                let text_content =
                    String::from_utf8_lossy(&audio_bytes[0..100.min(audio_bytes.len())]);
                if text_content.contains("error") || text_content.contains("detail") {
                    return Err(TTSError::ApiError(format!(
                        "Received error response instead of audio: {}",
                        text_content
                    )));
                }
                log::warn!("Audio data doesn't have standard MP3 headers but proceeding");
            }
        }

        Ok(AudioData {
            format: AudioFormat::MP3,
            data: audio_bytes.to_vec(),
            sample_rate: 22050,
            channels: 1,
            duration_ms: self.estimate_duration(text),
        })
    }

    fn estimate_duration(&self, text: &str) -> u32 {
        // Rough estimate: ~150 words per minute average speaking rate
        let word_count = text.split_whitespace().count();
        let minutes = word_count as f32 / 150.0;
        (minutes * 60.0 * 1000.0) as u32 // Convert to milliseconds
    }

    async fn get_voice_profile(&self, npc_name: &str) -> VoiceProfile {
        let profiles = self.voice_profiles.read().await;
        profiles
            .get(npc_name)
            .cloned()
            .unwrap_or_else(|| VoiceProfile::default_for_npc(npc_name))
    }

    fn generate_cache_key(
        &self,
        npc_name: &str,
        text: &str,
        emotions: &EmotionalState, // Use the main SDK's EmotionalState
    ) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        npc_name.hash(&mut hasher);
        text.hash(&mut hasher);

        // Round emotions to avoid too many cache misses
        let rounded_emotions = (
            (emotions.joy * 10.0).round() as i32,
            (emotions.anger * 10.0).round() as i32,
            (emotions.fear * 10.0).round() as i32,
            // (emotions.energy * 10.0).round() as i32,
        );
        rounded_emotions.hash(&mut hasher);

        format!("tts_{:x}", hasher.finish())
    }
}