subx-cli 1.6.0

AI subtitle processing CLI tool, which automatically matches, renames, and converts subtitle files.
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
411
412
413
414
415
416
417
418
419
//! Refactored sync engine with VAD (Voice Activity Detection) support.
//!
//! This module provides unified subtitle synchronization functionality using
//! local VAD (Voice Activity Detection) for voice detection and sync offset calculation.

use log::{debug, warn};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::path::Path;
use std::time::{Duration, Instant};

use crate::config::SyncConfig;
use crate::core::formats::Subtitle;
use crate::services::vad::VadSyncDetector;
use crate::{Result, error::SubXError};

/// Unified sync engine based on VAD voice detection.
///
/// This engine provides automatic subtitle synchronization using Voice Activity
/// Detection (VAD) to analyze audio tracks and calculate optimal sync offsets.
pub struct SyncEngine {
    config: SyncConfig,
    vad_detector: Option<VadSyncDetector>,
}

impl SyncEngine {
    /// Create a new sync engine instance.
    ///
    /// # Arguments
    ///
    /// * `config` - Sync configuration containing VAD settings and thresholds
    ///
    /// # Returns
    ///
    /// A new sync engine instance with initialized VAD detector if enabled.
    pub fn new(config: SyncConfig) -> Result<Self> {
        let vad_detector = if config.vad.enabled {
            match VadSyncDetector::new(config.vad.clone()) {
                Ok(det) => {
                    debug!(
                        "[SyncEngine] VAD detector initialized successfully with config: {:?}",
                        config.vad
                    );
                    Some(det)
                }
                Err(e) => {
                    warn!("[SyncEngine] VAD initialization failed: {}", e);
                    None
                }
            }
        } else {
            debug!("[SyncEngine] VAD is disabled in config");
            None
        };

        if vad_detector.is_none() {
            warn!("[SyncEngine] VAD detector is required but not available");
            return Err(SubXError::config(
                "VAD detector is required but not available",
            ));
        }

        debug!("[SyncEngine] SyncEngine created with VAD detector");
        Ok(Self {
            config,
            vad_detector,
        })
    }

    /// Detect sync offset using automatic or specified method.
    ///
    /// # Arguments
    ///
    /// * `audio_path` - Path to the audio file for analysis
    /// * `subtitle` - Subtitle data to synchronize
    /// * `method` - Optional sync method, defaults to automatic detection
    ///
    /// # Returns
    ///
    /// Sync result containing offset, confidence, and processing metadata.
    pub async fn detect_sync_offset(
        &self,
        audio_path: &Path,
        subtitle: &Subtitle,
        method: Option<SyncMethod>,
    ) -> Result<SyncResult> {
        debug!(
            "[SyncEngine] detect_sync_offset called | audio_path: {:?}, subtitle entries: {}, method: {:?}",
            audio_path,
            subtitle.entries.len(),
            method
        );
        let start = Instant::now();
        let m = method.unwrap_or_else(|| self.determine_default_method());
        debug!("[SyncEngine] Using sync method: {:?}", m);
        let mut res = match m {
            SyncMethod::Auto | SyncMethod::LocalVad => {
                self.vad_detect_sync_offset(audio_path, subtitle).await?
            }
            SyncMethod::Manual => {
                debug!("[SyncEngine] Manual method selected but not supported in this context");
                return Err(SubXError::config("Manual method requires explicit offset"));
            }
        };
        res.processing_duration = start.elapsed();
        debug!(
            "[SyncEngine] detect_sync_offset finished | offset_seconds: {:.3}, confidence: {:.3}, duration_ms: {}",
            res.offset_seconds,
            res.confidence,
            res.processing_duration.as_millis()
        );
        Ok(res)
    }

    async fn auto_detect_sync_offset(
        &self,
        audio_path: &Path,
        subtitle: &Subtitle,
    ) -> Result<SyncResult> {
        debug!(
            "[SyncEngine] auto_detect_sync_offset called | audio_path: {:?}, subtitle entries: {}",
            audio_path,
            subtitle.entries.len()
        );
        // Auto mode uses VAD
        if self.vad_detector.is_some() {
            return self.vad_detect_sync_offset(audio_path, subtitle).await;
        }
        Err(SubXError::audio_processing(
            "No detector available in auto mode",
        ))
    }

    /// Apply manual offset to subtitle timing.
    ///
    /// # Arguments
    ///
    /// * `subtitle` - Mutable subtitle data to modify
    /// * `offset_seconds` - Offset in seconds (positive delays, negative advances)
    ///
    /// # Returns
    ///
    /// Sync result with the applied offset and full confidence.
    ///
    /// # Errors
    ///
    /// Returns an error if the offset exceeds the configured maximum.
    pub fn apply_manual_offset(
        &self,
        subtitle: &mut Subtitle,
        offset_seconds: f32,
    ) -> Result<SyncResult> {
        debug!(
            "[SyncEngine] apply_manual_offset called | offset_seconds: {:.3}, entries: {}",
            offset_seconds,
            subtitle.entries.len()
        );
        // Validate offset against max_offset_seconds configuration
        if offset_seconds.abs() > self.config.max_offset_seconds {
            warn!(
                "[SyncEngine] Offset {:.2}s exceeds maximum allowed value {:.2}s. Aborting.",
                offset_seconds, self.config.max_offset_seconds
            );
            return Err(SubXError::config(format!(
                "Offset {:.2}s exceeds maximum allowed value {:.2}s. Please check the sync.max_offset_seconds configuration or use a smaller offset.",
                offset_seconds, self.config.max_offset_seconds
            )));
        }

        let start = Instant::now();
        for entry in &mut subtitle.entries {
            let offset_dur = Duration::from_secs_f32(offset_seconds.abs());
            if offset_seconds >= 0.0 {
                entry.start_time = entry.start_time.checked_add(offset_dur).ok_or_else(|| {
                    SubXError::audio_processing("Invalid offset results in negative time")
                })?;
                entry.end_time = entry.end_time.checked_add(offset_dur).ok_or_else(|| {
                    SubXError::audio_processing("Invalid offset results in negative time")
                })?;
            } else {
                // For negative offsets, clamp times to zero instead of erroring on underflow
                entry.start_time = if entry.start_time > offset_dur {
                    entry.start_time - offset_dur
                } else {
                    Duration::ZERO
                };
                entry.end_time = if entry.end_time > offset_dur {
                    entry.end_time - offset_dur
                } else {
                    Duration::ZERO
                };
            }
        }
        debug!(
            "[SyncEngine] Manual offset applied to all entries | offset_seconds: {:.3}",
            offset_seconds
        );
        Ok(SyncResult {
            offset_seconds,
            confidence: 1.0,
            method_used: SyncMethod::Manual,
            correlation_peak: 1.0,
            additional_info: Some(json!({
                "applied_offset": offset_seconds,
                "entries_modified": subtitle.entries.len(),
            })),
            processing_duration: start.elapsed(),
            warnings: Vec::new(),
        })
    }

    fn determine_default_method(&self) -> SyncMethod {
        debug!(
            "[SyncEngine] determine_default_method called | config.default_method: {}",
            self.config.default_method
        );
        match self.config.default_method.as_str() {
            "vad" => SyncMethod::LocalVad,
            _ => SyncMethod::Auto,
        }
    }

    async fn vad_detect_sync_offset(
        &self,
        audio_path: &Path,
        subtitle: &Subtitle,
    ) -> Result<SyncResult> {
        debug!(
            "[SyncEngine] vad_detect_sync_offset called | audio_path: {:?}, subtitle entries: {}",
            audio_path,
            subtitle.entries.len()
        );
        let det = self
            .vad_detector
            .as_ref()
            .ok_or_else(|| SubXError::audio_processing("VAD detector not available"))?;

        let mut result = det.detect_sync_offset(audio_path, subtitle, 0).await?; // analysis_window_seconds no longer used

        // Validate detected offset against max_offset_seconds configuration
        if result.offset_seconds.abs() > self.config.max_offset_seconds {
            warn!(
                "[SyncEngine] Detected offset {:.2}s exceeds configured maximum value {:.2}s. Clamping and warning.",
                result.offset_seconds, self.config.max_offset_seconds
            );

            // Provide warning but don't completely fail, allow user to decide
            result.warnings.push(format!(
                "Detected offset {:.2}s exceeds configured maximum value {:.2}s. Consider checking audio quality or adjusting sync.max_offset_seconds configuration.",
                result.offset_seconds, self.config.max_offset_seconds
            ));

            // Optionally: clamp to maximum value (preserving sign)
            let sign = if result.offset_seconds >= 0.0 {
                1.0
            } else {
                -1.0
            };
            let original_offset = result.offset_seconds;
            result.offset_seconds = sign * self.config.max_offset_seconds;

            result.additional_info = Some(json!({
                "original_offset": original_offset,
                "clamped_offset": result.offset_seconds,
                "reason": "Exceeded max_offset_seconds configuration"
            }));
        } else {
            debug!(
                "[SyncEngine] VAD sync offset detected | offset_seconds: {:.3}, confidence: {:.3}",
                result.offset_seconds, result.confidence
            );
        }

        Ok(result)
    }
}

/// Sync method enumeration.
///
/// Defines the available methods for subtitle synchronization,
/// from automatic detection to manual offset specification.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum SyncMethod {
    /// Automatic method selection (currently VAD only).
    Auto,
    /// Local VAD (Voice Activity Detection) processing.
    LocalVad,
    /// Manual offset specification.
    Manual,
}

/// Synchronization result structure.
///
/// Contains the complete results of subtitle synchronization analysis,
/// including calculated offset, confidence metrics, and processing metadata.
#[derive(Debug, Clone)]
pub struct SyncResult {
    /// Calculated time offset in seconds
    pub offset_seconds: f32,
    /// Confidence level of the detection (0.0-1.0)
    pub confidence: f32,
    /// Synchronization method that was used
    pub method_used: SyncMethod,
    /// Peak correlation value from analysis
    pub correlation_peak: f32,
    /// Additional method-specific information
    pub additional_info: Option<serde_json::Value>,
    /// Time taken to complete the analysis
    pub processing_duration: Duration,
    /// Any warnings generated during processing
    pub warnings: Vec<String>,
}

/// Method selection strategy for synchronization analysis.
///
/// Defines preferences and fallback behavior for automatic method selection
/// when multiple synchronization approaches are available.
#[derive(Debug, Clone)]
pub struct MethodSelectionStrategy {
    /// Preferred methods in order of preference
    pub preferred_methods: Vec<SyncMethod>,
    /// Minimum confidence threshold for accepting results
    pub min_confidence_threshold: f32,
    /// Whether to allow fallback to alternative methods
    pub allow_fallback: bool,
    /// Maximum time to spend on analysis attempts
    pub max_attempt_duration: u32,
}

// Unit test module: Supplement sync engine core behavior verification
#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{TestConfigBuilder, TestConfigService, service::ConfigService};
    use crate::core::formats::{Subtitle, SubtitleEntry, SubtitleFormatType, SubtitleMetadata};
    use std::time::Duration;

    #[tokio::test]
    async fn test_sync_engine_creation() {
        let config = TestConfigBuilder::new()
            .with_vad_enabled(true)
            .build_config();
        let config_service = TestConfigService::new(config);
        let result = SyncEngine::new(config_service.get_config().unwrap().sync);
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_manual_offset_application() {
        let config = TestConfigBuilder::new().build_config();
        let config_service = TestConfigService::new(config);
        let engine = SyncEngine::new(config_service.get_config().unwrap().sync).unwrap();

        let mut subtitle = create_test_subtitle();
        let original_start = subtitle.entries[0].start_time;

        let result = engine.apply_manual_offset(&mut subtitle, 2.5).unwrap();
        assert_eq!(result.offset_seconds, 2.5);
        assert_eq!(result.method_used, SyncMethod::Manual);
        assert_eq!(result.confidence, 1.0);

        let expected_start = original_start + Duration::from_secs_f32(2.5);
        assert_eq!(subtitle.entries[0].start_time, expected_start);
    }

    #[tokio::test]
    async fn test_manual_offset_negative_application() {
        let config = TestConfigBuilder::new().build_config();
        let config_service = TestConfigService::new(config);
        let engine = SyncEngine::new(config_service.get_config().unwrap().sync).unwrap();

        let mut subtitle = create_test_subtitle();
        let original_start = subtitle.entries[0].start_time;

        let result = engine.apply_manual_offset(&mut subtitle, -2.5).unwrap();
        assert_eq!(result.offset_seconds, -2.5);

        let expected_start = original_start - Duration::from_secs_f32(2.5);
        assert_eq!(subtitle.entries[0].start_time, expected_start);
    }

    #[tokio::test]
    async fn test_determine_default_method() {
        let test_cases = vec![("vad", SyncMethod::LocalVad), ("unknown", SyncMethod::Auto)];

        for (config_value, expected_method) in test_cases {
            let config = TestConfigBuilder::new()
                .with_sync_method(config_value)
                .build_config();
            let engine = SyncEngine::new(config.sync).unwrap();
            assert_eq!(engine.determine_default_method(), expected_method);
        }
    }

    #[tokio::test]
    async fn test_method_selection_strategy_struct() {
        let strategy = MethodSelectionStrategy {
            preferred_methods: vec![SyncMethod::LocalVad],
            min_confidence_threshold: 0.7,
            allow_fallback: true,
            max_attempt_duration: 60,
        };
        assert_eq!(strategy.preferred_methods.len(), 1);
        assert!(strategy.allow_fallback);
    }

    fn create_test_subtitle() -> Subtitle {
        Subtitle {
            entries: vec![SubtitleEntry::new(
                1,
                Duration::from_secs(10),
                Duration::from_secs(12),
                "Test subtitle".to_string(),
            )],
            metadata: SubtitleMetadata::default(),
            format: SubtitleFormatType::Srt,
        }
    }
}