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.

173 lines
6.0 KiB

  1. // This file is part of the NRGrip project.
  2. //
  3. // Copyright (c) 2016, 2018 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. strip_subchannel: bool)
  41. -> Result<(), NrgError> {
  42. // Seek to the first audio byte
  43. let first_audio_byte = metadata.first_audio_byte();
  44. try!(in_fd.seek(SeekFrom::Start(first_audio_byte)));
  45. // Open output file
  46. let audio_name = try!(make_output_file_name(img_path));
  47. let mut out_fd = try!(File::create(audio_name));
  48. // Copy the audio data
  49. let count = metadata.last_audio_byte() - first_audio_byte;
  50. if metadata.sector_size() == 0 {
  51. return Err(NrgError::AudioReadError);
  52. }
  53. let bytes_read =
  54. if strip_subchannel && metadata.sector_size() == RAW96_SEC_SIZE {
  55. try!(copy_raw96_audio(in_fd, &mut out_fd, count))
  56. } else {
  57. try!(copy_raw_audio(in_fd, &mut out_fd, count))
  58. };
  59. assert_eq!(count, bytes_read);
  60. Ok(())
  61. }
  62. /// Reads `count` bytes from `in_fd` and write them to `out_fd`.
  63. ///
  64. /// The offsets of `in_fd` and `out_fd` are not reset prior to reading and
  65. /// writing.
  66. ///
  67. /// Returns the number of bytes read/written.
  68. fn copy_raw_audio(in_fd: &mut File, out_fd: &mut File, count: u64)
  69. -> Result<u64, NrgError> {
  70. // The buffer size (~4,6 MiB) is a multiple of the standard audio CD sector
  71. // size, i.e. 2352 bytes (it doesn't have to be, though).
  72. const BUF_SIZE: usize = RAW_SEC_SIZE as usize * 1024 * 2;
  73. // Read/write audio data
  74. let mut bytes_read = 0;
  75. while bytes_read + BUF_SIZE as u64 <= count {
  76. let mut audio_buf = [0u8; BUF_SIZE];
  77. let mut nbytes = try!(in_fd.read(&mut audio_buf));
  78. if nbytes != BUF_SIZE {
  79. return Err(NrgError::AudioReadError);
  80. }
  81. bytes_read += nbytes as u64;
  82. nbytes = try!(out_fd.write(&audio_buf));
  83. if nbytes != BUF_SIZE {
  84. return Err(NrgError::AudioWriteError);
  85. }
  86. }
  87. // Read/write the last bytes
  88. let remaining: usize = (count - bytes_read) as usize;
  89. let mut audio_buf = vec![0u8; remaining];
  90. let mut nbytes = try!(in_fd.read(&mut audio_buf));
  91. if nbytes != remaining {
  92. return Err(NrgError::AudioReadError);
  93. }
  94. bytes_read += nbytes as u64;
  95. nbytes = try!(out_fd.write(&audio_buf));
  96. if nbytes != remaining {
  97. return Err(NrgError::AudioWriteError);
  98. }
  99. Ok(bytes_read)
  100. }
  101. /// Reads `count` bytes from `in_fd` and write them to `out_fd` after stripping
  102. /// the sub-channel bytes.
  103. ///
  104. /// `in_fd` is read by chunks of 2448 bytes, then the first 2352 bytes are
  105. /// written to `out_fd`, leaving out the 96 sub-channel bytes.
  106. ///
  107. /// The offsets of `in_fd` and `out_fd` are not reset prior to reading and
  108. /// writing.
  109. ///
  110. /// Returns the number of bytes read (not written).
  111. fn copy_raw96_audio(in_fd: &mut File, out_fd: &mut File, count: u64)
  112. -> Result<u64, NrgError> {
  113. const IN_BUF_SIZE: usize = RAW96_SEC_SIZE as usize;
  114. const OUT_BUF_SIZE: usize = RAW_SEC_SIZE as usize;
  115. // Read/write audio data
  116. let mut bytes_read = 0;
  117. while bytes_read < count {
  118. let mut audio_buf = vec![0u8; IN_BUF_SIZE];
  119. let mut nbytes = try!(in_fd.read(&mut audio_buf));
  120. if nbytes != IN_BUF_SIZE {
  121. return Err(NrgError::AudioReadError);
  122. }
  123. bytes_read += nbytes as u64;
  124. audio_buf.truncate(OUT_BUF_SIZE);
  125. nbytes = try!(out_fd.write(&audio_buf));
  126. if nbytes != OUT_BUF_SIZE {
  127. return Err(NrgError::AudioWriteError);
  128. }
  129. }
  130. Ok(bytes_read)
  131. }
  132. /// Generates the output file's name from the NRG image's name.
  133. ///
  134. /// The output file's name will be `img_path`'s base name stripped for its
  135. /// extension (if any), with a ".raw" extension.
  136. fn make_output_file_name(img_path: &str) -> Result<String, NrgError> {
  137. let mut name = PathBuf::from(img_path);
  138. name.set_extension("raw");
  139. let name = try!(name.file_name().ok_or(
  140. NrgError::FileName(name.to_string_lossy().into_owned())));
  141. // Make sure the new name and the original name are different
  142. if name == img_path {
  143. return Err(NrgError::FileName("Input and output file are identical"
  144. .to_string()));
  145. }
  146. Ok(name.to_string_lossy().into_owned())
  147. }