Extract audio and cue sheet from an NRG audio CD image.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

169 lines
5.9 KiB

  1. // This file is part of the NRGrip project.
  2. //
  3. // Copyright (c) 2016 Matteo Cypriani <mcy@lm7.fr>
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to
  7. // deal in the Software without restriction, including without limitation the
  8. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  9. // sell copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  20. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  21. // IN THE SOFTWARE.
  22. //! Module to extract the raw audio data from an NRG image file.
  23. use std::fs::File;
  24. use std::io::{Seek, SeekFrom, Read, Write};
  25. use std::path::PathBuf;
  26. use ::error::NrgError;
  27. use ::metadata::metadata::NrgMetadata;
  28. const RAW_SEC_SIZE: u16 = 2352;
  29. const RAW96_SEC_SIZE: u16 = 2448;
  30. /// Extracts the raw audio data from an NRG image.
  31. ///
  32. /// - `in_fd` is the handler to the NRG image file.
  33. /// - `img_path` is the name of the input NRG file.
  34. /// - `metadata` is the metadata extracted from `img_path` by nrgrip::metadata.
  35. ///
  36. /// The output file's name is derived from `img_path`.
  37. pub fn extract_nrg_raw_audio(in_fd: &mut File,
  38. img_path: &str,
  39. metadata: &NrgMetadata)
  40. -> Result<(), NrgError> {
  41. // Seek to the first audio byte
  42. let first_audio_byte = metadata.first_audio_byte();
  43. try!(in_fd.seek(SeekFrom::Start(first_audio_byte)));
  44. // Open output file
  45. let audio_name = try!(make_output_file_name(img_path));
  46. let mut out_fd = try!(File::create(audio_name));
  47. // Copy the audio data
  48. let count = metadata.last_audio_byte() - first_audio_byte;
  49. let bytes_read = match metadata.sector_size() {
  50. RAW96_SEC_SIZE => try!(copy_raw96_audio(in_fd, &mut out_fd, count)),
  51. 0 => return Err(NrgError::AudioReadError),
  52. _ => try!(copy_raw_audio(in_fd, &mut out_fd, count)),
  53. };
  54. assert_eq!(count, bytes_read);
  55. Ok(())
  56. }
  57. /// Reads `count` bytes from `in_fd` and write them to `out_fd`.
  58. ///
  59. /// The offsets of `in_fd` and `out_fd` are not reset prior to reading and
  60. /// writing.
  61. ///
  62. /// Returns the number of bytes read/written.
  63. fn copy_raw_audio(in_fd: &mut File, out_fd: &mut File, count: u64)
  64. -> Result<u64, NrgError> {
  65. // The buffer size (~4,6 MiB) is a multiple of the standard audio CD sector
  66. // size, i.e. 2352 bytes (it doesn't have to be, though).
  67. const BUF_SIZE: usize = RAW_SEC_SIZE as usize * 1024 * 2;
  68. // Read/write audio data
  69. let mut bytes_read = 0;
  70. while bytes_read + BUF_SIZE as u64 <= count {
  71. let mut audio_buf = [0u8; BUF_SIZE];
  72. let mut nbytes = try!(in_fd.read(&mut audio_buf));
  73. if nbytes != BUF_SIZE {
  74. return Err(NrgError::AudioReadError);
  75. }
  76. bytes_read += nbytes as u64;
  77. nbytes = try!(out_fd.write(&audio_buf));
  78. if nbytes != BUF_SIZE {
  79. return Err(NrgError::AudioWriteError);
  80. }
  81. }
  82. // Read/write the last bytes
  83. let remaining: usize = (count - bytes_read) as usize;
  84. let mut audio_buf = vec![0u8; remaining];
  85. let mut nbytes = try!(in_fd.read(&mut audio_buf));
  86. if nbytes != remaining {
  87. return Err(NrgError::AudioReadError);
  88. }
  89. bytes_read += nbytes as u64;
  90. nbytes = try!(out_fd.write(&audio_buf));
  91. if nbytes != remaining {
  92. return Err(NrgError::AudioWriteError);
  93. }
  94. Ok(bytes_read)
  95. }
  96. /// Reads `count` bytes from `in_fd` and write them to `out_fd` after stripping
  97. /// the sub-channel bytes.
  98. ///
  99. /// `in_fd` is read by chunks of 2448 bytes, then the first 2352 bytes are
  100. /// written to `out_fd`, leaving out the 96 sub-channel bytes.
  101. ///
  102. /// The offsets of `in_fd` and `out_fd` are not reset prior to reading and
  103. /// writing.
  104. ///
  105. /// Returns the number of bytes read (not written).
  106. fn copy_raw96_audio(in_fd: &mut File, out_fd: &mut File, count: u64)
  107. -> Result<u64, NrgError> {
  108. const IN_BUF_SIZE: usize = RAW96_SEC_SIZE as usize;
  109. const OUT_BUF_SIZE: usize = RAW_SEC_SIZE as usize;
  110. // Read/write audio data
  111. let mut bytes_read = 0;
  112. while bytes_read < count {
  113. let mut audio_buf = vec![0u8; IN_BUF_SIZE];
  114. let mut nbytes = try!(in_fd.read(&mut audio_buf));
  115. if nbytes != IN_BUF_SIZE {
  116. return Err(NrgError::AudioReadError);
  117. }
  118. bytes_read += nbytes as u64;
  119. audio_buf.truncate(OUT_BUF_SIZE);
  120. nbytes = try!(out_fd.write(&audio_buf));
  121. if nbytes != OUT_BUF_SIZE {
  122. return Err(NrgError::AudioWriteError);
  123. }
  124. }
  125. Ok(bytes_read)
  126. }
  127. /// Generates the output file's name from the NRG image's name.
  128. ///
  129. /// The output file's name will be `img_path`'s base name stripped for its
  130. /// extension (if any), with a ".raw" extension.
  131. fn make_output_file_name(img_path: &str) -> Result<String, NrgError> {
  132. let mut name = PathBuf::from(img_path);
  133. name.set_extension("raw");
  134. let name = try!(name.file_name().ok_or(
  135. NrgError::FileName(name.to_string_lossy().into_owned())));
  136. // Make sure the new name and the original name are different
  137. if name == img_path {
  138. return Err(NrgError::FileName("Input and output file are identical"
  139. .to_string()));
  140. }
  141. Ok(name.to_string_lossy().into_owned())
  142. }