├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── README.md ├── examples └── decode-encode.rs └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled files 2 | *.o 3 | *.so 4 | *.rlib 5 | *.dll 6 | 7 | # Executables 8 | *.exe 9 | 10 | # Generated by Cargo 11 | target/ 12 | Cargo.lock 13 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | 3 | sudo: true 4 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "vorbis" 3 | version = "0.1.0" 4 | authors = ["Pierre Krieger "] 5 | description = "High-level bindings for the official libvorbis library." 6 | repository = "https://github.com/tomaka/vorbis-rs" 7 | license = "Apache-2.0" 8 | 9 | [dependencies] 10 | libc = "0.2" 11 | ogg-sys = "0.0.9" 12 | rand = "0.3" 13 | vorbis-sys = "0.0.8" 14 | vorbis-encoder = "0.1" 15 | vorbisfile-sys = "0.0.8" 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vorbis-rs 2 | 3 | Simple vorbis decoder in Rust, using libvorbis. 4 | 5 | ```toml 6 | [dependencies.vorbis] 7 | git = "https://github.com/tomaka/vorbis-rs" 8 | ``` 9 | 10 | ## Example music 11 | 12 | The example music is under the **EFF Open Audio License Version 1.0**. 13 | -------------------------------------------------------------------------------- /examples/decode-encode.rs: -------------------------------------------------------------------------------- 1 | extern crate vorbis; 2 | 3 | use std::io::Write; 4 | 5 | fn main() { 6 | let mut args = std::env::args(); 7 | args.next(); 8 | // It needs 3 file address as arguments: 9 | // first for input vorbis, 10 | // second for pcm output file, 11 | // third for 12 | let error = "Error: Usage is "; 13 | let in_file = args.next().expect(error); 14 | let in_file = std::fs::File::open(in_file).unwrap(); 15 | let pcm_file = args.next().expect(error); 16 | let mut pcm_file = std::fs::File::create(pcm_file).unwrap(); 17 | let out_file = args.next().expect(error); 18 | let mut out_file = std::fs::File::create(out_file).unwrap(); 19 | let mut decoder = vorbis::Decoder::new(in_file).unwrap(); 20 | let packets = decoder.packets(); 21 | let mut data = Vec::new(); 22 | let mut channels = 0; 23 | let mut rate = 0; 24 | let mut bitrate_upper = 0; 25 | let mut bitrate_nominal = 0; 26 | let mut bitrate_lower = 0; 27 | let mut bitrate_window = 0; 28 | for p in packets { 29 | match p { 30 | Ok(packet) => { 31 | channels = packet.channels; 32 | rate = packet.rate; 33 | bitrate_upper = packet.bitrate_upper; 34 | bitrate_nominal = packet.bitrate_nominal; 35 | bitrate_lower = packet.bitrate_lower; 36 | bitrate_window = packet.bitrate_window; 37 | let mut file_data = vec![0u8; packet.data.len() << 1]; 38 | let mut index = 0; 39 | for sample in packet.data { 40 | file_data[index] = (sample as u32 & 255) as u8; 41 | index+=1; 42 | file_data[index] = ((sample as u32 >> 8) & 255) as u8; 43 | index+=1; 44 | data.push(sample); 45 | } 46 | pcm_file.write(&file_data[..]).unwrap(); 47 | }, 48 | _ => {} 49 | } 50 | } 51 | println!("PCM data size: {}", data.len()); 52 | println!("channels: {:?}", channels); 53 | println!("rate: {:?}", rate); 54 | println!("bitrate_upper: {:?}", bitrate_upper); 55 | println!("bitrate_nominal: {:?}", bitrate_nominal); 56 | println!("bitrate_lower: {:?}", bitrate_lower); 57 | println!("bitrate_window: {:?}", bitrate_window); 58 | let mut encoder = vorbis::Encoder::new(channels as u8, rate, vorbis::VorbisQuality::Midium).expect("Error in creating encoder"); 59 | out_file.write(encoder.encode(&data).expect("Error in encoding.").as_slice()).expect("Error in writing"); 60 | out_file.write(encoder.flush().expect("Error in flushing.").as_slice()).expect("Error in writing"); 61 | } 62 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | extern crate ogg_sys; 2 | extern crate vorbis_sys; 3 | extern crate vorbisfile_sys; 4 | extern crate vorbis_encoder; 5 | extern crate libc; 6 | extern crate rand; 7 | 8 | use std::io::{self, Read, Seek}; 9 | 10 | /// Allows you to decode a sound file stream into packets. 11 | pub struct Decoder where R: Read + Seek { 12 | // further informations are boxed so that a pointer can be passed to callbacks 13 | data: Box>, 14 | } 15 | 16 | /// 17 | pub struct PacketsIter<'a, R: 'a + Read + Seek>(&'a mut Decoder); 18 | 19 | /// 20 | pub struct PacketsIntoIter(Decoder); 21 | 22 | /// Errors that can happen while decoding & encoding 23 | #[derive(Debug)] 24 | pub enum VorbisError { 25 | ReadError(io::Error), 26 | NotVorbis, 27 | VersionMismatch, 28 | BadHeader, 29 | Hole, 30 | InvalidSetup, // OV_EINVAL - Invalid setup request, eg, out of range argument. 31 | Unimplemented, // OV_EIMPL - Unimplemented mode; unable to comply with quality level request. 32 | } 33 | 34 | impl std::error::Error for VorbisError { 35 | fn description(&self) -> &str { 36 | match self { 37 | &VorbisError::ReadError(_) => "A read from media returned an error", 38 | &VorbisError::NotVorbis => "Bitstream does not contain any Vorbis data", 39 | &VorbisError::VersionMismatch => "Vorbis version mismatch", 40 | &VorbisError::BadHeader => "Invalid Vorbis bitstream header", 41 | &VorbisError::InvalidSetup => "Invalid setup request, eg, out of range argument or initial file headers are corrupt", 42 | &VorbisError::Hole => "Interruption of data", 43 | &VorbisError::Unimplemented => "Unimplemented mode; unable to comply with quality level request.", 44 | } 45 | } 46 | 47 | fn cause(&self) -> Option<&std::error::Error> { 48 | match self { 49 | &VorbisError::ReadError(ref err) => Some(err as &std::error::Error), 50 | _ => None 51 | } 52 | } 53 | } 54 | 55 | impl std::fmt::Display for VorbisError { 56 | fn fmt(&self, fmt: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { 57 | write!(fmt, "{}", std::error::Error::description(self)) 58 | } 59 | } 60 | 61 | impl From for VorbisError { 62 | fn from(err: io::Error) -> VorbisError { 63 | VorbisError::ReadError(err) 64 | } 65 | } 66 | 67 | struct DecoderData where R: Read + Seek { 68 | vorbis: vorbisfile_sys::OggVorbis_File, 69 | reader: R, 70 | current_logical_bitstream: libc::c_int, 71 | read_error: Option, 72 | } 73 | 74 | unsafe impl Send for DecoderData {} 75 | 76 | /// Packet of data. 77 | /// 78 | /// Each sample is an `i16` ranging from I16_MIN to I16_MAX. 79 | /// 80 | /// The channels are interleaved in the data. For example if you have two channels, you will 81 | /// get a sample from channel 1, then a sample from channel 2, than a sample from channel 1, etc. 82 | #[derive(Clone, Debug)] 83 | pub struct Packet { 84 | pub data: Vec, 85 | pub channels: u16, 86 | pub rate: u64, 87 | pub bitrate_upper: u64, 88 | pub bitrate_nominal: u64, 89 | pub bitrate_lower: u64, 90 | pub bitrate_window: u64, 91 | } 92 | 93 | impl Decoder where R: Read + Seek { 94 | pub fn new(input: R) -> Result, VorbisError> { 95 | extern fn read_func(ptr: *mut libc::c_void, size: libc::size_t, nmemb: libc::size_t, 96 | datasource: *mut libc::c_void) -> libc::size_t where R: Read + Seek 97 | { 98 | use std::slice; 99 | 100 | /* 101 | * In practice libvorbisfile always sets size to 1. 102 | * This assumption makes things much simpler 103 | */ 104 | assert_eq!(size, 1); 105 | 106 | let ptr = ptr as *mut u8; 107 | 108 | let data: &mut DecoderData = unsafe { std::mem::transmute(datasource) }; 109 | 110 | let buffer = unsafe { slice::from_raw_parts_mut(ptr as *mut u8, nmemb as usize) }; 111 | 112 | loop { 113 | match data.reader.read(buffer) { 114 | Ok(nb) => return nb as libc::size_t, 115 | Err(ref e) if e.kind() == io::ErrorKind::Interrupted => (), 116 | Err(e) => { 117 | data.read_error = Some(e); 118 | return 0 119 | } 120 | } 121 | } 122 | } 123 | 124 | extern fn seek_func(datasource: *mut libc::c_void, offset: ogg_sys::ogg_int64_t, 125 | whence: libc::c_int) -> libc::c_int where R: Read + Seek 126 | { 127 | let data: &mut DecoderData = unsafe { std::mem::transmute(datasource) }; 128 | 129 | let result = match whence { 130 | libc::SEEK_SET => data.reader.seek(io::SeekFrom::Start(offset as u64)), 131 | libc::SEEK_CUR => data.reader.seek(io::SeekFrom::Current(offset)), 132 | libc::SEEK_END => data.reader.seek(io::SeekFrom::End(offset)), 133 | _ => unreachable!() 134 | }; 135 | 136 | match result { 137 | Ok(_) => 0, 138 | Err(_) => -1 139 | } 140 | } 141 | 142 | extern fn tell_func(datasource: *mut libc::c_void) -> libc::c_long 143 | where R: Read + Seek 144 | { 145 | let data: &mut DecoderData = unsafe { std::mem::transmute(datasource) }; 146 | data.reader.seek(io::SeekFrom::Current(0)).map(|v| v as libc::c_long).unwrap_or(-1) 147 | } 148 | 149 | let callbacks = { 150 | let mut callbacks: vorbisfile_sys::ov_callbacks = unsafe { std::mem::zeroed() }; 151 | callbacks.read_func = read_func::; 152 | callbacks.seek_func = seek_func::; 153 | callbacks.tell_func = tell_func::; 154 | callbacks 155 | }; 156 | 157 | let mut data = Box::new(DecoderData { 158 | vorbis: unsafe { std::mem::uninitialized() }, 159 | reader: input, 160 | current_logical_bitstream: 0, 161 | read_error: None, 162 | }); 163 | 164 | // initializing 165 | unsafe { 166 | let data_ptr = &mut *data as *mut DecoderData; 167 | let data_ptr = data_ptr as *mut libc::c_void; 168 | try!(check_errors(vorbisfile_sys::ov_open_callbacks(data_ptr, &mut data.vorbis, 169 | std::ptr::null(), 0, callbacks))); 170 | } 171 | 172 | Ok(Decoder { 173 | data: data, 174 | }) 175 | } 176 | 177 | pub fn time_seek(&mut self, s: f64) -> Result<(), VorbisError> { 178 | unsafe { 179 | check_errors(vorbisfile_sys::ov_time_seek(&mut self.data.vorbis, s)) 180 | } 181 | } 182 | 183 | pub fn time_tell(&mut self) -> Result { 184 | unsafe { 185 | Ok(vorbisfile_sys::ov_time_tell(&mut self.data.vorbis)) 186 | } 187 | } 188 | 189 | pub fn packets(&mut self) -> PacketsIter { 190 | PacketsIter(self) 191 | } 192 | 193 | pub fn into_packets(self) -> PacketsIntoIter { 194 | PacketsIntoIter(self) 195 | } 196 | 197 | fn next_packet(&mut self) -> Option> { 198 | let mut buffer = std::iter::repeat(0i16).take(2048).collect::>(); 199 | let buffer_len = buffer.len() * 2; 200 | 201 | match unsafe { 202 | vorbisfile_sys::ov_read(&mut self.data.vorbis, 203 | buffer.as_mut_ptr() as *mut libc::c_char, 204 | buffer_len as libc::c_int, 0, 2, 1, &mut self.data.current_logical_bitstream) 205 | } { 206 | 0 => { 207 | match self.data.read_error.take() { 208 | Some(err) => Some(Err(VorbisError::ReadError(err))), 209 | None => None, 210 | } 211 | }, 212 | 213 | err if err < 0 => { 214 | match check_errors(err as libc::c_int) { 215 | Err(e) => Some(Err(e)), 216 | Ok(_) => unreachable!() 217 | } 218 | }, 219 | 220 | len => { 221 | buffer.truncate(len as usize / 2); 222 | 223 | let infos = unsafe { vorbisfile_sys::ov_info(&mut self.data.vorbis, 224 | self.data.current_logical_bitstream) }; 225 | 226 | let infos: &vorbis_sys::vorbis_info = unsafe { std::mem::transmute(infos) }; 227 | 228 | Some(Ok(Packet { 229 | data: buffer, 230 | channels: infos.channels as u16, 231 | rate: infos.rate as u64, 232 | bitrate_upper: infos.bitrate_upper as u64, 233 | bitrate_nominal: infos.bitrate_nominal as u64, 234 | bitrate_lower: infos.bitrate_lower as u64, 235 | bitrate_window: infos.bitrate_window as u64, 236 | })) 237 | } 238 | } 239 | } 240 | } 241 | 242 | impl<'a, R> Iterator for PacketsIter<'a, R> where R: 'a + Read + Seek { 243 | type Item = Result; 244 | 245 | fn next(&mut self) -> Option> { 246 | self.0.next_packet() 247 | } 248 | } 249 | 250 | impl Iterator for PacketsIntoIter where R: Read + Seek { 251 | type Item = Result; 252 | 253 | fn next(&mut self) -> Option> { 254 | self.0.next_packet() 255 | } 256 | } 257 | 258 | impl Drop for Decoder where R: Read + Seek { 259 | fn drop(&mut self) { 260 | unsafe { 261 | vorbisfile_sys::ov_clear(&mut self.data.vorbis); 262 | } 263 | } 264 | } 265 | 266 | fn check_errors(code: libc::c_int) -> Result<(), VorbisError> { 267 | match code { 268 | 0 => Ok(()), 269 | 270 | vorbis_sys::OV_ENOTVORBIS => Err(VorbisError::NotVorbis), 271 | vorbis_sys::OV_EVERSION => Err(VorbisError::VersionMismatch), 272 | vorbis_sys::OV_EBADHEADER => Err(VorbisError::BadHeader), 273 | vorbis_sys::OV_EINVAL => Err(VorbisError::InvalidSetup), 274 | vorbis_sys::OV_HOLE => Err(VorbisError::Hole), 275 | 276 | vorbis_sys::OV_EREAD => unimplemented!(), 277 | 278 | vorbis_sys::OV_EIMPL => Err(VorbisError::Unimplemented), 279 | 280 | // indicates a bug or heap/stack corruption 281 | vorbis_sys::OV_EFAULT => panic!("Internal libvorbis error"), 282 | _ => panic!("Unknown vorbis error {}", code) 283 | } 284 | } 285 | 286 | #[derive(Debug)] 287 | pub enum VorbisQuality { 288 | VeryHighQuality, 289 | HighQuality, 290 | Quality, 291 | Midium, 292 | Performance, 293 | HighPerforamnce, 294 | VeryHighPerformance, 295 | } 296 | 297 | pub struct Encoder { 298 | e: vorbis_encoder::Encoder, 299 | } 300 | 301 | impl Encoder { 302 | pub fn new(channels: u8, rate: u64, quality: VorbisQuality) -> Result { 303 | let quality = match quality { 304 | VorbisQuality::VeryHighQuality => {1.0f32}, 305 | VorbisQuality::HighQuality => {0.8f32}, 306 | VorbisQuality::Quality => {0.6f32}, 307 | VorbisQuality::Midium => {0.4f32}, 308 | VorbisQuality::Performance => {0.3f32}, 309 | VorbisQuality::HighPerforamnce => {0.1f32}, 310 | VorbisQuality::VeryHighPerformance => {-0.1f32}, 311 | }; 312 | Ok(Encoder { 313 | e: match vorbis_encoder::Encoder::new(channels as u32, rate, quality) { 314 | Ok(e) => {e}, 315 | Err(i) => { 316 | match check_errors(i) { 317 | Ok(()) => panic!("Unexpected behavior, call hossein.noroozpour@gmail.com"), 318 | Err(err) => return Err(err), 319 | } 320 | } 321 | } 322 | }) 323 | } 324 | 325 | // data is an interleaved array of samples 326 | pub fn encode(&mut self, data: &Vec) -> Result, VorbisError> { 327 | Ok( 328 | match self.e.encode(&data) { 329 | Ok(d) => {d}, 330 | Err(i) => { 331 | match check_errors(i) { 332 | Ok(()) => panic!("Unexpected behavior, call hossein.noroozpour@gmail.com"), 333 | Err(err) => return Err(err), 334 | } 335 | } 336 | } 337 | ) 338 | } 339 | 340 | pub fn flush(&mut self) -> Result, VorbisError> { 341 | Ok( 342 | match self.e.flush() { 343 | Ok(d) => {d}, 344 | Err(i) => { 345 | match check_errors(i) { 346 | Ok(()) => panic!("Unexpected behavior, call hossein.noroozpour@gmail.com"), 347 | Err(err) => return Err(err), 348 | } 349 | } 350 | } 351 | ) 352 | } 353 | } 354 | --------------------------------------------------------------------------------