bckplayer 0.1.0

A cross-platform CLI media player interface for VLC
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
use anyhow::Result;
use reqwest::Client;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use std::process::{Command, Child};
use std::path::Path;
use base64::{Engine as _, engine::general_purpose};
use rand::Rng;

use crate::types::{MediaSource, PlayerState, PlaybackState, ConnectionStatus};
use crate::utils;

pub struct VlcController {
    client: Client,
    base_url: String,
    auth_header: Option<String>,
    state: Arc<Mutex<PlayerState>>,
    _host: String,
    _port: u16,
    _password: String,
    vlc_process: Option<Child>,
}

impl VlcController {
    pub fn new(host: Option<&str>, port: Option<u16>) -> Result<Self> {
        let host = host.unwrap_or("127.0.0.1").to_string();
        let port = port.unwrap_or(8080);
        let base_url = format!("http://{}:{}", host, port);
        
        // Generate a random password
        let password = Self::generate_password();
        
        // Find VLC executable
        let vlc_path = utils::find_vlc_executable()?;
        
        // Start VLC with HTTP interface
        let vlc_process = Self::start_vlc(&vlc_path, &password, port)?;
        
        let client = Client::builder()
            .timeout(Duration::from_secs(5))
            .build()?;

        let connection_status = ConnectionStatus {
            host: host.clone(),
            port,
            password_set: true,
            password: password.clone(),
            ..Default::default()
        };

        let state = PlayerState {
            connection_status,
            ..Default::default()
        };

        // Set up authentication
        let credentials = format!(":{}", password);
        let encoded = general_purpose::STANDARD.encode(credentials.as_bytes());
        let auth_header = Some(format!("Basic {}", encoded));

        let controller = Self {
            client,
            base_url,
            auth_header,
            state: Arc::new(Mutex::new(state)),
            _host: host,
            _port: port,
            _password: password,
            vlc_process: Some(vlc_process),
        };

        // Wait a moment for VLC to start up
        std::thread::sleep(Duration::from_millis(2000));

        Ok(controller)
    }

    fn generate_password() -> String {
        const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        const PASSWORD_LEN: usize = 16;
        let mut rng = rand::thread_rng();

        (0..PASSWORD_LEN)
            .map(|_| {
                let idx = rng.gen_range(0..CHARSET.len());
                CHARSET[idx] as char
            })
            .collect()
    }

    fn start_vlc(vlc_path: &Path, password: &str, port: u16) -> Result<Child> {
        let child = Command::new(vlc_path)
            .args([
                "--intf", "http",
                "--http-password", password,
                "--http-port", &port.to_string(),
                "--http-host", "127.0.0.1",
                "--extraintf", "dummy",
                "--no-video-title-show",
                "--quiet",
                "--fullscreen",
                "--loop"
            ])
            .spawn()
            .map_err(|e| anyhow::anyhow!("Failed to start VLC: {}", e))?;

        Ok(child)
    }

    pub async fn test_connection(&mut self) -> Result<bool> {
        const MAX_RETRIES: u32 = 3;
        let mut last_error = None;
        
        for attempt in 1..=MAX_RETRIES {
            let url = format!("{}/requests/status.xml", self.base_url);
            
            let mut request = self.client.get(&url);
            
            if let Some(ref auth) = self.auth_header {
                request = request.header("Authorization", auth);
            }

            match request.send().await {
                Ok(resp) => {
                    let success = resp.status().is_success();
                    
                    // Update connection status
                    {
                        let mut state = self.state.lock().unwrap();
                        state.connection_status.connected = success;
                        if success {
                            state.connection_status.last_error = None;
                        } else {
                            state.connection_status.last_error = Some(format!("HTTP status: {}", resp.status()));
                        }
                    }
                    
                    if success {
                        return Ok(true);
                    } else {
                        last_error = Some(anyhow::anyhow!("HTTP status: {}", resp.status()));
                    }
                }
                Err(e) => {
                    last_error = Some(anyhow::anyhow!("Connection failed: {}", e));
                }
            }
            
            if attempt < MAX_RETRIES {
                // Wait before retrying
                tokio::time::sleep(Duration::from_millis(200 * attempt as u64)).await;
            }
        }
        
        // Update connection status with final failure
        {
            let mut state = self.state.lock().unwrap();
            state.connection_status.connected = false;
            state.connection_status.last_error = last_error.as_ref().map(|e| e.to_string());
        }

        Ok(false)
    }

    async fn send_command(&self, command: &str, params: Option<&[(&str, &str)]>) -> Result<String> {
        self.send_command_with_retry(command, params, 3).await
    }

    async fn send_command_with_retry(&self, command: &str, params: Option<&[(&str, &str)]>, max_retries: u32) -> Result<String> {
        let mut last_error = None;
        
        for attempt in 1..=max_retries {
            let mut url = format!("{}/requests/status.xml", self.base_url);
            
            if !command.is_empty() {
                url.push_str(&format!("?command={}", urlencoding::encode(command)));
                
                if let Some(params) = params {
                    for (key, value) in params {
                        url.push_str(&format!("&{}={}", 
                            urlencoding::encode(key), 
                            urlencoding::encode(value)
                        ));
                    }
                }
            }

            let mut request = self.client.get(&url);
            
            if let Some(ref auth) = self.auth_header {
                request = request.header("Authorization", auth);
            }

            match request.send().await {
                Ok(response) => {
                    if response.status().is_success() {
                        match response.text().await {
                            Ok(text) => return Ok(text),
                            Err(e) => {
                                last_error = Some(anyhow::anyhow!("Failed to read response text: {}", e));
                            }
                        }
                    } else {
                        last_error = Some(anyhow::anyhow!("HTTP request failed with status: {}", response.status()));
                    }
                }
                Err(e) => {
                    last_error = Some(anyhow::anyhow!("Request failed: {}", e));
                }
            }
            
            if attempt < max_retries {
                // Wait before retrying, with exponential backoff
                let delay = Duration::from_millis(100 * (2_u64.pow(attempt - 1)));
                tokio::time::sleep(delay).await;
            }
        }
        
        Err(last_error.unwrap_or_else(|| anyhow::anyhow!("All retry attempts failed")))
    }

    pub async fn load_media(&mut self, source: &MediaSource) -> Result<()> {
        let path = match source {
            MediaSource::LocalFile(path) => path.clone(),
            MediaSource::Url(url) => url.clone(),
        };

        // Try to load media with retries
        let mut last_error = None;
        const MAX_RETRIES: u32 = 3;
        
        for attempt in 1..=MAX_RETRIES {
            match self.send_command_with_retry("in_play", Some(&[("input", &path)]), 2).await {
                Ok(_) => {
                    // Update state
                    {
                        let mut state = self.state.lock().unwrap();
                        state.state = PlaybackState::Loading;
                        state.media_info.path = path.clone();
                        state.media_info.filename = std::path::Path::new(&path)
                            .file_name()
                            .and_then(|name| name.to_str())
                            .unwrap_or(&path)
                            .to_string();
                    }

                    // Wait a bit for media to load
                    tokio::time::sleep(Duration::from_millis(1000)).await;
                    
                    // Enable fullscreen and loop after loading media
                    let _ = self.send_command_with_retry("loop", None, 2).await;
                    
                    // Update internal state to reflect fullscreen and loop
                    {
                        let mut state = self.state.lock().unwrap();
                        state.fullscreen = true;
                        state.media_info.loop_enabled = true;
                    }
                    
                    // Verify that the media actually loaded by checking state
                    match self.update_state_from_vlc().await {
                        Ok(_) => {
                            let state = self.state.lock().unwrap();
                            // If we're not in an error state, consider it successful
                            if !matches!(state.state, PlaybackState::Stopped) || state.media_info.duration.is_some() {
                                return Ok(());
                            } else {
                                last_error = Some(anyhow::anyhow!("Media failed to load - VLC shows stopped state"));
                            }
                        }
                        Err(e) => {
                            last_error = Some(anyhow::anyhow!("Failed to update state after loading: {}", e));
                        }
                    }
                }
                Err(e) => {
                    last_error = Some(anyhow::anyhow!("Failed to send load command: {}", e));
                }
            }
            
            if attempt < MAX_RETRIES {
                // Wait before retrying
                tokio::time::sleep(Duration::from_millis(500 * attempt as u64)).await;
            }
        }
        
        Err(last_error.unwrap_or_else(|| anyhow::anyhow!("Failed to load media after all retry attempts")))
    }

    pub async fn play_pause(&mut self) -> Result<()> {
        // Try the command with retries
        match self.send_command_with_retry("pl_pause", None, 3).await {
            Ok(_) => {
                // Wait a moment for the command to take effect
                tokio::time::sleep(Duration::from_millis(200)).await;
                self.update_state_from_vlc().await?;
                Ok(())
            }
            Err(e) => {
                // If the command failed, try to recover by checking VLC connection
                match self.test_connection().await {
                    Ok(true) => {
                        // Connection is fine, maybe the command just failed temporarily
                        Err(anyhow::anyhow!("Play/pause command failed: {}", e))
                    }
                    Ok(false) => {
                        Err(anyhow::anyhow!("Play/pause failed - VLC connection lost: {}", e))
                    }
                    Err(conn_err) => {
                        Err(anyhow::anyhow!("Play/pause failed and connection test failed: {} (original: {})", conn_err, e))
                    }
                }
            }
        }
    }

    pub async fn stop(&mut self) -> Result<()> {
        match self.send_command_with_retry("pl_stop", None, 3).await {
            Ok(_) => {
                // Update state immediately
                {
                    let mut state = self.state.lock().unwrap();
                    state.state = PlaybackState::Stopped;
                    state.media_info.position = 0.0;
                }
                Ok(())
            }
            Err(e) => {
                // Even if the command failed, set our internal state to stopped
                {
                    let mut state = self.state.lock().unwrap();
                    state.state = PlaybackState::Stopped;
                    state.media_info.position = 0.0;
                }
                Err(anyhow::anyhow!("Stop command failed (state updated anyway): {}", e))
            }
        }
    }

    pub async fn set_volume(&mut self, volume: f64) -> Result<()> {
        let volume = volume.clamp(0.0, 100.0) as u32;
        self.send_command("volume", Some(&[("val", &volume.to_string())])).await?;
        
        // Update state immediately
        {
            let mut state = self.state.lock().unwrap();
            state.media_info.volume = volume as f64;
        }
        
        Ok(())
    }

    pub async fn mute(&mut self) -> Result<()> {
        // Get current volume first
        let current_volume = {
            let state = self.state.lock().unwrap();
            state.media_info.volume
        };

        if current_volume > 0.0 {
            // Mute by setting volume to 0
            self.set_volume(0.0).await?;
            let mut state = self.state.lock().unwrap();
            state.media_info.muted = true;
        } else {
            // Unmute by setting volume to a reasonable level
            self.set_volume(50.0).await?;
            let mut state = self.state.lock().unwrap();
            state.media_info.muted = false;
        }
        
        Ok(())
    }

    pub async fn seek(&mut self, seconds: f64) -> Result<()> {
        let seek_value = if seconds >= 0.0 {
            format!("+{}s", seconds as u32)
        } else {
            format!("{}s", seconds as i32)
        };
        
        self.send_command("seek", Some(&[("val", &seek_value)])).await?;
        
        // Update state
        {
            let mut state = self.state.lock().unwrap();
            state.media_info.position = (state.media_info.position + seconds).max(0.0);
        }
        
        Ok(())
    }

    pub async fn set_speed(&mut self, speed: f64) -> Result<()> {
        // VLC HTTP interface doesn't directly support speed control
        // We'll just update our internal state for now
        let speed = speed.clamp(0.1, 10.0);
        let mut state = self.state.lock().unwrap();
        state.media_info.speed = speed;
        
        // Note: This won't actually change VLC's playback speed
        // This is a limitation of the HTTP interface
        Ok(())
    }

    pub async fn toggle_fullscreen(&mut self) -> Result<()> {
        self.send_command("fullscreen", None).await?;
        
        // Update state
        {
            let mut state = self.state.lock().unwrap();
            state.fullscreen = !state.fullscreen;
        }
        
        Ok(())
    }

    pub async fn toggle_loop(&mut self) -> Result<()> {
        self.send_command("loop", None).await?;
        
        // Update state
        {
            let mut state = self.state.lock().unwrap();
            state.media_info.loop_enabled = !state.media_info.loop_enabled;
        }
        
        Ok(())
    }

    pub async fn get_state(&mut self) -> PlayerState {
        // Update state from VLC before returning
        let _ = self.update_state_from_vlc().await;
        
        let state = self.state.lock().unwrap();
        state.clone()
    }

    pub async fn quit(&mut self) -> Result<()> {
        // Try to gracefully quit VLC first
        let _ = self.send_command("quit", None).await;
        
        // Give VLC a moment to respond
        tokio::time::sleep(Duration::from_millis(500)).await;
        
        // If we have a VLC process, terminate it
        if let Some(mut process) = self.vlc_process.take() {
            match process.try_wait() {
                Ok(Some(_)) => {
                    // Process has already exited
                }
                Ok(None) => {
                    // Process is still running, terminate it
                    let _ = process.kill();
                    let _ = process.wait();
                }
                Err(_) => {
                    // Error checking process status, try to kill anyway
                    let _ = process.kill();
                }
            }
        }
        
        Ok(())
    }

    async fn update_state_from_vlc(&mut self) -> Result<()> {
        match self.send_command_with_retry("", None, 2).await {
            Ok(response) => {
                // Parse the XML response to extract state information
                // This is a simplified parser - you might want to use a proper XML parser
                let mut state = self.state.lock().unwrap();
                
                if response.contains("<state>playing</state>") {
                    state.state = PlaybackState::Playing;
                } else if response.contains("<state>paused</state>") {
                    state.state = PlaybackState::Paused;
                } else if response.contains("<state>stopped</state>") {
                    state.state = PlaybackState::Stopped;
                }

                // Parse volume
                if let Some(volume_start) = response.find("<volume>") {
                    if let Some(volume_end) = response[volume_start..].find("</volume>") {
                        let volume_str = &response[volume_start + 8..volume_start + volume_end];
                        if let Ok(volume) = volume_str.parse::<f64>() {
                            state.media_info.volume = volume;
                        }
                    }
                }

                // Parse position and duration
                if let Some(pos_start) = response.find("<time>") {
                    if let Some(pos_end) = response[pos_start..].find("</time>") {
                        let pos_str = &response[pos_start + 6..pos_start + pos_end];
                        if let Ok(position) = pos_str.parse::<f64>() {
                            state.media_info.position = position;
                        }
                    }
                }

                if let Some(dur_start) = response.find("<length>") {
                    if let Some(dur_end) = response[dur_start..].find("</length>") {
                        let dur_str = &response[dur_start + 8..dur_start + dur_end];
                        if let Ok(duration) = dur_str.parse::<f64>() {
                            if duration > 0.0 {
                                state.media_info.duration = Some(duration);
                            }
                        }
                    }
                }

                // Update connection status
                state.connection_status.connected = true;
                state.connection_status.last_error = None;
                
                Ok(())
            }
            Err(e) => {
                // Don't fail completely if state update fails, just log the error
                let mut state = self.state.lock().unwrap();
                state.connection_status.last_error = Some(format!("State update failed: {}", e));
                Err(e)
            }
        }
    }
}