Merge pull request #4 from G2-Games/wasm

Web assembly work complete
This commit is contained in:
G2 2024-01-31 21:42:45 -06:00 committed by GitHub
commit a3a3ee3827
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 195 additions and 180 deletions

2
.cargo/config.toml Normal file
View file

@ -0,0 +1,2 @@
[target.'cfg(target_family = "wasm")']
rustflags = ["--cfg=web_sys_unstable_apis"]

View file

@ -10,9 +10,9 @@ license = "AGPL-3.0"
[dependencies]
hex = "0.4.3"
nusb = "0.1.4"
tokio = { version = "1.35.1", features = ["full"] }
cross_usb = "0.1"
tokio = { version = "1.35.1", features = ["macros", "rt", "rt-multi-thread"] }
[dependencies.minidisc-rs]
[dependencies.minidisc_rs]
path = "minidisc-rs"
version = "0.0.1"

View file

@ -1,5 +1,5 @@
[package]
name = "minidisc-rs"
name = "minidisc_rs"
version = "0.0.1"
homepage = "https://github.com/G2-Games/minidisc-cli/"
repository = "https://github.com/G2-Games/minidisc-cli/minidisc-rs/"
@ -21,7 +21,7 @@ unicode-normalization = "0.1.22"
hex = "0.4.3"
regex = "1.10.2"
lazy_static = "1.4.0"
nusb = "0.1.4"
cross_usb = "0.1"
num-derive = "0.3.3"
num-traits = "0.2.14"
rand = "0.8.5"
@ -31,5 +31,12 @@ getrandom = { version = "0.2.12", features = ["js"] }
# Relying on this fork for now as it has up-to-date deps
git = "https://github.com/uzabase/unicode-jp-rs.git"
[target.'cfg(target_family = "wasm")'.dependencies]
web-sys = { version = "0.3", features = ["console"] }
gloo = { version = "0.11.0", features = ["futures"] }
[lib]
crate-type = ["cdylib", "rlib"]
[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
dwarf-debug-info = true

View file

@ -1,11 +1,16 @@
#![cfg_attr(debug_assertions, allow(dead_code))]
use nofmt;
use once_cell::sync::Lazy;
use std::error::Error;
use std::time::Duration;
// USB stuff
use nusb::transfer::{Control, ControlIn, ControlOut, ControlType, Recipient, RequestBuffer};
use nusb::{Device, DeviceInfo, Interface};
//use nusb::transfer::{Control, ControlIn, ControlOut, ControlType, Recipient, RequestBuffer};
use cross_usb::{UsbDevice, UsbInterface};
use cross_usb::usb::{ControlIn, ControlOut, ControlType, Device, Interface, Recipient};
use super::utils::cross_sleep;
//use nusb::{Device, DeviceInfo, Interface};
const DEFAULT_TIMEOUT: Duration = Duration::new(10000, 0);
const BULK_WRITE_ENDPOINT: u8 = 0x02;
@ -85,8 +90,7 @@ pub struct DeviceId {
/// A connection to a NetMD device
pub struct NetMD {
usb_device: Device,
usb_interface: Interface,
usb_interface: UsbInterface,
model: DeviceId,
status: Option<Status>,
}
@ -95,10 +99,10 @@ impl NetMD {
const READ_REPLY_RETRY_INTERVAL: u32 = 10;
/// Creates a new interface to a NetMD device
pub async fn new(device_info: &DeviceInfo) -> Result<Self, Box<dyn Error>> {
pub async fn new(usb_device: &UsbDevice) -> Result<Self, Box<dyn Error>> {
let mut model = DeviceId {
vendor_id: device_info.vendor_id(),
product_id: device_info.product_id(),
vendor_id: usb_device.vendor_id().await,
product_id: usb_device.product_id().await,
name: None,
};
@ -116,11 +120,9 @@ impl NetMD {
Some(_) => (),
}
let usb_device = device_info.open()?;
let usb_interface = usb_device.claim_interface(0)?;
let usb_interface = usb_device.open_interface(0).await?;
Ok(Self {
usb_device,
usb_interface,
model,
status: None,
@ -157,10 +159,9 @@ impl NetMD {
length: 4,
})
.await
.into_result()
{
Ok(size) => size,
Err(error) => return Err(error.into()),
Err(error) => return Err(error),
};
let length_bytes = u16::from_le_bytes([poll_result[2], poll_result[3]]);
@ -190,9 +191,9 @@ impl NetMD {
// First poll to ensure the device is ready
match self.poll().await {
Ok(buffer) => match buffer.1[2] {
0 => 0,
_ => return Err("Device not ready!".into()),
},
0 => 0,
_ => return Err("Device not ready!".into()),
},
Err(error) => return Err(error),
};
@ -212,10 +213,9 @@ impl NetMD {
data: &command,
})
.await
.into_result()
{
Ok(_) => Ok(()),
Err(error) => Err(error.into()),
Err(error) => Err(error),
}
}
@ -239,17 +239,24 @@ impl NetMD {
use_factory_command: bool,
override_length: Option<i32>,
) -> Result<Vec<u8>, Box<dyn Error>> {
let mut length = self.poll().await?.0;
let mut length = 0;
let mut current_attempt = 0;
while length == 0 {
// Back off while trying again
let sleep_time = Self::READ_REPLY_RETRY_INTERVAL as u64
* (u64::pow(2, current_attempt as u32 / 10) - 1);
for attempt in 0..40 {
if attempt == 39 {
return Err("Failed to get response length".into());
}
std::thread::sleep(std::time::Duration::from_millis(sleep_time));
length = self.poll().await?.0;
current_attempt += 1;
if length > 0 {
break
}
// Back off while trying again
let sleep_time = Self::READ_REPLY_RETRY_INTERVAL
* (u32::pow(2, attempt / 10) - 1);
cross_sleep(sleep_time).await;
}
if let Some(value) = override_length {
@ -272,14 +279,12 @@ impl NetMD {
index: 0,
length,
})
.await
.into_result()?;
.await?;
Ok(reply)
}
// Default chunksize should be 0x10000
// TODO: Make these Async eventually
pub async fn read_bulk(
&mut self,
length: usize,
@ -301,13 +306,11 @@ impl NetMD {
while done < length {
let to_read = std::cmp::min(chunksize, length - done);
done -= to_read;
let buffer = RequestBuffer::new(to_read);
let res = match self
.usb_interface
.bulk_in(BULK_READ_ENDPOINT, buffer)
.bulk_in(BULK_READ_ENDPOINT, to_read)
.await
.into_result()
{
Ok(result) => result,
Err(error) => return Err(format!("USB error: {:?}", error).into()),
@ -319,12 +322,7 @@ impl NetMD {
Ok(final_result)
}
pub async fn write_bulk(&mut self, data: Vec<u8>) -> Result<usize, Box<dyn Error>> {
Ok(self
.usb_interface
.bulk_out(BULK_WRITE_ENDPOINT, data)
.await
.into_result()?
.actual_length())
pub async fn write_bulk(&mut self, data: &[u8]) -> Result<usize, Box<dyn Error>> {
self.usb_interface.bulk_out(BULK_WRITE_ENDPOINT, data).await
}
}

View file

@ -1,8 +1,10 @@
use std::{error::Error, thread::sleep, time::Duration};
#![cfg_attr(debug_assertions, allow(dead_code))]
use std::error::Error;
use num_derive::FromPrimitive;
use num_traits::FromPrimitive;
use super::interface::{NetMDInterface, MDTrack};
use super::utils::cross_sleep;
#[derive(FromPrimitive)]
#[derive(PartialEq)]
@ -57,20 +59,20 @@ pub async fn device_status(interface: &mut NetMDInterface) -> Result<DeviceStatu
}
pub async fn prepare_download(interface: &mut NetMDInterface) -> Result<(), Box<dyn Error>>{
while ![OperatingStatus::DiscBlank, OperatingStatus::Ready].contains(&device_status(interface).await?.state.or(Some(OperatingStatus::NoDisc)).unwrap()) {
sleep(Duration::from_millis(200));
while ![OperatingStatus::DiscBlank, OperatingStatus::Ready].contains(&device_status(interface).await?.state.unwrap_or(OperatingStatus::NoDisc)) {
cross_sleep(200).await;
}
let _ = interface.session_key_forget();
let _ = interface.leave_secure_session();
let _ = interface.session_key_forget().await;
let _ = interface.leave_secure_session().await;
interface.acquire().await?;
let _ = interface.disable_new_track_protection(1);
let _ = interface.disable_new_track_protection(1).await;
Ok(())
}
pub async fn download(interface: &mut NetMDInterface, track: MDTrack) -> Result<(), Box<dyn Error>>{
pub async fn download(interface: &mut NetMDInterface, _track: MDTrack) -> Result<(), Box<dyn Error>>{
prepare_download(interface).await?;
Ok(())

View file

@ -1,3 +1,4 @@
#![cfg_attr(debug_assertions, allow(dead_code))]
use crate::netmd::base;
use crate::netmd::query_utils::{format_query, scan_query, QueryValue};
use crate::netmd::utils::{
@ -12,8 +13,8 @@ use std::collections::HashMap;
use std::error::Error;
use lazy_static::lazy_static;
use std::thread::sleep;
use std::time::Duration;
use super::utils::cross_sleep;
#[derive(Copy, Clone)]
enum Action {
@ -137,7 +138,7 @@ enum DescriptorAction {
}
#[repr(u8)]
enum Status {
enum NetmdStatus {
// NetMD Protocol return status (first byte of request)
Control = 0x00,
Status = 0x01,
@ -163,23 +164,23 @@ lazy_static! {
]);
}
impl std::convert::TryFrom<u8> for Status {
impl std::convert::TryFrom<u8> for NetmdStatus {
type Error = Box<dyn Error>;
fn try_from(item: u8) -> Result<Self, Box<dyn Error>> {
match item {
0x00 => Ok(Status::Control),
0x01 => Ok(Status::Status),
0x02 => Ok(Status::SpecificInquiry),
0x03 => Ok(Status::Notify),
0x04 => Ok(Status::GeneralInquiry),
0x08 => Ok(Status::NotImplemented),
0x09 => Ok(Status::Accepted),
0x0a => Ok(Status::Rejected),
0x0b => Ok(Status::InTransition),
0x0c => Ok(Status::Implemented),
0x0d => Ok(Status::Changed),
0x0f => Ok(Status::Interim),
0x00 => Ok(NetmdStatus::Control),
0x01 => Ok(NetmdStatus::Status),
0x02 => Ok(NetmdStatus::SpecificInquiry),
0x03 => Ok(NetmdStatus::Notify),
0x04 => Ok(NetmdStatus::GeneralInquiry),
0x08 => Ok(NetmdStatus::NotImplemented),
0x09 => Ok(NetmdStatus::Accepted),
0x0a => Ok(NetmdStatus::Rejected),
0x0b => Ok(NetmdStatus::InTransition),
0x0c => Ok(NetmdStatus::Implemented),
0x0d => Ok(NetmdStatus::Changed),
0x0f => Ok(NetmdStatus::Interim),
_ => Err("Not a valid value".into()),
}
}
@ -203,7 +204,7 @@ impl NetMDInterface {
const MAX_INTERIM_READ_ATTEMPTS: u8 = 4;
const INTERIM_RESPONSE_RETRY_INTERVAL: u32 = 100;
pub async fn new(device: &nusb::DeviceInfo) -> Result<Self, Box<dyn Error>> {
pub async fn new(device: &cross_usb::UsbDevice) -> Result<Self, Box<dyn Error>> {
let net_md_device = base::NetMD::new(device).await?;
Ok(NetMDInterface { net_md_device })
}
@ -223,7 +224,7 @@ impl NetMDInterface {
self.change_descriptor_state(
&Descriptor::DiscSubunitIdentifier,
&DescriptorAction::OpenRead,
);
).await;
let mut query = format_query("1809 00 ff00 0000 0000".to_string(), vec![])?;
@ -291,7 +292,7 @@ impl NetMDInterface {
let _manufacturer_dep_data =
&buffer[buffer_offset..buffer_offset + manufacturer_dep_length as usize];
self.change_descriptor_state(&Descriptor::DiscSubunitIdentifier, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::DiscSubunitIdentifier, &DescriptorAction::Close).await;
for media in supported_media_type_specifications {
if media.supported_media_type != 0x301 {
@ -321,7 +322,7 @@ impl NetMDInterface {
Ok(result)
}
fn change_descriptor_state(&mut self, descriptor: &Descriptor, action: &DescriptorAction) {
async fn change_descriptor_state(&mut self, descriptor: &Descriptor, action: &DescriptorAction) {
let mut query = format_query("1808".to_string(), vec![]).unwrap();
query.append(&mut descriptor.get_array());
@ -330,7 +331,7 @@ impl NetMDInterface {
query.push(0x00);
let _ = self.send_query(&mut query, false, false);
let _ = self.send_query(&mut query, false, false).await;
}
/// Send a query to the NetMD player
@ -353,8 +354,8 @@ impl NetMDInterface {
test: bool,
) -> Result<(), Box<dyn Error>> {
let status_byte = match test {
true => Status::GeneralInquiry,
false => Status::Control,
true => NetmdStatus::GeneralInquiry,
false => NetmdStatus::Control,
};
let mut new_query = Vec::new();
@ -377,23 +378,24 @@ impl NetMDInterface {
Err(error) => return Err(error),
};
let status = match Status::try_from(data[0]) {
let status = match NetmdStatus::try_from(data[0]) {
Ok(status) => status,
Err(error) => return Err(error),
};
match status {
Status::NotImplemented => return Err("Not implemented".into()),
Status::Rejected => return Err("Rejected".into()),
Status::Interim if !accept_interim => {
let sleep_time = Self::INTERIM_RESPONSE_RETRY_INTERVAL as u64
* (u64::pow(2, current_attempt as u32) - 1);
let sleep_dur = std::time::Duration::from_millis(sleep_time);
std::thread::sleep(sleep_dur); // Sleep to wait before retrying
NetmdStatus::NotImplemented => return Err("Not implemented".into()),
NetmdStatus::Rejected => return Err("Rejected".into()),
NetmdStatus::Interim if !accept_interim => {
let sleep_time = Self::INTERIM_RESPONSE_RETRY_INTERVAL
* (u32::pow(2, current_attempt as u32) - 1);
cross_sleep(sleep_time).await;
current_attempt += 1;
continue; // Retry!
}
Status::Accepted | Status::Implemented | Status::Interim => {
NetmdStatus::Accepted | NetmdStatus::Implemented | NetmdStatus::Interim => {
if current_attempt >= Self::MAX_INTERIM_READ_ATTEMPTS {
return Err("Max interim retry attempts reached".into());
}
@ -470,7 +472,7 @@ impl NetMDInterface {
self.change_descriptor_state(
&Descriptor::OperatingStatusBlock,
&DescriptorAction::OpenRead,
);
).await;
let mut query = format_query(
"1809 8001 0230 8800 0030 8804 00 ff00 00000000".to_string(),
@ -484,7 +486,7 @@ impl NetMDInterface {
"1809 8001 0230 8800 0030 8804 00 1000 00090000 %x".to_string(),
)?;
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close).await;
let final_array = res[0].to_vec().unwrap();
@ -504,7 +506,7 @@ impl NetMDInterface {
self.change_descriptor_state(
&Descriptor::OperatingStatusBlock,
&DescriptorAction::OpenRead,
);
).await;
let mut query = format_query(
"1809 8001 0330 8802 0030 8805 0030 8806 00 ff00 00000000".to_string(),
vec![],
@ -520,7 +522,7 @@ impl NetMDInterface {
let operating_status = result[1].to_vec().unwrap();
let status_mode = result[0].to_i64().unwrap() as u8;
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close).await;
if operating_status.len() < 2 {
return Err("Unparsable operating system".into());
@ -542,7 +544,7 @@ impl NetMDInterface {
self.change_descriptor_state(
&Descriptor::OperatingStatusBlock,
&DescriptorAction::OpenRead,
);
).await;
let mut query = format_query(
"1809 8001 0330 %w 0030 8805 0030 %w 00 ff00 00000000".to_string(),
vec![QueryValue::Number(p1 as i64), QueryValue::Number(p2 as i64)],
@ -556,7 +558,7 @@ impl NetMDInterface {
"1809 8001 0330 %?%? %?%? %?%? %?%? %?%? %? 1000 00%?0000 %x %?".to_string(),
);
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close).await;
Ok(res.unwrap()[0].to_vec().unwrap())
}
@ -573,7 +575,7 @@ impl NetMDInterface {
self.change_descriptor_state(
&Descriptor::OperatingStatusBlock,
&DescriptorAction::OpenRead,
);
).await;
let mut query = format_query(
"1809 8001 0430 8802 0030 8805 0030 0003 0030 0002 00 ff00 00000000".to_string(),
@ -597,7 +599,7 @@ impl NetMDInterface {
result[4].to_i64().unwrap() as u16,
];
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close).await;
Ok(final_result)
}
@ -704,21 +706,21 @@ impl NetMDInterface {
// TODO: Ensure this is returning the correct value, it
// looks like it actually might be a 16 bit integer
pub async fn disc_flags(&mut self) -> Result<u8, Box<dyn Error>> {
self.change_descriptor_state(&Descriptor::RootTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::RootTD, &DescriptorAction::OpenRead).await;
let mut query = format_query("1806 01101000 ff00 0001000b".to_string(), vec![]).unwrap();
let reply = self.send_query(&mut query, false, false).await?;
let res = scan_query(reply, "1806 01101000 1000 0001000b %b".to_string()).unwrap();
self.change_descriptor_state(&Descriptor::RootTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::RootTD, &DescriptorAction::Close).await;
Ok(res[0].to_i64().unwrap() as u8)
}
/// The number of tracks on the disc
pub async fn track_count(&mut self) -> Result<u16, Box<dyn Error>> {
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead).await;
let mut query =
format_query("1806 02101001 3000 1000 ff00 00000000".to_string(), vec![]).unwrap();
@ -731,14 +733,14 @@ impl NetMDInterface {
)
.unwrap();
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close).await;
Ok(res[0].to_i64().unwrap() as u16)
}
async fn raw_disc_title(&mut self, wchar: bool) -> Result<String, Box<dyn Error>> {
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead).await;
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::OpenRead).await;
let mut done: i32 = 0;
let mut remaining: i32 = 0;
@ -792,8 +794,8 @@ impl NetMDInterface {
let res = result.join("");
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::Close).await;
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close).await;
Ok(res)
}
@ -926,7 +928,7 @@ impl NetMDInterface {
false => Descriptor::AudioUTOC1TD,
};
self.change_descriptor_state(&descriptor_type, &DescriptorAction::OpenRead);
self.change_descriptor_state(&descriptor_type, &DescriptorAction::OpenRead).await;
let mut track_titles: Vec<String> = vec![];
for i in tracks {
@ -955,7 +957,7 @@ impl NetMDInterface {
)
}
self.change_descriptor_state(&descriptor_type, &DescriptorAction::Close);
self.change_descriptor_state(&descriptor_type, &DescriptorAction::Close).await;
Ok(track_titles)
}
@ -973,7 +975,7 @@ impl NetMDInterface {
// Sets the title of the disc
pub async fn set_disc_title(
&mut self,
title: String,
title: &str,
wchar: bool,
) -> Result<(), Box<dyn Error>> {
let current_title = self.raw_disc_title(wchar).await?;
@ -986,7 +988,7 @@ impl NetMDInterface {
let wchar_value = match wchar {
true => {
new_title = sanitize_full_width_title(&title, false);
new_title = sanitize_full_width_title(title, false);
1
}
false => {
@ -998,10 +1000,10 @@ impl NetMDInterface {
let new_len = new_title.len();
if self.net_md_device.vendor_id().await == &0x04dd {
self.change_descriptor_state(&Descriptor::AudioUTOC1TD, &DescriptorAction::OpenWrite)
self.change_descriptor_state(&Descriptor::AudioUTOC1TD, &DescriptorAction::OpenWrite).await
} else {
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::OpenWrite)
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::Close).await;
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::OpenWrite).await
}
let mut query = format_query(
@ -1014,14 +1016,14 @@ impl NetMDInterface {
],
)?;
let _ = self.send_query(&mut query, false, false);
let _ = self.send_query(&mut query, false, false).await;
if self.net_md_device.vendor_id().await == &0x04dd {
self.change_descriptor_state(&Descriptor::AudioUTOC1TD, &DescriptorAction::Close)
self.change_descriptor_state(&Descriptor::AudioUTOC1TD, &DescriptorAction::Close).await
} else {
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::Close).await;
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::OpenRead).await;
self.change_descriptor_state(&Descriptor::DiscTitleTD, &DescriptorAction::Close).await;
}
Ok(())
@ -1031,17 +1033,17 @@ impl NetMDInterface {
pub async fn set_track_title(
&mut self,
track: u16,
title: String,
title: &str,
wchar: bool,
) -> Result<(), Box<dyn Error>> {
let new_title: Vec<u8>;
let (wchar_value, descriptor) = match wchar {
true => {
new_title = sanitize_full_width_title(&title, false);
new_title = sanitize_full_width_title(title, false);
(3, Descriptor::AudioUTOC4TD)
}
false => {
new_title = sanitize_half_width_title(title.clone());
new_title = sanitize_half_width_title(title);
(2, Descriptor::AudioUTOC1TD)
}
};
@ -1059,7 +1061,7 @@ impl NetMDInterface {
Err(error) => return Err(error),
};
self.change_descriptor_state(&descriptor, &DescriptorAction::OpenWrite);
self.change_descriptor_state(&descriptor, &DescriptorAction::OpenWrite).await;
let mut query = format_query(
"1807 022018%b %w 3000 0a00 5000 %w 0000 %w %*".to_string(),
vec![
@ -1076,7 +1078,7 @@ impl NetMDInterface {
reply,
"1807 022018%? %?%? 3000 0a00 5000 %?%? 0000 %?%?".to_string(),
);
self.change_descriptor_state(&descriptor, &DescriptorAction::Close);
self.change_descriptor_state(&descriptor, &DescriptorAction::Close).await;
Ok(())
}
@ -1114,7 +1116,7 @@ impl NetMDInterface {
p1: i32,
p2: i32,
) -> Result<Vec<u8>, Box<dyn Error>> {
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead).await;
let mut query = format_query(
"1806 02201001 %w %w %w ff00 00000000".to_string(),
@ -1131,7 +1133,7 @@ impl NetMDInterface {
"1806 02201001 %?%? %?%? %?%? 1000 00%?0000 %x".to_string(),
)?;
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close).await;
Ok(res[0].to_vec().unwrap())
}
@ -1143,7 +1145,7 @@ impl NetMDInterface {
) -> Result<Vec<std::time::Duration>, Box<dyn Error>> {
let mut times: Vec<std::time::Duration> = vec![];
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead).await;
for track in tracks {
let mut query = format_query(
"1806 02201001 %w %w %w ff00 00000000".to_string(),
@ -1175,7 +1177,7 @@ impl NetMDInterface {
times.push(length);
}
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close).await;
Ok(times)
}
@ -1206,7 +1208,7 @@ impl NetMDInterface {
/// Gets a track's flags
pub async fn track_flags(&mut self, track: u16) -> Result<u8, Box<dyn Error>> {
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::OpenRead).await;
let mut query = format_query(
"1806 01201001 %w ff00 00010008".to_string(),
vec![QueryValue::Number(track as i64)],
@ -1215,14 +1217,14 @@ impl NetMDInterface {
let res = scan_query(reply, "1806 01201001 %?%? 10 00 00010008 %b".to_string())?;
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close).await;
Ok(res[0].to_i64().unwrap() as u8)
}
/// Gets the disc capacity as a `std::time::Duration`
pub async fn disc_capacity(&mut self) -> Result<[std::time::Duration; 3], Box<dyn Error>> {
self.change_descriptor_state(&Descriptor::RootTD, &DescriptorAction::OpenRead);
self.change_descriptor_state(&Descriptor::RootTD, &DescriptorAction::OpenRead).await;
let mut query = format_query("1806 02101000 3080 0300 ff00 00000000".to_string(), vec![])?;
let reply = self.send_query(&mut query, false, false).await?;
let mut result: [std::time::Duration; 3] = [std::time::Duration::from_secs(0); 3];
@ -1245,7 +1247,7 @@ impl NetMDInterface {
result[i] = std::time::Duration::from_micros(time_micros);
}
self.change_descriptor_state(&Descriptor::RootTD, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::RootTD, &DescriptorAction::Close).await;
Ok(result)
}
@ -1254,7 +1256,7 @@ impl NetMDInterface {
self.change_descriptor_state(
&Descriptor::OperatingStatusBlock,
&DescriptorAction::OpenRead,
);
).await;
let mut query = format_query(
"1809 8001 0330 8801 0030 8805 0030 8807 00 ff00 00000000".to_string(),
vec![],
@ -1264,7 +1266,7 @@ impl NetMDInterface {
let res = scan_query(reply, "1809 8001 0330 8801 0030 8805 0030 8807 00 1000 000e0000 000c 8805 0008 80e0 0110 %b %b 4000".to_string())?;
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close);
self.change_descriptor_state(&Descriptor::OperatingStatusBlock, &DescriptorAction::Close).await;
Ok(res.into_iter().map(|x| x.to_i64().unwrap() as u8).collect())
}
@ -1502,7 +1504,7 @@ impl NetMDInterface {
}
// Sharps are slow
sleep(Duration::from_millis(200));
cross_sleep(200).await;
let total_bytes = pkt_size + 24; //framesizedict[wireformat] * frames + pktcount * 24;
@ -1522,7 +1524,7 @@ impl NetMDInterface {
)?;
// Sharps are slow
sleep(Duration::from_millis(200));
cross_sleep(200).await;
let mut _written_bytes = 0;
for (packet_count, (key, iv, data)) in packets.into_iter().enumerate() {
@ -1532,7 +1534,7 @@ impl NetMDInterface {
} else {
data.clone()
};
self.net_md_device.write_bulk(binpack).await?;
self.net_md_device.write_bulk(&binpack).await?;
_written_bytes += data.len();
}

View file

@ -8,6 +8,15 @@ use unicode_normalization::UnicodeNormalization;
extern crate kana;
use kana::*;
/// Sleep for a specified number of milliseconds on any platform
pub async fn cross_sleep(millis: u32) {
#[cfg(not(target_family = "wasm"))]
std::thread::sleep(std::time::Duration::from_millis(millis as u64));
#[cfg(target_family = "wasm")]
gloo::timers::future::TimeoutFuture::new(millis).await;
}
pub fn bcd_to_int(mut bcd: i32) -> i32 {
let mut value = 0;
let mut nibble = 0;
@ -89,15 +98,13 @@ fn check(string: String) -> Option<String> {
None
}
pub fn sanitize_half_width_title(mut title: String) -> Vec<u8> {
title = wide2ascii(&title);
title = nowidespace(&title);
title = hira2kata(&title);
title = combine(&title);
pub fn sanitize_half_width_title(title: &str) -> Vec<u8> {
let mut string_title = wide2ascii(title);
string_title = nowidespace(&string_title);
string_title = hira2kata(&string_title);
string_title = combine(&string_title);
println!("{}", title);
let new_title: String = title
let new_title: String = string_title
.chars()
.map(|c| {
check(c.to_string()).unwrap_or(
@ -109,7 +116,7 @@ pub fn sanitize_half_width_title(mut title: String) -> Vec<u8> {
let sjis_string = SHIFT_JIS.encode(&new_title).0;
if validate_shift_jis(sjis_string.clone().into()) {
return agressive_sanitize_title(&title).into();
return agressive_sanitize_title(title).into();
}
sjis_string.into()

View file

@ -1,53 +1,50 @@
use minidisc_rs::netmd::interface;
use nusb;
use cross_usb::usb::Device;
#[tokio::main]
async fn main() {
let devices = nusb::list_devices().unwrap();
let device = cross_usb::get_device(0x054c, 0x0186).await.unwrap();
for device in devices {
// Ensure the player is a minidisc player and not some other random device
let mut player_controller = match interface::NetMDInterface::new(&device).await {
Ok(player) => player,
Err(err) => continue,
};
dbg!(device.vendor_id().await);
// Ensure the player is a minidisc player and not some other random device
let mut player_controller = match interface::NetMDInterface::new(&device).await {
Ok(player) => player,
Err(err) => {
dbg!(err);
panic!();
},
};
println!(
"Player Model: {}",
player_controller
.net_md_device
.device_name()
.await
.clone()
.unwrap()
);
let now = std::time::Instant::now();
let half_title = player_controller.disc_title(false).await.unwrap_or("".to_string());
let full_title = player_controller.disc_title(true).await.unwrap_or("".to_string());
println!(
"Disc Title: {} | {}",
half_title,
full_title
);
let track_count = player_controller.track_count().await.unwrap();
println!("{}", track_count);
let track_titles = player_controller.track_titles((0..track_count).collect(), false).await.unwrap();
let track_titlesw = player_controller.track_titles((0..track_count).collect(), true).await.unwrap();
let track_lengths = player_controller.track_lengths((0..track_count).collect()).await.unwrap();
for (i, track) in track_titles.iter().enumerate() {
println!(
"Connected to VID: {:04x}, PID: {:04x}",
device.vendor_id(),
device.product_id(),
"Track {i} Info:\n Title: {track} | {}\n Length: {:?}",
track_titlesw[i], track_lengths[i]
);
println!(
"Player Model: {}",
player_controller
.net_md_device
.device_name()
.await
.clone()
.unwrap()
);
let now = std::time::Instant::now();
let half_title = player_controller.disc_title(false).await.unwrap_or("".to_string());
let full_title = player_controller.disc_title(true).await.unwrap_or("".to_string());
println!(
"Disc Title: {} | {}",
half_title,
full_title
);
let track_count = player_controller.track_count().await.unwrap();
println!("{}", track_count);
let track_titles = player_controller.track_titles((0..track_count).collect(), false).await.unwrap();
let track_titlesw = player_controller.track_titles((0..track_count).collect(), true).await.unwrap();
let track_lengths = player_controller.track_lengths((0..track_count).collect()).await.unwrap();
for (i, track) in track_titles.iter().enumerate() {
println!(
"Track {i} Info:\n Title: {track} | {}\n Length: {:?}",
track_titlesw[i], track_lengths[i]
);
}
println!("{:?}", now.elapsed());
}
println!("{:?}", now.elapsed());
}