libfreemkv 0.9.0

Open source raw disc access library for optical drives
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
//! Drive session — open, identify, and read from optical drives.
//!
//! Three-step open:
//!   1. `open()` — open device, identify drive. Always OEM.
//!   2. `wait_ready()` — wait for disc to spin up. Call before reading.
//!   3. `init()` — activate custom firmware. Removes riplock.
//!   4. `probe_disc()` — probe disc surface. Drive learns optimal speeds.

pub mod capture;

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(windows)]
mod windows;

use crate::error::{Error, Result};
use crate::identity::DriveId;
use crate::platform::mt1959::Mt1959;
use crate::platform::PlatformDriver;
use crate::profile::{self, DriveProfile};
use crate::scsi::ScsiTransport;
use crate::sector::SectorReader;
use std::path::Path;

/// Physical state of the drive tray and disc.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DriveStatus {
    /// Tray is open
    TrayOpen,
    /// Tray closed, no disc
    NoDisc,
    /// Tray closed, disc present and ready
    DiscPresent,
    /// Drive is loading or spinning up
    NotReady,
    /// Could not determine status
    Unknown,
}

/// Optical disc drive session -- open, identify, unlock, and read.
pub struct Drive {
    scsi: Box<dyn ScsiTransport>,
    driver: Option<Box<dyn PlatformDriver>>,
    pub profile: Option<DriveProfile>,
    pub platform: Option<profile::Platform>,
    pub drive_id: DriveId,
    device_path: String,
}

impl Drive {
    pub fn open(device: &Path) -> Result<Self> {
        let mut transport = crate::scsi::open(device)?;
        let profiles = profile::load_bundled()?;
        let drive_id = DriveId::from_drive(transport.as_mut())?;

        let m = profile::find_by_drive_id(&profiles, &drive_id);
        let (driver, platform, profile) = match m {
            Some(m) => (
                create_driver(m.platform, &m.profile).ok(),
                Some(m.platform),
                Some(m.profile),
            ),
            None => (None, None, None),
        };

        Ok(Drive {
            scsi: transport,
            driver,
            platform,
            profile,
            drive_id,
            device_path: device.to_string_lossy().to_string(),
        })
    }

    /// Whether this drive has a known profile (unlock parameters available).
    pub fn has_profile(&self) -> bool {
        self.profile.is_some()
    }

    pub fn wait_ready(&mut self) -> Result<()> {
        let tur = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00];
        let mut tried_reset = false;

        for _ in 0..60 {
            let mut buf = [0u8; 0];
            match self.scsi.as_mut().execute(
                &tur,
                crate::scsi::DataDirection::None,
                &mut buf,
                5_000,
            ) {
                Ok(_) => return Ok(()),
                Err(Error::ScsiError { sense_key: 5, .. }) if !tried_reset => {
                    // Illegal Request on TUR — drive may be stuck from a previous session.
                    // Try reset() which attempts multiple recovery approaches.
                    tried_reset = true;
                    if self.reset().is_ok() {
                        return Ok(());
                    }
                    // If reset failed but disc is present, proceed anyway —
                    // the scan path will handle errors individually.
                    if self.drive_status() == DriveStatus::DiscPresent {
                        return Ok(());
                    }
                }
                Err(_) => {}
            }
            std::thread::sleep(std::time::Duration::from_millis(500));
        }
        Err(Error::DeviceNotFound {
            path: format!("{}: drive not ready after 30s", self.device_path),
        })
    }

    /// Query the physical state of the drive — disc present, tray open, etc.
    /// Uses GET EVENT STATUS NOTIFICATION which works regardless of firmware state.
    pub fn drive_status(&mut self) -> DriveStatus {
        // GET EVENT STATUS NOTIFICATION: polled, media event class (0x10)
        let cdb = [0x4Au8, 0x01, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x08, 0x00];
        let mut buf = [0u8; 8];
        match self.scsi.as_mut().execute(
            &cdb,
            crate::scsi::DataDirection::FromDevice,
            &mut buf,
            5_000,
        ) {
            Ok(r) if r.bytes_transferred >= 6 => {
                let media_status = buf[5];
                // Bits 1-0: door/tray state
                // Bit 1: media present, Bit 0: tray open
                match media_status & 0x03 {
                    0x00 => DriveStatus::NoDisc,    // tray closed, no disc
                    0x01 => DriveStatus::TrayOpen,  // tray open
                    0x02 => DriveStatus::DiscPresent, // tray closed, disc present
                    0x03 => DriveStatus::DiscPresent, // tray closed, disc present
                    _ => DriveStatus::Unknown,
                }
            }
            _ => {
                // Fallback: try TUR
                let tur = [0x00u8, 0x00, 0x00, 0x00, 0x00, 0x00];
                let mut empty = [0u8; 0];
                match self.scsi.as_mut().execute(
                    &tur,
                    crate::scsi::DataDirection::None,
                    &mut empty,
                    5_000,
                ) {
                    Ok(_) => DriveStatus::DiscPresent,
                    Err(Error::ScsiError { sense_key: 2, .. }) => DriveStatus::NotReady,
                    Err(Error::ScsiError { sense_key: 6, .. }) => DriveStatus::NotReady, // UNIT ATTENTION
                    _ => DriveStatus::Unknown,
                }
            }
        }
    }

    /// Attempt to reset the drive to a clean state.
    ///
    /// Escalates through increasingly aggressive recovery:
    /// 1. Unlock tray + stop/start — handles normal stuck states
    /// 2. Eject cycle — clears LibreDrive firmware stuck state (proven on BU40N)
    /// 3. Re-init — firmware re-upload if profile available
    ///
    /// Note: step 2 physically ejects the tray. On slimline drives the user
    /// must push it back in manually. Returns Ok(()) if TUR succeeds after
    /// any step, even if the drive reports "tray open" (that's a valid state).
    pub fn reset(&mut self) -> Result<()> {
        let mut buf = [0u8; 0];
        let tur = [0x00u8, 0x00, 0x00, 0x00, 0x00, 0x00];

        // 1. Unlock + stop/start
        self.unlock_tray();
        let stop = [0x1Bu8, 0x00, 0x00, 0x00, 0x00, 0x00];
        let _ = self.scsi.as_mut().execute(
            &stop, crate::scsi::DataDirection::None, &mut buf, 5_000,
        );
        std::thread::sleep(std::time::Duration::from_millis(500));
        let start = [0x1Bu8, 0x00, 0x00, 0x00, 0x01, 0x00];
        let _ = self.scsi.as_mut().execute(
            &start, crate::scsi::DataDirection::None, &mut buf, 5_000,
        );
        std::thread::sleep(std::time::Duration::from_millis(2000));

        if self.scsi.as_mut().execute(
            &tur, crate::scsi::DataDirection::None, &mut buf, 5_000,
        ).is_ok() {
            return Ok(());
        }

        // 2. Eject cycle — clears MT1959 LibreDrive stuck state.
        // After eject, TUR returning "Not Ready — tray open" (sense key 2)
        // counts as success: the drive is functional, just needs disc reinserted.
        self.unlock_tray();
        let eject = [0x1Bu8, 0x00, 0x00, 0x00, 0x02, 0x00];
        let _ = self.scsi.as_mut().execute(
            &eject, crate::scsi::DataDirection::None, &mut buf, 30_000,
        );
        std::thread::sleep(std::time::Duration::from_millis(2000));

        match self.scsi.as_mut().execute(
            &tur, crate::scsi::DataDirection::None, &mut buf, 5_000,
        ) {
            Ok(_) => return Ok(()),
            Err(Error::ScsiError { sense_key: 2, .. }) => return Ok(()), // tray open = valid
            _ => {}
        }

        // 3. If still stuck and we have a profile, try re-init
        if self.driver.is_some() {
            self.init()?;
            std::thread::sleep(std::time::Duration::from_millis(1000));
            match self.scsi.as_mut().execute(
                &tur, crate::scsi::DataDirection::None, &mut buf, 5_000,
            ) {
                Ok(_) => return Ok(()),
                Err(Error::ScsiError { sense_key: 2, .. }) => return Ok(()),
                _ => {}
            }
        }

        Err(Error::DeviceNotFound {
            path: format!("{}: drive reset failed", self.device_path),
        })
    }

    pub fn platform_name(&self) -> &str {
        match self.platform {
            Some(ref p) => p.name(),
            None => "Unknown",
        }
    }

    pub fn device_path(&self) -> &str {
        &self.device_path
    }

    /// Initialize drive — unlock + firmware upload.
    /// Optional. Adds features: removes riplock, enables UHD reads, speed control.
    pub fn init(&mut self) -> Result<()> {
        match self.driver {
            Some(ref mut d) => d.init(self.scsi.as_mut()),
            None => Err(Error::UnsupportedDrive {
                vendor_id: self.drive_id.vendor_id.trim().to_string(),
                product_id: self.drive_id.product_id.trim().to_string(),
                product_revision: self.drive_id.product_revision.trim().to_string(),
            }),
        }
    }

    /// Probe disc surface so the drive firmware learns optimal read speeds
    /// per region. After this the host reads at max speed and the drive
    /// manages zones internally.
    pub fn probe_disc(&mut self) -> Result<()> {
        match self.driver {
            Some(ref mut d) => d.probe_disc(self.scsi.as_mut()),
            None => Err(Error::UnsupportedDrive {
                vendor_id: self.drive_id.vendor_id.trim().to_string(),
                product_id: self.drive_id.product_id.trim().to_string(),
                product_revision: self.drive_id.product_revision.trim().to_string(),
            }),
        }
    }

    /// Query a specific GET CONFIGURATION feature by code.
    /// Returns the feature data (without the 8-byte header), or None if not available.
    pub fn get_config_feature(&mut self, feature_code: u16) -> Option<Vec<u8>> {
        let cdb = [
            crate::scsi::SCSI_GET_CONFIGURATION, 0x02,
            (feature_code >> 8) as u8, feature_code as u8,
            0x00, 0x00, 0x00, 0x01, 0x00, 0x00,
        ];
        let mut buf = vec![0u8; 256];
        let r = self.scsi.as_mut()
            .execute(&cdb, crate::scsi::DataDirection::FromDevice, &mut buf, 5_000).ok()?;
        if r.bytes_transferred > 8 {
            Some(buf[8..r.bytes_transferred].to_vec())
        } else {
            None
        }
    }

    /// Read REPORT KEY RPC state (region playback control).
    pub fn report_key_rpc_state(&mut self) -> Option<Vec<u8>> {
        let cdb = [0xA4u8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x08, 0x00];
        let mut buf = vec![0u8; 8];
        let r = self.scsi.as_mut()
            .execute(&cdb, crate::scsi::DataDirection::FromDevice, &mut buf, 5_000).ok()?;
        if r.bytes_transferred > 0 { Some(buf[..r.bytes_transferred].to_vec()) } else { None }
    }

    /// Read MODE SENSE page data.
    pub fn mode_sense_page(&mut self, page: u8) -> Option<Vec<u8>> {
        let cdb = [0x5Au8, 0x00, page, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFC, 0x00];
        let mut buf = vec![0u8; 252];
        let r = self.scsi.as_mut()
            .execute(&cdb, crate::scsi::DataDirection::FromDevice, &mut buf, 5_000).ok()?;
        if r.bytes_transferred > 0 { Some(buf[..r.bytes_transferred].to_vec()) } else { None }
    }

    /// Read vendor-specific READ BUFFER data.
    pub fn read_buffer(&mut self, mode: u8, buffer_id: u8, length: u16) -> Option<Vec<u8>> {
        let cdb = crate::scsi::build_read_buffer(mode, buffer_id, 0, length as u32);
        let mut buf = vec![0u8; length as usize];
        let r = self.scsi.as_mut()
            .execute(&cdb, crate::scsi::DataDirection::FromDevice, &mut buf, 5_000).ok()?;
        if r.bytes_transferred > 0 { Some(buf[..r.bytes_transferred].to_vec()) } else { None }
    }

    pub fn is_ready(&self) -> bool {
        match self.driver {
            Some(ref d) => d.is_ready(),
            None => false,
        }
    }

    /// Read sectors from the disc. Raw SCSI READ(10).
    pub fn read(&mut self, lba: u32, count: u16, buf: &mut [u8]) -> Result<usize> {
        let cdb = [
            crate::scsi::SCSI_READ_10,
            0x00,
            (lba >> 24) as u8,
            (lba >> 16) as u8,
            (lba >> 8) as u8,
            lba as u8,
            0x00,
            (count >> 8) as u8,
            count as u8,
            0x00,
        ];
        let result = self.scsi.as_mut().execute(
            &cdb,
            crate::scsi::DataDirection::FromDevice,
            buf,
            30_000,
        )?;
        Ok(result.bytes_transferred)
    }

    /// Read the disc capacity in sectors (2048 bytes each).
    pub fn read_capacity(&mut self) -> Result<u32> {
        let cdb = [
            crate::scsi::SCSI_READ_CAPACITY, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let mut buf = [0u8; 8];
        self.scsi.as_mut().execute(
            &cdb, crate::scsi::DataDirection::FromDevice, &mut buf, 5_000,
        )?;
        let last_lba = u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]);
        Ok(last_lba + 1)
    }

    pub fn set_speed(&mut self, speed_kbs: u16) {
        let cdb = crate::scsi::build_set_cd_speed(speed_kbs);
        let mut dummy = [0u8; 0];
        let _ = self.scsi_execute(&cdb, crate::scsi::DataDirection::None, &mut dummy, 5_000);
    }

    /// Lock the tray so the disc cannot be ejected during a rip.
    pub fn lock_tray(&mut self) {
        let prevent = [0x1Eu8, 0x00, 0x00, 0x00, 0x01, 0x00];
        let mut buf = [0u8; 0];
        let _ = self.scsi.as_mut().execute(
            &prevent, crate::scsi::DataDirection::None, &mut buf, 5_000,
        );
    }

    /// Unlock the tray so the user can manually eject the disc.
    pub fn unlock_tray(&mut self) {
        let allow = [0x1Eu8, 0x00, 0x00, 0x00, 0x00, 0x00];
        let mut buf = [0u8; 0];
        let _ = self.scsi.as_mut().execute(
            &allow, crate::scsi::DataDirection::None, &mut buf, 5_000,
        );
    }

    /// Eject the disc tray. Unlocks first, then ejects.
    pub fn eject(&mut self) -> Result<()> {
        self.unlock_tray();
        let eject_cdb = [0x1Bu8, 0, 0, 0, 0x02, 0];
        let mut buf = [0u8; 0];
        self.scsi.as_mut().execute(
            &eject_cdb,
            crate::scsi::DataDirection::None,
            &mut buf,
            30_000,
        )?;
        Ok(())
    }

    pub fn scsi_execute(
        &mut self,
        cdb: &[u8],
        direction: crate::scsi::DataDirection,
        buf: &mut [u8],
        timeout_ms: u32,
    ) -> Result<crate::scsi::ScsiResult> {
        self.scsi.as_mut().execute(cdb, direction, buf, timeout_ms)
    }
}

impl SectorReader for Drive {
    fn read_sectors(&mut self, lba: u32, count: u16, buf: &mut [u8]) -> Result<usize> {
        self.read(lba, count, buf)
    }
}

/// Find all optical drives connected to this system.
/// Returns opened Drive objects ready for use.
pub fn find_drives() -> Vec<Drive> {
    discover_drives()
        .into_iter()
        .filter_map(|(path, _)| Drive::open(std::path::Path::new(&path)).ok())
        .collect()
}

/// Find the first optical drive.
/// Returns an opened Drive ready for use.
pub fn find_drive() -> Option<Drive> {
    find_drives().into_iter().next()
}

/// Internal: discover drive paths + IDs without opening full Drive objects.
fn discover_drives() -> Vec<(String, DriveId)> {
    #[cfg(target_os = "linux")]
    {
        linux::find_drives()
    }
    #[cfg(target_os = "macos")]
    {
        macos::find_drives()
    }
    #[cfg(windows)]
    {
        windows::find_drives()
    }
}

/// Resolve a device path to its raw SCSI device, with optional warning message.
pub(crate) fn resolve_device(path: &str) -> Result<(String, Option<String>)> {
    #[cfg(target_os = "linux")]
    {
        linux::resolve_device(path)
    }
    #[cfg(target_os = "macos")]
    {
        macos::resolve_device(path)
    }
    #[cfg(windows)]
    {
        windows::resolve_device(path)
    }
}

fn create_driver(
    platform: profile::Platform,
    profile: &DriveProfile,
) -> Result<Box<dyn PlatformDriver>> {
    match platform {
        profile::Platform::Mt1959A => Ok(Box::new(Mt1959::new(profile.clone(), false))),
        profile::Platform::Mt1959B => Ok(Box::new(Mt1959::new(profile.clone(), true))),
        profile::Platform::Renesas => Err(Error::UnsupportedDrive {
            vendor_id: profile.identity.vendor_id.trim().to_string(),
            product_id: String::new(),
            product_revision: "Renesas not yet implemented".to_string(),
        }),
    }
}