Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions libcdio-rs/src/mmc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ pub use get_config::*;
pub use get_event_status::*;
pub use inquiry::*;
pub use prevent_allow_medium_removal::*;
pub use read_cd::*;
pub use read_disc_info::*;
pub use read_subchannel::*;
pub use read_toc::*;
Expand All @@ -39,6 +40,7 @@ mod get_config;
mod get_event_status;
mod inquiry;
mod prevent_allow_medium_removal;
mod read_cd;
mod read_disc_info;
mod read_subchannel;
mod read_toc;
Expand Down Expand Up @@ -377,6 +379,7 @@ pub enum OsError {
enum MmcCommand {
#[allow(unused)]
GetConfiguration = 0x46,
ReadCd = 0xBE,
Inquiry = 0x12,
PreventAllowMediumRemoval = 0x1E,
ReadDiscInfo = 0x51,
Expand Down
227 changes: 227 additions & 0 deletions libcdio-rs/src/mmc/read_cd.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
// Copyright (C) 2026 Shiva Kiran Koninty <shiva@skran.xyz>
//
// This file is part of libcdio-rs.
//
// libcdio-rs is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// libcdio-rs is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with libcdio-rs. If not, see <https://www.gnu.org/licenses/>.

//! Routines based on `READ CD`.

use docsplay::Display;
use thiserror::Error;

use crate::{
Mmc,
mmc::{Cdb, MmcCommand, MmcDirection, MmcError},
};

/// Routines based on `READ CD`.
impl Mmc {
/// Read disc using MMC `READ CD`.
///
/// The transfer size is dependent on the opted fields in the read options.
/// See [`ReadCdOptions`].
pub fn read_cd(
&self,
options: ReadCdOptions,
sector: u32,
count: u16,
buf: &mut [u8],
) -> Result<(), MmcReadCdError> {
let mut cdb = Cdb::default();
cdb[0] = MmcCommand::ReadCd as u8;
if let Some(SectorOption::Cdda { dap: true }) = options.expected_sector_type {
cdb[1] |= 1 << 1;
}
if let Some(sector_type) = options.expected_sector_type {
cdb[1] |= (sector_type.discriminant() & 0b111) << 2;
}
cdb[2..=5].copy_from_slice(&sector.to_be_bytes());
cdb[7..=8].copy_from_slice(&count.to_be_bytes());
if options.include_sync {
cdb[9] |= 1 << 7;
}
if options.include_subheader {
cdb[9] |= 1 << 6;
}
if options.include_header {
cdb[9] |= 1 << 5;
}
if options.include_user_data {
cdb[9] |= 1 << 4;
}
if options.include_ecc {
cdb[9] |= 1 << 3;
}
if let Some(c2_error) = options.include_c2_error {
cdb[9] |= (c2_error as u8 & 0b11) << 1;
}
if let Some(subchan_option) = options.include_subchannel {
cdb[10] |= subchan_option as u8 & 0b111;
}

self.run_command(Some(MmcDirection::Read), buf, cdb)?;

Ok(())
}
}

/// Disc read options.
///
/// A few options are valid only for certain sector types.
/// Non-contiguous combinations of fields may not be feasible to read, and will
/// result in an error (such as include_sync + include_User_data).
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct ReadCdOptions {
/// Restrict read to sector type.
pub expected_sector_type: Option<SectorOption>,

/// Include sync fields (12 bytes per sector).
/// Sync fields are not present in CD-DA.
pub include_sync: bool,

/// Include headers (4 bytes per sector).
/// Headers are present in all sector types except CD-DA.
pub include_header: bool,

/// Include sub-headers (8 bytes per sector).
/// Sub-headers are present only in Mode2 formed sectors.
pub include_subheader: bool,

/// Include user data. Defaults to `true`.
/// Size depends on the sector type of the disc.
pub include_user_data: bool,

/// Include ECC/EDC, i.e the fields that follow user data. Present only in
/// Mode1 (288 bytes per sector) and Mode2 formed sectors
/// (Form1: 280 bytes per sector; Form2: 4 bytes per sector).
pub include_ecc: bool,

/// Include "C2 error bits" (294 to 296 bytes per sector).
pub include_c2_error: Option<C2Option>,

/// Include sub-channel information. (16 to 96 bytes per sector).
pub include_subchannel: Option<SubchannelOption>,
}

impl Default for ReadCdOptions {
/// Include only user data.
fn default() -> Self {
Self {
expected_sector_type: None,
include_sync: false,
include_header: false,
include_subheader: false,
include_user_data: true,
include_ecc: false,
include_c2_error: None,
include_subchannel: None,
}
}
}

/// Sector type to include.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum SectorOption {
/// IEC 908 (CD-DA) with user data of 2352 bytes.
Cdda {
/// Return data with flaw obsuring mechanisms such as audio data mute
/// and interpolate.
dap: bool,
} = 0b001,

/// User data of 2048 bytes.
#[default]
Mode1 = 0b010,

/// User data of 2336 bytes.
Mode2Formless = 0b011,

/// User data of 2048 bytes.
Mode2Form1 = 0b100,

/// User data of 2324 bytes.
Mode2Form2 = 0b101,
}
impl SectorOption {
fn discriminant(&self) -> u8 {
// SAFETY: `repr(u8)` is laid out as `repr(C)` `union` with the `u8`
// discriminant as its first field.
// Source:
// https://doc.rust-lang.org/stable/std/mem/fn.discriminant.html#accessing-the-numeric-value-of-the-discriminant
unsafe { *(&raw const *self).cast::<u8>() }
}
}

/// C2 error information to include.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum C2Option {
/// 294 bytes of "C2 error bits".
#[default]
Raw = 0b01,

/// 296 bytes consisting of:
/// - Block error byte: logical OR of all the 294 bytes of "C2 error bits"
/// - A pad byte of zero
/// - 294 bytes of "C2 error bits"
RawAndBlock = 0b10,
}

/// Sub-Channel information to include.
// This corresponds to the 'Sub-channel Selection Field Values'.
// Variant `0b000`, i.e 'no sub-channel data' can be represented using `None`.
// Variant `0b001`, i.e 'RawPw' has been marked as legacy since `MMC-6`.
#[repr(u8)]
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub enum SubchannelOption {
/// RAW P-W sub-channel data (96 bytes)
RawPw = 0b001,

/// Formatted Q sub-channel data (16 bytes).
#[default]
Q = 0b010,

/// Corrected and de-interleaved R-W sub-channel data (96 bytes).
Rw = 0b100,
}
Comment on lines +182 to +198

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this corresponds to

Image

of https://www.13thmonkey.org/documentation/SCSI/x3_304_1997.pdf I am seeing other fields mentioned, like 000b (no sub-channel data - which is mandatory to support).

If these are the only options supported right now, we should indicate that there are others and where one can find information on the other unsupported options.

@skr4n skr4n Aug 3, 2026

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The 000b variant is covered by the None variant of the Option<SubchannelOption> above.

In this table, we realistically have three choices: RAW, Q and P-W.
The 000b value is to not include this data.

Therefore, a user can specify:

  • To request RAW: Some(SubchannelOption::Raw).
  • To request Q: Some(SubchannelOption::Q).
  • To not include any sub-channel data: None.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok. Please add a comment adding this information, and it would be nice to refer to or include table 37 or reference this somewhere. We want to make things more transparent as to how some specifications are being followed.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When an Option is used to represent a type, it's implicitly understood that there is a choice to not give any values, akin to C's NULL (but properly typed).

Speaking of referring to tables in the spec, I'd have preferred to do that if there were any ambiguity in finding it.
In this case, there isn't any, since you were perfectly able to do just that above.
I feel it's redundant to have them.

Nevertheless, I've added the said comments.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What you have in the comments is good and sufficient.

I was able to find a table that matches the correspondences in this situation, but that doesn't mean this is good practice. Or that we want users to do this.

From experience, what I've found happens is that someone will find a different table or different piece of information. So they too feel that you could find it on your own, and therefore you didn't follow what they saw (but didn't specify what it was that they saw).

I understand that table numbers, pages, and table names in specs are fragile. But I'd like to have a solution somehow to reduce the problem of: you didn't follow the spec that I'm thinking of (and you should be able to find on your own); no, I didn't, I followed the spec that I am thinking of according to some table that you should be able to find on your own.


/// error from a `READ CD` command
#[derive(Debug, Display, Error)]
pub struct MmcReadCdError {
#[from]
pub source: MmcError,
}

#[cfg(test)]
mod tests {
use tracing::info;

use super::*;

#[test_log::test(test)]
#[ignore]
fn read_cd() {
let mmc = Mmc::new().unwrap();
const SIZE: usize = 23520;
let mut buf = vec![0; SIZE];
mmc.read_cd(ReadCdOptions::default(), 200, 10, &mut buf)
.unwrap();
info!(
"read buffer is populated about {:?} bytes out of {SIZE} bytes",
buf.iter().rposition(|z| *z != 0),
);
assert!(buf.iter().any(|e| *e != 0));
}
}