ra_mp64_srm_convert 0.9.1

A simple application to convert to and from Retroarch Mupen64 save file.
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
mod mempack;

use mempack::Mempack;

use std::{
  collections::{HashMap, VecDeque},
  ffi::{OsStr, OsString},
  fs::{File, OpenOptions},
  io::Read,
  io::{ErrorKind, Write},
  path::{Path, PathBuf},
  str::FromStr,
};
use structopt::StructOpt;

struct Eeprom {
  data: [u8; 0x800],
}
impl Eeprom {
  fn is_empty(&self) -> bool {
    self.data.iter().rposition(|b| *b != 0xff) == None
  }

  fn new() -> Self {
    Self {
      data: [0xff; 0x800],
    }
  }

  fn save(&self, file: &mut File) -> std::io::Result<()> {
    file.write_all(&self.data)
  }
}

struct Sram {
  data: [u8; 0x8000],
}
impl Sram {
  fn is_empty(&self) -> bool {
    self.data.iter().rposition(|b| *b != 0xff) == None
  }

  fn new() -> Self {
    Self {
      data: [0xff; 0x8000],
    }
  }

  fn save(&self, file: &mut File) -> std::io::Result<()> {
    file.write_all(&self.data)
  }
}

struct FlashRam {
  data: [u8; 0x20000],
}
impl FlashRam {
  fn is_empty(&self) -> bool {
    self.data.iter().rposition(|b| *b != 0xff) == None
  }

  fn new() -> Self {
    Self {
      data: [0xff; 0x20000],
    }
  }

  fn save(&self, file: &mut File) -> std::io::Result<()> {
    file.write_all(&self.data)
  }
}

struct Srm {
  eeprom: Eeprom,
  mempack: [Mempack; 4],
  sram: Sram,
  flashram: FlashRam,
}

impl Srm {
  fn new() -> Self {
    Self {
      eeprom: Eeprom::new(),
      mempack: [
        Mempack::new(),
        Mempack::new(),
        Mempack::new(),
        Mempack::new(),
      ],
      sram: Sram::new(),
      flashram: FlashRam::new(),
    }
  }

  fn init(&mut self) {
    // Initialize the mempacks
    for mp in &mut self.mempack {
      mp.init()
    }
  }

  fn load(&mut self, file: &mut File) -> std::io::Result<()> {
    file.read(&mut self.eeprom.data)?;
    for i in 0..4 {
      let mut data = [0; 0x8000];
      file.read_exact(data.as_mut())?;
      self.mempack[i] = data.into();
    }
    file.read(&mut self.sram.data)?;
    file.read(&mut self.flashram.data).map(|_| ())
  }

  fn save(&self, file: &mut File) -> std::io::Result<()> {
    self.eeprom.save(file)?;
    for mp in &self.mempack {
      mp.save(file)?;
    }
    self.sram.save(file)?;
    self.flashram.save(file)
  }
}

enum SaveType {
  UNSUPPORTED,
  SRM,
  FLA,
  EEP,
  SRA,
  MPK,
}
impl FromStr for SaveType {
  type Err = &'static str;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    match s.to_uppercase().as_str() {
      "SRM" => Ok(SaveType::SRM),
      "FLA" => Ok(SaveType::FLA),
      "EEP" => Ok(SaveType::EEP),
      "MPK" => Ok(SaveType::MPK),
      "SRA" => Ok(SaveType::SRA),
      _ => Err("Unexpected save type"),
    }
  }
}
impl From<&OsStr> for SaveType {
  fn from(s: &OsStr) -> Self {
    match s.to_ascii_uppercase().to_str() {
      Some("SRM") => SaveType::SRM,
      Some("FLA") => SaveType::FLA,
      Some("EEP") => SaveType::EEP,
      Some("MPK") => SaveType::MPK,
      Some("SRA") => SaveType::SRA,
      _ => SaveType::UNSUPPORTED,
    }
  }
}

#[derive(Default)]
struct ConvertArgs<'a> {
  overwrite: bool,
  out_dir: Option<&'a PathBuf>,
  srm_file: Option<&'a PathBuf>,
  eep_file: Option<&'a PathBuf>,
  mpk_files: [Option<&'a PathBuf>; 4],
  sra_file: Option<&'a PathBuf>,
  fla_file: Option<&'a PathBuf>,
}

fn output_file(in_path: &Path, out_dir: &Option<&PathBuf>) -> PathBuf {
  out_dir.map_or_else(
    || in_path.to_owned(),
    |dir| {
      let mut out_dir = dir.to_path_buf();
      out_dir.push(in_path.file_name().unwrap());
      out_dir
    },
  )
}

fn to_srm<'a>(args: ConvertArgs<'a>) -> std::io::Result<()> {
  // here we should get the files to put into the srm
  let mut srm = Box::new(Srm::new());
  srm.init();

  let mut load_opts = OpenOptions::new();
  load_opts.read(true);

  // setup now the save options in case the srm file exists, which we should update
  let mut save_opts = OpenOptions::new();
  save_opts
    .create(args.overwrite)
    .create_new(!args.overwrite)
    .write(true);

  // If the srm file exists, its update mode!
  if let Some(srm_file) = &args.srm_file {
    if srm_file.is_file() {
      srm.load(&mut load_opts.open(srm_file)?)?;
      save_opts.create(true).create_new(false);
    }
  }

  if let Some(path) = args.eep_file {
    load_opts.open(path)?.read(&mut srm.eeprom.data)?;
  }
  for (i, mp) in args.mpk_files.iter().enumerate() {
    if let Some(path) = mp {
      let mut data = [0u8; 0x8000];
      load_opts.open(path)?.read(data.as_mut())?;
      srm.mempack[i] = data.into();
    }
  }
  if let Some(path) = args.sra_file {
    load_opts.open(path)?.read(&mut srm.sram.data)?;
  }
  if let Some(path) = args.fla_file {
    load_opts.open(path)?.read(&mut srm.flashram.data)?;
  }

  let mut srm_file = save_opts.open(output_file(args.srm_file.unwrap(), &args.out_dir))?;
  srm.save(&mut srm_file)
}

fn from_srm<'a>(args: ConvertArgs<'a>) -> std::io::Result<()> {
  let input = args.srm_file.as_ref().unwrap();

  let mut srm = Box::from(Srm::new());
  {
    let mut file = OpenOptions::new().read(true).open(input)?;
    srm.load(&mut file)?;
  }

  let mut open_opts = OpenOptions::new();
  open_opts
    .create(args.overwrite)
    .create_new(!args.overwrite)
    .write(true);
  let mut existing_open = OpenOptions::new();
  existing_open.create(true).write(true);

  if !srm.eeprom.is_empty() {
    let mut file = args.eep_file.map_or_else(
      || open_opts.open(output_file(&input.with_extension("eep"), &args.out_dir)),
      |f| existing_open.open(output_file(f, &args.out_dir)),
    )?;
    srm.eeprom.save(&mut file)?;
  }
  for (i, mp) in srm.mempack.iter().enumerate() {
    if mp.is_empty() {
      continue;
    }
    let mut file = args.mpk_files[i].map_or_else(
      || {
        let mut file_name = input.file_stem().unwrap().to_owned();
        file_name.push((i + 1).to_string());
        file_name.push(".mpk");
        open_opts.open(output_file(&input.with_file_name(file_name), &args.out_dir))
      },
      |f| existing_open.open(output_file(f, &args.out_dir)),
    )?;
    mp.save(&mut file)?;
  }
  if !srm.sram.is_empty() {
    let mut file = args.sra_file.map_or_else(
      || open_opts.open(output_file(&input.with_extension("sra"), &args.out_dir)),
      |f| existing_open.open(output_file(f, &args.out_dir)),
    )?;
    srm.sram.save(&mut file)?;
  }
  if !srm.flashram.is_empty() {
    let mut file = args.fla_file.map_or_else(
      || open_opts.open(output_file(&input.with_extension("fla"), &args.out_dir)),
      |f| existing_open.open(output_file(f, &args.out_dir)),
    )?;
    srm.flashram.save(&mut file)?;
  }
  Ok(())
}

#[derive(StructOpt)]
/// A simple converter for Retroarch's Mupen64 core save files.
/// It detects the input file and "converts" it into an *.srm, or extracts from it into the other files.
struct MupenSrmConvert {
  #[structopt(long)]
  /// If set, the program can overwrite an existing filesystem files
  overwrite: bool,

  #[structopt(long, parse(from_os_str))]
  /// Specify the output directory for the created file (or files)
  output_dir: Option<PathBuf>,

  #[structopt(parse(from_os_str), min_values = 1, required = true)]
  /// The input file(s).
  /// It can be *.srm (to extract), or *.sra, *.fla, *.eep or *.mpk (to create, based on file name)
  files: Vec<PathBuf>,
}

fn run() -> std::io::Result<Vec<(String, std::io::Error)>> {
  let args = MupenSrmConvert::from_args();
  let mut map = HashMap::<OsString, VecDeque<(PathBuf, SaveType)>>::new();

  // if there is out dir, check!
  if let Some(out_dir) = args.output_dir.as_ref() {
    if out_dir.exists() && !out_dir.is_dir() {
      return Err(std::io::Error::new(
        ErrorKind::Other,
        "Ouput directory path is not a directory!",
      ));
    }
    if !out_dir.exists() {
      std::fs::create_dir_all(out_dir)?;
    }
  }

  for file in args.files.into_iter() {
    if file.exists() && !file.is_file() {
      continue;
    }

    let save_type: SaveType = if let Some(ext) = file.extension() {
      ext.into()
    } else {
      continue;
    };
    match save_type {
      SaveType::UNSUPPORTED => continue,
      _ => {}
    }

    // get the vector
    let vector = file
      .file_stem()
      .map(|name| map.entry(name.into()).or_default());

    if let Some(v) = vector {
      v.push_back((file, save_type));
    }
  }

  if map.len() == 0 {
    return Err(std::io::Error::new(
      ErrorKind::Other,
      "Invalid input file(s)",
    ));
  }

  let mut file_errs = vec![];

  let work_groups = map.len();

  // Now work per file name
  for files in map.into_values() {
    let (path, save_type) = files.front().unwrap();

    let mut args = ConvertArgs {
      overwrite: args.overwrite,
      ..ConvertArgs::default()
    };

    let mut mpk_idx = 0;
    for (file, stype) in &files {
      match stype {
        SaveType::EEP => args.eep_file = Some(file),
        SaveType::FLA => args.fla_file = Some(file),
        SaveType::MPK => {
          args.mpk_files[mpk_idx] = Some(file);
          mpk_idx += 1;
        }
        SaveType::SRA => args.sra_file = Some(file),
        SaveType::SRM => args.srm_file = Some(file),
        _ => unreachable!(),
      }
    }

    match match save_type {
      SaveType::SRM => from_srm(args),
      _ => {
        let srmp = path.with_extension("srm");
        if args.srm_file.is_none() {
          args.srm_file = Some(&srmp);
        }
        to_srm(args)
      }
    } {
      Ok(_) => {}
      Err(error) => file_errs.push((
        path.file_name().unwrap().to_str().unwrap().to_owned(),
        error,
      )),
    }
  }

  if work_groups == file_errs.len() {
    let mut msg = Vec::with_capacity(file_errs.len() + 1);
    msg.push("Could not process any file!".to_owned());
    for err in file_errs.into_iter() {
      msg.push(format!("-  While working with '{}': {}", err.0, err.1));
    }
    Err(std::io::Error::new(ErrorKind::Other, msg.join("\n")))
  } else {
    Ok(file_errs)
  }
}

fn main() {
  match run() {
    Ok(file_errs) => {
      if !file_errs.is_empty() {
        println!("WARN: Some errors found while working");
      }
      for err in file_errs.into_iter() {
        println!("ERROR: while working with '{}': {}", err.0, err.1)
      }
    }
    Err(error) => {
      write!(std::io::stderr(), "ERROR: {}", error).unwrap();
    }
  }
}