mirror of
https://github.com/G2-Games/minidisc-cli.git
synced 2025-06-23 01:12:52 -05:00
Compare commits
3 commits
cafd518f9d
...
278ba2e8bd
Author | SHA1 | Date | |
---|---|---|---|
278ba2e8bd | |||
c51d2b700a | |||
6c1a66a97d |
6 changed files with 754 additions and 708 deletions
|
@ -17,12 +17,14 @@ encoding_rs = "0.8.33"
|
|||
magic-crypt = "3.1.12"
|
||||
nofmt = "1.0.0"
|
||||
once_cell = "1.18.0"
|
||||
regex = "1.9.5"
|
||||
unicode-jp = "0.4.0"
|
||||
unicode-normalization = "0.1.22"
|
||||
hex = "0.4.3"
|
||||
des = "0.8.1"
|
||||
webusb = "0.5.0"
|
||||
unicode-jp = "0.4.0"
|
||||
regex = "1.10.2"
|
||||
lazy_static = "1.4.0"
|
||||
yusb = "0.1.2"
|
||||
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
|
|
@ -1,20 +1,20 @@
|
|||
use nofmt;
|
||||
use once_cell::sync::Lazy;
|
||||
use webusb::{UsbDevice, UsbRecipient, UsbRequestType, UsbControlTransferParameters};
|
||||
use std::error::Error;
|
||||
use yusb::{Device, DeviceHandle, Direction, Recipient, RequestType};
|
||||
|
||||
const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::new(9999999, 0);
|
||||
|
||||
|
||||
const STANDARD_SEND: u8 =
|
||||
yusb::request_type(Direction::Out, RequestType::Vendor, Recipient::Interface);
|
||||
const STANDARD_RECV: u8 =
|
||||
yusb::request_type(Direction::In, RequestType::Vendor, Recipient::Interface);
|
||||
const BULK_WRITE_ENDPOINT: u8 = 0x02;
|
||||
const BULK_READ_ENDPOINT: u8 = 0x81;
|
||||
|
||||
pub const CHUNKSIZE: u32 = 0x10000;
|
||||
|
||||
// TODO: I think this sucks, figure out a better way
|
||||
pub static DEVICE_IDS: Lazy<Vec<DeviceId>> = Lazy::new(|| {
|
||||
nofmt::pls! {
|
||||
Vec::from([
|
||||
pub static DEVICE_IDS: Lazy<Box<[DeviceId]>> = Lazy::new(|| {
|
||||
nofmt::pls! {Box::new(
|
||||
[
|
||||
DeviceId {vendor_id: 0x04dd, product_id: 0x7202, name: Some(String::from("Sharp IM-MT899H"))},
|
||||
DeviceId {vendor_id: 0x04dd, product_id: 0x9013, name: Some(String::from("Sharp IM-DR400"))},
|
||||
DeviceId {vendor_id: 0x04dd, product_id: 0x9014, name: Some(String::from("Sharp IM-DR80"))},
|
||||
|
@ -65,6 +65,7 @@ pub static DEVICE_IDS: Lazy<Vec<DeviceId>> = Lazy::new(|| {
|
|||
}
|
||||
});
|
||||
|
||||
/// The current status of the Minidisc device
|
||||
pub enum Status {
|
||||
Ready,
|
||||
Playing,
|
||||
|
@ -76,14 +77,16 @@ pub enum Status {
|
|||
DiscBlank,
|
||||
}
|
||||
|
||||
/// The ID of a device, including the name
|
||||
pub struct DeviceId {
|
||||
vendor_id: u16,
|
||||
product_id: u16,
|
||||
name: Option<String>,
|
||||
}
|
||||
|
||||
/// A connection to a NetMD device
|
||||
pub struct NetMD {
|
||||
device_connection: UsbDevice,
|
||||
device: DeviceHandle,
|
||||
model: DeviceId,
|
||||
status: Option<Status>,
|
||||
}
|
||||
|
@ -92,12 +95,12 @@ impl NetMD {
|
|||
const READ_REPLY_RETRY_INTERVAL: u32 = 10;
|
||||
|
||||
/// Creates a new `NetMD` struct
|
||||
pub fn new(
|
||||
device: UsbDevice,
|
||||
) -> Result<Self, Box<dyn Error>> {
|
||||
pub fn new(device: Device) -> Result<Self, Box<dyn Error>> {
|
||||
let descriptor = device.device_descriptor()?;
|
||||
|
||||
let mut model = DeviceId {
|
||||
vendor_id: device.vendor_id,
|
||||
product_id: device.product_id,
|
||||
vendor_id: descriptor.vendor_id(),
|
||||
product_id: descriptor.product_id(),
|
||||
name: None,
|
||||
};
|
||||
|
||||
|
@ -116,7 +119,7 @@ impl NetMD {
|
|||
}
|
||||
|
||||
Ok(Self {
|
||||
device_connection: device,
|
||||
device: device.open()?,
|
||||
model,
|
||||
status: None,
|
||||
})
|
||||
|
@ -140,18 +143,19 @@ impl NetMD {
|
|||
/// Poll the device to get either the result
|
||||
/// of the previous command, or the status
|
||||
pub fn poll(&mut self) -> Result<(u16, [u8; 4]), Box<dyn Error>> {
|
||||
let poll_result: [u8; 4] = match self.device_connection.control_transfer_in(
|
||||
UsbControlTransferParameters {
|
||||
request_type: UsbRequestType::Vendor,
|
||||
recipient: UsbRecipient::Interface,
|
||||
request: 0x01,
|
||||
value: 0,
|
||||
index: 0,
|
||||
},
|
||||
4
|
||||
// Create an array to store the result of the poll
|
||||
let mut poll_result = [0u8; 4];
|
||||
|
||||
let _status = match self.device.read_control(
|
||||
STANDARD_RECV,
|
||||
0x01,
|
||||
0,
|
||||
0,
|
||||
&mut poll_result,
|
||||
DEFAULT_TIMEOUT,
|
||||
) {
|
||||
Ok(result) => result.try_into().unwrap(),
|
||||
Err(error) => return Err(format!("USB error: {:?}", error).into()),
|
||||
Ok(size) => size,
|
||||
Err(error) => return Err(error.into()),
|
||||
};
|
||||
|
||||
let length_bytes = [poll_result[2], poll_result[3]];
|
||||
|
@ -186,18 +190,12 @@ impl NetMD {
|
|||
true => 0xff,
|
||||
};
|
||||
|
||||
match self.device_connection.control_transfer_out(
|
||||
UsbControlTransferParameters {
|
||||
request_type: UsbRequestType::Vendor,
|
||||
recipient: UsbRecipient::Interface,
|
||||
request,
|
||||
value: 0,
|
||||
index: 0,
|
||||
},
|
||||
&command
|
||||
) {
|
||||
match self
|
||||
.device
|
||||
.write_control(STANDARD_SEND, request, 0, 0, &command, DEFAULT_TIMEOUT)
|
||||
{
|
||||
Ok(_) => Ok(()),
|
||||
Err(error) => Err(format!("USB error: {:?}", error).into()),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -231,9 +229,8 @@ impl NetMD {
|
|||
current_attempt += 1;
|
||||
}
|
||||
|
||||
match override_length {
|
||||
Some(value) => length = value as u16,
|
||||
None => (),
|
||||
if let Some(value) = override_length {
|
||||
length = value as u16
|
||||
}
|
||||
|
||||
let request = match use_factory_command {
|
||||
|
@ -242,18 +239,15 @@ impl NetMD {
|
|||
};
|
||||
|
||||
// Create a buffer to fill with the result
|
||||
match self.device_connection.control_transfer_in(
|
||||
UsbControlTransferParameters {
|
||||
request_type: UsbRequestType::Vendor,
|
||||
recipient: UsbRecipient::Interface,
|
||||
request,
|
||||
value: 0,
|
||||
index: 0,
|
||||
},
|
||||
length as usize
|
||||
) {
|
||||
Ok(data) => Ok(data),
|
||||
Err(error) => return Err(format!("USB error: {:?}", error).into()),
|
||||
let mut buf: Vec<u8> = vec![0; length as usize];
|
||||
|
||||
// Create a buffer to fill with the result
|
||||
match self
|
||||
.device
|
||||
.read_control(STANDARD_RECV, request, 0, 0, &mut buf, DEFAULT_TIMEOUT)
|
||||
{
|
||||
Ok(_) => Ok(buf),
|
||||
Err(error) => Err(error.into()),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -276,30 +270,26 @@ impl NetMD {
|
|||
while done < length {
|
||||
let to_read = std::cmp::min(chunksize, length - done);
|
||||
done -= to_read;
|
||||
let mut buffer;
|
||||
let mut buffer: Vec<u8> = vec![0; to_read as usize];
|
||||
|
||||
buffer = match self.device_connection.transfer_in(
|
||||
BULK_READ_ENDPOINT,
|
||||
to_read as usize,
|
||||
) {
|
||||
match self
|
||||
.device
|
||||
.read_bulk(BULK_READ_ENDPOINT, &mut buffer, DEFAULT_TIMEOUT)
|
||||
{
|
||||
Ok(result) => result,
|
||||
Err(error) => return Err(format!("USB error: {:?}", error).into())
|
||||
Err(error) => return Err(format!("USB error: {:?}", error).into()),
|
||||
};
|
||||
|
||||
final_result.extend_from_slice(&mut buffer);
|
||||
final_result.extend_from_slice(&buffer);
|
||||
}
|
||||
|
||||
Ok(final_result)
|
||||
}
|
||||
|
||||
pub fn write_bulk(&mut self, data: &mut Vec<u8>) -> Result<usize, Box<dyn Error>> {
|
||||
let written = match self.device_connection.transfer_out(
|
||||
BULK_WRITE_ENDPOINT,
|
||||
data
|
||||
) {
|
||||
Ok(output) => output,
|
||||
Err(error) => return Err(format!("USB error: {:?}", error).into())
|
||||
};
|
||||
pub fn write_bulk(&mut self, data: &mut [u8]) -> Result<usize, Box<dyn Error>> {
|
||||
let written = self
|
||||
.device
|
||||
.write_bulk(BULK_WRITE_ENDPOINT, data, DEFAULT_TIMEOUT)?;
|
||||
|
||||
Ok(written)
|
||||
}
|
||||
|
|
|
@ -9,9 +9,11 @@ use std::collections::HashMap;
|
|||
use std::error::Error;
|
||||
use magic_crypt::{MagicCrypt, SecureBit, MagicCryptTrait, new_magic_crypt};
|
||||
use hex;
|
||||
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
use webusb;
|
||||
use yusb;
|
||||
use lazy_static::lazy_static;
|
||||
|
||||
#[derive(Copy, Clone)]
|
||||
enum Action {
|
||||
|
@ -35,8 +37,9 @@ pub enum DiscFormat {
|
|||
SPStereo = 6,
|
||||
}
|
||||
|
||||
#[derive(Clone, Hash, Eq, PartialEq)]
|
||||
enum WireFormat {
|
||||
PCM = 0x00,
|
||||
Pcm = 0x00,
|
||||
L105kbps = 0x90,
|
||||
LP2 = 0x94,
|
||||
LP4 = 0xA8,
|
||||
|
@ -45,7 +48,7 @@ enum WireFormat {
|
|||
impl WireFormat {
|
||||
fn frame_size(&self) -> u16 {
|
||||
match self {
|
||||
WireFormat::PCM => 2048,
|
||||
WireFormat::Pcm => 2048,
|
||||
WireFormat::L105kbps => 192,
|
||||
WireFormat::LP2 => 152,
|
||||
WireFormat::LP4 => 96,
|
||||
|
@ -103,7 +106,7 @@ enum Descriptor {
|
|||
DiscTitleTD,
|
||||
AudioUTOC1TD,
|
||||
AudioUTOC4TD,
|
||||
DSITD,
|
||||
Dstid,
|
||||
AudioContentsTD,
|
||||
RootTD,
|
||||
|
||||
|
@ -117,7 +120,7 @@ impl Descriptor {
|
|||
Descriptor::DiscTitleTD => vec![0x10, 0x18, 0x01],
|
||||
Descriptor::AudioUTOC1TD => vec![0x10, 0x18, 0x02],
|
||||
Descriptor::AudioUTOC4TD => vec![0x10, 0x18, 0x03],
|
||||
Descriptor::DSITD => vec![0x10, 0x18, 0x04],
|
||||
Descriptor::Dstid => vec![0x10, 0x18, 0x04],
|
||||
Descriptor::AudioContentsTD => vec![0x10, 0x10, 0x01],
|
||||
Descriptor::RootTD => vec![0x10, 0x10, 0x00],
|
||||
Descriptor::DiscSubunitIdentifier => vec![0x00],
|
||||
|
@ -151,6 +154,15 @@ enum Status {
|
|||
Interim = 0x0f,
|
||||
}
|
||||
|
||||
lazy_static!{
|
||||
static ref FRAME_SIZE: HashMap<WireFormat, usize> = HashMap::from([
|
||||
(WireFormat::Pcm, 2048),
|
||||
(WireFormat::LP2, 192),
|
||||
(WireFormat::L105kbps, 152),
|
||||
(WireFormat::LP4, 96),
|
||||
]);
|
||||
}
|
||||
|
||||
impl std::convert::TryFrom<u8> for Status {
|
||||
type Error = Box<dyn Error>;
|
||||
|
||||
|
@ -192,13 +204,13 @@ impl NetMDInterface {
|
|||
const INTERIM_RESPONSE_RETRY_INTERVAL: u32 = 100;
|
||||
|
||||
pub fn new(
|
||||
device: webusb::UsbDevice,
|
||||
device: yusb::Device,
|
||||
) -> Result<Self, Box<dyn Error>> {
|
||||
let net_md_device = base::NetMD::new(device).unwrap();
|
||||
Ok(NetMDInterface { net_md_device })
|
||||
}
|
||||
|
||||
fn construct_multibyte(&mut self, buffer: &Vec<u8>, n: u8, offset: &mut usize) -> u32 {
|
||||
fn construct_multibyte(&mut self, buffer: &[u8], n: u8, offset: &mut usize) -> u32 {
|
||||
let mut output: u32 = 0;
|
||||
for _ in 0..n as usize {
|
||||
output <<= 8;
|
||||
|
@ -360,7 +372,7 @@ impl NetMDInterface {
|
|||
while current_attempt < Self::MAX_INTERIM_READ_ATTEMPTS {
|
||||
data = match self.net_md_device.read_reply(None) {
|
||||
Ok(reply) => reply,
|
||||
Err(error) => return Err(error.into()),
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
|
||||
let status = match Status::try_from(data[0]) {
|
||||
|
@ -810,8 +822,8 @@ impl NetMDInterface {
|
|||
|
||||
if title.ends_with(delim) {
|
||||
let first_entry = title.split(delim).collect::<Vec<&str>>()[0];
|
||||
if first_entry.starts_with(title_marker) {
|
||||
title = first_entry[title_marker.len()..].to_string();
|
||||
if let Some(stripped_title) = first_entry.strip_prefix(title_marker) {
|
||||
title = stripped_title.to_string();
|
||||
} else {
|
||||
title = String::new();
|
||||
}
|
||||
|
@ -833,19 +845,19 @@ impl NetMDInterface {
|
|||
let mut full_width_group_list = raw_full_title.split("//");
|
||||
|
||||
for (i, group) in group_list.enumerate() {
|
||||
if group == "" {
|
||||
if group.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if group.starts_with("0;") || group.find(";") == None || raw_title.find("//") == None {
|
||||
if group.starts_with("0;") || group.find(';').is_none() || !raw_title.contains("//") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let track_range: String = match group.split_once(";") {
|
||||
let track_range: String = match group.split_once(';') {
|
||||
Some(string) => string.0.to_string(),
|
||||
None => return Err("No groups were found".into()),
|
||||
};
|
||||
if track_range.len() == 0 {
|
||||
if track_range.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -856,15 +868,15 @@ impl NetMDInterface {
|
|||
let full_width_group_name = full_width_group_list
|
||||
.find(|n| n.starts_with(&full_width_range))
|
||||
.unwrap()
|
||||
.split_once(";")
|
||||
.split_once(';')
|
||||
.unwrap()
|
||||
.1;
|
||||
|
||||
let mut track_minmax: Vec<&str> = Vec::new();
|
||||
if track_range.find("-") != None {
|
||||
track_minmax = track_range.split("-").collect();
|
||||
if track_range.find('-').is_some() {
|
||||
track_minmax = track_range.split('-').collect();
|
||||
} else {
|
||||
track_minmax.push(&track_range.as_str());
|
||||
track_minmax.push(track_range.as_str());
|
||||
}
|
||||
|
||||
let (track_min, mut track_max) = (
|
||||
|
@ -872,7 +884,7 @@ impl NetMDInterface {
|
|||
track_minmax[1].parse::<u16>().unwrap(),
|
||||
);
|
||||
|
||||
track_max = u16::min(track_max, track_count as u16);
|
||||
track_max = u16::min(track_max, track_count);
|
||||
|
||||
// TODO: Do some error handling here
|
||||
assert!(track_min <= track_max);
|
||||
|
@ -895,7 +907,7 @@ impl NetMDInterface {
|
|||
));
|
||||
}
|
||||
|
||||
for i in 0..track_count as u16 {
|
||||
for i in 0..track_count {
|
||||
if !track_dict.contains_key(&i) {
|
||||
result.insert(0, (None, None, Vec::from([i])))
|
||||
}
|
||||
|
@ -1022,23 +1034,18 @@ impl NetMDInterface {
|
|||
},
|
||||
};
|
||||
|
||||
let old_len: u16;
|
||||
let new_len = new_title.len();
|
||||
|
||||
match self.track_title(track, wchar) {
|
||||
let old_len: u16 = match self.track_title(track, wchar) {
|
||||
Ok(current_title) => {
|
||||
if title == current_title {
|
||||
return Ok(())
|
||||
}
|
||||
old_len = length_after_encoding_to_jis(¤t_title) as u16;
|
||||
length_after_encoding_to_jis(¤t_title) as u16
|
||||
},
|
||||
Err(error) if error.to_string() == "Rejected" => {
|
||||
old_len = 0;
|
||||
},
|
||||
Err(error) => {
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Err(error) if error.to_string() == "Rejected" => 0,
|
||||
Err(error) => return Err(error)
|
||||
};
|
||||
|
||||
self.change_descriptor_state(&descriptor, &DescriptorAction::OpenWrite);
|
||||
let mut query = format_query(
|
||||
|
@ -1105,7 +1112,7 @@ impl NetMDInterface {
|
|||
|
||||
self.change_descriptor_state(&Descriptor::AudioContentsTD, &DescriptorAction::Close);
|
||||
|
||||
return Ok(res[0].to_vec().unwrap());
|
||||
Ok(res[0].to_vec().unwrap())
|
||||
}
|
||||
|
||||
/// Gets the length of tracks as a `std::time::Duration` from a set
|
||||
|
@ -1318,7 +1325,7 @@ impl NetMDInterface {
|
|||
let chainlen = keychain.len();
|
||||
let databytes = 16 + 16 * chainlen + 24;
|
||||
|
||||
if depth < 1 || depth > 63 {
|
||||
if !(1..=63).contains(&depth) {
|
||||
return Err("Supplied depth is invalid".into());
|
||||
}
|
||||
if ekbsignature.len() != 24 {
|
||||
|
@ -1386,7 +1393,7 @@ impl NetMDInterface {
|
|||
return Err("Supplied Session Key length wrong".into());
|
||||
}
|
||||
|
||||
let message = vec![vec![1, 1, 1, 1], contentid, keyenckey].concat();
|
||||
let message = [vec![1, 1, 1, 1], contentid, keyenckey].concat();
|
||||
|
||||
let mc = MagicCrypt::new(
|
||||
hex_session_key,
|
||||
|
@ -1465,19 +1472,17 @@ impl NetMDInterface {
|
|||
// Sharps are slow
|
||||
sleep(Duration::from_millis(200));
|
||||
|
||||
let mut packet_count = 0;
|
||||
let mut written_bytes = 0;
|
||||
for (key, iv, data) in packets {
|
||||
let mut _written_bytes = 0;
|
||||
for (packet_count, (key, iv, data)) in packets.into_iter().enumerate(){
|
||||
let mut binpack;
|
||||
if packet_count == 0 {
|
||||
let packed_length: Vec<u8> = pkt_size.to_le_bytes().to_vec();
|
||||
binpack = vec![vec![0, 0, 0, 0], packed_length, key, iv, data.clone()].concat();
|
||||
binpack = [vec![0, 0, 0, 0], packed_length, key, iv, data.clone()].concat();
|
||||
} else {
|
||||
binpack = data.clone();
|
||||
}
|
||||
self.net_md_device.write_bulk(&mut binpack)?;
|
||||
packet_count += 1;
|
||||
written_bytes += data.len();
|
||||
_written_bytes += data.len();
|
||||
}
|
||||
|
||||
reply = self.read_reply(false)?;
|
||||
|
@ -1492,8 +1497,8 @@ impl NetMDInterface {
|
|||
|
||||
let reply_data = String::from_utf8(mc.decrypt_bytes_to_bytes(&res[1].to_vec().unwrap())?).unwrap().chars().collect::<Vec<char>>();
|
||||
|
||||
let part1 = String::from_iter(reply_data.clone()[0..8].into_iter());
|
||||
let part2 = String::from_iter(reply_data.clone()[12..32].into_iter());
|
||||
let part1 = String::from_iter(reply_data.clone()[0..8].iter());
|
||||
let part2 = String::from_iter(reply_data.clone()[12..32].iter());
|
||||
|
||||
Ok((res[0].to_i64().unwrap(), part1, part2))
|
||||
}
|
||||
|
@ -1530,7 +1535,7 @@ pub fn retailmac(
|
|||
) -> Result<(), Box<dyn Error>> {
|
||||
let subkey_a = key[0..8].to_vec();
|
||||
let beginning = value[0..value.len() - 8].to_vec();
|
||||
let end = value[value.len() - 8..].to_vec();
|
||||
let _end = value[value.len() - 8..].to_vec();
|
||||
|
||||
let mc = MagicCrypt::new(
|
||||
String::from_utf8(subkey_a).unwrap(),
|
||||
|
@ -1539,13 +1544,21 @@ pub fn retailmac(
|
|||
);
|
||||
let step1 = mc.encrypt_bytes_to_bytes(&beginning);
|
||||
|
||||
let iv2 = String::from_utf8(step1);
|
||||
let _iv2 = String::from_utf8(step1);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct EKBOpenSource {
|
||||
lazy_static!{
|
||||
static ref DISC_FOR_WIRE: HashMap<WireFormat, DiscFormat> = HashMap::from([
|
||||
(WireFormat::Pcm, DiscFormat::SPStereo),
|
||||
(WireFormat::LP2, DiscFormat::LP2),
|
||||
(WireFormat::L105kbps, DiscFormat::LP2),
|
||||
(WireFormat::LP4, DiscFormat::LP4),
|
||||
]);
|
||||
}
|
||||
|
||||
struct EKBOpenSource {
|
||||
}
|
||||
|
||||
impl EKBOpenSource {
|
||||
|
@ -1577,14 +1590,66 @@ impl EKBOpenSource {
|
|||
*/
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct MDTrack {
|
||||
title: String,
|
||||
format: WireFormat,
|
||||
data: Vec<u8>,
|
||||
chunk_size: i32,
|
||||
full_width_title: Option<String>,
|
||||
encrypt_packets_iterator: EncryptPacketsIterator
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct EncryptPacketsIterator {
|
||||
kek: Vec<u8>,
|
||||
frame_size: i32,
|
||||
data: Vec<u8>,
|
||||
chunk_size: i32
|
||||
}
|
||||
|
||||
impl MDTrack {
|
||||
pub fn full_width_title(self) -> String {
|
||||
self.full_width_title.unwrap_or("".to_string())
|
||||
}
|
||||
|
||||
pub fn title(&self) -> String {
|
||||
self.title.clone()
|
||||
}
|
||||
|
||||
pub fn data_format(&self) -> WireFormat {
|
||||
self.format.clone()
|
||||
}
|
||||
|
||||
pub fn frame_count(&self) -> usize {
|
||||
self.total_size() / self.frame_size()
|
||||
}
|
||||
|
||||
pub fn frame_size(&self) -> usize {
|
||||
*FRAME_SIZE.get(&self.format).unwrap()
|
||||
}
|
||||
|
||||
pub fn chunk_size(self) -> i32 {
|
||||
self.chunk_size
|
||||
}
|
||||
|
||||
pub fn total_size(&self) -> usize {
|
||||
let frame_size = self.frame_size();
|
||||
let mut len = self.data.len();
|
||||
if len % frame_size != 0 {
|
||||
len = len + (frame_size - (len % frame_size));
|
||||
}
|
||||
len
|
||||
}
|
||||
|
||||
pub fn content_id() -> [u8; 20] {
|
||||
[0x01, 0x0f, 0x50, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x48,
|
||||
0xa2, 0x8d, 0x3e, 0x1a, 0x3b, 0x0c, 0x44, 0xaf, 0x2f, 0xa0]
|
||||
}
|
||||
|
||||
pub fn get_kek() -> [u8; 8] {
|
||||
[0x14, 0xe3, 0x83, 0x4e, 0xe2, 0xd3, 0xcc, 0xa5]
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
use once_cell::sync::Lazy;
|
||||
use lazy_static::lazy_static;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub const MAPPINGS_JP: Lazy<HashMap<String, String>> = Lazy::new(|| {[
|
||||
lazy_static! {
|
||||
pub static ref MAPPINGS_JP: HashMap<String, String> = HashMap::from([
|
||||
("!".to_string(), "!".to_string()),
|
||||
("\"".to_string(), """.to_string()),
|
||||
("#".to_string(), "#".to_string()),
|
||||
|
@ -191,9 +192,9 @@ pub const MAPPINGS_JP: Lazy<HashMap<String, String>> = Lazy::new(|| {[
|
|||
("」".to_string(), "」".to_string()),
|
||||
("。".to_string(), "。".to_string()),
|
||||
("、".to_string(), "、".to_string())
|
||||
].into_iter().collect()});
|
||||
]);
|
||||
|
||||
pub const MAPPINGS_RU: Lazy<HashMap<String, String>> = Lazy::new(|| {[
|
||||
pub static ref MAPPINGS_RU: HashMap<String, String> = HashMap::from([
|
||||
("а".to_string(), "a".to_string()),
|
||||
("б".to_string(), "b".to_string()),
|
||||
("в".to_string(), "v".to_string()),
|
||||
|
@ -260,9 +261,9 @@ pub const MAPPINGS_RU: Lazy<HashMap<String, String>> = Lazy::new(|| {[
|
|||
("Э".to_string(), "E".to_string()),
|
||||
("Ю".to_string(), "Iu".to_string()),
|
||||
("Я".to_string(), "Ia".to_string())
|
||||
].into_iter().collect()});
|
||||
]);
|
||||
|
||||
pub const MAPPINGS_DE: Lazy<HashMap<String, String>> = Lazy::new(|| {[
|
||||
pub static ref MAPPINGS_DE: HashMap<String, String> = HashMap::from([
|
||||
("Ä".to_string(), "Ae".to_string()),
|
||||
("ä".to_string(), "ae".to_string()),
|
||||
("Ö".to_string(), "Oe".to_string()),
|
||||
|
@ -270,9 +271,9 @@ pub const MAPPINGS_DE: Lazy<HashMap<String, String>> = Lazy::new(|| {[
|
|||
("Ü".to_string(), "Ue".to_string()),
|
||||
("ü".to_string(), "ue".to_string()),
|
||||
("ß".to_string(), "ss".to_string())
|
||||
].into_iter().collect()});
|
||||
]);
|
||||
|
||||
pub const MAPPINGS_HW: Lazy<HashMap<String, String>> = Lazy::new(|| {[
|
||||
pub static ref MAPPINGS_HW: HashMap<String, String> = HashMap::from([
|
||||
("-".to_string(),"-".to_string()),
|
||||
("ー".to_string(),"-".to_string()),
|
||||
("ァ".to_string(),"ァ".to_string()),
|
||||
|
@ -551,6 +552,7 @@ pub const MAPPINGS_HW: Lazy<HashMap<String, String>> = Lazy::new(|| {[
|
|||
("ゔ".to_string(),"ヴ".to_string()),
|
||||
("ゝ".to_string(),"ヽ".to_string()),
|
||||
("ゞ".to_string(),"ヾ".to_string()),
|
||||
].into_iter().collect()});
|
||||
]);
|
||||
|
||||
pub const ALLOWED_HW_KANA: Lazy<Vec<String>> = Lazy::new(|| {MAPPINGS_HW.values().cloned().collect()});
|
||||
pub static ref ALLOWED_HW_KANA: Vec<String> = MAPPINGS_HW.values().cloned().collect();
|
||||
}
|
||||
|
|
|
@ -1,26 +1,23 @@
|
|||
use crate::netmd::utils;
|
||||
use once_cell::sync::Lazy;
|
||||
use lazy_static::lazy_static;
|
||||
use std::collections::hash_map::HashMap;
|
||||
use std::error::Error;
|
||||
|
||||
/**
|
||||
%b, w, d, q - explained above (can have endiannes overriden by '>' and '<' operators, f. ex. %>d %<q)
|
||||
%s - Uint8Array preceded by 2 bytes of length
|
||||
%x - Uint8Array preceded by 2 bytes of length
|
||||
%z - Uint8Array preceded by 1 byte of length
|
||||
%* - raw Uint8Array
|
||||
%B - BCD-encoded 1-byte number
|
||||
%W - BCD-encoded 2-byte number
|
||||
*/
|
||||
|
||||
const FORMAT_TYPE_LEN_DICT: Lazy<HashMap<char, i32>> = Lazy::new(|| {
|
||||
HashMap::from([
|
||||
lazy_static!{
|
||||
/// %b, w, d, q - explained above (can have endiannes overriden by '>' and '<' operators, f. ex. %>d %<q)
|
||||
/// %s - Uint8Array preceded by 2 bytes of length
|
||||
/// %x - Uint8Array preceded by 2 bytes of length
|
||||
/// %z - Uint8Array preceded by 1 byte of length
|
||||
/// %* - raw Uint8Array
|
||||
/// %B - BCD-encoded 1-byte number
|
||||
/// %W - BCD-encoded 2-byte number
|
||||
static ref FORMAT_TYPE_LEN_DICT: HashMap<char, i32> = HashMap::from([
|
||||
('b', 1), // byte
|
||||
('w', 2), // word
|
||||
('d', 4), // doubleword
|
||||
('q', 8), // quadword
|
||||
])
|
||||
});
|
||||
]);
|
||||
}
|
||||
|
||||
const DEBUG: bool = false;
|
||||
|
||||
|
@ -108,7 +105,7 @@ pub fn format_query(
|
|||
result.push(0);
|
||||
}
|
||||
}
|
||||
character if character == '*' => {
|
||||
'*' => {
|
||||
let mut array_value = arg_stack.next().unwrap().to_vec().unwrap();
|
||||
result.append(&mut array_value);
|
||||
}
|
||||
|
@ -215,17 +212,17 @@ pub fn scan_query(
|
|||
character if character == '*' || character == '#' => {
|
||||
let mut result_buffer: Vec<u8> = Vec::new();
|
||||
let temp_stack = input_stack.clone();
|
||||
for entry in temp_stack.take(initial_length as usize) {
|
||||
for entry in temp_stack.take(initial_length) {
|
||||
result_buffer.push(entry);
|
||||
input_stack.next();
|
||||
}
|
||||
result.push(QueryValue::Array(result_buffer));
|
||||
}
|
||||
character if character == 'B' => {
|
||||
'B' => {
|
||||
let v = input_stack.next().unwrap();
|
||||
result.push(QueryValue::Number(utils::bcd_to_int(v as i32) as i64));
|
||||
}
|
||||
character if character == 'W' => {
|
||||
'W' => {
|
||||
let v = (input_stack.next().unwrap() as i32) << 8
|
||||
| input_stack.next().unwrap() as i32;
|
||||
result.push(QueryValue::Number(utils::bcd_to_int(v) as i64));
|
||||
|
|
|
@ -2,7 +2,7 @@ use crate::netmd::mappings::{ALLOWED_HW_KANA, MAPPINGS_DE, MAPPINGS_HW, MAPPINGS
|
|||
use diacritics;
|
||||
use encoding_rs::SHIFT_JIS;
|
||||
use regex::Regex;
|
||||
use std::collections::hash_map::HashMap;
|
||||
use std::{collections::hash_map::HashMap, error::Error, vec::IntoIter};
|
||||
use unicode_normalization::UnicodeNormalization;
|
||||
|
||||
extern crate kana;
|
||||
|
@ -14,7 +14,7 @@ pub fn bcd_to_int(mut bcd: i32) -> i32 {
|
|||
|
||||
while bcd != 0 {
|
||||
let nibble_value = bcd & 0xf;
|
||||
bcd = bcd >> 4;
|
||||
bcd >>= 4;
|
||||
value += nibble_value * i32::pow(10, nibble);
|
||||
nibble += 1;
|
||||
}
|
||||
|
@ -36,7 +36,7 @@ pub fn int_to_bcd(mut value: i32) -> i32 {
|
|||
bcd
|
||||
}
|
||||
|
||||
pub fn half_width_to_full_width_range(range: &String) -> String {
|
||||
pub fn half_width_to_full_width_range(range: &str) -> String {
|
||||
let mappings: HashMap<char, char> = HashMap::from([
|
||||
('0', '0'),
|
||||
('1', '1'),
|
||||
|
@ -60,21 +60,15 @@ pub fn half_width_to_full_width_range(range: &String) -> String {
|
|||
}
|
||||
|
||||
pub fn get_bytes<const S: usize>(
|
||||
iterator: &mut std::vec::IntoIter<u8>,
|
||||
) -> Result<[u8; S], Box<dyn std::error::Error>> {
|
||||
let mut bytes = [0; S];
|
||||
|
||||
for i in 0..S {
|
||||
bytes[i] = match iterator.next() {
|
||||
Some(byte) => byte,
|
||||
None => return Err("Could not retrieve byte from file".into()),
|
||||
};
|
||||
}
|
||||
iterator: &mut IntoIter<u8>,
|
||||
) -> Result<[u8; S], Box<dyn Error>> {
|
||||
let byte_vec: Vec<u8> = iterator.take(S).collect();
|
||||
let bytes: [u8; S] = byte_vec.try_into().unwrap();
|
||||
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub fn length_after_encoding_to_jis(string: &String) -> usize {
|
||||
pub fn length_after_encoding_to_jis(string: &str) -> usize {
|
||||
let new_string = SHIFT_JIS.encode(string);
|
||||
|
||||
new_string.0.len()
|
||||
|
@ -83,11 +77,7 @@ pub fn length_after_encoding_to_jis(string: &String) -> usize {
|
|||
pub fn validate_shift_jis(sjis_string: Vec<u8>) -> bool {
|
||||
let (_, _, had_errors) = SHIFT_JIS.decode(&sjis_string);
|
||||
|
||||
if had_errors {
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
had_errors
|
||||
}
|
||||
|
||||
fn check(string: String) -> Option<String> {
|
||||
|
@ -124,11 +114,11 @@ pub fn sanitize_half_width_title(mut title: String) -> Vec<u8> {
|
|||
return agressive_sanitize_title(&title).into();
|
||||
}
|
||||
|
||||
return sjis_string.into();
|
||||
sjis_string.into()
|
||||
}
|
||||
|
||||
// TODO: This function is bad, probably should do the string sanitization in the frontend
|
||||
pub fn sanitize_full_width_title(title: &String, just_remap: bool) -> Vec<u8> {
|
||||
pub fn sanitize_full_width_title(title: &str, just_remap: bool) -> Vec<u8> {
|
||||
let new_title: String = title
|
||||
.chars()
|
||||
.map(|character| {
|
||||
|
@ -161,13 +151,13 @@ pub fn sanitize_full_width_title(title: &String, just_remap: bool) -> 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();
|
||||
}
|
||||
|
||||
return sjis_string.into();
|
||||
sjis_string.into()
|
||||
}
|
||||
|
||||
pub fn agressive_sanitize_title(title: &String) -> String {
|
||||
pub fn agressive_sanitize_title(title: &str) -> String {
|
||||
let re = Regex::new(r"[^\x00-\x7F]").unwrap();
|
||||
re.replace_all(
|
||||
&diacritics::remove_diacritics(title)
|
||||
|
|
Loading…
Reference in a new issue